repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
iservport/helianto
helianto-core/src/main/java/org/helianto/core/test/EntityTestSupport.java
1747
package org.helianto.core.test; import org.helianto.core.domain.Entity; import java.util.ArrayList; import java.util.List; /** * Class to support <code>Entity</code> tests. * * @author Mauricio Fernandes de Castro */ public class EntityTestSupport { public static Entity entity = createEntity(); public static int testKey; /** * Test support method to create an <code>Entity</code>. * * @param id */ public static Entity createEntity(int id) { Entity entity = EntityTestSupport.createEntity(); entity.setId(id); return entity; } /** * Test support method to create an <code>Entity</code>. */ public static Entity createEntity() { Entity entity = EntityTestSupport.createEntity("DEFAULT"); return entity; } /** * Test support method to create an <code>Entity</code>. */ public static Entity createEntity(String contextName) { Entity entity = EntityTestSupport.createEntity(contextName, DomainTestSupport.getNonRepeatableStringValue(testKey++, 20)); return entity; } /** * Test support method to create an <code>Entity</code>. */ public static Entity createEntity(String contextName, String alias) { Entity entity = new Entity(contextName, alias); return entity; } /** * Test support method to create a <code>Entity</code> list. * * @param entityListSize */ public static List<Entity> createEntityList(int entityListSize) { List<Entity> entityList = new ArrayList<Entity>(); for (int i=0;i<entityListSize;i++) { entityList.add(createEntity("DEFAULT")); } return entityList; } }
apache-2.0
genericsystem/genericsystem2015
gs-kernel/src/test/java/org/genericsystem/remote/MetaRelationTest.java
1116
package org.genericsystem.remote; //package org.genericsystem.kernel; // //import java.util.Collections; // //import org.testng.annotations.Test; // //@Test //public class MetaRelationTest extends AbstractTest { // // public void test001_setMetaAttribute_engineEngine() { // // Root engine = new Root(); // Vertex metaAttribute = engine.setMetaAttribute(); // Vertex metaRelation = engine.setMetaAttribute(Collections.singletonList(engine)); // assert metaRelation.getMeta() == metaAttribute; // assert metaRelation.inheritsFrom(metaAttribute); // } // // public void test002_setMetaAttribute_relation() { // // Root engine = new Root(); // Vertex metaAttribute = engine.setMetaAttribute(); // Vertex metaRelation = engine.setMetaAttribute(Collections.singletonList(engine)); // Vertex car = engine.addInstance("Car"); // Vertex power = engine.addInstance("Power", car); // Vertex color = engine.addInstance("Color"); // Vertex carColor = engine.addInstance("carColor", new Vertex[] { car, color }); // assert carColor.isInstanceOf(metaRelation); // assert power.isInstanceOf(metaAttribute); // } // }
apache-2.0
serge-rider/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/dialogs/connection/ConnectionPageNetwork.java
9725
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.dialogs.connection; import org.eclipse.jface.dialogs.ControlEnableState; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.model.connection.DBPDriver; import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration; import org.jkiss.dbeaver.registry.DataSourceDescriptor; import org.jkiss.dbeaver.registry.configurator.UIPropertyConfiguratorDescriptor; import org.jkiss.dbeaver.registry.configurator.UIPropertyConfiguratorRegistry; import org.jkiss.dbeaver.registry.network.NetworkHandlerDescriptor; import org.jkiss.dbeaver.registry.network.NetworkHandlerRegistry; import org.jkiss.dbeaver.ui.IObjectPropertyConfigurator; import org.jkiss.dbeaver.ui.UIUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Network handlers edit dialog page */ public class ConnectionPageNetwork extends ConnectionWizardPage { public static final String PAGE_NAME = ConnectionPageNetwork.class.getSimpleName(); private static final Log log = Log.getLog(ConnectionPageNetwork.class); private TabFolder handlersFolder; private DataSourceDescriptor prevDataSource; private static class HandlerBlock { private final IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator; private final Composite blockControl; private final Button useHandlerCheck; private final TabItem tabItem; ControlEnableState blockEnableState; private final Map<String, DBWHandlerConfiguration> loadedConfigs = new HashMap<>(); private HandlerBlock(IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator, Composite blockControl, Button useHandlerCheck, TabItem tabItem) { this.configurator = configurator; this.blockControl = blockControl; this.useHandlerCheck = useHandlerCheck; this.tabItem = tabItem; } } private final ConnectionWizard wizard; private Map<NetworkHandlerDescriptor, HandlerBlock> configurations = new HashMap<>(); ConnectionPageNetwork(ConnectionWizard wizard) { super(PAGE_NAME); this.wizard = wizard; setTitle(CoreMessages.dialog_connection_network_title); setDescription(CoreMessages.dialog_tunnel_title); } @Override public void createControl(Composite parent) { handlersFolder = new TabFolder(parent, SWT.TOP | SWT.FLAT); handlersFolder.setLayoutData(new GridData(GridData.FILL_BOTH)); setControl(handlersFolder); } private void createHandlerTab(final NetworkHandlerDescriptor descriptor) throws DBException { IObjectPropertyConfigurator<DBWHandlerConfiguration> configurator; try { String implName = descriptor.getHandlerType().getImplName(); UIPropertyConfiguratorDescriptor configDescriptor = UIPropertyConfiguratorRegistry.getInstance().getDescriptor(implName); if (configDescriptor == null) { return; } configurator = configDescriptor.createConfigurator(); } catch (DBException e) { log.error("Can't create network configurator '" + descriptor.getId() + "'", e); return; } TabItem tabItem = new TabItem(handlersFolder, SWT.NONE); tabItem.setText(descriptor.getLabel()); tabItem.setToolTipText(descriptor.getDescription()); Composite composite = new Composite(handlersFolder, SWT.NONE); tabItem.setControl(composite); composite.setLayout(new GridLayout(1, false)); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); final Button useHandlerCheck = UIUtils.createCheckbox(composite, NLS.bind(CoreMessages.dialog_tunnel_checkbox_use_handler, descriptor.getLabel()), false); useHandlerCheck.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { HandlerBlock handlerBlock = configurations.get(descriptor); DBWHandlerConfiguration handlerConfiguration = handlerBlock.loadedConfigs.get(wizard.getPageSettings().getActiveDataSource().getId()); handlerConfiguration.setEnabled(useHandlerCheck.getSelection()); enableHandlerContent(descriptor); } }); Composite handlerComposite = UIUtils.createPlaceholder(composite, 1); configurations.put(descriptor, new HandlerBlock(configurator, handlerComposite, useHandlerCheck, tabItem)); handlerComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); configurator.createControl(handlerComposite); } @Override public void activatePage() { DataSourceDescriptor dataSource = wizard.getPageSettings().getActiveDataSource(); DBPDriver driver = wizard.getSelectedDriver(); NetworkHandlerRegistry registry = NetworkHandlerRegistry.getInstance(); if (prevDataSource == null || prevDataSource != dataSource) { for (TabItem item : handlersFolder.getItems()) { item.dispose(); } for (NetworkHandlerDescriptor descriptor : registry.getDescriptors(dataSource)) { try { createHandlerTab(descriptor); } catch (DBException e) { log.warn(e); } } prevDataSource = dataSource; handlersFolder.layout(true, true); // for (TabItem item : handlersFolder.getItems()) { // ((Composite)item.getControl()).layout(false); // } } TabItem selectItem = null; for (NetworkHandlerDescriptor descriptor : registry.getDescriptors(dataSource)) { DBWHandlerConfiguration configuration = dataSource.getConnectionConfiguration().getHandler(descriptor.getId()); if (configuration == null) { configuration = new DBWHandlerConfiguration(descriptor, driver); } HandlerBlock handlerBlock = configurations.get(descriptor); if (handlerBlock == null) { continue; } //handlerBlock.useHandlerCheck.setSelection(configuration.isEnabled()); if (selectItem == null && configuration.isEnabled()) { selectItem = handlerBlock.tabItem; } if (!handlerBlock.loadedConfigs.containsKey(dataSource.getId())) { handlerBlock.configurator.loadSettings(configuration); handlerBlock.loadedConfigs.put(dataSource.getId(), configuration); } enableHandlerContent(descriptor); } if (selectItem != null) { handlersFolder.setSelection(selectItem); } else { handlersFolder.setSelection(0); } } protected void enableHandlerContent(NetworkHandlerDescriptor descriptor) { HandlerBlock handlerBlock = configurations.get(descriptor); DBWHandlerConfiguration handlerConfiguration = handlerBlock.loadedConfigs.get(wizard.getPageSettings().getActiveDataSource().getId()); handlerBlock.useHandlerCheck.setSelection(handlerConfiguration.isEnabled()); if (handlerConfiguration.isEnabled()) { if (handlerBlock.blockEnableState != null) { handlerBlock.blockEnableState.restore(); handlerBlock.blockEnableState = null; } } else if (handlerBlock.blockEnableState == null) { handlerBlock.blockEnableState = ControlEnableState.disable(handlerBlock.blockControl); } } @Override public void saveSettings(DataSourceDescriptor dataSource) { boolean foundHandlers = false; java.util.List<DBWHandlerConfiguration> handlers = new ArrayList<>(); for (HandlerBlock handlerBlock : configurations.values()) { DBWHandlerConfiguration configuration = handlerBlock.loadedConfigs.get(dataSource.getId()); if (configuration != null) { foundHandlers = true; handlerBlock.configurator.saveSettings(configuration); handlers.add(configuration); } } if (foundHandlers) { dataSource.getConnectionConfiguration().setHandlers(handlers); } } }
apache-2.0
joel-costigliola/assertj-core
src/test/java/org/assertj/core/internal/files/Files_assertHasDigest_DigestBytes_Test.java
6237
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.internal.files; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.error.ShouldBeFile.shouldBeFile; import static org.assertj.core.error.ShouldBeReadable.shouldBeReadable; import static org.assertj.core.error.ShouldExist.shouldExist; import static org.assertj.core.error.ShouldHaveDigest.shouldHaveDigest; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.security.MessageDigest; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.DigestDiff; import org.assertj.core.internal.Files; import org.assertj.core.internal.FilesBaseTest; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link Files#assertHasDigest(AssertionInfo, File, MessageDigest, byte[])}</code> * * @author Valeriy Vyrva */ class Files_assertHasDigest_DigestBytes_Test extends FilesBaseTest { private final MessageDigest digest = mock(MessageDigest.class); private final byte[] expected = new byte[0]; @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> files.assertHasDigest(INFO, null, digest, expected)) .withMessage(actualIsNull()); } @Test void should_fail_with_should_exist_error_if_actual_does_not_exist() { // GIVEN given(actual.exists()).willReturn(false); // WHEN catchThrowable(() -> files.assertHasDigest(INFO, actual, digest, expected)); // THEN verify(failures).failure(INFO, shouldExist(actual)); } @Test void should_fail_if_actual_exists_but_is_not_file() { // GIVEN given(actual.exists()).willReturn(true); given(actual.isFile()).willReturn(false); // WHEN catchThrowable(() -> files.assertHasDigest(INFO, actual, digest, expected)); // THEN verify(failures).failure(INFO, shouldBeFile(actual)); } @Test void should_fail_if_actual_exists_but_is_not_readable() { // GIVEN given(actual.exists()).willReturn(true); given(actual.isFile()).willReturn(true); given(actual.canRead()).willReturn(false); // WHEN catchThrowable(() -> files.assertHasDigest(INFO, actual, digest, expected)); // THEN verify(failures).failure(INFO, shouldBeReadable(actual)); } @Test void should_throw_error_if_digest_is_null() { assertThatNullPointerException().isThrownBy(() -> files.assertHasDigest(INFO, null, (MessageDigest) null, expected)) .withMessage("The message digest algorithm should not be null"); } @Test void should_throw_error_if_expected_is_null() { assertThatNullPointerException().isThrownBy(() -> files.assertHasDigest(INFO, null, digest, (byte[]) null)) .withMessage("The binary representation of digest to compare to should not be null"); } @Test void should_throw_error_wrapping_caught_IOException() throws IOException { // GIVEN IOException cause = new IOException(); given(actual.exists()).willReturn(true); given(actual.isFile()).willReturn(true); given(actual.canRead()).willReturn(true); given(nioFilesWrapper.newInputStream(any())).willThrow(cause); // WHEN Throwable error = catchThrowable(() -> files.assertHasDigest(INFO, actual, digest, expected)); // THEN assertThat(error).isInstanceOf(UncheckedIOException.class) .hasCause(cause); } @Test void should_throw_error_wrapping_caught_NoSuchAlgorithmException() { // GIVEN String unknownDigestAlgorithm = "UnknownDigestAlgorithm"; // WHEN Throwable error = catchThrowable(() -> files.assertHasDigest(INFO, actual, unknownDigestAlgorithm, expected)); // THEN assertThat(error).isInstanceOf(IllegalStateException.class) .hasMessage("Unable to find digest implementation for: <UnknownDigestAlgorithm>"); } @Test void should_fail_if_actual_does_not_have_expected_digest() throws IOException { // GIVEN InputStream stream = getClass().getResourceAsStream("/red.png"); given(actual.exists()).willReturn(true); given(actual.isFile()).willReturn(true); given(actual.canRead()).willReturn(true); given(nioFilesWrapper.newInputStream(any())).willReturn(stream); given(digest.digest()).willReturn(new byte[] { 0, 1 }); // WHEN catchThrowable(() -> files.assertHasDigest(INFO, actual, digest, expected)); // THEN verify(failures).failure(INFO, shouldHaveDigest(actual, new DigestDiff("0001", "", digest))); failIfStreamIsOpen(stream); } @Test void should_pass_if_actual_has_expected_digest() throws IOException { // GIVEN InputStream stream = getClass().getResourceAsStream("/red.png"); given(actual.exists()).willReturn(true); given(actual.isFile()).willReturn(true); given(actual.canRead()).willReturn(true); given(nioFilesWrapper.newInputStream(any())).willReturn(stream); given(digest.digest()).willReturn(expected); // WHEN files.assertHasDigest(INFO, actual, digest, expected); // THEN failIfStreamIsOpen(stream); } }
apache-2.0
micromagic/eterna
main/src/share/self/micromagic/util/CustomResultIterator.java
2942
/* * Copyright 2009-2015 xinjunli (micromagic@sina.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 self.micromagic.util; import java.util.LinkedList; import java.sql.SQLException; import self.micromagic.eterna.digester.ConfigurationException; import self.micromagic.eterna.security.Permission; import self.micromagic.eterna.sql.ResultIterator; import self.micromagic.eterna.sql.ResultReaderManager; import self.micromagic.eterna.sql.ResultRow; import self.micromagic.eterna.sql.impl.AbstractResultIterator; import self.micromagic.eterna.sql.impl.ResultRowImpl; public class CustomResultIterator extends AbstractResultIterator implements ResultIterator { private int recordCount = 0; private Permission permission; private int rowNum; public CustomResultIterator(ResultReaderManager rrm, Permission permission) throws ConfigurationException { super(rrm, permission); this.permission = permission; this.result = new LinkedList(); } private CustomResultIterator(Permission permission) { this.permission = permission; } public ResultRow createRow(Object[] values) throws ConfigurationException { if (values.length != this.readerManager.getReaderCount()) { throw new ConfigurationException("The values count must same as the ResultReaderManager's readers count."); } try { this.rowNum++; ResultRow row = new ResultRowImpl(values, this, this.rowNum, this.permission); this.result.add(row); return row; } catch (SQLException ex) { throw new ConfigurationException(ex); } } public void finishCreateRow() { this.resultItr = this.result.iterator(); this.recordCount = this.result.size(); } public int getRealRecordCount() { return this.recordCount; } public int getRecordCount() { return this.recordCount; } public boolean isRealRecordCountAvailable() { return true; } public boolean isHasMoreRecord() { return false; } public ResultIterator copy() throws ConfigurationException { CustomResultIterator ritr = new CustomResultIterator(this.permission); this.copy(ritr); return ritr; } protected void copy(ResultIterator copyObj) throws ConfigurationException { super.copy(copyObj); CustomResultIterator ritr = (CustomResultIterator) copyObj; ritr.recordCount = this.recordCount; } }
apache-2.0
leibing8912/QuickInquiry
jkchat/src/main/java/cn/jianke/jkchat/data/dao/JkChatConversationDaoWrapper.java
7135
package cn.jianke.jkchat.data.dao; import android.content.Context; import com.jk.chat.gen.JkChatConversationDao; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; import cn.jianke.jkchat.domain.JkChatConversation; import cn.jianke.jkchat.domain.JkChatMessage; /** * @className: JkChatConversationDaoWrapper * @classDescription: 健客聊天会话数据库包装(封装一些常用方法) * @author: leibing * @createTime: 2017/2/22 */ public class JkChatConversationDaoWrapper { // sington private static JkChatConversationDaoWrapper instance; // 健客聊天会话Dao private JkChatConversationDao mJkChatConversationDao; /** * Constructor * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param context 引用 * @return */ private JkChatConversationDaoWrapper(Context context){ // init jk chat conversation dao mJkChatConversationDao = JkChatDaoManager.getInstance( context.getApplicationContext()).getDaoSession().getJkChatConversationDao(); } /** * sington * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param context 引用(此处传入application引用防止内存泄漏) * @return */ public static JkChatConversationDaoWrapper getInstance(Context context){ if (instance == null){ synchronized(JkChatMessageDaoWrapper.class){ if (instance == null){ instance = new JkChatConversationDaoWrapper(context); } } } return instance; } /** * 获取数据库中最新一条会话信息(按时间降序) * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param * @return 会话信息 */ public JkChatConversation findLastConversation(){ JkChatConversation result = null; if (mJkChatConversationDao != null) { QueryBuilder jkCtQb = mJkChatConversationDao.queryBuilder(); List<JkChatConversation> mJkChatConversationList = // 按时间降序排序 jkCtQb.orderDesc(JkChatConversationDao .Properties.ConversationCreateTime) // 只查询一条数据 .limit(1) // 返回查询结果 .list(); if (mJkChatConversationList != null && mJkChatConversationList.size() == 1) { // 获取数据库中最新聊天会话数据 result = mJkChatConversationList.get(0); } } return result; } /** * 获取数据库最新一条会话消息中的状态 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param * @return 会话状态 */ public int getLastConversationStatus() { JkChatConversation result = findLastConversation(); if (result != null){ return result.getStatus(); } return JkChatConversation.STATUS_NULL; } /** * 设置数据库最新一条会话消息中的状态 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param status 会话状态 * @return */ public void setLastConversationStatus(int status) { try { JkChatConversation mJkChatConversation = findLastConversation(); if (mJkChatConversation != null){ mJkChatConversation.setStatus(status); if (mJkChatConversationDao != null){ mJkChatConversationDao.update(mJkChatConversation); } } }catch (Exception ex){ ex.printStackTrace(); } } /** * 获取数据库最新一条会话消息中的是否登录标识 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param * @return */ public String getLastConversationIsLogin() { String isLogin = null; try { JkChatConversation mJkChatConversation = findLastConversation(); if (mJkChatConversation != null){ isLogin = mJkChatConversation.getIsLogin(); } }catch (Exception ex){ ex.printStackTrace(); } return isLogin; } /** * 在数据库中根据cid更新tid,如果没有该记录时则创建 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param cid 会话id * @param tid 消息id * @param status 状态 * @param createdTime 会话创建时间 * @return */ public void updataTidByCid(String cid, String tid, int status, long createdTime) { if (mJkChatConversationDao != null){ QueryBuilder jkCtQb = mJkChatConversationDao.queryBuilder(); List<JkChatConversation> mJkChatConversationList = // 条件查询cid jkCtQb.where(JkChatConversationDao.Properties.Cid.eq(cid)) // 返回查询结果 .list(); if (mJkChatConversationList != null && mJkChatConversationList.size() != 0) { // 更新会话 for (JkChatConversation mJkChatConversation : mJkChatConversationList){ mJkChatConversation.setTid(tid); mJkChatConversation.setStatus(status); mJkChatConversation.setConversationCreateTime(createdTime); // 更新数据 mJkChatConversationDao.update(mJkChatConversation); } }else { // 创建会话 JkChatConversation newJkChatConversation = new JkChatConversation(); newJkChatConversation.setCid(cid); newJkChatConversation.setTid(tid); newJkChatConversation.setStatus(status); newJkChatConversation.setConversationCreateTime(createdTime); // 插入数据 mJkChatConversationDao.insert(newJkChatConversation); } } } /** * 保存会话消息 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param mJkChatConversation 健客聊天会话信息 * @return */ public void saveConversation(JkChatConversation mJkChatConversation){ if (mJkChatConversationDao != null){ mJkChatConversationDao.insert(mJkChatConversation); } } /** * 更新会话消息 * @author leibing * @createTime 2017/2/22 * @lastModify 2017/2/22 * @param mJkChatConversation 健客聊天会话信息 * @return */ public void updateConversation(JkChatConversation mJkChatConversation){ if (mJkChatConversationDao != null){ mJkChatConversationDao.update(mJkChatConversation); } } }
apache-2.0
jorseph/SearchRestaurant
app/src/main/java/com/example/currentplacedetailsonmap/data/LocationInfo.java
2078
package com.example.currentplacedetailsonmap.data; import java.io.Serializable; public class LocationInfo implements Serializable { private String placeid; private String lat; private String lng; private String vicinity; //addr private String tel; private String name; private String atype; private String photo_URL; private int rating; private int score; private boolean nowopen; private String phone; public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public LocationInfo(String placeid, String lat, String lng, String vicinity, String tel, String name, String atype, String photo_URL,int rating, int score, boolean nowopen, String phone) { super(); this.placeid = placeid; this.lat = lat; this.lng = lng; this.vicinity = vicinity; this.tel = tel; this.name = name; this.atype = atype; this.photo_URL = photo_URL; this.rating = rating; this.score = score; this.nowopen = nowopen; this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLat() { return lat; } public void setLat(String lat) { this.lat = lat; } public String getLng() { return lng; } public void setLng(String lng) { this.lng = lng; } public String getVicinity() { return vicinity; } public void setVicinity(String vicinity) { this.vicinity = vicinity; } public String getAtype() { return atype; } public void setAtype(String atype) { this.atype = atype; } public String getPhoto() { return photo_URL; } public String getPlaceid() {return placeid;} public void setPhoto(Integer photo) { this.photo_URL = photo_URL; } public int getRating() {return rating;} public int getScore() {return score;} public void setScore(int score) {this.score = score;} public boolean getOpen() {return nowopen;} public void setOpen(boolean nowopen) {this.nowopen = nowopen;} public String getPhone() {return phone;} public void setPhone(String phone) {this.phone = phone;} }
apache-2.0
vindell/spring-boot-starter-rocketmq
src/main/java/org/apache/rocketmq/spring/boot/handler/impl/RocketmqEventMessageOrderlyHandler.java
1872
package org.apache.rocketmq.spring.boot.handler.impl; import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.spring.boot.event.RocketmqEvent; import org.apache.rocketmq.spring.boot.handler.AbstractRouteableMessageHandler; import org.apache.rocketmq.spring.boot.handler.MessageOrderlyHandler; import org.apache.rocketmq.spring.boot.handler.chain.HandlerChain; import org.apache.rocketmq.spring.boot.handler.chain.HandlerChainResolver; import org.apache.rocketmq.spring.boot.handler.chain.ProxiedHandlerChain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RocketmqEventMessageOrderlyHandler extends AbstractRouteableMessageHandler<RocketmqEvent> implements MessageOrderlyHandler { private static final Logger LOG = LoggerFactory.getLogger(RocketmqEventMessageOrderlyHandler.class); public RocketmqEventMessageOrderlyHandler(HandlerChainResolver<RocketmqEvent> filterChainResolver) { super(filterChainResolver); } @Override public boolean preHandle(MessageExt msgExt, ConsumeOrderlyContext context) throws Exception { return true; } @Override public void handleMessage(MessageExt msgExt, ConsumeOrderlyContext context) throws Exception { //构造原始链对象 HandlerChain<RocketmqEvent> originalChain = new ProxiedHandlerChain(); //执行事件处理链 this.doHandler(new RocketmqEvent(msgExt, context.getMessageQueue()), originalChain); } @Override public void postHandle(MessageExt msgExt, ConsumeOrderlyContext context) throws Exception { } @Override public void afterCompletion(MessageExt msgExt, ConsumeOrderlyContext context, Exception ex) throws Exception { if(ex != null) { LOG.warn("Consume message failed. messageExt:{}", msgExt, ex); } } }
apache-2.0
China-ls/wechat4java
src/main/java/weixin/popular/bean/paymch/MchBaseResult.java
1987
package weixin.popular.bean.paymch; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "xml") @XmlAccessorType(XmlAccessType.FIELD) public class MchBaseResult { protected String return_code; protected String return_msg; protected String appid; protected String mch_id; protected String nonce_str; protected String sign; protected String result_code; protected String err_code; protected String err_code_des; public String getReturn_code() { return return_code; } public void setReturn_code(String return_code) { this.return_code = return_code; } public String getReturn_msg() { return return_msg; } public void setReturn_msg(String return_msg) { this.return_msg = return_msg; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getMch_id() { return mch_id; } public void setMch_id(String mch_id) { this.mch_id = mch_id; } public String getNonce_str() { return nonce_str; } public void setNonce_str(String nonce_str) { this.nonce_str = nonce_str; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getResult_code() { return result_code; } public void setResult_code(String result_code) { this.result_code = result_code; } public String getErr_code() { return err_code; } public void setErr_code(String err_code) { this.err_code = err_code; } public String getErr_code_des() { return err_code_des; } public void setErr_code_des(String err_code_des) { this.err_code_des = err_code_des; } }
apache-2.0
pascalrobert/aribaweb
src/util/src/main/java/ariba/util/core/Crypto.java
9878
/* Copyright 1996-2008 Ariba, 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. $Id: //ariba/platform/util/core/ariba/util/core/Crypto.java#8 $ */ package ariba.util.core; import java.util.Iterator; import java.util.List; import java.util.Map; import ariba.util.log.Log; /** Disclaimer. This is not production security! This is a weak attempt to thwart direct or accidental packet sniffing from obtaining cleartext passwords. Of course real encryption is the solution but at this moment is not achievable due to schedule constraints. @aribaapi private */ public class Crypto implements CryptoInterface { private CryptoChar cryptoChar; private boolean passThrough = false; public Crypto (Object key) { this.cryptoChar = new CryptoChar(key.hashCode()); } public Crypto (Object key, boolean enabled) { this.passThrough = !enabled; this.cryptoChar = new CryptoChar(key.hashCode()); } public Object encrypt (Object target) { if (this.passThrough) { return target; } // Log.runtime.debug("encrypt %s", target); if (target instanceof String) { return this.encrypt((String)target); } if (target instanceof Map) { return this.encrypt((Map)target); } if (target instanceof List) { return this.encrypt((List)target); } return target; } public char encrypt (char ch) { return this.cryptoChar.encrypt(ch); } public String encrypt (String string) { int strLen = string.length(); char [] charBuffer = new char[strLen]; string.getChars(0, strLen, charBuffer, 0); reverse(charBuffer, strLen); for (int idx = 0; idx < strLen; idx++) { charBuffer[idx] = this.encrypt(charBuffer[idx]); } return new String(charBuffer); } public static char [] reverse (char [] charBuffer, int charBufferLength) { int halfStrLen = charBufferLength/2; for (int idx = 0; idx < halfStrLen; idx++) { char temp = charBuffer[idx]; int revIdx = charBufferLength-idx-1; charBuffer[idx] = charBuffer[revIdx]; charBuffer[revIdx] = temp; } return charBuffer; } public Map encrypt (Map map) { int size = map.size(); // calling new Map with size zero is a no-no Map result = (size>0)?MapUtil.map(size):MapUtil.map(); Iterator e = map.keySet().iterator(); while (e.hasNext()) { Object key = e.next(); Object value = map.get(key); result.put(this.encrypt(key), this.encrypt(value)); } return result; } public List encrypt (List vector) { int size = vector.size(); // calling ListUtil.list with size zero is a no-no List result = (size>0)?ListUtil.list(size):ListUtil.list(); for (int idx = 0; idx < size; idx++) { Object value = vector.get(idx); result.add(this.encrypt(value)); } return result; } public Object decrypt (Object target) { if (this.passThrough) { return target; } // Log.runtime.debug("decrypt %s", target); if (target instanceof String) { return this.decrypt((String)target); } if (target instanceof Map) { return this.decrypt((Map)target); } if (target instanceof List) { return this.decrypt((List)target); } return target; } public char decrypt (char ch) { return this.cryptoChar.decrypt(ch); } public String decrypt (String string) { int strLen = string.length(); char [] charBuffer = new char[strLen]; string.getChars(0, strLen, charBuffer, 0); reverse(charBuffer, strLen); for (int idx = 0; idx < strLen; idx++) { charBuffer[idx] = this.decrypt(charBuffer[idx]); } return new String(charBuffer); } public Map decrypt (Map map) { int size = map.size(); // calling new Map with size zero is a no-no Map result = (size>0)?MapUtil.map(size):MapUtil.map(); Iterator e = map.keySet().iterator(); while (e.hasNext()) { Object key = e.next(); Object value = map.get(key); result.put(this.decrypt(key), this.decrypt(value)); } return result; } public List decrypt (List vector) { int size = vector.size(); // calling ListUtil.list with size zero is a no-no List result = (size>0)?ListUtil.list(size):ListUtil.list(); for (int idx = 0; idx < size; idx++) { Object value = vector.get(idx); result.add(this.decrypt(value)); } return result; } /* public static void main (String [] args) { test(0,(char)0xFFFF); test(0,'a'); for (int idx = 0; idx < 16; idx++) { bigtest(idx, args); } } public static void test (int key, char input) { PrintStream out = System.out; Random random = new Random(); out.println("input is " + input); Crypto captCrunch = new Crypto(key); char x = captCrunch.encrypt(input); out.println("crypted is " + x); char y = captCrunch.decrypt(x); out.println("decrypted is " + y); } public static String formatArray (String [] args) { String output = Constants.EmptyString; for (int idx = 0; idx < args.length; idx++) { output = output + " arg[" + idx + "] = " + args[idx]; } return output; } public static void bigtest (int key, String [] args) { PrintStream out = System.out; out.println("Crypting " + formatArray(args)); Crypto captCrunch = new Crypto(key); List vector = ListUtil.list(); for (int idx = 0; idx<args.length - 1; idx+=2) { vector.add(Constants.getInteger(idx)); Map map = new Map(); map.put(args[idx], args[idx+1]); vector.add(map); } out.println("List - precrypt: " + vector); vector = captCrunch.encrypt(vector); out.println("List - prostcrypt: " + vector); vector = (List) captCrunch.decrypt(vector); out.println("List - prostdecrypt: " + vector); } */ } class CryptoChar { static final int CharBitLength = 16; static final int MinShift = 5; int encryptLowerCharShiftCount; int encryptUpperCharShiftCount; char encryptLowerCharMask; char encryptUpperCharMask; char decryptLowerCharMask; char decryptUpperCharMask; int decryptLowerCharShiftCount; int decryptUpperCharShiftCount; public CryptoChar (int key) { this.encryptLowerCharShiftCount = Math.abs(key % (CharBitLength-MinShift)) + MinShift; Log.util.debug("CryptoChar - key: %s", this.encryptLowerCharShiftCount); this.init(); } private void init () { this.encryptUpperCharShiftCount = CharBitLength - this.encryptLowerCharShiftCount; this.encryptLowerCharMask = (char) (0xFFFF >>> this.encryptLowerCharShiftCount); this.encryptUpperCharMask = (char) (0xFFFF << this.encryptUpperCharShiftCount); this.decryptLowerCharMask = (char) (this.encryptUpperCharMask >>> this.encryptUpperCharShiftCount); this.decryptUpperCharMask = (char) (this.encryptLowerCharMask << this.encryptLowerCharShiftCount); this.decryptLowerCharShiftCount = this.encryptUpperCharShiftCount; this.decryptUpperCharShiftCount = this.encryptLowerCharShiftCount; } public char encrypt (char val) { char lowerShifted = (char) (val << this.encryptLowerCharShiftCount); char upperShifted = (char) ((val & this.encryptUpperCharMask) >>> this.encryptUpperCharShiftCount); char retVal = (char)(lowerShifted | upperShifted); return retVal; } /* public void dumpChar (char x) { PrintStream out = System.out; byte upper = (byte)(x << CharBitLength); byte lower = (byte)x; out.println(this.dumpByte(upper)+this.dumpByte(lower)); } public String dumpByte (byte x) { String output = Constants.EmptyString; for (int idx = 0; idx < 16; idx++) { boolean on = ((x & 0x80)==0); if (on) { output = output + "1"; } else { output = output + "0"; } x = (byte)(x << 1); } return output; } */ public char decrypt (char val) { char lowerShifted = (char) (val << this.decryptLowerCharShiftCount); char upperShifted = (char) ((val & this.decryptUpperCharMask) >>> this.decryptUpperCharShiftCount); char retVal = (char)(lowerShifted | upperShifted); return retVal; } }
apache-2.0
ThoughtWorksInc/go-plugin-util
src/maven/ActivationFile.java
2240
package maven; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * This is the file specification used to activate the profile. The missing value will be the location * of a file that needs to exist, and if it doesn't the profile will be activated. On the other hand exists will test * for the existence of the file and if it is there the profile will be activated. * * * <p>Java class for ActivationFile complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ActivationFile"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;all> * &lt;element name="missing" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="exists" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/all> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ActivationFile", propOrder = { }) public class ActivationFile { protected String missing; protected String exists; /** * Gets the value of the missing property. * * @return * possible object is * {@link String } * */ public String getMissing() { return missing; } /** * Sets the value of the missing property. * * @param value * allowed object is * {@link String } * */ public void setMissing(String value) { this.missing = value; } /** * Gets the value of the exists property. * * @return * possible object is * {@link String } * */ public String getExists() { return exists; } /** * Sets the value of the exists property. * * @param value * allowed object is * {@link String } * */ public void setExists(String value) { this.exists = value; } }
apache-2.0
CChengz/dot.r
workspace/fits/ke/src/main/java/uk/ac/abdn/fits/hibernate/dao/OperationalHoursDAO.java
465
package uk.ac.abdn.fits.hibernate.dao; /** * @author Cheng Zeng, University of Aberdeen * */ import java.util.List; import org.springframework.transaction.annotation.Transactional; import uk.ac.abdn.fits.hibernate.model.OperationalHours; @Transactional(readOnly = false) public interface OperationalHoursDAO { void insertOperationalHours(OperationalHours operational_hours); List<OperationalHours> getOperationalHoursByOpId(int operator_id); }
apache-2.0
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201308/UserServiceInterface.java
5273
/** * UserServiceInterface.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201308; public interface UserServiceInterface extends java.rmi.Remote { /** * Creates a new {@link User}. * * The following fields are required: * <ul> * <li>{@link User#email}</li> * <li>{@link User#name}</li> * </ul> * * * @param user the user to create * * @return the new user with its ID filled in */ public com.google.api.ads.dfp.v201308.User createUser(com.google.api.ads.dfp.v201308.User user) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Creates new {@link User} objects. * * * @param users the users to create * * @return the created users with their IDs filled in */ public com.google.api.ads.dfp.v201308.User[] createUsers(com.google.api.ads.dfp.v201308.User[] users) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Returns the {@link Role} objects that are defined for the users * of the * network. * * * @return the roles defined for the user's network */ public com.google.api.ads.dfp.v201308.Role[] getAllRoles() throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Returns the current {@link User}. * * * @return the current user */ public com.google.api.ads.dfp.v201308.User getCurrentUser() throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Returns the {@link User} uniquely identified by the given ID. * * * @param userId The optional ID of the user. For current user set to * {@code null}. * * @return the {@code User} uniquely identified by the given ID */ public com.google.api.ads.dfp.v201308.User getUser(java.lang.Long userId) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Gets a {@link UserPage} of {@link User} objects that satisfy * the given * {@link Statement#query}. The following fields are supported * for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code email}</td> * <td>{@link User#email}</td> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link User#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link User#name}</td> * </tr> * <tr> * <td>{@code roleId}</td> * <td>{@link User#roleId} * </tr> * <tr> * <td>{@code rolename}</td> * <td>{@link User#roleName} * </tr> * <tr> * <td>{@code status}</td> * <td>{@code ACTIVE} if {@link User#isActive} is true; {@code * INACTIVE} * otherwise</td> * </tr> * </table> * * * @param filterStatement a Publisher Query Language statement used to * filter * a set of users * * @return the users that match the given filter */ public com.google.api.ads.dfp.v201308.UserPage getUsersByStatement(com.google.api.ads.dfp.v201308.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Performs actions on {@link User} objects that match the given * {@link Statement#query}. * * * @param userAction the action to perform * * @param filterStatement a Publisher Query Language statement used to * filter * a set of users * * @return the result of the action performed */ public com.google.api.ads.dfp.v201308.UpdateResult performUserAction(com.google.api.ads.dfp.v201308.UserAction userAction, com.google.api.ads.dfp.v201308.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Updates the specified {@link User}. * * * @param user the user to update * * @return the updated user */ public com.google.api.ads.dfp.v201308.User updateUser(com.google.api.ads.dfp.v201308.User user) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; /** * Updates the specified {@link User} objects. * * * @param users the users to update * * @return the updated users */ public com.google.api.ads.dfp.v201308.User[] updateUsers(com.google.api.ads.dfp.v201308.User[] users) throws java.rmi.RemoteException, com.google.api.ads.dfp.v201308.ApiException; }
apache-2.0
hanahmily/sky-walking
apm-sniffer/apm-sdk-plugin/motan-plugin/src/main/java/org/apache/skywalking/apm/plugin/motan/MotanConsumerInterceptor.java
4540
/* * 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.skywalking.apm.plugin.motan; import com.weibo.api.motan.rpc.Request; import com.weibo.api.motan.rpc.Response; import com.weibo.api.motan.rpc.URL; import java.lang.reflect.Method; import org.apache.skywalking.apm.agent.core.context.ContextCarrier; import org.apache.skywalking.apm.agent.core.context.tag.Tags; import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance; import org.apache.skywalking.apm.agent.core.context.CarrierItem; import org.apache.skywalking.apm.agent.core.context.ContextManager; import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceConstructorInterceptor; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor; import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult; import org.apache.skywalking.apm.network.trace.component.ComponentsDefine; /** * {@link MotanProviderInterceptor} create span by fetch request url from * {@link EnhancedInstance#getSkyWalkingDynamicField()} and transport serialized context * data to provider side through {@link Request#setAttachment(String, String)}. * * @author zhangxin */ public class MotanConsumerInterceptor implements InstanceConstructorInterceptor, InstanceMethodsAroundInterceptor { @Override public void onConstruct(EnhancedInstance objInst, Object[] allArguments) { objInst.setSkyWalkingDynamicField(allArguments[1]); } @Override public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable { URL url = (URL)objInst.getSkyWalkingDynamicField(); Request request = (Request)allArguments[0]; if (url != null) { ContextCarrier contextCarrier = new ContextCarrier(); String remotePeer = url.getHost() + ":" + url.getPort(); AbstractSpan span = ContextManager.createExitSpan(generateOperationName(url, request), contextCarrier, remotePeer); span.setComponent(ComponentsDefine.MOTAN); Tags.URL.set(span, url.getIdentity()); SpanLayer.asRPCFramework(span); CarrierItem next = contextCarrier.items(); while (next.hasNext()) { next = next.next(); request.setAttachment(next.getHeadKey(), next.getHeadValue()); } } } @Override public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Object ret) throws Throwable { Response response = (Response)ret; if (response != null && response.getException() != null) { AbstractSpan span = ContextManager.activeSpan(); span.errorOccurred(); span.log(response.getException()); } ContextManager.stopSpan(); return ret; } @Override public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes, Throwable t) { AbstractSpan span = ContextManager.activeSpan(); span.errorOccurred(); span.log(t); } /** * Generate operation name. * * @return operation name. */ private static String generateOperationName(URL serviceURI, Request request) { return new StringBuilder(serviceURI.getPath()).append(".").append(request.getMethodName()).append("(") .append(request.getParamtersDesc()).append(")").toString(); } }
apache-2.0
breskeby/sourcerer
model/src/main/groovy/org/eclipse/buildship/docs/model/SimpleClassMetaDataRepository.java
3132
/* * Copyright 2010 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.eclipse.buildship.docs.model; import groovy.lang.Closure; import org.eclipse.buildship.docs.source.model.Action; import java.io.*; import java.util.HashMap; import java.util.Map; public class SimpleClassMetaDataRepository<T extends Attachable<T>> implements ClassMetaDataRepository<T> { private final Map<String, T> classes = new HashMap<String, T>(); @SuppressWarnings("unchecked") public void load(File repoFile) { try { FileInputStream inputStream = new FileInputStream(repoFile); try { ObjectInputStream objInputStream = new ObjectInputStream(new BufferedInputStream(inputStream)); classes.clear(); classes.putAll((Map<String, T>) objInputStream.readObject()); } finally { inputStream.close(); } } catch (Exception e) { throw new RuntimeException(String.format("Could not load meta-data from %s.", repoFile), e); } } public void store(File repoFile) { try { FileOutputStream outputStream = new FileOutputStream(repoFile); try { ObjectOutputStream objOutputStream = new ObjectOutputStream(new BufferedOutputStream(outputStream)); objOutputStream.writeObject(classes); objOutputStream.close(); } finally { outputStream.close(); } } catch (IOException e) { throw new RuntimeException(String.format("Could not write meta-data to %s.", repoFile), e); } } public T get(String fullyQualifiedClassName) { T t = find(fullyQualifiedClassName); if (t == null) { throw new RuntimeException(String.format("No meta-data is available for class '%s'.", fullyQualifiedClassName)); } return t; } public T find(String fullyQualifiedClassName) { T t = classes.get(fullyQualifiedClassName); if (t != null) { t.attach(this); } return t; } public void put(String fullyQualifiedClassName, T metaData) { classes.put(fullyQualifiedClassName, metaData); } public void each(Closure cl) { for (Map.Entry<String, T> entry : classes.entrySet()) { cl.call(new Object[]{entry.getKey(), entry.getValue()}); } } public void each(Action<? super T> action) { for (T t : classes.values()) { action.execute(t); } } }
apache-2.0
apache/incubator-asterixdb
asterixdb/asterix-runtime/src/main/java/org/apache/asterix/runtime/aggregates/std/IntermediateStddevPopAggregateDescriptor.java
2654
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.runtime.aggregates.std; import org.apache.asterix.om.functions.BuiltinFunctions; import org.apache.asterix.om.functions.IFunctionDescriptor; import org.apache.asterix.om.functions.IFunctionDescriptorFactory; import org.apache.asterix.runtime.aggregates.base.AbstractAggregateFunctionDynamicDescriptor; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.runtime.base.IAggregateEvaluator; import org.apache.hyracks.algebricks.runtime.base.IAggregateEvaluatorFactory; import org.apache.hyracks.algebricks.runtime.base.IEvaluatorContext; import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; public class IntermediateStddevPopAggregateDescriptor extends AbstractAggregateFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new IntermediateStddevPopAggregateDescriptor(); } }; @Override public FunctionIdentifier getIdentifier() { return BuiltinFunctions.INTERMEDIATE_STDDEV_POP; } @Override public IAggregateEvaluatorFactory createAggregateEvaluatorFactory(final IScalarEvaluatorFactory[] args) { return new IAggregateEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public IAggregateEvaluator createAggregateEvaluator(final IEvaluatorContext ctx) throws HyracksDataException { return new IntermediateStddevAggregateFunction(args, ctx, true, sourceLoc); } }; } }
apache-2.0
syntelos/gwtcc
src/com/google/gwt/dev/util/arg/OptionGuiLogger.java
937
/* * Copyright 2008 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.google.gwt.dev.util.arg; /** * Option to set whether to use a GUI logger instead of stdout. */ public interface OptionGuiLogger { /** * Returns true if a GUI logger should be used. */ boolean isUseGuiLogger(); /** * Sets whether or not to use a GUI logger. */ void setUseGuiLogger(boolean useGuiLogger); }
apache-2.0
solimant/druid
benchmarks/src/main/java/io/druid/benchmark/TimeParseBenchmark.java
3489
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.benchmark; import com.google.common.base.Function; import io.druid.java.util.common.parsers.TimestampParser; import org.joda.time.DateTime; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; @State(Scope.Benchmark) public class TimeParseBenchmark { // 1 million rows int numRows = 1000000; // Number of batches of same times @Param({"10000", "100000", "500000", "1000000"}) int numBatches; static final String DATA_FORMAT = "MM/dd/yyyy HH:mm:ss Z"; static Function<String, DateTime> timeFn = TimestampParser.createTimestampParser(DATA_FORMAT); private String[] rows; @Setup public void setup() { SimpleDateFormat format = new SimpleDateFormat(DATA_FORMAT); long start = System.currentTimeMillis(); int rowsPerBatch = numRows / numBatches; int numRowInBatch = 0; rows = new String[numRows]; for (int i = 0; i < numRows; ++i) { if (numRowInBatch >= rowsPerBatch) { numRowInBatch = 0; start += 5000; // new batch, add 5 seconds } rows[i] = format.format(new Date(start)); numRowInBatch++; } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void parseNoContext(Blackhole blackhole) { for (String row : rows) { blackhole.consume(timeFn.apply(row).getMillis()); } } @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public void parseWithContext(Blackhole blackhole) { String lastTimeString = null; long lastTime = 0L; for (String row : rows) { if (!row.equals(lastTimeString)) { lastTimeString = row; lastTime = timeFn.apply(row).getMillis(); } blackhole.consume(lastTime); } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(TimeParseBenchmark.class.getSimpleName()) .warmupIterations(1) .measurementIterations(10) .forks(1) .build(); new Runner(opt).run(); } }
apache-2.0
gitee2008/glaf
src/main/java/com/glaf/core/util/DBUtils.java
86107
/* * 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.glaf.core.util; import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.glaf.core.domain.ColumnDefinition; import com.glaf.core.domain.TableDefinition; import com.glaf.core.el.ExpressionTools; import com.glaf.core.entity.SqlExecutor; import com.glaf.core.jdbc.DBConnectionFactory; public class DBUtils { protected final static Log logger = LogFactory.getLog(DBUtils.class); public final static String newline = System.getProperty("line.separator"); public static final String DB2 = "db2"; public static final String H2 = "h2"; public static final String HBASE = "hbase"; public static final String MYSQL = "mysql"; public static final String ORACLE = "oracle"; public static final String SQLITE = "sqlite"; public static final String SQLSERVER = "sqlserver"; public static final String POSTGRESQL = "postgresql"; public static final String VOLTDB = "voltdb"; public static void alterTable(Connection connection, TableDefinition tableDefinition) { List<String> cloumns = new java.util.ArrayList<String>(); Statement statement = null; Statement stmt = null; ResultSet rs = null; try { String dbType = DBConnectionFactory.getDatabaseType(connection); stmt = connection.createStatement(); rs = stmt.executeQuery("select * from " + tableDefinition.getTableName() + " where 1=0 "); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String column = rsmd.getColumnName(i); cloumns.add(column.toUpperCase()); } logger.debug(tableDefinition.getTableName() + " cloumns:" + cloumns); JdbcUtils.close(stmt); JdbcUtils.close(rs); Collection<ColumnDefinition> fields = tableDefinition.getColumns(); for (ColumnDefinition field : fields) { if (field.getColumnName() != null && !cloumns.contains(field.getColumnName().toUpperCase())) { String sql = getAddColumnSql(dbType, tableDefinition.getTableName(), field); if (sql != null && sql.length() > 0) { statement = connection.createStatement(); logger.info("alter table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql); JdbcUtils.close(statement); } } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(statement); } } public static void alterTable(String systemName, String tableName, List<ColumnDefinition> columns) { Connection conn = null; PreparedStatement pstmt = null; ResultSetMetaData rsmd = null; Statement stmt = null; ResultSet rs = null; List<String> columnNames = new java.util.ArrayList<String>(); try { conn = DBConnectionFactory.getConnection(systemName); conn.setAutoCommit(false); pstmt = conn.prepareStatement(" select * from " + tableName + " where 1=0 "); rs = pstmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { columnNames.add(rsmd.getColumnName(i).toLowerCase()); } if (columns != null && !columns.isEmpty()) { String dbType = DBConnectionFactory.getDatabaseType(conn); for (ColumnDefinition column : columns) { if (columnNames.contains(column.getColumnName().toLowerCase())) { continue; } String javaType = column.getJavaType(); String sql = " alter table " + tableName + " add " + column.getColumnName(); if (DB2.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " varchar(" + column.getLength() + ")"; } else { sql += " varchar(250) "; } } else if ("Integer".equals(javaType)) { sql += " integer "; } else if ("Long".equals(javaType)) { sql += " bigint "; } else if ("Double".equals(javaType)) { sql += " double precision "; } else if ("Date".equals(javaType)) { sql += " timestamp "; } else if ("Clob".equals(javaType)) { sql += " clob(10240000) "; } else if ("Blob".equals(javaType)) { sql += " blob "; } else if ("byte[]".equals(javaType)) { sql += " blob "; } else if ("Boolean".equals(javaType)) { sql += " smallint "; } } else if (ORACLE.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " NVARCHAR2(" + column.getLength() + ")"; } else { sql += " NVARCHAR2(250)"; } } else if ("Integer".equals(javaType)) { sql += " INTEGER "; } else if ("Long".equals(javaType)) { sql += " NUMBER(19,0) "; } else if ("Double".equals(javaType)) { sql += " NUMBER(*,10) "; } else if ("Date".equals(javaType)) { sql += " TIMESTAMP(6) "; } else if ("Clob".equals(javaType)) { sql += " CLOB "; } else if ("Blob".equals(javaType)) { sql += " BLOB "; } else if ("byte[]".equals(javaType)) { sql += " BLOB "; } else if ("Boolean".equals(javaType)) { sql += " NUMBER(1,0) "; } } else if (MYSQL.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " varchar(" + column.getLength() + ")"; } else { sql += " varchar(250)"; } } else if ("Integer".equals(javaType)) { sql += " int "; } else if ("Long".equals(javaType)) { sql += " bigint "; } else if ("Double".equals(javaType)) { sql += " double "; } else if ("Date".equals(javaType)) { sql += " datetime "; } else if ("Clob".equals(javaType)) { sql += " longtext "; } else if ("Blob".equals(javaType)) { sql += " longblob "; } else if ("byte[]".equals(javaType)) { sql += " longblob "; } else if ("Boolean".equals(javaType)) { sql += " tinyint "; } } else if (POSTGRESQL.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " varchar(" + column.getLength() + ")"; } else { sql += " varchar(250)"; } } else if ("Integer".equals(javaType)) { sql += " integer "; } else if ("Long".equals(javaType)) { sql += " bigint "; } else if ("Double".equals(javaType)) { sql += " double precision "; } else if ("Date".equals(javaType)) { sql += " timestamp "; } else if ("Clob".equals(javaType)) { sql += " text "; } else if ("Blob".equals(javaType)) { sql += " bytea "; } else if ("byte[]".equals(javaType)) { sql += " bytea "; } else if ("Boolean".equals(javaType)) { sql += " boolean "; } } else if (SQLSERVER.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " nvarchar(" + column.getLength() + ")"; } else { sql += " nvarchar(250)"; } } else if ("Integer".equals(javaType)) { sql += " int "; } else if ("Long".equals(javaType)) { sql += " numeric(19,0) "; } else if ("Double".equals(javaType)) { sql += " double precision "; } else if ("Date".equals(javaType)) { sql += " datetime "; } else if ("Clob".equals(javaType)) { sql += " nvarchar(max) "; } else if ("Blob".equals(javaType)) { sql += " varbinary(max) "; } else if ("byte[]".equals(javaType)) { sql += " varbinary(max) "; } else if ("Boolean".equals(javaType)) { sql += " tinyint "; } } else if (H2.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " varchar(" + column.getLength() + ")"; } else { sql += " varchar(250)"; } } else if ("Integer".equals(javaType)) { sql += " int "; } else if ("Long".equals(javaType)) { sql += " bigint "; } else if ("Double".equals(javaType)) { sql += " double "; } else if ("Date".equals(javaType)) { sql += " timestamp "; } else if ("Clob".equals(javaType)) { sql += " clob "; } else if ("Blob".equals(javaType)) { sql += " longvarbinary "; } else if ("byte[]".equals(javaType)) { sql += " longvarbinary "; } else if ("Boolean".equals(javaType)) { sql += " boolean "; } } else if (SQLITE.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " TEXT(" + column.getLength() + ")"; } else { sql += " TEXT(250)"; } } else if ("Integer".equals(javaType)) { sql += " INTEGER "; } else if ("Long".equals(javaType)) { sql += " INTEGER "; } else if ("Double".equals(javaType)) { sql += " REAL "; } else if ("Date".equals(javaType)) { sql += " TEXT "; } else if ("Clob".equals(javaType)) { sql += " TEXT "; } else if ("Blob".equals(javaType)) { sql += " BLOB "; } else if ("byte[]".equals(javaType)) { sql += " BLOB "; } } else if (HBASE.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " VARCHAR(" + column.getLength() + ")"; } else { sql += " VARCHAR(250)"; } } else if ("Integer".equals(javaType)) { sql += " INTEGER "; } else if ("Long".equals(javaType)) { sql += " BIGINT "; } else if ("Double".equals(javaType)) { sql += " DOUBLE "; } else if ("Date".equals(javaType)) { sql += " TIMESTAMP "; } else if ("Clob".equals(javaType)) { sql += " VARCHAR "; } else if ("Blob".equals(javaType)) { sql += " VARBINARY "; } else if ("byte[]".equals(javaType)) { sql += " VARBINARY "; } else if ("Boolean".equals(javaType)) { sql += " BOOLEAN "; } } else if (VOLTDB.equalsIgnoreCase(dbType)) { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " VARCHAR(" + column.getLength() + ")"; } else { sql += " VARCHAR(250)"; } } else if ("Integer".equals(javaType)) { sql += " INTEGER "; } else if ("Long".equals(javaType)) { sql += " BIGINT "; } else if ("Double".equals(javaType)) { sql += " FLOAT "; } else if ("Date".equals(javaType)) { sql += " TIMESTAMP "; } else if ("Clob".equals(javaType)) { sql += " VARCHAR(4000) "; } else if ("Blob".equals(javaType)) { sql += " VARBINARY(102400000) "; } else if ("byte[]".equals(javaType)) { sql += " VARBINARY(255) "; } } else { if ("String".equals(javaType)) { if (column.getLength() > 0) { sql += " varchar(" + column.getLength() + ")"; } else { sql += " varchar(50)"; } } else if ("Integer".equals(javaType)) { sql += " int "; } else if ("Long".equals(javaType)) { sql += " bigint "; } else if ("Double".equals(javaType)) { sql += " double "; } else if ("Date".equals(javaType)) { sql += " timestamp "; } else if ("Clob".equals(javaType)) { sql += " clob "; } else if ("Blob".equals(javaType)) { sql += " blob "; } else if ("byte[]".equals(javaType)) { sql += " blob "; } else if ("Boolean".equals(javaType)) { sql += " boolean "; } } logger.info("execute alter:" + sql); stmt = conn.createStatement(); stmt.executeUpdate(sql); JdbcUtils.close(stmt); } } JdbcUtils.close(pstmt); conn.commit(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } public static void alterTable(String systemName, TableDefinition tableDefinition) { List<String> cloumns = new java.util.ArrayList<String>(); Connection connection = null; Statement statement = null; Statement stmt = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(systemName); connection.setAutoCommit(false); String dbType = DBConnectionFactory.getDatabaseType(connection); stmt = connection.createStatement(); rs = stmt.executeQuery("select * from " + tableDefinition.getTableName() + " where 1=0 "); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String column = rsmd.getColumnName(i); cloumns.add(column.toUpperCase()); } logger.debug(tableDefinition.getTableName() + " cloumns:" + cloumns); JdbcUtils.close(stmt); JdbcUtils.close(rs); Collection<ColumnDefinition> fields = tableDefinition.getColumns(); for (ColumnDefinition field : fields) { if (field.getColumnName() != null && !cloumns.contains(field.getColumnName().toUpperCase())) { String sql = getAddColumnSql(dbType, tableDefinition.getTableName(), field); if (sql != null && sql.length() > 0) { statement = connection.createStatement(); logger.info("alter table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql); JdbcUtils.close(statement); } } } connection.commit(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(stmt); JdbcUtils.close(rs); JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static void alterTable(TableDefinition tableDefinition) { List<String> cloumns = new java.util.ArrayList<String>(); Connection connection = null; Statement statement = null; Statement stmt = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(); connection.setAutoCommit(false); String dbType = DBConnectionFactory.getDatabaseType(connection); stmt = connection.createStatement(); rs = stmt.executeQuery("select * from " + tableDefinition.getTableName() + " where 1=0 "); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String column = rsmd.getColumnName(i); cloumns.add(column.toUpperCase()); } logger.debug(tableDefinition.getTableName() + " cloumns:" + cloumns); Collection<ColumnDefinition> fields = tableDefinition.getColumns(); for (ColumnDefinition field : fields) { if (field.getColumnName() != null && !cloumns.contains(field.getColumnName().toUpperCase())) { String sql = getAddColumnSql(dbType, tableDefinition.getTableName(), field); if (sql != null && sql.length() > 0) { statement = connection.createStatement(); logger.info("alter table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql); JdbcUtils.close(statement); } } } connection.commit(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(stmt); JdbcUtils.close(rs); JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static void createIndex(Connection connection, String tableName, String columnName, String indexName) { DatabaseMetaData dbmd = null; Statement stmt = null; ResultSet rs = null; boolean hasIndex = false; boolean autoCommit = false; try { autoCommit = connection.getAutoCommit(); dbmd = connection.getMetaData(); rs = dbmd.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String col = rs.getString("COLUMN_NAME"); if (StringUtils.equalsIgnoreCase(columnName, col)) { hasIndex = true; break; } } JdbcUtils.close(rs); if (!hasIndex) { String sql = " create index " + indexName.toUpperCase() + " on " + tableName + " (" + columnName + ") "; connection.setAutoCommit(false); stmt = connection.createStatement(); stmt.executeUpdate(sql); JdbcUtils.close(stmt); connection.commit(); connection.setAutoCommit(autoCommit); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); } } public static void createIndex(String systemName, String tableName, String columnName, String indexName) { Connection connection = null; DatabaseMetaData dbmd = null; Statement stmt = null; ResultSet rs = null; boolean hasIndex = false; try { connection = DBConnectionFactory.getConnection(systemName); dbmd = connection.getMetaData(); rs = dbmd.getIndexInfo(null, null, tableName, false, false); while (rs.next()) { String col = rs.getString("COLUMN_NAME"); if (StringUtils.equalsIgnoreCase(columnName, col)) { hasIndex = true; break; } } JdbcUtils.close(rs); if (!hasIndex) { String sql = " create index " + indexName.toUpperCase() + " on " + tableName + " (" + columnName + ") "; connection.setAutoCommit(false); stmt = connection.createStatement(); stmt.executeUpdate(sql); JdbcUtils.close(stmt); connection.commit(); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(connection); } } /** * 创建数据库表,如果已经存在,则不重建 * * @param connection * JDBC连接 * @param tableDefinition * 表定义 */ public static String createTable(Connection connection, TableDefinition tableDefinition) { Statement statement = null; try { String tableName = tableDefinition.getTableName(); if (tableExists(connection, tableName)) { return null; } String dbType = DBConnectionFactory.getDatabaseType(connection); logger.info("dbType:" + dbType); String sql = getCreateTableScript(dbType, tableDefinition); if (sql != null && sql.length() > 0) { connection.setAutoCommit(false); statement = connection.createStatement(); logger.info("create table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql.replaceAll("\n", "")); JdbcUtils.close(statement); connection.commit(); return sql; } return null; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); } } public static String createTable(String systemName, TableDefinition tableDefinition) { Connection connection = null; Statement statement = null; try { connection = DBConnectionFactory.getConnection(systemName); connection.setAutoCommit(false); String dbType = DBConnectionFactory.getDatabaseType(connection); String sql = getCreateTableScript(dbType, tableDefinition); if (sql != null && sql.length() > 0) { statement = connection.createStatement(); logger.info("create table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql.replaceAll("\n", "")); JdbcUtils.close(statement); connection.commit(); return sql; } return null; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static String createTable(TableDefinition tableDefinition) { Connection connection = null; Statement statement = null; try { connection = DBConnectionFactory.getConnection(); connection.setAutoCommit(false); String dbType = DBConnectionFactory.getDatabaseType(connection); String sql = getCreateTableScript(dbType, tableDefinition); if (sql != null && sql.length() > 0) { statement = connection.createStatement(); logger.info("create table " + tableDefinition.getTableName() + ":\n" + sql); statement.execute(sql.replaceAll("\n", "")); JdbcUtils.close(statement); connection.commit(); return sql; } return null; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } /** * 创建数据库表,如果已经存在,则删除重建 * * @param connection * JDBC连接 * @param tableDefinition * 表定义 */ public static void dropAndCreateTable(Connection connection, TableDefinition tableDefinition) { String tableName = tableDefinition.getTableName(); if (tableExists(connection, tableName)) { dropTable(connection, tableName); } if (!tableExists(connection, tableName)) { createTable(connection, tableDefinition); } } /** * 如果已经存在,则删除 * * @param connection * JDBC连接 * @param tableDefinition * 表定义 */ public static void dropTable(Connection connection, String tableName) { Statement statement = null; try { String dbType = DBConnectionFactory.getDatabaseType(connection); /** * 只能在开发模式下才能删除表,正式环境只能删除临时表。 */ if (System.getProperty("devMode") != null || StringUtils.equalsIgnoreCase(dbType, SQLITE) || StringUtils.equalsIgnoreCase(dbType, H2) || StringUtils.startsWithIgnoreCase(tableName, "temp") || StringUtils.startsWithIgnoreCase(tableName, "tmp")) { if (tableExists(connection, tableName)) { statement = connection.createStatement(); statement.executeUpdate(" drop table " + tableName); JdbcUtils.close(statement); logger.info("drop table:" + tableName); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); } } /** * 如果已经存在,则删除 * * @param connection * JDBC连接 * @param tableDefinition * 表定义 */ public static void dropTable(String systemName, String tableName) { Connection connection = null; Statement statement = null; try { connection = DBConnectionFactory.getConnection(systemName); String dbType = DBConnectionFactory.getDatabaseType(connection); /** * 只能在开发模式下才能删除表,正式环境只能删除临时表。 */ if (System.getProperty("devMode") != null || StringUtils.equalsIgnoreCase(dbType, SQLITE) || StringUtils.equalsIgnoreCase(dbType, H2) || StringUtils.startsWithIgnoreCase(tableName, "temp") || StringUtils.startsWithIgnoreCase(tableName, "tmp")) { if (tableExists(connection, tableName)) { connection.setAutoCommit(false); statement = connection.createStatement(); statement.executeUpdate(" drop table " + tableName); JdbcUtils.close(statement); connection.commit(); logger.info("drop table:" + tableName); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } /** * 删除临时表数据 * * @param connection * @param tableName */ public static void emptyTable(Connection connection, String tableName) { if (StringUtils.startsWithIgnoreCase(tableName, "temp") || StringUtils.startsWithIgnoreCase(tableName, "tmp")) { Statement statement = null; try { if (tableExists(connection, tableName)) { statement = connection.createStatement(); statement.executeUpdate(" delete from " + tableName); JdbcUtils.close(statement); logger.info("empty table:" + tableName); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); } } } /** * 删除临时表数据 * * @param tableName */ public static void emptyTable(String tableName) { if (StringUtils.startsWithIgnoreCase(tableName, "temp") || StringUtils.startsWithIgnoreCase(tableName, "tmp")) { Connection connection = null; Statement statement = null; try { connection = DBConnectionFactory.getConnection(); if (tableExists(connection, tableName)) { connection.setAutoCommit(false); statement = connection.createStatement(); statement.executeUpdate(" delete from " + tableName); connection.commit(); JdbcUtils.close(statement); logger.info("empty table:" + tableName); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(connection); JdbcUtils.close(statement); } } } /** * 删除临时表数据 * * @param systemName * @param tableName */ public static void emptyTable(String systemName, String tableName) { if (StringUtils.startsWithIgnoreCase(tableName, "temp") || StringUtils.startsWithIgnoreCase(tableName, "tmp")) { Connection connection = null; Statement statement = null; try { connection = DBConnectionFactory.getConnection(systemName); if (tableExists(connection, tableName)) { connection.setAutoCommit(false); statement = connection.createStatement(); statement.executeUpdate(" delete from " + tableName); JdbcUtils.close(statement); connection.commit(); logger.info("empty table:" + tableName); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } } public static void executeBatchSchemaResourceIgnoreException(Connection conn, String ddlStatements) { Statement statement = null; String sqlStatement = null; try { statement = conn.createStatement(); StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { // logger.debug(sqlStatement); try { // statement.executeUpdate(sqlStatement); statement.addBatch(sqlStatement); } catch (Exception ex) { // logger.error(" execute statement error: " + sqlStatement, ex); } finally { // JdbcUtils.close(statement); } } } statement.executeBatch(); } catch (Exception ex) { throw new RuntimeException("execute statement error: " + sqlStatement, ex); } finally { JdbcUtils.close(statement); } } public static void executeSchemaResource(Connection conn, String ddlStatements) { Exception exception = null; Statement statement = null; String sqlStatement = null; try { StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { logger.debug(sqlStatement); try { statement = conn.createStatement(); statement.executeUpdate(sqlStatement); JdbcUtils.close(statement); } catch (Exception ex) { if (exception == null) { exception = ex; } logger.debug(" execute statement error: " + sqlStatement, ex); } finally { JdbcUtils.close(statement); } } } if (exception != null) { exception.printStackTrace(); throw exception; } logger.info("execute statement successful"); } catch (Exception ex) { throw new RuntimeException("execute statement error: " + sqlStatement, ex); } finally { JdbcUtils.close(statement); } } public static String executeSchemaResource(String systemName, String ddlStatements) { StringBuilder buffer = new StringBuilder(); Connection connection = null; Statement statement = null; String sqlStatement = null; try { connection = DBConnectionFactory.getConnection(systemName); connection.setAutoCommit(false); StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { // logger.debug(sqlStatement); try { statement = connection.createStatement(); statement.executeUpdate(sqlStatement); JdbcUtils.close(statement); } catch (Exception ex) { buffer.append(FileUtils.newline); buffer.append(sqlStatement).append(";"); buffer.append(FileUtils.newline); } finally { JdbcUtils.close(statement); } } } if (buffer.length() == 0) { // 如果没有异常就提交事务 connection.commit(); } return buffer.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static void executeSchemaResource(String operation, String resourceName, InputStream inputStream, Map<String, Object> context) { Exception exception = null; Connection connection = null; Statement statement = null; String sqlStatement = null; try { connection = DBConnectionFactory.getConnection(); connection.setAutoCommit(false); byte[] bytes = FileUtils.getBytes(inputStream); String ddlStatements = new String(bytes); StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { sqlStatement = ExpressionTools.evaluate(sqlStatement, context); try { statement = connection.createStatement(); statement.execute(sqlStatement); } catch (Exception e) { if (exception == null) { exception = e; } logger.debug("problem during schema " + operation + ", statement '" + sqlStatement, e); } finally { JdbcUtils.close(statement); } } } if (exception != null) { throw exception; } connection.commit(); logger.info("extension db schema " + operation + " successful"); } catch (Exception e) { throw new RuntimeException("couldn't " + operation + " db schema: " + sqlStatement, e); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static void executeSchemaResourceIgnoreException(Connection conn, String ddlStatements) { Statement statement = null; String sqlStatement = null; try { StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { logger.debug(sqlStatement); statement = conn.createStatement(); try { statement.executeUpdate(sqlStatement); } catch (Exception ex) { logger.error(" execute statement error: " + sqlStatement, ex); } finally { JdbcUtils.close(statement); } } } } catch (Exception ex) { throw new RuntimeException("couldn't execute db schema: " + sqlStatement, ex); } finally { JdbcUtils.close(statement); } } public static String executeSchemaResourceIgnoreException(String systemName, String ddlStatements) { StringBuilder buffer = new StringBuilder(); Connection connection = null; Statement statement = null; String sqlStatement = null; try { connection = DBConnectionFactory.getConnection(systemName); connection.setAutoCommit(false); StringTokenizer tokenizer = new StringTokenizer(ddlStatements, ";"); while (tokenizer.hasMoreTokens()) { sqlStatement = tokenizer.nextToken().trim(); if (StringUtils.isNotEmpty(sqlStatement) && !sqlStatement.startsWith("#")) { // logger.debug(sqlStatement); try { statement = connection.createStatement(); statement.executeUpdate(sqlStatement); connection.commit(); } catch (Exception ex) { buffer.append(FileUtils.newline); buffer.append(sqlStatement).append(";"); buffer.append(FileUtils.newline); } finally { JdbcUtils.close(statement); } } } return buffer.toString(); } catch (Exception ex) { throw new RuntimeException("can't get connection: ", ex); } finally { JdbcUtils.close(statement); JdbcUtils.close(connection); } } public static String getAddColumnSql(String dbType, String tableName, ColumnDefinition field) { StringBuilder buffer = new StringBuilder(); buffer.append(" alter table ").append(tableName); buffer.append(" add ").append(field.getColumnName()); if (H2.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" clob "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" longvarbinary "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" longvarbinary "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" boolean "); } else if ("String".equals(field.getJavaType())) { buffer.append(" varchar "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (DB2.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" clob (10240000) "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" blob "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" blob "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" smallint "); } else if ("String".equals(field.getJavaType())) { buffer.append(" varchar "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (ORACLE.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" NUMBER(19,0) "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" NUMBER(*,10) "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" TIMESTAMP(6) "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" CLOB "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" BLOB "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" BLOB "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" NUMBER(1,0) "); } else if ("String".equals(field.getJavaType())) { buffer.append(" NVARCHAR2 "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (MYSQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" datetime "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" longtext "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" longblob "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" longblob "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" tinyint "); } else if ("String".equals(field.getJavaType())) { buffer.append(" varchar"); if (field.getLength() > 0) { buffer.append("(").append(field.getLength()).append(") "); } else { buffer.append("(250) "); } } } else if (SQLSERVER.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" datetime "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" nvarchar(max) "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" varbinary(max) "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" varbinary(max) "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" tinyint "); } else if ("String".equals(field.getJavaType())) { buffer.append(" nvarchar "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (POSTGRESQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" text "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" bytea "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" bytea "); } else if ("Boolean".equals(field.getJavaType())) { buffer.append(" boolean "); } else if ("String".equals(field.getJavaType())) { buffer.append(" varchar "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (SQLITE.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" INTEGER "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" REAL "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" TEXT "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" TEXT "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" BLOB "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" BLOB "); } else if ("String".equals(field.getJavaType())) { buffer.append(" TEXT "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (HBASE.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" BIGINT "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" DOUBLE "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" TIMESTAMP "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" VARCHAR "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" VARBINARY "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" VARBINARY "); } else if ("String".equals(field.getJavaType())) { buffer.append(" VARCHAR "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (VOLTDB.equalsIgnoreCase(dbType)) { if ("Integer".equals(field.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(field.getJavaType())) { buffer.append(" BIGINT "); } else if ("Double".equals(field.getJavaType())) { buffer.append(" FLOAT "); } else if ("Date".equals(field.getJavaType())) { buffer.append(" TIMESTAMP "); } else if ("Clob".equals(field.getJavaType())) { buffer.append(" VARCHAR "); } else if ("Blob".equals(field.getJavaType())) { buffer.append(" VARBINARY "); } else if ("byte[]".equals(field.getJavaType())) { buffer.append(" VARBINARY "); } else if ("String".equals(field.getJavaType())) { buffer.append(" VARCHAR "); if (field.getLength() > 0) { buffer.append(" (").append(field.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else { throw new RuntimeException(dbType + " is not support database type."); } buffer.append(";"); return buffer.toString(); } public static String getAlterTable(TableDefinition classDefinition) { StringBuilder buffer = new StringBuilder(); List<String> cloumns = new java.util.ArrayList<String>(); Connection connection = null; Statement stmt = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(); String dbType = DBConnectionFactory.getDatabaseType(connection); stmt = connection.createStatement(); rs = stmt.executeQuery("select * from " + classDefinition.getTableName() + " where 1=0 "); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int i = 1; i <= columnCount; i++) { String column = rsmd.getColumnName(i); cloumns.add(column.toUpperCase()); } Collection<ColumnDefinition> fields = classDefinition.getColumns(); for (ColumnDefinition field : fields) { if (field.getColumnName() != null && !cloumns.contains(field.getColumnName().toUpperCase())) { String str = getAddColumnSql(dbType, classDefinition.getTableName(), field); buffer.append(str); buffer.append("\r\r"); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(connection); } return buffer.toString(); } public static List<ColumnDefinition> getColumnDefinitions(Connection conn, String tableName) { List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); ResultSet rs = null; try { List<String> primaryKeys = getPrimaryKeys(conn, tableName); String dbType = DBConnectionFactory.getDatabaseType(conn); DatabaseMetaData metaData = conn.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getColumns(null, null, tableName, null); while (rs.next()) { String columnName = rs.getString("COLUMN_NAME"); String typeName = rs.getString("TYPE_NAME"); int dataType = rs.getInt("DATA_TYPE"); int nullable = rs.getInt("NULLABLE"); int length = rs.getInt("COLUMN_SIZE"); int ordinal = rs.getInt("ORDINAL_POSITION"); ColumnDefinition column = new ColumnDefinition(); column.setColumnName(columnName.toLowerCase()); column.setTitle(column.getName()); column.setEnglishTitle(column.getName()); column.setJavaType(FieldType.getJavaType(dataType)); column.setName(StringTools.camelStyle(column.getColumnName().toLowerCase())); if (nullable == 1) { column.setNullable(true); } else { column.setNullable(false); } column.setLength(length); column.setOrdinal(ordinal); if ("String".equals(column.getJavaType())) { if (column.getLength() > 8000) { column.setJavaType("Clob"); } } if ("Double".equals(column.getJavaType())) { if (column.getLength() == 19) { column.setJavaType("Long"); } } if (StringUtils.equalsIgnoreCase(typeName, "bool") || StringUtils.equalsIgnoreCase(typeName, "boolean") || StringUtils.equalsIgnoreCase(typeName, "bit") || StringUtils.equalsIgnoreCase(typeName, "tinyint") || StringUtils.equalsIgnoreCase(typeName, "smallint")) { column.setJavaType("Boolean"); } if (primaryKeys.contains(columnName.toLowerCase())) { column.setPrimaryKey(true); } if (!columns.contains(column)) { logger.debug("column name:" + column.getColumnName()); columns.add(column); } } return columns; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); } } public static List<ColumnDefinition> getColumnDefinitions(String tableName) { List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); Connection conn = null; ResultSet rs = null; try { List<String> primaryKeys = getPrimaryKeys(tableName); conn = DBConnectionFactory.getConnection(); String dbType = DBConnectionFactory.getDatabaseType(conn); DatabaseMetaData metaData = conn.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getColumns(null, null, tableName, null); while (rs.next()) { String name = rs.getString("COLUMN_NAME"); String typeName = rs.getString("TYPE_NAME"); int dataType = rs.getInt("DATA_TYPE"); int nullable = rs.getInt("NULLABLE"); int length = rs.getInt("COLUMN_SIZE"); int ordinal = rs.getInt("ORDINAL_POSITION"); ColumnDefinition column = new ColumnDefinition(); column.setColumnName(name); column.setJavaType(FieldType.getJavaType(dataType)); if (nullable == 1) { column.setNullable(true); } else { column.setNullable(false); } column.setLength(length); column.setOrdinal(ordinal); column.setName(StringTools.camelStyle(column.getColumnName().toLowerCase())); logger.debug(name + " typeName:" + typeName + "[" + dataType + "] " + FieldType.getJavaType(dataType)); if ("String".equals(column.getJavaType())) { if (column.getLength() > 8000) { column.setJavaType("Clob"); } } if ("Double".equals(column.getJavaType())) { if (column.getLength() == 19) { column.setJavaType("Long"); } } if (StringUtils.equalsIgnoreCase(typeName, "bool") || StringUtils.equalsIgnoreCase(typeName, "boolean") || StringUtils.equalsIgnoreCase(typeName, "bit") || StringUtils.equalsIgnoreCase(typeName, "tinyint") || StringUtils.equalsIgnoreCase(typeName, "smallint")) { column.setJavaType("Boolean"); } if (primaryKeys.contains(name) || primaryKeys.contains(name.toUpperCase()) || primaryKeys.contains(name.toLowerCase())) { column.setPrimaryKey(true); } if (!columns.contains(column)) { columns.add(column); } } return columns; } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(conn); } } public static List<ColumnDefinition> getColumnDefinitions(String systemName, String tableName) { Connection conn = null; try { conn = DBConnectionFactory.getConnection(systemName); return getColumnDefinitions(conn, tableName); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } } private static String getColumnScript(String dbType, ColumnDefinition column) { StringBuilder buffer = new StringBuilder(500); buffer.append(newline); buffer.append(" ").append(column.getColumnName().toUpperCase()); if (DB2.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" clob (10240000) "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" blob "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" blob "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" smallint "); } else if ("String".equals(column.getJavaType())) { buffer.append(" varchar "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (ORACLE.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" NUMBER(19,0) "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" NUMBER(*,10) "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" TIMESTAMP(6) "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" CLOB "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" BLOB "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" BLOB "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" NUMBER(1,0) "); } else if ("String".equals(column.getJavaType())) { buffer.append(" VARCHAR2 "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (MYSQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" datetime "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" longtext "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" longblob "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" longblob "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" tinyint "); } else if ("String".equals(column.getJavaType())) { buffer.append(" varchar "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (SQLSERVER.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" datetime "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" nvarchar(max) "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" varbinary(max) "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" varbinary(max) "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" tinyint "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" tinyint "); } else if ("String".equals(column.getJavaType())) { buffer.append(" nvarchar "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (POSTGRESQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" text "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" bytea "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" bytea "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" boolean "); } else if ("String".equals(column.getJavaType())) { buffer.append(" varchar "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (250) "); } } } else if (H2.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" timestamp "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" clob "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" longvarbinary "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" longvarbinary "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" boolean "); } else if ("String".equals(column.getJavaType())) { buffer.append(" varchar "); if (column.getLength() > 0 && column.getLength() <= 4000) { buffer.append(" (").append(column.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (SQLITE.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" REAL "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" TEXT "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" TEXT "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" BLOB "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" BLOB "); } else if ("String".equals(column.getJavaType())) { buffer.append(" TEXT "); } } else if (HBASE.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Boolean".equals(column.getJavaType())) { buffer.append(" BOOLEAN "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" BIGINT "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" DOUBLE "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" TIMESTAMP "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" VARCHAR "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" VARBINARY "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" VARBINARY "); } else if ("String".equals(column.getJavaType())) { buffer.append(" VARCHAR "); } } else if (VOLTDB.equalsIgnoreCase(dbType)) { if ("Integer".equals(column.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(column.getJavaType())) { buffer.append(" BIGINT "); } else if ("Double".equals(column.getJavaType())) { buffer.append(" FLOAT "); } else if ("Date".equals(column.getJavaType())) { buffer.append(" TIMESTAMP "); } else if ("Clob".equals(column.getJavaType())) { buffer.append(" VARCHAR "); } else if ("Blob".equals(column.getJavaType())) { buffer.append(" VARBINARY "); } else if ("byte[]".equals(column.getJavaType())) { buffer.append(" VARBINARY "); } else if ("String".equals(column.getJavaType())) { buffer.append(" VARCHAR "); } } buffer.append(","); return buffer.toString(); } public static String getCreateTableDDL() { StringBuilder buffer = new StringBuilder(); List<String> tables = getTables(); String dbType = DBConnectionFactory.getDatabaseType(); if (tables != null && !tables.isEmpty()) { for (String tableName : tables) { List<ColumnDefinition> columns = getColumnDefinitions(tableName); TableDefinition tableDefinition = new TableDefinition(); tableDefinition.setTableName(tableName); List<String> pks = getPrimaryKeys(tableName); if (pks != null && columns != null && !columns.isEmpty()) { for (ColumnDefinition c : columns) { if (pks.contains(c.getColumnName())) { c.setPrimaryKey(true); tableDefinition.setIdColumn(c); } } } tableDefinition.setColumns(columns); String str = getCreateTableScript(dbType, tableDefinition); buffer.append(str); buffer.append(FileUtils.newline); buffer.append(FileUtils.newline); } } return buffer.toString(); } public static String getCreateTableDDL(String targetDbType) { StringBuilder buffer = new StringBuilder(); List<String> tables = getTables(); if (tables != null && !tables.isEmpty()) { for (String tableName : tables) { List<ColumnDefinition> columns = getColumnDefinitions(tableName); TableDefinition tableDefinition = new TableDefinition(); tableDefinition.setTableName(tableName); List<String> pks = getPrimaryKeys(tableName); if (pks != null && columns != null && !columns.isEmpty()) { for (ColumnDefinition c : columns) { if (pks.contains(c.getColumnName())) { c.setPrimaryKey(true); tableDefinition.setIdColumn(c); } } } tableDefinition.setColumns(columns); String str = getCreateTableScript(targetDbType, tableDefinition); buffer.append(str); buffer.append(FileUtils.newline); buffer.append(FileUtils.newline); } } return buffer.toString(); } public static String getCreateTableScript(String dbType, TableDefinition tableDefinition) { StringBuilder buffer = new StringBuilder(4000); Collection<ColumnDefinition> columns = tableDefinition.getColumns(); buffer.append(" create table ").append(tableDefinition.getTableName().toUpperCase()); buffer.append(" ( "); Collection<String> cols = new HashSet<String>(); List<ColumnDefinition> idColumns = tableDefinition.getIdColumns(); ColumnDefinition idColumn = tableDefinition.getIdColumn(); if (idColumns != null && !idColumns.isEmpty()) { for (ColumnDefinition col : idColumns) { buffer.append(getPrimaryKeyScript(dbType, col)); cols.add(col.getColumnName().trim().toLowerCase()); } } else if (idColumn != null) { buffer.append(getPrimaryKeyScript(dbType, idColumn)); cols.add(idColumn.getColumnName().trim().toLowerCase()); } for (ColumnDefinition column : columns) { if (cols.contains(column.getColumnName().trim().toLowerCase())) { continue; } buffer.append(getColumnScript(dbType, column)); cols.add(column.getColumnName().trim().toLowerCase()); } if (HBASE.equalsIgnoreCase(dbType)) { if (idColumn != null) { buffer.append(newline); buffer.append(" CONSTRAINT PK_").append(idColumn.getColumnName().toUpperCase()) .append(" PRIMARY KEY (").append(idColumn.getColumnName().toUpperCase()).append(") "); } } else { if (tableDefinition.getIdColumns() != null && !tableDefinition.getIdColumns().isEmpty()) { buffer.append(newline); buffer.append(" primary key ("); for (ColumnDefinition col : tableDefinition.getIdColumns()) { buffer.append(col.getColumnName().toUpperCase()).append(", "); } buffer.delete(buffer.length() - 2, buffer.length()); buffer.append(") "); } else if (tableDefinition.getIdColumn() != null) { buffer.append(newline); buffer.append(" primary key (").append(idColumn.getColumnName().toUpperCase()).append(") "); } } if (buffer.toString().endsWith(",")) { buffer.delete(buffer.length() - 1, buffer.length()); } buffer.append(newline); if (MYSQL.equalsIgnoreCase(dbType)) { buffer.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin;"); } else if (ORACLE.equalsIgnoreCase(dbType)) { buffer.append(")"); } else { buffer.append(");"); } return buffer.toString(); } public static List<String> getPrimaryKeys(Connection connection, String tableName) { ResultSet rs = null; List<String> primaryKeys = new java.util.ArrayList<String>(); try { String dbType = DBConnectionFactory.getDatabaseType(connection); DatabaseMetaData metaData = connection.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getPrimaryKeys(null, null, tableName); while (rs.next()) { primaryKeys.add(rs.getString("column_name").toLowerCase()); } // logger.debug(tableName + " primaryKeys:" + primaryKeys); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); } return primaryKeys; } public static List<String> getPrimaryKeys(String tableName) { List<String> primaryKeys = new java.util.ArrayList<String>(); Connection connection = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(); String dbType = DBConnectionFactory.getDatabaseType(connection); DatabaseMetaData metaData = connection.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getPrimaryKeys(null, null, tableName); while (rs.next()) { primaryKeys.add(rs.getString("column_name")); } // logger.debug(tableName + " primaryKeys:" + primaryKeys); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(connection); } return primaryKeys; } public static List<String> getPrimaryKeys(String systemName, String tableName) { List<String> primaryKeys = new java.util.ArrayList<String>(); Connection connection = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(systemName); String dbType = DBConnectionFactory.getDatabaseType(connection); DatabaseMetaData metaData = connection.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getPrimaryKeys(null, null, tableName); while (rs.next()) { primaryKeys.add(rs.getString("column_name")); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(connection); } return primaryKeys; } private static String getPrimaryKeyScript(String dbType, ColumnDefinition idField) { StringBuilder buffer = new StringBuilder(500); buffer.append(newline); buffer.append(" ").append(idField.getColumnName().toUpperCase()); if (DB2.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" timestamp "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" varchar "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (ORACLE.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" NUMBER(19,0) "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" NUMBER(*,10) "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" TIMESTAMP(6) "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" VARCHAR2 "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (MYSQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" datetime "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" varchar "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (SQLSERVER.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" datetime "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" nvarchar "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (POSTGRESQL.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" double precision "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" timestamp "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" varchar "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (H2.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" integer "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" bigint "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" double "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" timestamp "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" varchar "); if (idField.getLength() > 0) { buffer.append(" (").append(idField.getLength()).append(") "); } else { buffer.append(" (50) "); } } } else if (SQLITE.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" INTEGER "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" REAL "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" TEXT "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" TEXT "); } } else if (HBASE.equalsIgnoreCase(dbType)) { if ("Integer".equals(idField.getJavaType())) { buffer.append(" INTEGER "); } else if ("Long".equals(idField.getJavaType())) { buffer.append(" BIGINT "); } else if ("Double".equals(idField.getJavaType())) { buffer.append(" DOUBLE "); } else if ("Date".equals(idField.getJavaType())) { buffer.append(" TIMESTAMP "); } else if ("String".equals(idField.getJavaType())) { buffer.append(" VARCHAR "); } } buffer.append(" not null, "); return buffer.toString(); } /** * 获取保密表 * * @return */ public static List<String> getSecretTables() { List<String> tables = new ArrayList<String>(); tables.add("userinfo"); tables.add("sys_user"); tables.add("SYS_KEY"); tables.add("SYS_SERVER"); tables.add("SYS_PROPERTY"); return tables; } public static int getTableCount(Connection connection, String tableName) { Statement stmt = null; ResultSet rs = null; try { stmt = connection.createStatement(); rs = stmt.executeQuery(" select count(*) from " + tableName); if (rs.next()) { return rs.getInt(1); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); } return -1; } public static int getTableCount(String tableName) { Connection connection = null; Statement stmt = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(); stmt = connection.createStatement(); rs = stmt.executeQuery(" select count(*) from " + tableName); if (rs.next()) { return rs.getInt(1); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(connection); } return -1; } public static List<String> getTables() { List<String> tables = new java.util.ArrayList<String>(); String[] types = { "TABLE" }; Connection connection = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); rs = metaData.getTables(null, null, null, types); while (rs.next()) { tables.add(rs.getObject("TABLE_NAME").toString().toLowerCase()); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(connection); } return tables; } public static List<String> getTables(Connection connection) { List<String> tables = new java.util.ArrayList<String>(); String[] types = { "TABLE" }; ResultSet rs = null; try { DatabaseMetaData metaData = connection.getMetaData(); rs = metaData.getTables(null, null, null, types); while (rs.next()) { tables.add(rs.getObject("TABLE_NAME").toString().toLowerCase()); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); } return tables; } public static List<String> getTables(String systemName) { List<String> tables = new java.util.ArrayList<String>(); String[] types = { "TABLE" }; Connection connection = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(systemName); DatabaseMetaData metaData = connection.getMetaData(); rs = metaData.getTables(null, null, null, types); while (rs.next()) { tables.add(rs.getObject("TABLE_NAME").toString().toLowerCase()); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(connection); } return tables; } /** * 获取保密表 * * @return */ public static List<String> getUnWritableSecretTables() { List<String> tables = new ArrayList<String>(); tables.add("USERINFO"); tables.add("SYS_USER"); tables.add("SYS_KEY"); tables.add("SYS_SERVER"); tables.add("SYS_PROPERTY"); tables.add("SYS_DATABASE"); tables.add("SYS_LOGIN_INFO"); return tables; } public static List<String> getUpperCasePrimaryKeys(String systemName, String tableName) { List<String> primaryKeys = new java.util.ArrayList<String>(); Connection connection = null; ResultSet rs = null; try { connection = DBConnectionFactory.getConnection(systemName); String dbType = DBConnectionFactory.getDatabaseType(connection); DatabaseMetaData metaData = connection.getMetaData(); if (H2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (ORACLE.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (DB2.equals(dbType)) { tableName = tableName.toUpperCase(); } else if (MYSQL.equals(dbType)) { tableName = tableName.toLowerCase(); } else if (POSTGRESQL.equals(dbType)) { tableName = tableName.toLowerCase(); } rs = metaData.getPrimaryKeys(null, null, tableName); while (rs.next()) { primaryKeys.add(rs.getString("column_name").toUpperCase()); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(connection); } return primaryKeys; } public static boolean isAllowedSql(String sql) { if (StringUtils.isEmpty(sql)) { return false; } boolean isLegal = true; sql = sql.toLowerCase(); if (sql.indexOf("sys_key") != -1) { isLegal = false; } if (sql.indexOf("sys_database") != -1) { isLegal = false; } if (sql.indexOf("sys_server") != -1) { isLegal = false; } if (sql.indexOf("sys_identity_token") != -1) { isLegal = false; } return isLegal; } public static boolean isAllowedTable(String tableName) { if (StringUtils.equalsIgnoreCase(tableName, "SYS_DATABASE")) { return false; } else if (StringUtils.equalsIgnoreCase(tableName, "SYS_SERVER")) { return false; } else if (StringUtils.equalsIgnoreCase(tableName, "SYS_KEY")) { return false; } else if (StringUtils.equalsIgnoreCase(tableName, "SYS_IDENTITY_TOKEN")) { return false; } return true; } public static boolean isLegalQuerySql(String sql) { if (StringUtils.isEmpty(sql)) { return false; } boolean isLegal = true; sql = sql.toLowerCase(); if (sql.indexOf(" insert ") != -1) { isLegal = false; } if (sql.indexOf(" update ") != -1) { isLegal = false; } if (sql.indexOf(" delete ") != -1) { isLegal = false; } if (sql.indexOf(" create ") != -1) { isLegal = false; } if (sql.indexOf(" alter ") != -1) { isLegal = false; } if (sql.indexOf(" drop ") != -1) { isLegal = false; } return isLegal; } public static boolean isTableColumn(String columnName) { if (columnName == null || columnName.trim().length() < 2 || columnName.trim().length() > 26) { return false; } char[] sourceChrs = columnName.toCharArray(); Character chr = Character.valueOf(sourceChrs[0]); if (!((chr.charValue() == 95) || (65 <= chr.charValue() && chr.charValue() <= 90) || (97 <= chr.charValue() && chr.charValue() <= 122))) { return false; } for (int i = 1; i < sourceChrs.length; i++) { chr = Character.valueOf(sourceChrs[i]); if (!((chr.charValue() == 95) || (47 <= chr.charValue() && chr.charValue() <= 57) || (65 <= chr.charValue() && chr.charValue() <= 90) || (97 <= chr.charValue() && chr.charValue() <= 122))) { return false; } } return true; } public static boolean isTableName(String sourceString) { if (sourceString == null || sourceString.trim().length() < 2 || sourceString.trim().length() > 25) { return false; } char[] sourceChrs = sourceString.toCharArray(); Character chr = Character.valueOf(sourceChrs[0]); if (!((chr.charValue() == 95) || (65 <= chr.charValue() && chr.charValue() <= 90) || (97 <= chr.charValue() && chr.charValue() <= 122))) { return false; } for (int i = 1; i < sourceChrs.length; i++) { chr = Character.valueOf(sourceChrs[i]); if (!((chr.charValue() == 95) || (47 <= chr.charValue() && chr.charValue() <= 57) || (65 <= chr.charValue() && chr.charValue() <= 90) || (97 <= chr.charValue() && chr.charValue() <= 122))) { return false; } } return true; } public static boolean isTemoraryTable(String tableName) { tableName = tableName.toLowerCase(); if (tableName.startsWith("tmp_")) { return true; } if (tableName.startsWith("temp_")) { return true; } if (tableName.startsWith("_log_")) { return true; } if (tableName.startsWith("demo_")) { return true; } if (tableName.startsWith("wwv_")) { return true; } if (tableName.startsWith("aq_")) { return true; } if (tableName.startsWith("bsln_")) { return true; } if (tableName.startsWith("mgmt_")) { return true; } if (tableName.startsWith("ogis_")) { return true; } if (tableName.startsWith("ols_")) { return true; } if (tableName.startsWith("em_")) { return true; } if (tableName.startsWith("openls_")) { return true; } if (tableName.startsWith("mrac_")) { return true; } if (tableName.startsWith("orddcm_")) { return true; } if (tableName.startsWith("x_")) { return true; } if (tableName.startsWith("wlm_")) { return true; } if (tableName.startsWith("olap_")) { return true; } if (tableName.startsWith("ggs_")) { return true; } if (tableName.startsWith("logmnrc_")) { return true; } if (tableName.startsWith("logmnrg_")) { return true; } if (tableName.startsWith("olap_")) { return true; } if (tableName.startsWith("sto_")) { return true; } if (tableName.startsWith("sdo_")) { return true; } if (tableName.startsWith("sys_iot_")) { return true; } if (tableName.indexOf("$") != -1) { return true; } if (tableName.indexOf("+") != -1) { return true; } if (tableName.indexOf("-") != -1) { return true; } if (tableName.indexOf("?") != -1) { return true; } if (tableName.indexOf("=") != -1) { return true; } return false; } private static Map<String, Object> lowerKeyMap(Map<String, Object> params) { Map<String, Object> dataMap = new java.util.HashMap<String, Object>(); Set<Entry<String, Object>> entrySet = params.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); dataMap.put(key, value); dataMap.put(key.toLowerCase(), value); } return dataMap; } public static void main(String[] args) { System.out.println(DBUtils.isAllowedSql(" select * from sys_user")); List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); ColumnDefinition c1 = new ColumnDefinition(); c1.setColumnName("choosepublishflag"); c1.setLength(1); c1.setJavaType("String"); columns.add(c1); ColumnDefinition c2 = new ColumnDefinition(); c2.setColumnName("choosepublishtime"); c2.setJavaType("Long"); columns.add(c2); // DBUtils.alterTable("qlhighway", "volume", columns); System.out.println(); // FileUtils.save("data/pMagicDev.sql", // DBUtils.getCreateTableDDL("pMagicDev") // .getBytes()); FileUtils.save("data/glaf.sql", DBUtils.getCreateTableDDL("glaf").getBytes()); } public static String removeOrders(String sql) { Pattern pattern = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(sql); StringBuffer buf = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buf, ""); } matcher.appendTail(buf); return buf.toString(); } public static boolean renameTable(Connection connection, String sourceTable, String targetTable) { if (DBUtils.isAllowedTable(sourceTable) && DBUtils.isAllowedTable(targetTable)) { try { String sql = ""; String dbType = DBConnectionFactory.getDatabaseType(connection); if (MYSQL.equalsIgnoreCase(dbType)) { sql = " rename table " + sourceTable + " to " + targetTable; } else if (DB2.equalsIgnoreCase(dbType)) { sql = " rename table " + sourceTable + " to " + targetTable; } else if (ORACLE.equalsIgnoreCase(dbType)) { sql = " alter table " + sourceTable + " rename to " + targetTable; } else if (POSTGRESQL.equalsIgnoreCase(dbType)) { sql = " alter table " + sourceTable + " rename to " + targetTable; } else if (SQLSERVER.equalsIgnoreCase(dbType)) { sql = " EXEC sp_rename '" + sourceTable + "', '" + targetTable + "'"; } if (StringUtils.isNotEmpty(sql)) { executeSchemaResource(connection, sql); return true; } } catch (Exception ex) { throw new RuntimeException(ex); } } return false; } public static boolean renameTable(String systemName, String sourceTable, String targetTable) { Connection connection = null; try { connection = DBConnectionFactory.getConnection(systemName); connection.setAutoCommit(false); connection.commit(); return renameTable(connection, sourceTable, targetTable); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(connection); } } public static SqlExecutor replaceSQL(String sql, Map<String, Object> params) { SqlExecutor sqlExecutor = new SqlExecutor(); sqlExecutor.setSql(sql); if (sql == null || params == null) { return sqlExecutor; } List<Object> values = new java.util.ArrayList<Object>(); Map<String, Object> dataMap = lowerKeyMap(params); StringBuffer sb = new StringBuffer(); int begin = 0; int end = 0; boolean flag = false; for (int i = 0; i < sql.length(); i++) { if (sql.charAt(i) == '#' && sql.charAt(i + 1) == '{') { sb.append(sql.substring(end, i)); begin = i + 2; flag = true; } if (flag && sql.charAt(i) == '}') { String temp = sql.substring(begin, i); temp = temp.toLowerCase(); if (dataMap.get(temp) != null) { Object value = dataMap.get(temp); /** * 如果是Collection参数,必须至少有一个值 */ if (value != null && value instanceof Collection) { Collection<?> coll = (Collection<?>) value; if (coll != null && !coll.isEmpty()) { Iterator<?> iter = coll.iterator(); while (iter.hasNext()) { values.add(iter.next()); sb.append(" ? "); if (iter.hasNext()) { sb.append(", "); } } } } else { sb.append(" ? "); values.add(value); } end = i + 1; flag = false; } else { sb.append(" ? "); end = i + 1; flag = false; values.add(null); } } if (i == sql.length() - 1) { sb.append(sql.substring(end, i + 1)); } } sqlExecutor.setParameter(values); sqlExecutor.setSql(sb.toString()); return sqlExecutor; } public static boolean tableExists(Connection connection, String tableName) { DatabaseMetaData dbmd = null; ResultSet rs = null; boolean exists = false; try { dbmd = connection.getMetaData(); rs = dbmd.getTables(null, null, null, new String[] { "TABLE" }); while (rs.next()) { String table = rs.getString("TABLE_NAME"); if (StringUtils.equalsIgnoreCase(tableName, table)) { exists = true; } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); } return exists; } /** * 判断表是否已经存在 * * @param systemName * @param tableName * @return */ public static boolean tableExists(String tableName) { Connection conn = null; try { conn = DBConnectionFactory.getConnection(); return tableExists(conn, tableName); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } } /** * 判断表是否已经存在 * * @param systemName * @param tableName * @return */ public static boolean tableExists(String systemName, String tableName) { Connection conn = null; try { conn = DBConnectionFactory.getConnection(systemName); return tableExists(conn, tableName); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } } }
apache-2.0
xydu/carve
carve-core/src/test/java/com/qiyi/usercloud/carve/demoservice/AddressBookProtos.java
62319
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: qiantao.proto package com.qiyi.usercloud.carve.demoservice; public final class AddressBookProtos { private AddressBookProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface PersonOrBuilder extends com.google.protobuf.MessageOrBuilder { // required string name = 1; /** * <code>required string name = 1;</code> */ boolean hasName(); /** * <code>required string name = 1;</code> */ java.lang.String getName(); /** * <code>required string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); // required int32 id = 2; /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ boolean hasId(); /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ int getId(); // optional string email = 3; /** * <code>optional string email = 3;</code> */ boolean hasEmail(); /** * <code>optional string email = 3;</code> */ java.lang.String getEmail(); /** * <code>optional string email = 3;</code> */ com.google.protobuf.ByteString getEmailBytes(); // optional double doubleF = 4; /** * <code>optional double doubleF = 4;</code> */ boolean hasDoubleF(); /** * <code>optional double doubleF = 4;</code> */ double getDoubleF(); // optional float floatF = 5; /** * <code>optional float floatF = 5;</code> */ boolean hasFloatF(); /** * <code>optional float floatF = 5;</code> */ float getFloatF(); // optional bytes bytesF = 6; /** * <code>optional bytes bytesF = 6;</code> */ boolean hasBytesF(); /** * <code>optional bytes bytesF = 6;</code> */ com.google.protobuf.ByteString getBytesF(); // optional bool boolF = 7; /** * <code>optional bool boolF = 7;</code> */ boolean hasBoolF(); /** * <code>optional bool boolF = 7;</code> */ boolean getBoolF(); } /** * Protobuf type {@code tutorial.Person} */ public static final class Person extends com.google.protobuf.GeneratedMessage implements PersonOrBuilder { // Use Person.newBuilder() to construct. private Person(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Person(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Person defaultInstance; public static Person getDefaultInstance() { return defaultInstance; } public Person getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); 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; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; name_ = input.readBytes(); break; } case 16: { bitField0_ |= 0x00000002; id_ = input.readInt32(); break; } case 26: { bitField0_ |= 0x00000004; email_ = input.readBytes(); break; } case 33: { bitField0_ |= 0x00000008; doubleF_ = input.readDouble(); break; } case 45: { bitField0_ |= 0x00000010; floatF_ = input.readFloat(); break; } case 50: { bitField0_ |= 0x00000020; bytesF_ = input.readBytes(); break; } case 56: { bitField0_ |= 0x00000040; boolF_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_Person_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_Person_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.class, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder.class); } public static com.google.protobuf.Parser<Person> PARSER = new com.google.protobuf.AbstractParser<Person>() { public Person parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Person(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Person> getParserForType() { return PARSER; } private int bitField0_; // required string name = 1; public static final int NAME_FIELD_NUMBER = 1; private java.lang.Object name_; /** * <code>required string name = 1;</code> */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>required string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // required int32 id = 2; public static final int ID_FIELD_NUMBER = 2; private int id_; /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public boolean hasId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public int getId() { return id_; } // optional string email = 3; public static final int EMAIL_FIELD_NUMBER = 3; private java.lang.Object email_; /** * <code>optional string email = 3;</code> */ public boolean hasEmail() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string email = 3;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { email_ = s; } return s; } } /** * <code>optional string email = 3;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional double doubleF = 4; public static final int DOUBLEF_FIELD_NUMBER = 4; private double doubleF_; /** * <code>optional double doubleF = 4;</code> */ public boolean hasDoubleF() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional double doubleF = 4;</code> */ public double getDoubleF() { return doubleF_; } // optional float floatF = 5; public static final int FLOATF_FIELD_NUMBER = 5; private float floatF_; /** * <code>optional float floatF = 5;</code> */ public boolean hasFloatF() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional float floatF = 5;</code> */ public float getFloatF() { return floatF_; } // optional bytes bytesF = 6; public static final int BYTESF_FIELD_NUMBER = 6; private com.google.protobuf.ByteString bytesF_; /** * <code>optional bytes bytesF = 6;</code> */ public boolean hasBytesF() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional bytes bytesF = 6;</code> */ public com.google.protobuf.ByteString getBytesF() { return bytesF_; } // optional bool boolF = 7; public static final int BOOLF_FIELD_NUMBER = 7; private boolean boolF_; /** * <code>optional bool boolF = 7;</code> */ public boolean hasBoolF() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional bool boolF = 7;</code> */ public boolean getBoolF() { return boolF_; } private void initFields() { name_ = ""; id_ = 0; email_ = ""; doubleF_ = 0D; floatF_ = 0F; bytesF_ = com.google.protobuf.ByteString.EMPTY; boolF_ = false; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasName()) { memoizedIsInitialized = 0; return false; } if (!hasId()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt32(2, id_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getEmailBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeDouble(4, doubleF_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeFloat(5, floatF_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeBytes(6, bytesF_); } if (((bitField0_ & 0x00000040) == 0x00000040)) { output.writeBool(7, boolF_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, id_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getEmailBytes()); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(4, doubleF_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeFloatSize(5, floatF_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, bytesF_); } if (((bitField0_ & 0x00000040) == 0x00000040)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(7, boolF_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code tutorial.Person} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_Person_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_Person_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.class, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder.class); } // Construct using com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); name_ = ""; bitField0_ = (bitField0_ & ~0x00000001); id_ = 0; bitField0_ = (bitField0_ & ~0x00000002); email_ = ""; bitField0_ = (bitField0_ & ~0x00000004); doubleF_ = 0D; bitField0_ = (bitField0_ & ~0x00000008); floatF_ = 0F; bitField0_ = (bitField0_ & ~0x00000010); bytesF_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); boolF_ = false; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_Person_descriptor; } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person getDefaultInstanceForType() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.getDefaultInstance(); } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person build() { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person buildPartial() { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person result = new com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.name_ = name_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.id_ = id_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.email_ = email_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.doubleF_ = doubleF_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.floatF_ = floatF_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.bytesF_ = bytesF_; if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000040; } result.boolF_ = boolF_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person) { return mergeFrom((com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person other) { if (other == com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.getDefaultInstance()) return this; if (other.hasName()) { bitField0_ |= 0x00000001; name_ = other.name_; onChanged(); } if (other.hasId()) { setId(other.getId()); } if (other.hasEmail()) { bitField0_ |= 0x00000004; email_ = other.email_; onChanged(); } if (other.hasDoubleF()) { setDoubleF(other.getDoubleF()); } if (other.hasFloatF()) { setFloatF(other.getFloatF()); } if (other.hasBytesF()) { setBytesF(other.getBytesF()); } if (other.hasBoolF()) { setBoolF(other.getBoolF()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasName()) { return false; } if (!hasId()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required string name = 1; private java.lang.Object name_ = ""; /** * <code>required string name = 1;</code> */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>required string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>required string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } /** * <code>required string name = 1;</code> */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000001); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>required string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } // required int32 id = 2; private int id_ ; /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public boolean hasId() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public int getId() { return id_; } /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public Builder setId(int value) { bitField0_ |= 0x00000002; id_ = value; onChanged(); return this; } /** * <code>required int32 id = 2;</code> * * <pre> * Unique ID number for this person. * </pre> */ public Builder clearId() { bitField0_ = (bitField0_ & ~0x00000002); id_ = 0; onChanged(); return this; } // optional string email = 3; private java.lang.Object email_ = ""; /** * <code>optional string email = 3;</code> */ public boolean hasEmail() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string email = 3;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref) .toStringUtf8(); email_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string email = 3;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string email = 3;</code> */ public Builder setEmail( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; email_ = value; onChanged(); return this; } /** * <code>optional string email = 3;</code> */ public Builder clearEmail() { bitField0_ = (bitField0_ & ~0x00000004); email_ = getDefaultInstance().getEmail(); onChanged(); return this; } /** * <code>optional string email = 3;</code> */ public Builder setEmailBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; email_ = value; onChanged(); return this; } // optional double doubleF = 4; private double doubleF_ ; /** * <code>optional double doubleF = 4;</code> */ public boolean hasDoubleF() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional double doubleF = 4;</code> */ public double getDoubleF() { return doubleF_; } /** * <code>optional double doubleF = 4;</code> */ public Builder setDoubleF(double value) { bitField0_ |= 0x00000008; doubleF_ = value; onChanged(); return this; } /** * <code>optional double doubleF = 4;</code> */ public Builder clearDoubleF() { bitField0_ = (bitField0_ & ~0x00000008); doubleF_ = 0D; onChanged(); return this; } // optional float floatF = 5; private float floatF_ ; /** * <code>optional float floatF = 5;</code> */ public boolean hasFloatF() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>optional float floatF = 5;</code> */ public float getFloatF() { return floatF_; } /** * <code>optional float floatF = 5;</code> */ public Builder setFloatF(float value) { bitField0_ |= 0x00000010; floatF_ = value; onChanged(); return this; } /** * <code>optional float floatF = 5;</code> */ public Builder clearFloatF() { bitField0_ = (bitField0_ & ~0x00000010); floatF_ = 0F; onChanged(); return this; } // optional bytes bytesF = 6; private com.google.protobuf.ByteString bytesF_ = com.google.protobuf.ByteString.EMPTY; /** * <code>optional bytes bytesF = 6;</code> */ public boolean hasBytesF() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>optional bytes bytesF = 6;</code> */ public com.google.protobuf.ByteString getBytesF() { return bytesF_; } /** * <code>optional bytes bytesF = 6;</code> */ public Builder setBytesF(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; bytesF_ = value; onChanged(); return this; } /** * <code>optional bytes bytesF = 6;</code> */ public Builder clearBytesF() { bitField0_ = (bitField0_ & ~0x00000020); bytesF_ = getDefaultInstance().getBytesF(); onChanged(); return this; } // optional bool boolF = 7; private boolean boolF_ ; /** * <code>optional bool boolF = 7;</code> */ public boolean hasBoolF() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * <code>optional bool boolF = 7;</code> */ public boolean getBoolF() { return boolF_; } /** * <code>optional bool boolF = 7;</code> */ public Builder setBoolF(boolean value) { bitField0_ |= 0x00000040; boolF_ = value; onChanged(); return this; } /** * <code>optional bool boolF = 7;</code> */ public Builder clearBoolF() { bitField0_ = (bitField0_ & ~0x00000040); boolF_ = false; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:tutorial.Person) } static { defaultInstance = new Person(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:tutorial.Person) } public interface AddressBookOrBuilder extends com.google.protobuf.MessageOrBuilder { // repeated .tutorial.Person person = 1; /** * <code>repeated .tutorial.Person person = 1;</code> */ java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> getPersonList(); /** * <code>repeated .tutorial.Person person = 1;</code> */ com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person getPerson(int index); /** * <code>repeated .tutorial.Person person = 1;</code> */ int getPersonCount(); /** * <code>repeated .tutorial.Person person = 1;</code> */ java.util.List<? extends com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder> getPersonOrBuilderList(); /** * <code>repeated .tutorial.Person person = 1;</code> */ com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder getPersonOrBuilder( int index); } /** * Protobuf type {@code tutorial.AddressBook} * * <pre> * Our address book file is just one of these. * </pre> */ public static final class AddressBook extends com.google.protobuf.GeneratedMessage implements AddressBookOrBuilder { // Use AddressBook.newBuilder() to construct. private AddressBook(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private AddressBook(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final AddressBook defaultInstance; public static AddressBook getDefaultInstance() { return defaultInstance; } public AddressBook getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AddressBook( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); 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; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { person_ = new java.util.ArrayList<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person>(); mutable_bitField0_ |= 0x00000001; } person_.add(input.readMessage(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { person_ = java.util.Collections.unmodifiableList(person_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_AddressBook_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.class, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.Builder.class); } public static com.google.protobuf.Parser<AddressBook> PARSER = new com.google.protobuf.AbstractParser<AddressBook>() { public AddressBook parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AddressBook(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<AddressBook> getParserForType() { return PARSER; } // repeated .tutorial.Person person = 1; public static final int PERSON_FIELD_NUMBER = 1; private java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> person_; /** * <code>repeated .tutorial.Person person = 1;</code> */ public java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> getPersonList() { return person_; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public java.util.List<? extends com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder> getPersonOrBuilderList() { return person_; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public int getPersonCount() { return person_.size(); } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person getPerson(int index) { return person_.get(index); } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder getPersonOrBuilder( int index) { return person_.get(index); } private void initFields() { person_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; for (int i = 0; i < getPersonCount(); i++) { if (!getPerson(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (int i = 0; i < person_.size(); i++) { output.writeMessage(1, person_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < person_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, person_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code tutorial.AddressBook} * * <pre> * Our address book file is just one of these. * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBookOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_AddressBook_fieldAccessorTable .ensureFieldAccessorsInitialized( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.class, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.Builder.class); } // Construct using com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getPersonFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (personBuilder_ == null) { person_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { personBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook getDefaultInstanceForType() { return com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.getDefaultInstance(); } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook build() { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook buildPartial() { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook result = new com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook(this); int from_bitField0_ = bitField0_; if (personBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { person_ = java.util.Collections.unmodifiableList(person_); bitField0_ = (bitField0_ & ~0x00000001); } result.person_ = person_; } else { result.person_ = personBuilder_.build(); } onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook) { return mergeFrom((com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook other) { if (other == com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook.getDefaultInstance()) return this; if (personBuilder_ == null) { if (!other.person_.isEmpty()) { if (person_.isEmpty()) { person_ = other.person_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePersonIsMutable(); person_.addAll(other.person_); } onChanged(); } } else { if (!other.person_.isEmpty()) { if (personBuilder_.isEmpty()) { personBuilder_.dispose(); personBuilder_ = null; person_ = other.person_; bitField0_ = (bitField0_ & ~0x00000001); personBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getPersonFieldBuilder() : null; } else { personBuilder_.addAllMessages(other.person_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { for (int i = 0; i < getPersonCount(); i++) { if (!getPerson(i).isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.qiyi.usercloud.carve.demoservice.AddressBookProtos.AddressBook) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // repeated .tutorial.Person person = 1; private java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> person_ = java.util.Collections.emptyList(); private void ensurePersonIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { person_ = new java.util.ArrayList<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person>(person_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder> personBuilder_; /** * <code>repeated .tutorial.Person person = 1;</code> */ public java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> getPersonList() { if (personBuilder_ == null) { return java.util.Collections.unmodifiableList(person_); } else { return personBuilder_.getMessageList(); } } /** * <code>repeated .tutorial.Person person = 1;</code> */ public int getPersonCount() { if (personBuilder_ == null) { return person_.size(); } else { return personBuilder_.getCount(); } } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person getPerson(int index) { if (personBuilder_ == null) { return person_.get(index); } else { return personBuilder_.getMessage(index); } } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder setPerson( int index, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person value) { if (personBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePersonIsMutable(); person_.set(index, value); onChanged(); } else { personBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder setPerson( int index, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder builderForValue) { if (personBuilder_ == null) { ensurePersonIsMutable(); person_.set(index, builderForValue.build()); onChanged(); } else { personBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder addPerson(com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person value) { if (personBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePersonIsMutable(); person_.add(value); onChanged(); } else { personBuilder_.addMessage(value); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder addPerson( int index, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person value) { if (personBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePersonIsMutable(); person_.add(index, value); onChanged(); } else { personBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder addPerson( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder builderForValue) { if (personBuilder_ == null) { ensurePersonIsMutable(); person_.add(builderForValue.build()); onChanged(); } else { personBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder addPerson( int index, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder builderForValue) { if (personBuilder_ == null) { ensurePersonIsMutable(); person_.add(index, builderForValue.build()); onChanged(); } else { personBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder addAllPerson( java.lang.Iterable<? extends com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person> values) { if (personBuilder_ == null) { ensurePersonIsMutable(); super.addAll(values, person_); onChanged(); } else { personBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder clearPerson() { if (personBuilder_ == null) { person_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { personBuilder_.clear(); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public Builder removePerson(int index) { if (personBuilder_ == null) { ensurePersonIsMutable(); person_.remove(index); onChanged(); } else { personBuilder_.remove(index); } return this; } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder getPersonBuilder( int index) { return getPersonFieldBuilder().getBuilder(index); } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder getPersonOrBuilder( int index) { if (personBuilder_ == null) { return person_.get(index); } else { return personBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .tutorial.Person person = 1;</code> */ public java.util.List<? extends com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder> getPersonOrBuilderList() { if (personBuilder_ != null) { return personBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(person_); } } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder addPersonBuilder() { return getPersonFieldBuilder().addBuilder( com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.getDefaultInstance()); } /** * <code>repeated .tutorial.Person person = 1;</code> */ public com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder addPersonBuilder( int index) { return getPersonFieldBuilder().addBuilder( index, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.getDefaultInstance()); } /** * <code>repeated .tutorial.Person person = 1;</code> */ public java.util.List<com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder> getPersonBuilderList() { return getPersonFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder> getPersonFieldBuilder() { if (personBuilder_ == null) { personBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.Person.Builder, com.qiyi.usercloud.carve.demoservice.AddressBookProtos.PersonOrBuilder>( person_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); person_ = null; } return personBuilder_; } // @@protoc_insertion_point(builder_scope:tutorial.AddressBook) } static { defaultInstance = new AddressBook(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:tutorial.AddressBook) } private static com.google.protobuf.Descriptors.Descriptor internal_static_tutorial_Person_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_tutorial_Person_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_tutorial_AddressBook_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_tutorial_AddressBook_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\rqiantao.proto\022\010tutorial\"q\n\006Person\022\014\n\004n" + "ame\030\001 \002(\t\022\n\n\002id\030\002 \002(\005\022\r\n\005email\030\003 \001(\t\022\017\n\007" + "doubleF\030\004 \001(\001\022\016\n\006floatF\030\005 \001(\002\022\016\n\006bytesF\030" + "\006 \001(\014\022\r\n\005boolF\030\007 \001(\010\"/\n\013AddressBook\022 \n\006p" + "erson\030\001 \003(\0132\020.tutorial.PersonB@\n+com.bai" + "du.bjf.remoting.protobuf.complexListB\021Ad" + "dressBookProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_tutorial_Person_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_tutorial_Person_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_tutorial_Person_descriptor, new java.lang.String[] { "Name", "Id", "Email", "DoubleF", "FloatF", "BytesF", "BoolF", }); internal_static_tutorial_AddressBook_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_tutorial_AddressBook_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_tutorial_AddressBook_descriptor, new java.lang.String[] { "Person", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } }
apache-2.0
weiwenqiang/GitHub
MVP/RxJava2ToMVP/Rx-Mvp-master/app/src/main/java/com/rx/mvp/cn/view/iface/IPhoneAddressView.java
305
package com.rx.mvp.cn.view.iface; import com.rx.mvp.cn.base.IBaseView; import com.rx.mvp.cn.model.bean.AddressBean; /** * 手机归属地页面view接口 * * @author ZhongDaFeng */ public interface IPhoneAddressView extends IBaseView { //显示结果 void showResult(AddressBean bean); }
apache-2.0
markusgumbel/dshl7
hl7-javasig/src/org/hl7/types/impl/QSETPeriodicHullImpl.java
4182
/* The contents of this file are subject to the Health Level-7 Public * License Version 1.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.hl7.org/HPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and * limitations under the License. * * The Original Code is all this file. * * The Initial Developer of the Original Code is . * Portions created by Initial Developer are Copyright (C) 2002-2004 * Health Level Seven, Inc. All Rights Reserved. * * Contributor(s): */ package org.hl7.types.impl; import org.hl7.types.ANY; import org.hl7.types.BL; import org.hl7.types.Criterion; import org.hl7.types.INT; import org.hl7.types.IVL; import org.hl7.types.PQ; import org.hl7.types.QSET; import org.hl7.types.QTY; import org.hl7.types.SET; import org.hl7.types.TS; /* * Result of periodic hull operation between two QSETs */ public class QSETPeriodicHullImpl<T extends QTY> extends QSETTermBase<T> implements QSET<T> { /* * The hull is considered the space (inclusive) of occurence intervals of _thisset and _thatset. Note: this is * different from the intervals of _thatset and _thisset. As of now, we assume that the two sets are interleaving */ QSET<T> _thisset; // occurs first QSET<T> _thatset; // occurs second @Override public String toString() { return _thisset.toString() + " .. " + _thatset.toString(); } public static QSETPeriodicHullImpl valueOf(final QSET thisset, final QSET thatset) { return new QSETPeriodicHullImpl(thisset, thatset); } private QSETPeriodicHullImpl(final QSET<T> thisset, final QSET<T> thatset) { _thisset = thisset; _thatset = thatset; } public QSET<T> getThisSet() { return _thisset; } public QSET<T> getThatSet() { return _thatset; } public BL contains(final T element) { return this.nextTo(element).low().lessOrEqual(element).and(element.lessOrEqual(this.nextTo(element).high())); } public BL contains(final SET<T> subset) { if (subset instanceof IVL) { final IVL<T> ivl = (IVL) subset; return this.contains(ivl.low()).and(this.contains(ivl.high())).and( this.nextTo(ivl.low()).equal(this.nextTo(ivl.high()))); } else { throw new UnsupportedOperationException(); } } public IVL<T> hull() { throw new UnsupportedOperationException(); } public IVL<T> nextTo(final T element) { IVL<T> thisIVL, thatIVL; thisIVL = _thisset.nextTo(element); thatIVL = _thatset.nextTo(element); if (thisIVL.low().lessOrEqual(element).isTrue()) { return IVLimpl.valueOf(thisIVL.lowClosed(), thisIVL.low(), thatIVL.high(), thatIVL.highClosed()); } else if (thatIVL.high().lessOrEqual(thisIVL.low()).isTrue()) { final PQ diff = (PQ) _thisset.nextAfter(thisIVL.low()).low().minus(thisIVL.low()); return IVLimpl.valueOf(thisIVL.lowClosed(), (T) ((TS) thisIVL.low()).minus(diff), thatIVL.high(), thatIVL .highClosed()); } else { return IVLimpl.valueOf(thisIVL.lowClosed(), thisIVL.low(), thatIVL.high(), thatIVL.highClosed()); } } public IVL<T> nextAfter(final T element) { final IVL<T> ans = this.nextTo(element); if (element.lessOrEqual(ans.low()).isTrue()) { return ans; } else { // we have to get the next ans final IVL<T> thisIVL = _thisset.nextAfter(ans.high()); final IVL<T> thatIVL = _thatset.nextAfter(ans.high()); return IVLimpl.valueOf(thisIVL.lowClosed(), thisIVL.low(), thatIVL.high(), thatIVL.highClosed()); } } public BL interleaves(final QSET<T> otherset) { throw new UnsupportedOperationException(); } @Override public BL equal(final ANY that) { throw new UnsupportedOperationException(); } public INT cardinality() { throw new UnsupportedOperationException(); } public BL isEmpty() { return _thisset.isEmpty().and(_thatset.isEmpty()); } public T any() { throw new UnsupportedOperationException(); } public SET<T> select(final Criterion c) { throw new UnsupportedOperationException(); } }
apache-2.0
wuranbo/elasticsearch
core/src/main/java/org/elasticsearch/action/bulk/BulkRequest.java
25029
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.bulk; import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.CompositeIndicesRequest; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.replication.ReplicationRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.VersionType; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; /** * A bulk request holds an ordered {@link IndexRequest}s, {@link DeleteRequest}s and {@link UpdateRequest}s * and allows to executes it in a single batch. * * Note that we only support refresh on the bulk request not per item. * @see org.elasticsearch.client.Client#bulk(BulkRequest) */ public class BulkRequest extends ActionRequest implements CompositeIndicesRequest, WriteRequest<BulkRequest> { private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(BulkRequest.class)); private static final int REQUEST_OVERHEAD = 50; /** * Requests that are part of this request. It is only possible to add things that are both {@link ActionRequest}s and * {@link WriteRequest}s to this but java doesn't support syntax to declare that everything in the array has both types so we declare * the one with the least casts. */ final List<DocWriteRequest> requests = new ArrayList<>(); private final Set<String> indices = new HashSet<>(); List<Object> payloads = null; protected TimeValue timeout = BulkShardRequest.DEFAULT_TIMEOUT; private ActiveShardCount waitForActiveShards = ActiveShardCount.DEFAULT; private RefreshPolicy refreshPolicy = RefreshPolicy.NONE; private long sizeInBytes = 0; public BulkRequest() { } /** * Adds a list of requests to be executed. Either index or delete requests. */ public BulkRequest add(DocWriteRequest... requests) { for (DocWriteRequest request : requests) { add(request, null); } return this; } public BulkRequest add(DocWriteRequest request) { return add(request, null); } /** * Add a request to the current BulkRequest. * @param request Request to add * @param payload Optional payload * @return the current bulk request */ public BulkRequest add(DocWriteRequest request, @Nullable Object payload) { if (request instanceof IndexRequest) { add((IndexRequest) request, payload); } else if (request instanceof DeleteRequest) { add((DeleteRequest) request, payload); } else if (request instanceof UpdateRequest) { add((UpdateRequest) request, payload); } else { throw new IllegalArgumentException("No support for request [" + request + "]"); } indices.add(request.index()); return this; } /** * Adds a list of requests to be executed. Either index or delete requests. */ public BulkRequest add(Iterable<DocWriteRequest> requests) { for (DocWriteRequest request : requests) { add(request); } return this; } /** * Adds an {@link IndexRequest} to the list of actions to execute. Follows the same behavior of {@link IndexRequest} * (for example, if no id is provided, one will be generated, or usage of the create flag). */ public BulkRequest add(IndexRequest request) { return internalAdd(request, null); } public BulkRequest add(IndexRequest request, @Nullable Object payload) { return internalAdd(request, payload); } BulkRequest internalAdd(IndexRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); // lack of source is validated in validate() method sizeInBytes += (request.source() != null ? request.source().length() : 0) + REQUEST_OVERHEAD; indices.add(request.index()); return this; } /** * Adds an {@link UpdateRequest} to the list of actions to execute. */ public BulkRequest add(UpdateRequest request) { return internalAdd(request, null); } public BulkRequest add(UpdateRequest request, @Nullable Object payload) { return internalAdd(request, payload); } BulkRequest internalAdd(UpdateRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); if (request.doc() != null) { sizeInBytes += request.doc().source().length(); } if (request.upsertRequest() != null) { sizeInBytes += request.upsertRequest().source().length(); } if (request.script() != null) { sizeInBytes += request.script().getIdOrCode().length() * 2; } indices.add(request.index()); return this; } /** * Adds an {@link DeleteRequest} to the list of actions to execute. */ public BulkRequest add(DeleteRequest request) { return add(request, null); } public BulkRequest add(DeleteRequest request, @Nullable Object payload) { Objects.requireNonNull(request, "'request' must not be null"); requests.add(request); addPayload(payload); sizeInBytes += REQUEST_OVERHEAD; indices.add(request.index()); return this; } private void addPayload(Object payload) { if (payloads == null) { if (payload == null) { return; } payloads = new ArrayList<>(requests.size() + 10); // add requests#size-1 elements to the payloads if it null (we add for an *existing* request) for (int i = 1; i < requests.size(); i++) { payloads.add(null); } } payloads.add(payload); } /** * The list of requests in this bulk request. */ public List<DocWriteRequest> requests() { return this.requests; } /** * The list of optional payloads associated with requests in the same order as the requests. Note, elements within * it might be null if no payload has been provided. * <p> * Note, if no payloads have been provided, this method will return null (as to conserve memory overhead). */ @Nullable public List<Object> payloads() { return this.payloads; } /** * The number of actions in the bulk request. */ public int numberOfActions() { return requests.size(); } /** * The estimated size in bytes of the bulk request. */ public long estimatedSizeInBytes() { return sizeInBytes; } /** * Adds a framed data in binary format */ public BulkRequest add(byte[] data, int from, int length) throws IOException { return add(data, from, length, null, null); } /** * Adds a framed data in binary format */ public BulkRequest add(byte[] data, int from, int length, @Nullable String defaultIndex, @Nullable String defaultType) throws IOException { return add(new BytesArray(data, from, length), defaultIndex, defaultType); } /** * Adds a framed data in binary format */ public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType) throws IOException { return add(data, defaultIndex, defaultType, null, null, null, null, null, true); } /** * Adds a framed data in binary format */ public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType, boolean allowExplicitIndex) throws IOException { return add(data, defaultIndex, defaultType, null, null, null, null, null, allowExplicitIndex); } public BulkRequest add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultType, @Nullable String defaultRouting, @Nullable String[] defaultFields, @Nullable FetchSourceContext defaultFetchSourceContext, @Nullable String defaultPipeline, @Nullable Object payload, boolean allowExplicitIndex) throws IOException { XContent xContent = XContentFactory.xContent(data); int line = 0; int from = 0; int length = data.length(); byte marker = xContent.streamSeparator(); while (true) { int nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } line++; // now parse the action // EMPTY is safe here because we never call namedObject try (XContentParser parser = xContent.createParser(NamedXContentRegistry.EMPTY, data.slice(from, nextMarker - from))) { // move pointers from = nextMarker + 1; // Move to START_OBJECT XContentParser.Token token = parser.nextToken(); if (token == null) { continue; } assert token == XContentParser.Token.START_OBJECT; // Move to FIELD_NAME, that's the action token = parser.nextToken(); assert token == XContentParser.Token.FIELD_NAME; String action = parser.currentName(); String index = defaultIndex; String type = defaultType; String id = null; String routing = defaultRouting; String parent = null; FetchSourceContext fetchSourceContext = defaultFetchSourceContext; String[] fields = defaultFields; String opType = null; long version = Versions.MATCH_ANY; VersionType versionType = VersionType.INTERNAL; int retryOnConflict = 0; String pipeline = defaultPipeline; // at this stage, next token can either be END_OBJECT (and use default index and type, with auto generated id) // or START_OBJECT which will have another set of parameters token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("_index".equals(currentFieldName)) { if (!allowExplicitIndex) { throw new IllegalArgumentException("explicit index in bulk is not allowed"); } index = parser.text(); } else if ("_type".equals(currentFieldName)) { type = parser.text(); } else if ("_id".equals(currentFieldName)) { id = parser.text(); } else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) { routing = parser.text(); } else if ("_parent".equals(currentFieldName) || "parent".equals(currentFieldName)) { parent = parser.text(); } else if ("op_type".equals(currentFieldName) || "opType".equals(currentFieldName)) { opType = parser.text(); } else if ("_version".equals(currentFieldName) || "version".equals(currentFieldName)) { version = parser.longValue(); } else if ("_version_type".equals(currentFieldName) || "_versionType".equals(currentFieldName) || "version_type".equals(currentFieldName) || "versionType".equals(currentFieldName)) { versionType = VersionType.fromString(parser.text()); } else if ("_retry_on_conflict".equals(currentFieldName) || "_retryOnConflict".equals(currentFieldName)) { retryOnConflict = parser.intValue(); } else if ("pipeline".equals(currentFieldName)) { pipeline = parser.text(); } else if ("fields".equals(currentFieldName)) { throw new IllegalArgumentException("Action/metadata line [" + line + "] contains a simple value for parameter [fields] while a list is expected"); } else if ("_source".equals(currentFieldName)) { fetchSourceContext = FetchSourceContext.parse(parser); } else { throw new IllegalArgumentException("Action/metadata line [" + line + "] contains an unknown parameter [" + currentFieldName + "]"); } } else if (token == XContentParser.Token.START_ARRAY) { if ("fields".equals(currentFieldName)) { DEPRECATION_LOGGER.deprecated("Deprecated field [fields] used, expected [_source] instead"); List<Object> values = parser.list(); fields = values.toArray(new String[values.size()]); } else { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]"); } } else if (token == XContentParser.Token.START_OBJECT && "_source".equals(currentFieldName)) { fetchSourceContext = FetchSourceContext.parse(parser); } else if (token != XContentParser.Token.VALUE_NULL) { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected a simple value for field [" + currentFieldName + "] but found [" + token + "]"); } } } else if (token != XContentParser.Token.END_OBJECT) { throw new IllegalArgumentException("Malformed action/metadata line [" + line + "], expected " + XContentParser.Token.START_OBJECT + " or " + XContentParser.Token.END_OBJECT + " but found [" + token + "]"); } if ("delete".equals(action)) { add(new DeleteRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType), payload); } else { nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } line++; // order is important, we set parent after routing, so routing will be set to parent if not set explicitly // we use internalAdd so we don't fork here, this allows us not to copy over the big byte array to small chunks // of index request. if ("index".equals(action)) { if (opType == null) { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .setPipeline(pipeline).source(data.slice(from, nextMarker - from)), payload); } else { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .create("create".equals(opType)).setPipeline(pipeline) .source(data.slice(from, nextMarker - from)), payload); } } else if ("create".equals(action)) { internalAdd(new IndexRequest(index, type, id).routing(routing).parent(parent).version(version).versionType(versionType) .create(true).setPipeline(pipeline) .source(data.slice(from, nextMarker - from)), payload); } else if ("update".equals(action)) { UpdateRequest updateRequest = new UpdateRequest(index, type, id).routing(routing).parent(parent).retryOnConflict(retryOnConflict) .version(version).versionType(versionType) .routing(routing) .parent(parent); // EMPTY is safe here because we never call namedObject try (XContentParser sliceParser = xContent.createParser(NamedXContentRegistry.EMPTY, data.slice(from, nextMarker - from))) { updateRequest.fromXContent(sliceParser); } if (fetchSourceContext != null) { updateRequest.fetchSource(fetchSourceContext); } if (fields != null) { updateRequest.fields(fields); } IndexRequest upsertRequest = updateRequest.upsertRequest(); if (upsertRequest != null) { upsertRequest.version(version); upsertRequest.versionType(versionType); } IndexRequest doc = updateRequest.doc(); if (doc != null) { doc.version(version); doc.versionType(versionType); } internalAdd(updateRequest, payload); } // move pointers from = nextMarker + 1; } } } return this; } /** * Sets the number of shard copies that must be active before proceeding with the write. * See {@link ReplicationRequest#waitForActiveShards(ActiveShardCount)} for details. */ public BulkRequest waitForActiveShards(ActiveShardCount waitForActiveShards) { this.waitForActiveShards = waitForActiveShards; return this; } /** * A shortcut for {@link #waitForActiveShards(ActiveShardCount)} where the numerical * shard count is passed in, instead of having to first call {@link ActiveShardCount#from(int)} * to get the ActiveShardCount. */ public BulkRequest waitForActiveShards(final int waitForActiveShards) { return waitForActiveShards(ActiveShardCount.from(waitForActiveShards)); } public ActiveShardCount waitForActiveShards() { return this.waitForActiveShards; } @Override public BulkRequest setRefreshPolicy(RefreshPolicy refreshPolicy) { this.refreshPolicy = refreshPolicy; return this; } @Override public RefreshPolicy getRefreshPolicy() { return refreshPolicy; } /** * A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>. */ public final BulkRequest timeout(TimeValue timeout) { this.timeout = timeout; return this; } /** * A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>. */ public final BulkRequest timeout(String timeout) { return timeout(TimeValue.parseTimeValue(timeout, null, getClass().getSimpleName() + ".timeout")); } public TimeValue timeout() { return timeout; } private int findNextMarker(byte marker, int from, BytesReference data, int length) { for (int i = from; i < length; i++) { if (data.get(i) == marker) { return i; } } return -1; } /** * @return Whether this bulk request contains index request with an ingest pipeline enabled. */ public boolean hasIndexRequestsWithPipelines() { for (DocWriteRequest actionRequest : requests) { if (actionRequest instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) actionRequest; if (Strings.hasText(indexRequest.getPipeline())) { return true; } } } return false; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (requests.isEmpty()) { validationException = addValidationError("no requests added", validationException); } for (DocWriteRequest request : requests) { // We first check if refresh has been set if (((WriteRequest<?>) request).getRefreshPolicy() != RefreshPolicy.NONE) { validationException = addValidationError( "RefreshPolicy is not supported on an item request. Set it on the BulkRequest instead.", validationException); } ActionRequestValidationException ex = ((WriteRequest<?>) request).validate(); if (ex != null) { if (validationException == null) { validationException = new ActionRequestValidationException(); } validationException.addValidationErrors(ex.validationErrors()); } } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); waitForActiveShards = ActiveShardCount.readFrom(in); int size = in.readVInt(); for (int i = 0; i < size; i++) { requests.add(DocWriteRequest.readDocumentRequest(in)); } refreshPolicy = RefreshPolicy.readFrom(in); timeout = new TimeValue(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); waitForActiveShards.writeTo(out); out.writeVInt(requests.size()); for (DocWriteRequest request : requests) { DocWriteRequest.writeDocumentRequest(out, request); } refreshPolicy.writeTo(out); timeout.writeTo(out); } @Override public String getDescription() { return "requests[" + requests.size() + "], indices[" + Strings.collectionToDelimitedString(indices, ", ") + "]"; } }
apache-2.0
googleapis/java-automl
proto-google-cloud-automl-v1/src/main/java/com/google/cloud/automl/v1/AnnotationSpecOrBuilder.java
2549
/* * Copyright 2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/automl/v1/annotation_spec.proto package com.google.cloud.automl.v1; public interface AnnotationSpecOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.automl.v1.AnnotationSpec) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Output only. Resource name of the annotation spec. * Form: * 'projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/annotationSpecs/{annotation_spec_id}' * </pre> * * <code>string name = 1;</code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * Output only. Resource name of the annotation spec. * Form: * 'projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/annotationSpecs/{annotation_spec_id}' * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * Required. The name of the annotation spec to show in the interface. The name can be * up to 32 characters long and must match the regexp `[a-zA-Z0-9_]+`. * </pre> * * <code>string display_name = 2;</code> * * @return The displayName. */ java.lang.String getDisplayName(); /** * * * <pre> * Required. The name of the annotation spec to show in the interface. The name can be * up to 32 characters long and must match the regexp `[a-zA-Z0-9_]+`. * </pre> * * <code>string display_name = 2;</code> * * @return The bytes for displayName. */ com.google.protobuf.ByteString getDisplayNameBytes(); /** * * * <pre> * Output only. The number of examples in the parent dataset * labeled by the annotation spec. * </pre> * * <code>int32 example_count = 9;</code> * * @return The exampleCount. */ int getExampleCount(); }
apache-2.0
intellimate/IzouSDK
src/main/java/org/intellimate/izou/sdk/events/Event.java
9531
package org.intellimate.izou.sdk.events; import org.intellimate.izou.events.EventBehaviourControllerModel; import org.intellimate.izou.events.EventLifeCycle; import org.intellimate.izou.events.EventModel; import org.intellimate.izou.identification.Identification; import org.intellimate.izou.resource.ListResourceProvider; import org.intellimate.izou.resource.ResourceModel; import org.intellimate.izou.sdk.resource.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; /** * This class represents an Event. * This class is immutable! for every change it will return an new instance! */ public class Event implements EventModel<Event> { private final String type; private final Identification source; private final List<String> descriptors; private final ListResourceProvider listResourceContainer; private final EventBehaviourController eventBehaviourController; private final ConcurrentHashMap<EventLifeCycle, List<Consumer<EventLifeCycle>>> lifeCycleListeners = new ConcurrentHashMap<>(); /** * Creates a new Event Object * @param type the Type of the Event, try to use the predefined Event types * @param source the source of the Event, most likely a this reference. * @param descriptors the descriptors to initialize the Event with * @throws IllegalArgumentException if one of the Arguments is null or empty */ protected Event(String type, Identification source, List<String> descriptors) throws IllegalArgumentException { if(type == null || type.isEmpty()) throw new IllegalArgumentException("illegal type"); if(source == null) throw new IllegalArgumentException("source is null"); this.type = type; this.source = source; this.descriptors = Collections.unmodifiableList(descriptors); listResourceContainer = new ListResourceProviderImpl(); eventBehaviourController = new EventBehaviourController(); } /** * Creates a new Event Object * @param type the Type of the Event, try to use the predefined Event types * @param source the source of the Event, most likely a this reference. * @param listResourceContainer the ResourceContainer * @param descriptors the descriptors to initialize the Event with * @param eventBehaviourController the Controller of the Event * @throws IllegalArgumentException if one of the Arguments is null or empty */ protected Event(String type, Identification source, ListResourceProvider listResourceContainer, List<String> descriptors, EventBehaviourController eventBehaviourController)throws IllegalArgumentException { if(type == null || type.isEmpty()) throw new IllegalArgumentException("illegal type"); if(source == null) throw new IllegalArgumentException("source is null"); this.type = type; this.source = source; this.descriptors = Collections.unmodifiableList(new ArrayList<>(descriptors)); this.listResourceContainer = listResourceContainer; this.eventBehaviourController = eventBehaviourController; } /** * Creates a new Event Object * @param type the Type of the Event, try to use the predefined Event types * @param source the source of the Event, most likely a this reference. * @return an Optional, that may be empty if type is null or empty or source is null */ public static Optional<Event> createEvent(String type, Identification source) { try { return Optional.of(new Event(type, source, new ArrayList<>())); } catch (IllegalArgumentException e) { return Optional.empty(); } } /** * Creates a new Event Object * @param type the Type of the Event, try to use the predefined Event types * @param source the source of the Event, most likely a this reference. * @param descriptors the descriptors * @return an Optional, that may be empty if type is null or empty or source is null */ public static Optional<Event> createEvent(String type, Identification source, List<String> descriptors) { try { return Optional.of(new Event(type, source, descriptors)); } catch (IllegalArgumentException e) { return Optional.empty(); } } /** * The ID of the Event. * It describes the Type of the Event. * @return A String containing an ID */ @Override public String getID() { return type; } /** * The type of the Event. * It describes the Type of the Event. * @return A String containing an ID */ @Override public String getType() { return type; } /** * returns the Source of the Event, e.g. the object who fired it. * @return an identifiable */ @Override public Identification getSource() { return source; } /** * returns all the Resources the Event currently has * @return an instance of ListResourceContainer */ @Override public ListResourceProvider getListResourceContainer() { return listResourceContainer; } /** * adds a Resource to the Container * @param resource an instance of the resource to add * @return the resulting Event (which is the same instance) */ @Override public Event addResource(ResourceModel resource) { listResourceContainer.addResource(resource); return this; } /** * adds a List of Resources to the Container * @param resources a list containing all the resources */ @Override public Event addResources(List<ResourceModel> resources) { listResourceContainer.addResource(resources); return this; } /** * returns a List containing all the Descriptors. * @return a List containing the Descriptors */ @Override public List<String> getDescriptors() { return descriptors; } /** * returns a List containing all the Descriptors and the type. * @return a List containing the Descriptors */ @Override public List<String> getAllInformations() { ArrayList<String> strings = new ArrayList<>(descriptors); strings.add(type); return strings; } /** * sets the Descriptors (but not the Event-Type). * <p> * Replaces all existing descriptors. * Since Event is immutable, it will create a new Instance. * </p> * @param descriptors a List containing all the Descriptors * @return the resulting Event (which is the same instance) */ public Event setDescriptors(List<String> descriptors) { return new Event(getType(), getSource(), descriptors); } /** * sets the Descriptors (but not the Event-Type). * @param descriptor a String describing the Event. * @return the resulting Event (which is the same instance) */ public Event addDescriptor(String descriptor) { List<String> newDescriptors = new ArrayList<>(); newDescriptors.addAll(descriptors); newDescriptors.add(descriptor); return new Event(getType(), getSource(), newDescriptors); } /** * replaces the Descriptors * @param descriptors a list containing the Descriptors. * @return the resulting Event (which is the same instance) */ public Event replaceDescriptors(List<String> descriptors) { return new Event(getType(), getSource(), descriptors); } /** * returns whether the event contains the specific descriptor. * this method also checks whether it matches the type. * @param descriptor a String with the ID of the Descriptor * @return boolean when the Event contains the descriptor, false when not. */ @Override public boolean containsDescriptor(String descriptor) { return descriptors.contains(descriptor) || type.equals(descriptor); } /** * returns the associated EventBehaviourController * @return an instance of EventBehaviourController */ @Override public EventBehaviourControllerModel getEventBehaviourController() { return eventBehaviourController; } @Override public void lifecycleCallback(EventLifeCycle eventLifeCycle) { lifeCycleListeners.getOrDefault(eventLifeCycle, new LinkedList<>()).stream() .forEach(eventLifeCycleConsumer -> eventLifeCycleConsumer.accept(eventLifeCycle)); } /** * adds the Consumer to the specified EventLifeCycle. * In its current implementation the invocation of the Callback method is parallel, but the notificaton of the listners not. * @param eventLifeCycle the EventLifeCycle to target * @param cycleCallback the callback */ @SuppressWarnings("unused") public Event addEventLifeCycleListener(EventLifeCycle eventLifeCycle, Consumer<EventLifeCycle> cycleCallback) { lifeCycleListeners.compute(eventLifeCycle, (unused, list) -> { if (list == null) list = new ArrayList<>(); list.add(cycleCallback); return list; }); return this; } @Override public String toString() { return "Event{" + "type='" + type + '\'' + ", source=" + source + ", descriptors=" + descriptors + ", listResourceContainer=" + listResourceContainer + '}'; } }
apache-2.0
phonedeck/gcm4j
src/main/java/com/phonedeck/gcm4j/DefaultConnectionFactory.java
402
package com.phonedeck.gcm4j; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * Connection Factory that uses {@link URL#openConnection()}. * */ public class DefaultConnectionFactory implements ConnectionFactory { @Override public HttpURLConnection open(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); } }
apache-2.0
kejunxia/AndroidMvc
library/android-mvc-test/src/main/java/com/shipdream/lib/android/mvc/view/viewpager/BaseTabFragment.java
2856
/* * Copyright 2016 Kejun Xia * * 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.shipdream.lib.android.mvc.view.viewpager; import android.os.Bundle; import android.view.View; import com.shipdream.lib.android.mvc.FragmentController; import com.shipdream.lib.android.mvc.MvcFragment; import com.shipdream.lib.android.mvc.Reason; import com.shipdream.lib.android.mvc.view.help.LifeCycleMonitor; public abstract class BaseTabFragment<C extends FragmentController> extends MvcFragment<C> { protected abstract LifeCycleMonitor getLifeCycleMonitor(); @Override public void onViewReady(View view, Bundle savedInstanceState, Reason reason) { getLifeCycleMonitor().onCreateView(view, savedInstanceState); getLifeCycleMonitor().onViewCreated(view, savedInstanceState); super.onViewReady(view, savedInstanceState, reason); getLifeCycleMonitor().onViewReady(view, savedInstanceState, reason); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getLifeCycleMonitor().onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); getLifeCycleMonitor().onResume(); } @Override protected void onReturnForeground() { super.onReturnForeground(); getLifeCycleMonitor().onReturnForeground(); } @Override protected void onPushToBackStack() { super.onPushToBackStack(); getLifeCycleMonitor().onPushToBackStack(); } @Override protected void onPopAway() { super.onPopAway(); getLifeCycleMonitor().onPopAway(); } @Override protected void onPoppedOutToFront() { super.onPoppedOutToFront(); getLifeCycleMonitor().onPoppedOutToFront(); } @Override protected void onOrientationChanged(int lastOrientation, int currentOrientation) { super.onOrientationChanged(lastOrientation, currentOrientation); getLifeCycleMonitor().onOrientationChanged(lastOrientation, currentOrientation); } @Override public void onDestroyView() { super.onDestroyView(); getLifeCycleMonitor().onDestroyView(); } @Override public void onDestroy() { getLifeCycleMonitor().onDestroy(); super.onDestroy(); } }
apache-2.0
Blaxcraft/MineRad
src/main/java/us/mcsw/minerad/blocks/BlockMicrowave.java
1325
package us.mcsw.minerad.blocks; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import us.mcsw.core.BlockMR; import us.mcsw.minerad.ref.TextureReference; import us.mcsw.minerad.tiles.TileMicrowave; public class BlockMicrowave extends BlockMR implements ITileEntityProvider { IIcon active = null; public BlockMicrowave() { super(Material.iron, "microwave"); setHardness(4.0f); isBlockContainer = true; } @Override public TileEntity createNewTileEntity(World w, int m) { return new TileMicrowave(); } @Override public void registerBlockIcons(IIconRegister reg) { super.registerBlockIcons(reg); active = reg.registerIcon(TextureReference.RESOURCE_PREFIX + "microwaveOn"); } @Override public IIcon getIcon(IBlockAccess ba, int x, int y, int z, int m) { TileEntity te = ba.getTileEntity(x, y, z); if (te != null && te instanceof TileMicrowave) { TileMicrowave tm = (TileMicrowave) te; if (tm.isRunning()) { return active; } } return super.getIcon(ba, x, y, z, m); } }
apache-2.0
inkstand-io/scribble
scribble-security/src/main/java/io/inkstand/scribble/security/SimpleUserPrincipal.java
1122
/* * Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch * * 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.inkstand.scribble.security; import java.security.Principal; /** * A Principal to be used in test that carries a username information. * * @author <a href="mailto:gerald.muecke@gmail.com">Gerald M&uuml;cke</a> * */ public class SimpleUserPrincipal implements Principal { private final String name; public SimpleUserPrincipal(final String name) { super(); this.name = name; } @Override public String getName() { return this.name; } }
apache-2.0
3dcitydb/importer-exporter
impexp-core/src/main/java/org/citydb/core/operation/importer/filter/type/FeatureTypeFilter.java
4449
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * 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.citydb.core.operation.importer.filter.type; import org.citydb.core.database.schema.mapping.*; import org.citydb.core.query.filter.FilterException; import javax.xml.namespace.QName; import java.util.HashSet; import java.util.List; import java.util.Set; public class FeatureTypeFilter { private final SchemaMapping schemaMapping; private final Set<QName> typeNames = new HashSet<>(); private final Set<FeatureType> featureTypes = new HashSet<>(); public FeatureTypeFilter(SchemaMapping schemaMapping) { this.schemaMapping = schemaMapping; } public FeatureTypeFilter(QName typeName, SchemaMapping schemaMapping) { this(schemaMapping); addFeatureType(typeName); } public FeatureTypeFilter(List<QName> typeNames, SchemaMapping schemaMapping) { this(schemaMapping); typeNames.forEach(this::addFeatureType); } public FeatureTypeFilter(org.citydb.config.project.query.filter.type.FeatureTypeFilter typeFilter, SchemaMapping schemaMapping) throws FilterException { if (typeFilter == null) throw new FilterException("The feature type filter must not be null."); this.schemaMapping = schemaMapping; typeFilter.getTypeNames().forEach(this::addFeatureType); } public void addFeatureType(QName typeName) { typeNames.add(typeName); FeatureType featureType = schemaMapping.getFeatureType(typeName); if (featureType != null) featureTypes.add(featureType); } public boolean isSatisfiedBy(QName name, boolean allowFlatHierarchies) { if (typeNames.isEmpty() || typeNames.contains(name)) return true; if (allowFlatHierarchies) { // if flat hierarchies shall be supported, we check whether the // feature to be tested can be represented as nested feature // of at least one of the features given in the filter settings. // if so, the nested feature passes this filter. FeatureType candidate = schemaMapping.getFeatureType(name); if (candidate != null) { Set<FeatureType> visitedFeatures = new HashSet<>(); Set<FeatureProperty> visitedProperties = new HashSet<>(); for (FeatureType parent : featureTypes) { if (isPartOf(parent, candidate, visitedFeatures, visitedProperties)) { typeNames.add(name); return true; } } } } return false; } private boolean isPartOf(FeatureType parent, FeatureType candidate, Set<FeatureType> visitedFeatures, Set<FeatureProperty> visitedProperties) { visitedFeatures.add(parent); for (AbstractProperty property : parent.listProperties(false, true)) { if (property.getElementType() != PathElementType.FEATURE_PROPERTY) continue; FeatureProperty featureProperty = (FeatureProperty) property; if (!visitedProperties.add(featureProperty)) continue; FeatureType target = featureProperty.getType(); // we do not accept the feature property if it may contain top-level features; // otherwise we would allow any feature to bypass the given filter settings if (target.isAbstract() && target.listSubTypes(true).stream().anyMatch(FeatureType::isTopLevel)) continue; if (candidate.isEqualToOrSubTypeOf(target)) return true; if (visitedFeatures.add(target) && isPartOf(target, candidate, visitedFeatures, visitedProperties)) return true; for (FeatureType subType : target.listSubTypes(true)) { if (visitedFeatures.add(subType) && isPartOf(subType, candidate, visitedFeatures, visitedProperties)) return true; } } return false; } }
apache-2.0
R2RMLManuelFernandez/R2RML
src/view/menu/ontology/OpenOntologyIRI.java
12983
/* * Copyright 2015 Manuel Fernández Pérez * * 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 view.menu.ontology; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import model.menu.bookmarks.OntologySource; import model.menu.bookmarks.StaXListOntologySourcesParser; import model.menu.bookmarks.StaXListOntologySourcesWriter; import net.miginfocom.swing.MigLayout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import view.util.PreferencesMediator; /** * Opens an ontology from its IRI * * @author Manuel Fernandez Perez * */ public class OpenOntologyIRI extends JDialog { private static final long serialVersionUID = -3632433535651195352L; private JPanel contentPane; private JLabel labelOntologyIRI; private JTextField textFieldOntologyIRI; private JLabel labelOr; private JLabel labelSelectBookmark; private JButton buttonAddToBookmarks; private JButton buttonDeleteBookmark; private JButton buttonImportBookmarks; private JFileChooser fileChooserImportBookmarks; private JButton buttonExportBookmarks; private JFileChooser fileChooserExportBookmarks; private JList<String> listBookMark; private JScrollPane scrollPaneListBookMark; private JButton buttonNext; private JButton buttonCancel; private StaXListOntologySourcesParser bookmarkParser; private StaXListOntologySourcesWriter bookmarkWriter; private PreferencesMediator prefs; @SuppressWarnings("unused") private static Logger logger = LoggerFactory.getLogger(OpenOntologyIRI.class); /** * Create the dialog. * @param prefs */ public OpenOntologyIRI(JFrame frame, PreferencesMediator prefs) { super(frame, true); this.prefs = prefs; initialize(); } /** * Initialize the contents of the dialog. */ private void initialize() { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setBounds(100, 100, 550, 450); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new MigLayout("", "[20.00][][]", "[][][][10.00][][50px:50,grow][][][]")); labelOntologyIRI = new JLabel("Insert Ontology IRI: "); contentPane.add(labelOntologyIRI, "cell 1 1,alignx center"); textFieldOntologyIRI = new JTextField(); contentPane.add(textFieldOntologyIRI, "cell 2 1,growx"); textFieldOntologyIRI.setColumns(10); labelOr = new JLabel("Or"); labelOr.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(labelOr, "cell 1 2,alignx center"); buttonAddToBookmarks = new JButton("Add To Bookmarks"); buttonAddToBookmarks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { buttonAddBookmarkActionPerformed(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); contentPane.add(buttonAddToBookmarks, "cell 2 2,alignx trailing,aligny top"); labelSelectBookmark = new JLabel("Select Bookmark: "); labelSelectBookmark.setVerticalAlignment(SwingConstants.TOP); contentPane.add(labelSelectBookmark, "cell 1 4,alignx center,aligny top"); scrollPaneListBookMark = new JScrollPane(); contentPane.add(scrollPaneListBookMark, "cell 2 4 1 2,grow"); listBookMark = new JList<String>(); listBookMark.setModel(new DefaultListModel<String>()); listBookMark.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { listBookmarkValueChanged(e); } }); scrollPaneListBookMark.setViewportView(listBookMark); listBookMark.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); readBookmarks(); buttonDeleteBookmark = new JButton("Delete Bookmark"); buttonDeleteBookmark.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { buttonDeleteBookmarkActionPerformed(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); contentPane.add(buttonDeleteBookmark, "flowx,cell 2 6,alignx right"); fileChooserImportBookmarks = new JFileChooser(prefs.getMostRecentInputBookmarksFilePathVal()); buttonImportBookmarks = new JButton("Import Bookmarks"); buttonImportBookmarks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { buttonImportBookmarksActionPerformed(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); contentPane.add(buttonImportBookmarks, "cell 2 6"); fileChooserExportBookmarks = new JFileChooser(prefs.getMostRecentOutputBookmarksFilePathVal()); buttonExportBookmarks = new JButton("Export Bookmarks"); buttonExportBookmarks.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { buttonExportBookmarksActionPerformed(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); contentPane.add(buttonExportBookmarks, "cell 2 6"); buttonNext = new JButton("Next ..."); buttonNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonNextActionPerformed(e); } }); contentPane.add(buttonNext, "flowx,cell 2 8,alignx trailing"); buttonCancel = new JButton("Cancel"); buttonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonCancelActionPerformed(e); } }); contentPane.add(buttonCancel, "cell 2 8,alignx trailing"); } /** * loads the bookmark from the bookmark list onto the ontology text field * * @param le */ protected void listBookmarkValueChanged(ListSelectionEvent le) { if (!le.getValueIsAdjusting()) { String selected = listBookMark.getSelectedValue(); textFieldOntologyIRI.setText(selected); } } /** * Adds a bokkmark to the bookmark list and updates the XML bookmark file. * * @param ae * @throws Exception */ private void buttonAddBookmarkActionPerformed(ActionEvent ae) throws Exception { String bookmarkToAdd = textFieldOntologyIRI.getText(); if (!(bookmarkToAdd.equals(""))) { DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); listModel.addElement(bookmarkToAdd); writeBookmarks(); } else { JOptionPane.showMessageDialog(this, "Please enter an IRI to add to bookmarks", "Enter an IRI", JOptionPane.WARNING_MESSAGE); } } /** * Delete a bokkmark from the bookmark list and updates the XML bookmark file. * * @param ae * @throws Exception */ private void buttonDeleteBookmarkActionPerformed(ActionEvent ae) throws Exception { String bookmarkToDelete = listBookMark.getSelectedValue(); if (bookmarkToDelete != null) { DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); listModel.removeElement(bookmarkToDelete); writeBookmarks(); } else { JOptionPane.showMessageDialog(this, "Please select a bookmark to delete", "Select a bookmark", JOptionPane.WARNING_MESSAGE); } } /** * Loads the bookmarks from an XML file into the bookmark list and updates the XML bookmark file * * @param e * @throws Exception */ protected void buttonImportBookmarksActionPerformed(ActionEvent e) throws Exception { int result = fileChooserImportBookmarks.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { prefs.setMostRecentInputBookmarksFilePathVal(fileChooserImportBookmarks.getSelectedFile().getPath()); StaXListOntologySourcesParser importBookmarkParser = new StaXListOntologySourcesParser("ontology", "iri", fileChooserImportBookmarks.getSelectedFile().getPath()); List<OntologySource> readBookmarks = importBookmarkParser.read(); if (!readBookmarks.isEmpty()) { for (OntologySource bookmark: readBookmarks) { DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); listModel.addElement(bookmark.toString()); } writeBookmarks(); } else { JOptionPane.showMessageDialog(this, "The selected file doesnt content any ontology bookmark", "Select a file", JOptionPane.WARNING_MESSAGE); } } } /** * Exports the bookmarks from the bookmark list to an an XML file * * @param ae * @throws Exception */ private void buttonExportBookmarksActionPerformed(ActionEvent ae) throws Exception { int result = fileChooserExportBookmarks.showSaveDialog(null); if (result == JFileChooser.APPROVE_OPTION) { prefs.setMostRecentOutputBookmarksFilePathVal(fileChooserExportBookmarks.getSelectedFile().getPath()); StaXListOntologySourcesWriter exportBookmarkWriter = new StaXListOntologySourcesWriter("bookmarks", "iri", fileChooserExportBookmarks.getSelectedFile().getPath()); ArrayList<String> bookmarksToWrite = new ArrayList<String>(0); DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); int bookmarksSize = listModel.size(); for (int i = 0; i < bookmarksSize; i++) { bookmarksToWrite.add(listModel.get(i)); } exportBookmarkWriter.save(bookmarksToWrite); } } /** * Returns the control to the parent component. A valid ontology IRI is in the text field * * @param ae */ private void buttonNextActionPerformed(ActionEvent ae) { if (textFieldOntologyIRI.getText().isEmpty()) { JOptionPane.showMessageDialog(this, "Please, enter an ontology IRI", "Enter an IRI", JOptionPane.WARNING_MESSAGE); } else { this.dispose(); } } /** * Cancels the action in progres and returns the control to the parent component * * @param ae */ private void buttonCancelActionPerformed(ActionEvent ae) { this.dispose(); } /** * Load the bookmarks from the XML bookmark file into the bookmark list */ private void readBookmarks() { bookmarkParser= new StaXListOntologySourcesParser("ontology", "iri", "resources/xmls/Bookmarks.xml"); List<OntologySource> readBookmarks = bookmarkParser.read(); if (!readBookmarks.isEmpty()) { for (OntologySource bookmark: readBookmarks) { DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); listModel.addElement(bookmark.getSource()); } } } /** * Writes the bookmarks from the bookmark list into the XML bookmark file * * @throws Exception */ private void writeBookmarks() throws Exception { bookmarkWriter= new StaXListOntologySourcesWriter("bookmarks", "iri", "resources/xmls/Bookmarks.xml"); ArrayList<String> bookmarksToWrite = new ArrayList<String>(0); DefaultListModel<String> listModel = (DefaultListModel<String>) listBookMark.getModel(); int bookmarksSize = listModel.size(); for (int i = 0; i < bookmarksSize; i++) { bookmarksToWrite.add(listModel.get(i)); } bookmarkWriter.save(bookmarksToWrite); } /** * Returns the IRI of the ontology * * @return */ public String getOntologyIRI() { return textFieldOntologyIRI.getText().trim(); } }
apache-2.0
bcopeland/hbase-thrift
src/main/java/org/apache/hadoop/hbase/client/coprocessor/Exec.java
4921
/* * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client.coprocessor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Row; import org.apache.hadoop.hbase.io.HbaseObjectWritable; import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.ipc.Invocation; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Classes; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.reflect.Method; /** * Represents an arbitrary method invocation against a Coprocessor * instance. In order for a coprocessor implementation to be remotely callable * by clients, it must define and implement a {@link CoprocessorProtocol} * subclass. Only methods defined in the {@code CoprocessorProtocol} interface * will be callable by clients. * * <p> * This class is used internally by * {@link org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)} * to wrap the {@code CoprocessorProtocol} method invocations requested in * RPC calls. It should not be used directly by HBase clients. * </p> * * @see ExecResult * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call) * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback) */ public class Exec extends Invocation implements Row { private Configuration conf = HBaseConfiguration.create(); /** Row key used as a reference for any region lookups */ private byte[] referenceRow; private Class<? extends CoprocessorProtocol> protocol; public Exec() { } public Exec(Configuration configuration, byte[] row, Class<? extends CoprocessorProtocol> protocol, Method method, Object[] parameters) { super(method, parameters); this.conf = configuration; this.referenceRow = row; this.protocol = protocol; } public Class<? extends CoprocessorProtocol> getProtocol() { return protocol; } public byte[] getRow() { return referenceRow; } public int compareTo(Row row) { return Bytes.compareTo(referenceRow, row.getRow()); } @Override public void write(DataOutput out) throws IOException { // fields for Invocation out.writeUTF(this.methodName); out.writeInt(parameterClasses.length); for (int i = 0; i < parameterClasses.length; i++) { HbaseObjectWritable.writeObject(out, parameters[i], parameters[i] != null ? parameters[i].getClass() : parameterClasses[i], conf); out.writeUTF(parameterClasses[i].getName()); } // fields for Exec Bytes.writeByteArray(out, referenceRow); out.writeUTF(protocol.getName()); } @Override public void readFields(DataInput in) throws IOException { // fields for Invocation methodName = in.readUTF(); parameters = new Object[in.readInt()]; parameterClasses = new Class[parameters.length]; HbaseObjectWritable objectWritable = new HbaseObjectWritable(); for (int i = 0; i < parameters.length; i++) { parameters[i] = HbaseObjectWritable.readObject(in, objectWritable, this.conf); String parameterClassName = in.readUTF(); try { parameterClasses[i] = Classes.extendedForName(parameterClassName); } catch (ClassNotFoundException e) { throw new IOException("Couldn't find class: " + parameterClassName); } } // fields for Exec referenceRow = Bytes.readByteArray(in); String protocolName = in.readUTF(); try { protocol = (Class<CoprocessorProtocol>)conf.getClassByName(protocolName); } catch (ClassNotFoundException cnfe) { throw new IOException("Protocol class "+protocolName+" not found", cnfe); } } }
apache-2.0
SweetyDonut/java_pft
Sandbox/src/main/java/ru/stqa/pft/sandbox/Square.java
230
package ru.stqa.pft.sandbox; /** * Created by Даниил on 06.05.2017. */ public class Square { public double l; public Square(double l) { this.l = l; } public double area() { return this.l * this.l; } }
apache-2.0
liuxing521a/xcnet
xcnet-common/src/main/java/org/itas/xcnet/common/serialize/support/java/JavaObjectOutput.java
2605
/* * Copyright 2014-2015 itas group * * 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.itas.xcnet.common.serialize.support.java; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import org.itas.xcnet.common.serialize.ObjectOutput; /** * Java Object output. * * @author liuzhen<liuxing521a@163.com> * @createTime 2015年5月15日下午3:10:18 */ public class JavaObjectOutput implements ObjectOutput { private final ObjectOutputStream out; public JavaObjectOutput(OutputStream os) throws IOException { out = new ObjectOutputStream(os); } public JavaObjectOutput(OutputStream os, boolean compact) throws IOException { out = compact ? new CompactedObjectOutputStream(os) : new ObjectOutputStream(os); } @Override public void writeBool(boolean v) throws IOException { out.writeBoolean(v); } @Override public void writeByte(byte v) throws IOException { out.writeByte(v); } @Override public void writeShort(short v) throws IOException { out.writeShort(v); } @Override public void writeInt(int v) throws IOException { out.writeInt(v); } @Override public void writeLong(long v) throws IOException { out.writeLong(v); } @Override public void writeFloat(float v) throws IOException { out.writeFloat(v); } @Override public void writeDouble(double v) throws IOException { out.writeDouble(v); } @Override public void writeBytes(byte[] v) throws IOException { if (v == null) out.writeInt(-1); else out.write(v); } @Override public void writeBytes(byte[] v, int off, int len) throws IOException { out.writeInt(len); out.write(v, off, len); } @Override public void writeUTF8(String v) throws IOException { if (v == null) { out.writeInt(-1); } else { out.writeInt(v.length()); out.writeUTF(v); } } @Override public void writeObject(Object o) throws IOException { if (o == null) { out.writeInt(-1); } else { out.writeInt(1); out.writeObject(o); } } @Override public void flushBuffer() throws IOException { out.flush(); } }
apache-2.0
dengdunan/MobileSafe
app/src/main/java/mobilesafe/dda/com/activity/EnterPwdActivity.java
6857
package mobilesafe.dda.com.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.dda.mobilesafe.utils.UIUtils; /** * Created by nuo on 2016/6/28. * Created by 11:27. * 描述:输入密码的界面 */ public class EnterPwdActivity extends Activity implements OnClickListener { private EditText et_pwd; private Button bt_0; private Button bt_1; private Button bt_2; private Button bt_3; private Button bt_4; private Button bt_5; private Button bt_6; private Button bt_7; private Button bt_8; private Button bt_9; private Button bt_clean_all; private Button bt_delete; private Button bt_ok; private String packageName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_pwd); initUI(); } private void initUI() { Intent intent = getIntent(); if (intent != null) { packageName = intent.getStringExtra("packageName"); } et_pwd = (EditText) findViewById(R.id.et_pwd); bt_0 = (Button) findViewById(R.id.bt_0); bt_1 = (Button) findViewById(R.id.bt_1); bt_2 = (Button) findViewById(R.id.bt_2); bt_3 = (Button) findViewById(R.id.bt_3); bt_4 = (Button) findViewById(R.id.bt_4); bt_5 = (Button) findViewById(R.id.bt_5); bt_6 = (Button) findViewById(R.id.bt_6); bt_7 = (Button) findViewById(R.id.bt_7); bt_8 = (Button) findViewById(R.id.bt_8); bt_9 = (Button) findViewById(R.id.bt_9); bt_ok = (Button) findViewById(R.id.bt_ok); bt_ok.setOnClickListener(this); bt_clean_all = (Button) findViewById(R.id.bt_clean_all); bt_delete = (Button) findViewById(R.id.bt_delete); //隐藏当前的键盘 et_pwd.setInputType(InputType.TYPE_NULL); // 清空 bt_clean_all.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { et_pwd.setText(""); } }); // 删除 bt_delete.setOnClickListener(new OnClickListener() { private String str; @Override public void onClick(View v) { str = et_pwd.getText().toString(); if (str.length() == 0) { return; } et_pwd.setText(str.substring(0, str.length() - 1)); } }); bt_0.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_0.getText().toString()); } }); bt_1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_1.getText().toString()); } }); bt_2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_2.getText().toString()); } }); bt_3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_3.getText().toString()); } }); bt_4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_4.getText().toString()); } }); bt_5.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_5.getText().toString()); } }); bt_6.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_6.getText().toString()); } }); bt_7.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_7.getText().toString()); } }); bt_8.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_8.getText().toString()); } }); bt_9.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String str = et_pwd.getText().toString(); et_pwd.setText(str + bt_9.getText().toString()); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_ok: String result = et_pwd.getText().toString(); if ("123".equals(result)) { // 如果密码正确。说明是自己人 /** * 是自己家人。不要拦截他 */ //System.out.println("密码输入正确"); Intent intent = new Intent(); // 发送广播。停止保护 intent.setAction("com.dda.mobilesafe.stopprotect"); // 跟狗说。现在停止保护信息 intent.putExtra("packageName", packageName); sendBroadcast(intent); finish(); } else { UIUtils.showToast(EnterPwdActivity.this, "密码错误"); } break; } } @Override public void onBackPressed() { // 当用户输入后退健 的时候。我们进入到桌面 Intent intent = new Intent(); intent.setAction("android.intent.action.MAIN"); intent.addCategory("android.intent.category.HOME"); intent.addCategory("android.intent.category.DEFAULT"); intent.addCategory("android.intent.category.MONKEY"); startActivity(intent); } }
apache-2.0
yext/closure-templates
java/src/com/google/template/soy/data/internal/AugmentedParamStore.java
2522
/* * Copyright 2013 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.google.template.soy.data.internal; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.template.soy.data.SoyRecord; import com.google.template.soy.data.SoyValueProvider; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Implementation of ParamStore that represents a backing store augmented with additional fields * (params). The additional fields may hide fields from the backing store. * * <p>Important: Do not use outside of Soy code (treat as superpackage-private). * */ public final class AugmentedParamStore extends ParamStore { /** The backing store (can be any SoyRecord, not necessarily ParamStore) being augmented. */ private final SoyRecord backingStore; /** The internal map holding the additional fields (params). */ private final Map<String, SoyValueProvider> localStore; public AugmentedParamStore(@Nullable SoyRecord backingStore, int expectedKeys) { this.backingStore = backingStore; this.localStore = Maps.newHashMapWithExpectedSize(expectedKeys); } @Override public AugmentedParamStore setField(String name, @Nonnull SoyValueProvider valueProvider) { Preconditions.checkNotNull(valueProvider); localStore.put(name, valueProvider); return this; } @Override public boolean hasField(String name) { return localStore.containsKey(name) || backingStore.hasField(name); } @Override public SoyValueProvider getFieldProvider(String name) { SoyValueProvider val = localStore.get(name); return (val != null) ? val : backingStore.getFieldProvider(name); } @Override public ImmutableMap<String, SoyValueProvider> recordAsMap() { return ImmutableMap.<String, SoyValueProvider>builder() .putAll(localStore) .putAll(backingStore.recordAsMap()) .build(); } }
apache-2.0
dlwhitehurst/MusicRecital
src/main/java/org/musicrecital/service/impl/RoleManagerImpl.java
1780
/** * Copyright 2014 David L. Whitehurst * * 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.musicrecital.service.impl; import org.musicrecital.dao.RoleDao; import org.musicrecital.model.Role; import org.musicrecital.service.RoleManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Implementation of RoleManager interface. * * @author <a href="mailto:dan@getrolling.com">Dan Kibler</a> */ @Service("roleManager") public class RoleManagerImpl extends GenericManagerImpl<Role, Long> implements RoleManager { RoleDao roleDao; @Autowired public RoleManagerImpl(RoleDao roleDao) { super(roleDao); this.roleDao = roleDao; } /** * {@inheritDoc} */ public List<Role> getRoles(Role role) { return dao.getAll(); } /** * {@inheritDoc} */ public Role getRole(String rolename) { return roleDao.getRoleByName(rolename); } /** * {@inheritDoc} */ public Role saveRole(Role role) { return dao.save(role); } /** * {@inheritDoc} */ public void removeRole(String rolename) { roleDao.removeRole(rolename); } }
apache-2.0
albertoteloko/wave-server
router/http/src/main/java/com/acs/wave/router/HTTPResponseBuilder.java
3696
package com.acs.wave.router; import com.acs.wave.router.constants.ProtocolVersion; import com.acs.wave.router.constants.RedirectStatus; import com.acs.wave.router.functional.BodyWriter; import com.acs.wave.router.constants.ResponseStatus; import com.acs.wave.utils.ExceptionUtils; import java.util.Optional; import static com.acs.wave.router.constants.ResponseStatus.OK; public class HTTPResponseBuilder { private ProtocolVersion protocolVersion; private ResponseStatus responseStatus; private HTTPHeaders headers; private byte[] body; private final HTTPRequest request; private final HTTPRouter httpRouter; HTTPResponseBuilder(HTTPRequest request, HTTPRouter httpRouter) { this(request, httpRouter, new HTTPHeaders()); } HTTPResponseBuilder(HTTPRequest request, HTTPRouter httpRouter, HTTPHeaders headers) { this.request = request; this.httpRouter = httpRouter; this.headers = headers; version(request.protocolVersion); status(OK); } public HTTPResponse build() { return new HTTPResponse(protocolVersion, responseStatus, headers, body); } public Optional<HTTPResponse> buildOption() { return Optional.of(build()); } public HTTPResponse redirect(String url) { return redirect(url, RedirectStatus.FOUND); } public Optional<HTTPResponse> redirectOption(String url) { return redirectOption(url, RedirectStatus.FOUND); } public HTTPResponse redirect(String url, RedirectStatus redirectStatus) { HTTPResponseBuilder responseBuilder = clone(); responseBuilder.header("Location", url); return httpRouter.getErrorResponse(request, responseBuilder, redirectStatus.status); } public Optional<HTTPResponse> redirectOption(String url, RedirectStatus status) { return Optional.of(redirect(url, status)); } public HTTPResponse error(ResponseStatus errorCode) { return httpRouter.getErrorResponse(request, this, errorCode); } public Optional<HTTPResponse> errorOption(ResponseStatus errorCode) { return Optional.of(error(errorCode)); } public HTTPResponse serve(String url) { return httpRouter.process(request.ofUri(url)); } public Optional<HTTPResponse> serveOption(String url) { return Optional.of(serve(url)); } public HTTPResponseBuilder header(String key, Object value) { headers.add(key, value); return this; } public HTTPResponseBuilder version(ProtocolVersion protocolVersion) { this.protocolVersion = protocolVersion; return this; } public HTTPResponseBuilder status(ResponseStatus responseStatus) { this.responseStatus = responseStatus; return this; } public HTTPResponseBuilder body(byte[] body) { this.body = body; return this; } public HTTPResponseBuilder body(String body) { this.body = stringToBytes(body); return this; } public <T> HTTPResponseBuilder body(T body, BodyWriter<T> converter) { this.body = converter.write(body); if (!headers.containsKey("Content-Type")) { header("Content-Type", converter.contentType()); } return this; } public HTTPResponseBuilder clone() { return new HTTPResponseBuilder(request, httpRouter, headers.clone()); } private byte[] stringToBytes(String string) { byte[] result = null; try { result = string.getBytes("UTF-8"); } catch (Exception e) { ExceptionUtils.throwRuntimeException(e); } return result; } }
apache-2.0
nengxu/OrientDB
server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/get/OServerCommandGetStaticContent.java
9117
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.server.network.protocol.http.command.get; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.server.config.OServerCommandConfiguration; import com.orientechnologies.orient.server.config.OServerEntryConfiguration; import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest; import com.orientechnologies.orient.server.network.protocol.http.OHttpResponse; import com.orientechnologies.orient.server.network.protocol.http.OHttpUtils; public class OServerCommandGetStaticContent extends OServerCommandConfigurableAbstract { private static final String[] DEF_PATTERN = { "GET|www", "GET|studio/", "GET|", "GET|*.htm", "GET|*.html", "GET|*.xml", "GET|*.jpeg", "GET|*.jpg", "GET|*.png", "GET|*.gif", "GET|*.js", "GET|*.otf", "GET|*.css", "GET|*.swf", "GET|favicon.ico", "GET|robots.txt" }; private static final String CONFIG_HTTP_CACHE = "http.cache:"; private static final String CONFIG_ROOT_PATH = "root.path"; private static final String CONFIG_FILE_PATH = "file.path"; private Map<String, OStaticContentCachedEntry> cacheContents; private Map<String, String> cacheHttp = new HashMap<String, String>(); private String cacheHttpDefault = "Cache-Control: max-age=3000"; private String rootPath; private String filePath; public OServerCommandGetStaticContent() { super(DEF_PATTERN); } public OServerCommandGetStaticContent(final OServerCommandConfiguration iConfiguration) { super(iConfiguration.pattern); // LOAD HTTP CACHE CONFIGURATION for (OServerEntryConfiguration par : iConfiguration.parameters) { if (par.name.startsWith(CONFIG_HTTP_CACHE)) { final String filter = par.name.substring(CONFIG_HTTP_CACHE.length()); if (filter.equalsIgnoreCase("default")) cacheHttpDefault = par.value; else if (filter.length() > 0) { final String[] filters = filter.split(" "); for (String f : filters) { cacheHttp.put(f, par.value); } } } else if (par.name.startsWith(CONFIG_ROOT_PATH)) rootPath = par.value; else if (par.name.startsWith(CONFIG_FILE_PATH)) filePath = par.value; } } @Override public boolean beforeExecute(OHttpRequest iRequest, OHttpResponse iResponse) throws IOException { String header = cacheHttpDefault; if (cacheHttp.size() > 0) { final String resource = getResource(iRequest); // SEARCH IN CACHE IF ANY for (Entry<String, String> entry : cacheHttp.entrySet()) { final int wildcardPos = entry.getKey().indexOf('*'); final String partLeft = entry.getKey().substring(0, wildcardPos); final String partRight = entry.getKey().substring(wildcardPos + 1); if (resource.startsWith(partLeft) && resource.endsWith(partRight)) { // FOUND header = entry.getValue(); break; } } } iResponse.setHeader(header); return true; } @Override public boolean execute(final OHttpRequest iRequest, final OHttpResponse iResponse) throws Exception { iRequest.data.commandInfo = "Get static content"; iRequest.data.commandDetail = iRequest.url; if (filePath == null && rootPath == null) { // GET GLOBAL CONFIG rootPath = iRequest.configuration.getValueAsString("orientdb.www.path", "src/site"); if (rootPath == null) { OLogManager.instance().warn(this, "No path configured. Specify the 'root.path', 'file.path' or the global 'orientdb.www.path' variable", rootPath); return false; } } if (filePath == null) { // CHECK DIRECTORY final File wwwPathDirectory = new File(rootPath); if (!wwwPathDirectory.exists()) OLogManager.instance().warn(this, "path variable points to '%s' but it doesn't exists", rootPath); if (!wwwPathDirectory.isDirectory()) OLogManager.instance().warn(this, "path variable points to '%s' but it isn't a directory", rootPath); } if (cacheContents == null && OGlobalConfiguration.SERVER_CACHE_FILE_STATIC.getValueAsBoolean()) // CREATE THE CACHE IF ENABLED cacheContents = new HashMap<String, OStaticContentCachedEntry>(); InputStream is = null; long contentSize = 0; String type = null; try { String path; if (filePath != null) // SINGLE FILE path = filePath; else { // GET FROM A DIRECTORY final String url = getResource(iRequest); if (url.startsWith("/www")) path = rootPath + url.substring("/www".length(), url.length()); else path = rootPath + url; } if (cacheContents != null) { synchronized (cacheContents) { final OStaticContentCachedEntry cachedEntry = cacheContents.get(path); if (cachedEntry != null) { is = new ByteArrayInputStream(cachedEntry.content); contentSize = cachedEntry.size; type = cachedEntry.type; } } } if (is == null) { File inputFile = new File(path); if (!inputFile.exists()) { OLogManager.instance().debug(this, "Static resource not found: %s", path); iResponse.sendStream(404, "File not found", null, null, 0); return false; } if (filePath == null && inputFile.isDirectory()) { inputFile = new File(path + "/index.htm"); if (inputFile.exists()) path = path + "/index.htm"; else { inputFile = new File(path + "/index.html"); if (inputFile.exists()) path = path + "/index.html"; } } if (path.endsWith(".htm") || path.endsWith(".html")) type = "text/html"; else if (path.endsWith(".png")) type = "image/png"; else if (path.endsWith(".jpeg")) type = "image/jpeg"; else if (path.endsWith(".js")) type = "application/x-javascript"; else if (path.endsWith(".css")) type = "text/css"; else if (path.endsWith(".ico")) type = "image/x-icon"; else if (path.endsWith(".otf")) type = "font/opentype"; else type = "text/plain"; is = new BufferedInputStream(new FileInputStream(inputFile)); contentSize = inputFile.length(); if (cacheContents != null) { // READ THE ENTIRE STREAM AND CACHE IT IN MEMORY final byte[] buffer = new byte[(int) contentSize]; for (int i = 0; i < contentSize; ++i) buffer[i] = (byte) is.read(); OStaticContentCachedEntry cachedEntry = new OStaticContentCachedEntry(); cachedEntry.content = buffer; cachedEntry.size = contentSize; cachedEntry.type = type; cacheContents.put(path, cachedEntry); is = new ByteArrayInputStream(cachedEntry.content); } } iResponse.sendStream(OHttpUtils.STATUS_OK_CODE, OHttpUtils.STATUS_OK_DESCRIPTION, type, is, contentSize); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { } } return false; } protected String getResource(final OHttpRequest iRequest) { final String url; if (OHttpUtils.URL_SEPARATOR.equals(iRequest.url)) url = "/www/index.htm"; else { int pos = iRequest.url.indexOf('?'); if (pos > -1) url = iRequest.url.substring(0, pos); else url = iRequest.url; } return url; } }
apache-2.0
argius/Stew4
src/net/argius/stew/command/Download.java
6380
package net.argius.stew.command; import static java.sql.Types.*; import java.io.*; import java.sql.*; import net.argius.stew.*; /** * The Download command used to save selected data to files. */ public final class Download extends Command { private static final Logger log = Logger.getLogger(Download.class); @Override public void execute(Connection conn, Parameter parameter) throws CommandException { if (!parameter.has(2)) { throw new UsageException(getUsage()); } final String root = parameter.at(1); final String sql = parameter.after(2); if (log.isDebugEnabled()) { log.debug("root: " + root); log.debug("SQL: " + sql); } try { Statement stmt = prepareStatement(conn, parameter.asString()); try { ResultSet rs = executeQuery(stmt, sql); try { download(rs, root); } finally { rs.close(); } } finally { stmt.close(); } } catch (IOException ex) { throw new CommandException(ex); } catch (SQLException ex) { throw new CommandException(ex); } } private void download(ResultSet rs, String root) throws IOException, SQLException { final int targetColumn = 1; ResultSetMetaData meta = rs.getMetaData(); final int columnCount = meta.getColumnCount(); assert columnCount >= 1; final int columnType = meta.getColumnType(targetColumn); final boolean isBinary; switch (columnType) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case FLOAT: case REAL: case DOUBLE: case NUMERIC: case DECIMAL: // numeric to string isBinary = false; break; case BOOLEAN: case BIT: case DATE: case TIME: case TIMESTAMP: // object to string isBinary = false; break; case BINARY: case VARBINARY: case LONGVARBINARY: case BLOB: // binary to stream isBinary = true; break; case CHAR: case VARCHAR: case LONGVARCHAR: case CLOB: // char to binary-stream isBinary = true; break; case OTHER: // ? to binary-stream (experimental) // (e.g.: XML) isBinary = true; break; case DATALINK: case JAVA_OBJECT: case DISTINCT: case STRUCT: case ARRAY: case REF: default: throw new CommandException(String.format("unsupported type: %d", columnType)); } byte[] buffer = new byte[(isBinary) ? 0x10000 : 0]; int count = 0; while (rs.next()) { ++count; StringBuilder fileName = new StringBuilder(); for (int i = 2; i <= columnCount; i++) { fileName.append(rs.getString(i)); } final File path = resolvePath(root); final File file = (columnCount == 1) ? path : new File(path, fileName.toString()); if (file.exists()) { throw new IOException(getMessage("e.file-already-exists", file.getAbsolutePath())); } if (isBinary) { InputStream is = rs.getBinaryStream(targetColumn); if (is == null) { mkdirs(file); if (!file.createNewFile()) { throw new IOException(getMessage("e.failed-create-new-file", file.getAbsolutePath())); } } else { try { mkdirs(file); OutputStream os = new FileOutputStream(file); try { while (true) { int readLength = is.read(buffer); if (readLength <= 0) { break; } os.write(buffer, 0, readLength); } } finally { os.close(); } } finally { is.close(); } } } else { mkdirs(file); PrintWriter out = new PrintWriter(file); try { out.print(rs.getObject(targetColumn)); } finally { out.close(); } } outputMessage("i.downloaded", getSizeString(file.length()), file); } outputMessage("i.selected", count); } private void mkdirs(File file) throws IOException { final File dir = file.getParentFile(); if (!dir.isDirectory()) { if (log.isDebugEnabled()) { log.debug(String.format("mkdir [%s]", dir.getAbsolutePath())); } if (dir.mkdirs()) { outputMessage("i.did-mkdir", dir); } else { throw new IOException(getMessage("e.failed-mkdir-filedir", file)); } } } static String getSizeString(long size) { if (size >= 512) { final double convertedSize; final String unit; if (size >= 536870912) { convertedSize = size * 1f / 1073741824f; unit = "GB"; } else if (size >= 524288) { convertedSize = size * 1f / 1048576f; unit = "MB"; } else { convertedSize = size * 1f / 1024f; unit = "KB"; } return String.format("%.3f", convertedSize).replaceFirst("\\.?0+$", "") + unit; } return String.format("%dbyte%s", size, size < 2 ? "" : "s"); } }
apache-2.0
ondrejvelisek/perun-wui
perun-wui-registrar/src/main/java/cz/metacentrum/perun/wui/registrar/widgets/items/PerunFormItem.java
3923
package cz.metacentrum.perun.wui.registrar.widgets.items; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Widget; import cz.metacentrum.perun.wui.json.Events; import cz.metacentrum.perun.wui.model.beans.ApplicationFormItemData; import cz.metacentrum.perun.wui.registrar.client.resources.PerunRegistrarTranslation; import cz.metacentrum.perun.wui.registrar.widgets.items.validators.PerunFormItemValidator; import org.gwtbootstrap3.client.ui.FormGroup; /** * Represents general form item. Encapsulate and view of ApplicationFormItemData returned from RPC. * * @author Ondrej Velisek <ondrejvelisek@gmail.com> */ public abstract class PerunFormItem extends FormGroup { private ApplicationFormItemData itemData; private String lang; PerunRegistrarTranslation translation; public PerunFormItem(ApplicationFormItemData itemData, String lang) { this.itemData = itemData; this.lang = lang; this.translation = GWT.create(PerunRegistrarTranslation.class); } /** * generate whole UI form item described in itemData. With all texts and functionality. * It will be added automatically to the DOM. Do not use add() method inside. * * @return specific FormItem describes in itemData. */ protected abstract Widget initFormItem(); protected PerunRegistrarTranslation getTranslation() { return translation; } public ApplicationFormItemData getItemData() { return itemData; } public String getLang() { return lang; } /** * Get current Value of item. It have to be consistent with Perun RPC documentation for each item. * It should be value which user see in the visible form. * * @return Value of item. */ public abstract String getValue(); /** * Set value (usually prefilled value). It have to be consistent with Perun RPC documentation for each item. * It should be displayed visible in the form. * FORM ITEM HAS TO HAVE PARENT WHEN YOU CALL THIS METHOD. use add(this). It is because refreshing of Select. * * @param value */ public abstract void setValue(String value); /** * Validate current value localy. It doesn't use Perun RPC. * Be carefull, because of it, true doesn't mean field is filled correctly. * It should visible show result of controll (e.g. color widget, red = error, green = success, ...) * * @return true if item is filled with valid value. */ public abstract boolean validateLocal(); /** * Validate current value localy and remotely. It can call Perun RPC. * It should visible show result of controll (e.g. color widget, red = error, green = success, ...) * * @param events callback events. */ public abstract void validate(Events<Boolean> events); /** * @return result of last validation. */ public abstract PerunFormItemValidator.Result getLastValidationResult(); /** * focus editable widget. * * @return true if item was focused, false if item cant be focused. (e.g. non editable static item) */ public abstract boolean focus(); /** * Safely return items label/description or if not defined than shortname. * If nothing defined, return empty string. * * @return items label or shortname */ public String getLabelOrShortName() { if (getItemData() == null) { return ""; } if (getItemData().getFormItem() != null) { if (getItemData().getFormItem().getItemTexts(getLang()) != null) { if ((getItemData().getFormItem().getItemTexts(getLang()).getLabel() != null) && (!getItemData().getFormItem().getItemTexts(getLang()).getLabel().isEmpty())) { return getItemData().getFormItem().getItemTexts(getLang()).getLabel(); } } if ((getItemData().getFormItem().getShortname() != null) && (!getItemData().getFormItem().getShortname().isEmpty())) { return getItemData().getFormItem().getShortname(); } } if (getItemData().getShortname() != null) { return getItemData().getShortname(); } return ""; } }
apache-2.0
amilamanoj/iotuc-miner
iot-miner-ws/src/test/java/de/tum/in/i17/iotminer/IotMinerApplicationTests.java
341
package de.tum.in.i17.iotminer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class IotMinerApplicationTests { @Test public void contextLoads() { } }
apache-2.0
bbxyard/bbxyard
yard/skills/66-java/spboot/src/main/java/com/imooc/config/MyWebMvcConfigure.java
1184
package com.imooc.config; import com.imooc.controller.interceptor.handlers.OneInterceptor; import com.imooc.controller.interceptor.handlers.TwoInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebMvcConfigure implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { /** * 单一hook */ registry.addInterceptor(new OneInterceptor()).addPathPatterns("/hook/one/**"); registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/hook/two/**"); /** * 拦截器,按顺序hook */ registry.addInterceptor(new OneInterceptor()).addPathPatterns("/hook/one-two/**"); registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/hook/one-two/**"); registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/hook/two-one/**"); registry.addInterceptor(new OneInterceptor()).addPathPatterns("/hook/two-one/**"); } }
apache-2.0
klyushnik/upcItemDB_Client
zxing/build/generated/source/r/androidTest/debug/com/google/zxing/client/android/R.java
12958
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.google.zxing.client.android; public final class R { public static final class array { public static final int country_codes = 0x7f070000; public static final int preferences_front_light_options = 0x7f070001; public static final int preferences_front_light_values = 0x7f070002; } public static final class color { public static final int contents_text = 0x7f080000; public static final int encode_view = 0x7f080001; public static final int possible_result_points = 0x7f080002; public static final int result_minor_text = 0x7f080003; public static final int result_points = 0x7f080004; public static final int result_text = 0x7f080005; public static final int result_view = 0x7f080006; public static final int status_text = 0x7f080007; public static final int transparent = 0x7f080008; public static final int viewfinder_laser = 0x7f080009; public static final int viewfinder_mask = 0x7f08000a; } public static final class dimen { public static final int half_padding = 0x7f090000; public static final int standard_padding = 0x7f090001; } public static final class drawable { public static final int launcher_icon = 0x7f020000; public static final int share_via_barcode = 0x7f020001; } public static final class id { public static final int app_picker_list_item_icon = 0x7f0a0007; public static final int app_picker_list_item_label = 0x7f0a0008; public static final int barcode_image_view = 0x7f0a000e; public static final int bookmark_title = 0x7f0a0009; public static final int bookmark_url = 0x7f0a000a; public static final int contents_supplement_text_view = 0x7f0a0015; public static final int contents_text_view = 0x7f0a0014; public static final int decode = 0x7f0a0000; public static final int decode_failed = 0x7f0a0001; public static final int decode_succeeded = 0x7f0a0002; public static final int format_text_view = 0x7f0a000f; public static final int help_contents = 0x7f0a0019; public static final int history_detail = 0x7f0a001b; public static final int history_title = 0x7f0a001a; public static final int image_view = 0x7f0a0018; public static final int launch_product_query = 0x7f0a0003; public static final int menu_encode = 0x7f0a002a; public static final int menu_help = 0x7f0a0029; public static final int menu_history = 0x7f0a0027; public static final int menu_history_clear_text = 0x7f0a002c; public static final int menu_history_send = 0x7f0a002b; public static final int menu_settings = 0x7f0a0028; public static final int menu_share = 0x7f0a0026; public static final int meta_text_view = 0x7f0a0013; public static final int meta_text_view_label = 0x7f0a0012; public static final int page_number_view = 0x7f0a001f; public static final int preview_view = 0x7f0a000b; public static final int query_button = 0x7f0a001d; public static final int query_text_view = 0x7f0a001c; public static final int quit = 0x7f0a0004; public static final int restart_preview = 0x7f0a0005; public static final int result_button_view = 0x7f0a0016; public static final int result_list_view = 0x7f0a001e; public static final int result_view = 0x7f0a000d; public static final int return_scan_result = 0x7f0a0006; public static final int share_app_button = 0x7f0a0021; public static final int share_bookmark_button = 0x7f0a0022; public static final int share_clipboard_button = 0x7f0a0024; public static final int share_contact_button = 0x7f0a0023; public static final int share_text_view = 0x7f0a0025; public static final int snippet_view = 0x7f0a0020; public static final int status_view = 0x7f0a0017; public static final int time_text_view = 0x7f0a0011; public static final int type_text_view = 0x7f0a0010; public static final int viewfinder_view = 0x7f0a000c; } public static final class layout { public static final int app_picker_list_item = 0x7f030000; public static final int bookmark_picker_list_item = 0x7f030001; public static final int capture = 0x7f030002; public static final int encode = 0x7f030003; public static final int help = 0x7f030004; public static final int history_list_item = 0x7f030005; public static final int search_book_contents = 0x7f030006; public static final int search_book_contents_header = 0x7f030007; public static final int search_book_contents_list_item = 0x7f030008; public static final int share = 0x7f030009; } public static final class menu { public static final int capture = 0x7f0c0000; public static final int encode = 0x7f0c0001; public static final int history = 0x7f0c0002; } public static final class raw { public static final int beep = 0x7f050000; } public static final class string { public static final int app_name = 0x7f060000; public static final int app_picker_name = 0x7f060001; public static final int bookmark_picker_name = 0x7f060002; public static final int button_add_calendar = 0x7f060003; public static final int button_add_contact = 0x7f060004; public static final int button_book_search = 0x7f060005; public static final int button_cancel = 0x7f060006; public static final int button_custom_product_search = 0x7f060007; public static final int button_dial = 0x7f060008; public static final int button_email = 0x7f060009; public static final int button_get_directions = 0x7f06000a; public static final int button_mms = 0x7f06000b; public static final int button_ok = 0x7f06000c; public static final int button_open_browser = 0x7f06000d; public static final int button_product_search = 0x7f06000e; public static final int button_search_book_contents = 0x7f06000f; public static final int button_share_app = 0x7f060010; public static final int button_share_bookmark = 0x7f060011; public static final int button_share_by_email = 0x7f060012; public static final int button_share_by_sms = 0x7f060013; public static final int button_share_clipboard = 0x7f060014; public static final int button_share_contact = 0x7f060015; public static final int button_show_map = 0x7f060016; public static final int button_sms = 0x7f060017; public static final int button_web_search = 0x7f060018; public static final int button_wifi = 0x7f060019; public static final int contents_contact = 0x7f06001a; public static final int contents_email = 0x7f06001b; public static final int contents_location = 0x7f06001c; public static final int contents_phone = 0x7f06001d; public static final int contents_sms = 0x7f06001e; public static final int contents_text = 0x7f06001f; public static final int history_clear_one_history_text = 0x7f060020; public static final int history_clear_text = 0x7f060021; public static final int history_email_title = 0x7f060022; public static final int history_empty = 0x7f060023; public static final int history_empty_detail = 0x7f060024; public static final int history_send = 0x7f060025; public static final int history_title = 0x7f060026; public static final int menu_encode_mecard = 0x7f060027; public static final int menu_encode_vcard = 0x7f060028; public static final int menu_help = 0x7f060029; public static final int menu_history = 0x7f06002a; public static final int menu_settings = 0x7f06002b; public static final int menu_share = 0x7f06002c; public static final int msg_bulk_mode_scanned = 0x7f06002d; public static final int msg_camera_framework_bug = 0x7f06002e; public static final int msg_default_format = 0x7f06002f; public static final int msg_default_meta = 0x7f060030; public static final int msg_default_mms_subject = 0x7f060031; public static final int msg_default_status = 0x7f060032; public static final int msg_default_time = 0x7f060033; public static final int msg_default_type = 0x7f060034; public static final int msg_encode_contents_failed = 0x7f060035; public static final int msg_error = 0x7f060036; public static final int msg_google_books = 0x7f060037; public static final int msg_google_product = 0x7f060038; public static final int msg_intent_failed = 0x7f060039; public static final int msg_invalid_value = 0x7f06003a; public static final int msg_redirect = 0x7f06003b; public static final int msg_sbc_book_not_searchable = 0x7f06003c; public static final int msg_sbc_failed = 0x7f06003d; public static final int msg_sbc_no_page_returned = 0x7f06003e; public static final int msg_sbc_page = 0x7f06003f; public static final int msg_sbc_results = 0x7f060040; public static final int msg_sbc_searching_book = 0x7f060041; public static final int msg_sbc_snippet_unavailable = 0x7f060042; public static final int msg_share_explanation = 0x7f060043; public static final int msg_share_text = 0x7f060044; public static final int msg_sure = 0x7f060045; public static final int msg_unmount_usb = 0x7f060046; public static final int preferences_actions_title = 0x7f060047; public static final int preferences_auto_focus_title = 0x7f060048; public static final int preferences_auto_open_web_title = 0x7f060049; public static final int preferences_bulk_mode_summary = 0x7f06004a; public static final int preferences_bulk_mode_title = 0x7f06004b; public static final int preferences_copy_to_clipboard_title = 0x7f06004c; public static final int preferences_custom_product_search_summary = 0x7f06004d; public static final int preferences_custom_product_search_title = 0x7f06004e; public static final int preferences_decode_1D_industrial_title = 0x7f06004f; public static final int preferences_decode_1D_product_title = 0x7f060050; public static final int preferences_decode_Aztec_title = 0x7f060051; public static final int preferences_decode_Data_Matrix_title = 0x7f060052; public static final int preferences_decode_PDF417_title = 0x7f060053; public static final int preferences_decode_QR_title = 0x7f060054; public static final int preferences_device_bug_workarounds_title = 0x7f060055; public static final int preferences_disable_barcode_scene_mode_title = 0x7f060056; public static final int preferences_disable_continuous_focus_summary = 0x7f060057; public static final int preferences_disable_continuous_focus_title = 0x7f060058; public static final int preferences_disable_exposure_title = 0x7f060059; public static final int preferences_disable_metering_title = 0x7f06005a; public static final int preferences_front_light_auto = 0x7f06005b; public static final int preferences_front_light_off = 0x7f06005c; public static final int preferences_front_light_on = 0x7f06005d; public static final int preferences_front_light_summary = 0x7f06005e; public static final int preferences_front_light_title = 0x7f06005f; public static final int preferences_general_title = 0x7f060060; public static final int preferences_history_summary = 0x7f060061; public static final int preferences_history_title = 0x7f060062; public static final int preferences_invert_scan_summary = 0x7f060063; public static final int preferences_invert_scan_title = 0x7f060064; public static final int preferences_name = 0x7f060065; public static final int preferences_orientation_title = 0x7f060066; public static final int preferences_play_beep_title = 0x7f060067; public static final int preferences_remember_duplicates_summary = 0x7f060068; public static final int preferences_remember_duplicates_title = 0x7f060069; public static final int preferences_result_title = 0x7f06006a; public static final int preferences_scanning_title = 0x7f06006b; public static final int preferences_search_country = 0x7f06006c; public static final int preferences_supplemental_summary = 0x7f06006d; public static final int preferences_supplemental_title = 0x7f06006e; public static final int preferences_vibrate_title = 0x7f06006f; public static final int result_address_book = 0x7f060070; public static final int result_calendar = 0x7f060071; public static final int result_email_address = 0x7f060072; public static final int result_geo = 0x7f060073; public static final int result_isbn = 0x7f060074; public static final int result_product = 0x7f060075; public static final int result_sms = 0x7f060076; public static final int result_tel = 0x7f060077; public static final int result_text = 0x7f060078; public static final int result_uri = 0x7f060079; public static final int result_wifi = 0x7f06007a; public static final int sbc_name = 0x7f06007b; public static final int wifi_changing_network = 0x7f06007c; } public static final class style { public static final int CaptureTheme = 0x7f0b0000; public static final int ResultButton = 0x7f0b0001; public static final int ShareButton = 0x7f0b0002; } public static final class xml { public static final int preferences = 0x7f040000; } }
apache-2.0
scriptella/scriptella-etl
tools/src/test/scriptella/tools/ant/EtlTemplateTaskTest.java
2171
/* * Copyright 2006-2012 The Scriptella Project 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 scriptella.tools.ant; import org.apache.tools.ant.BuildException; import scriptella.AbstractTestCase; import scriptella.tools.template.DataMigrator; import scriptella.tools.template.TemplateManager; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * Tests for {@link scriptella.tools.ant.EtlTemplateTask}. * * @author Fyodor Kupolov * @version 1.0 */ public class EtlTemplateTaskTest extends AbstractTestCase { private Map<String, ?> props; public void test() { EtlTemplateTask t = new EtlTemplateTask() { @Override//Verify that data migrator template is used protected void create(TemplateManager tm, Map<String, ?> properties) throws IOException { assertTrue(tm instanceof DataMigrator); props = properties; } @Override//Return mock properties to isolate from Ant protected Map<String, ?> getProperties() { Map<String, Object> m = new HashMap<String, Object>(); m.put("a", "AA"); m.put("b", "BB"); return m; } }; try { t.execute(); fail("Required attribute exception expected"); } catch (BuildException e) { //OK } t.setName(DataMigrator.class.getSimpleName()); t.execute(); assertTrue(props != null && "AA".equals(props.get("a")) && props.size() == 2); } }
apache-2.0
jiajunhui/XFolder
app/src/main/java/com/kk/taurus/xfolder/bean/StateRecord.java
763
package com.kk.taurus.xfolder.bean; import java.io.Serializable; /** * Created by Taurus on 2017/5/12. */ public class StateRecord implements Serializable { private int focusPosition; private int scrollToPosition; private int offset; public int getFocusPosition() { return focusPosition; } public void setFocusPosition(int focusPosition) { this.focusPosition = focusPosition; } public int getScrollToPosition() { return scrollToPosition; } public void setScrollToPosition(int scrollToPosition) { this.scrollToPosition = scrollToPosition; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } }
apache-2.0
Geomatys/sis
core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/projection/ProjectionException.java
3662
/* * 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.sis.referencing.operation.projection; import org.opengis.referencing.operation.TransformException; /** * Thrown by {@link NormalizedProjection} when a map projection failed. * * <div class="section">When this exception is thrown</div> * Apache SIS implementations of map projections return a {@linkplain Double#isFinite(double) finite} number * under normal conditions, but may also return an {@linkplain Double#isInfinite(double) infinite} number or * {@linkplain Double#isNaN(double) NaN} value, or throw this exception. * The behavior depends on the reason why the projection can not return a finite number: * * <ul> * <li>If the expected mathematical value is infinite (for example the Mercator projection at ±90° of latitude), * then the map projection should return a {@link Double#POSITIVE_INFINITY} or {@link Double#NEGATIVE_INFINITY}, * depending on the sign of the correct mathematical answer.</li> * <li>If no real number is expected to exist for the input coordinate (for example at a latitude greater than 90°), * then the map projection should return {@link Double#NaN}.</li> * <li>If a real number is expected to exist but the map projection fails to compute it (for example because an * iterative algorithm does not converge), then the projection should throw {@code ProjectionException}.</li> * </ul> * * @author André Gosselin (MPO) * @author Martin Desruisseaux (MPO, IRD, Geomatys) * @version 0.6 * @since 0.6 * @module */ public class ProjectionException extends TransformException { /** * Serial number for inter-operability with different versions. */ private static final long serialVersionUID = 3031350727691500915L; /** * Constructs a new exception with no detail message. */ public ProjectionException() { } /** * Constructs a new exception with the specified detail message. * * @param message the details message, or {@code null} if none. */ public ProjectionException(final String message) { super(message); } /** * Constructs a new exception with the specified cause. * The details message is copied from the cause. * * @param cause the cause, or {@code null} if none. */ public ProjectionException(final Throwable cause) { // Reproduce the behavior of standard Throwable(Throwable) constructor. super((cause != null) ? cause.toString() : null, cause); } /** * Constructs a new exception with the specified detail message and cause. * * @param message the details message, or {@code null} if none. * @param cause the cause, or {@code null} if none. */ public ProjectionException(final String message, final Throwable cause) { super(message, cause); } }
apache-2.0
atmelino/JATexperimental
src/jat/coreNOSA/gps/URE_Model.java
6016
package jat.coreNOSA.gps; /* JAT: Java Astrodynamics Toolkit * * Copyright (c) 2003 National Aeronautics and Space Administration. All rights reserved. * * This file is part of JAT. JAT is free software; you can * redistribute it and/or modify it under the terms of the * NASA Open Source Agreement * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * NASA Open Source Agreement for more details. * * You should have received a copy of the NASA Open Source Agreement * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * File Created on Jun 20, 2003 */ //import jat.gps.*; import jat.coreNOSA.cm.Constants; import jat.coreNOSA.cm.TwoBody; import jat.coreNOSA.math.MatrixVector.data.Matrix; import jat.coreNOSA.math.MatrixVector.data.RandomNumber; import jat.coreNOSA.math.MatrixVector.data.VectorN; /** * <P> * The URE_Model Class provides a model of the errors in the GPS system * due to GPS SV ephemeris and clock errors. For this simulation, they * are modeled as random constants with sigmas from: * * Reference: J. F. Zumberge and W. I. Bertiger, "Ephemeris and Clock * Navigation Message Accuracy", Global Positioning System: Theory and * Applications, Volume 1, edited by Parkinson and Spilker. * * @author * @version 1.0 */ public class URE_Model { /** Radial ephemeris error sigma in meters */ private static final double sigma_r = 1.2; /** Cross-track ephemeris error sigma in meters */ private static final double sigma_c = 3.2; /** Along-track ephemeris error sigma in meters */ private static final double sigma_a = 4.5; /** SV Clock error sigma in meters */ private static final double sigma_t = 1.12E-08 * Constants.c; private static final double sigma_ure = Math.sqrt(sigma_r*sigma_r + sigma_c*sigma_c + sigma_a*sigma_a + sigma_t*sigma_t); public static final double correlationTime = 7200.0; private double qbias; private double q; /** Radial ephemeris error vector, one entry per GPS SV */ private VectorN dr; /** Crosstrack ephemeris error vector, one entry per GPS SV */ private VectorN dc; /** Alongtrack ephemeris error vector, one entry per GPS SV */ private VectorN da; /** SV Clock error vector, one entry per GPS SV */ private VectorN dtc; /** Size of the GPS Constellation */ private int size; /** Constructor * @param n size of the GPS Constellation */ public URE_Model(int n) { this.size = n; dr = new VectorN(n); dc = new VectorN(n); da = new VectorN(n); dtc = new VectorN(n); RandomNumber rn = new RandomNumber(); for (int i = 0; i < n; i++) { double radial = rn.normal(0.0, sigma_r); dr.set(i, radial); double crosstrack = rn.normal(0.0, sigma_c); dc.set(i, crosstrack); double alongtrack = rn.normal(0.0, sigma_a); da.set(i, alongtrack); double clock = rn.normal(0.0, sigma_t); dtc.set(i, clock); } double dt = 1.0; double exponent = -2.0*dt/correlationTime; this.qbias = sigma_ure*sigma_ure*(1.0 - Math.exp(exponent)); // in (rad/sec)^2/Hz this.q = 2.0 * sigma_ure*sigma_ure / correlationTime; } /** Constructor * @param n size of the GPS Constellation * @param seed long containing random number seed to be used */ public URE_Model(int n, long seed) { this.size = n; dr = new VectorN(n); dc = new VectorN(n); da = new VectorN(n); dtc = new VectorN(n); RandomNumber rn = new RandomNumber(seed); for (int i = 0; i < n; i++) { double radial = rn.normal(0.0, sigma_r); dr.set(i, radial); double crosstrack = rn.normal(0.0, sigma_c); dc.set(i, crosstrack); double alongtrack = rn.normal(0.0, sigma_a); da.set(i, alongtrack); double clock = rn.normal(0.0, sigma_t); dtc.set(i, clock); } double dt = 1.0; double exponent = -2.0*dt/correlationTime; this.qbias = sigma_ure*sigma_ure*(1.0 - Math.exp(exponent)); // in (rad/sec)^2/Hz this.q = 2.0 * sigma_ure*sigma_ure / correlationTime; } /** Compute the User range error due to SV clock and ephemeris errors. * @param i GPS SV index * @param los GPS line of sight vector * @param rGPS GPS SV position vector * @param vGPS GPS SV velocity vector * @return the user range error in meters */ public double ure (int i, VectorN los, VectorN rGPS, VectorN vGPS) { // get the transformation from RIC to ECI TwoBody orbit = new TwoBody(Constants.GM_Earth, rGPS, vGPS); Matrix rot = orbit.RSW2ECI(); // form the ephemeris error vector for the ith GPS SV VectorN error = new VectorN(this.dr.x[i], this.da.x[i], this.dc.x[i]); // rotate the ephemeris error to the ECI frame VectorN errECI = rot.times(error); // find the magnitude of the projection of the error vector onto the LOS vector double drho = errECI.projectionMag(los); // add the SV clock error double out = drho + this.dtc.x[i]; return out; } /** * Compute the derivatives for the URE state. * The URE is modeled as a first order Gauss-Markov process. * Used by GPS_INS Process Model. * @param ure URE state vector * @return the time derivative of the URE */ public VectorN ureProcess(VectorN ure) { double coef = -1.0/correlationTime; VectorN out = ure.times(coef); return out; } /** * Return the URE noise strength to be used in * the process noise matrix Q. * @return URE noise strength */ public double biasQ() { return this.qbias; } /** * Return the URE noise strength to be used in * the process noise matrix Q. * @return URE noise strength */ public double Q() { return this.q; } /** * Return the URE sigma * @return URE sigma */ public double sigma() { return sigma_ure; } }
apache-2.0
charithag/carbon-device-mgt-framework
components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
6767
/* * Copyright (c) 2014, 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.carbon.policy.mgt.core.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.policy.mgt.core.dao.impl.FeatureDAOImpl; import org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl; import org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl; import org.wso2.carbon.policy.mgt.core.dao.impl.ProfileDAOImpl; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.Hashtable; import java.util.List; public class PolicyManagementDAOFactory { private static DataSource dataSource; private static final Log log = LogFactory.getLog(PolicyManagementDAOFactory.class); private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>(); public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); } public static void init(DataSource dtSource) { dataSource = dtSource; } public static DataSource getDataSource() { if (dataSource != null) { return dataSource; } throw new RuntimeException("Data source is not yet configured."); } public static PolicyDAO getPolicyDAO() { return new PolicyDAOImpl(); } public static ProfileDAO getProfileDAO() { return new ProfileDAOImpl(); } public static FeatureDAO getFeatureDAO() { return new FeatureDAOImpl(); } public static MonitoringDAO getMonitoringDAO() { return new MonitoringDAOImpl(); } /** * Resolve data source from the data source definition * * @param config data source configuration * @return data source resolved from the data source definition */ private static DataSource resolveDataSource(DataSourceConfig config) { DataSource dataSource = null; if (config == null) { throw new RuntimeException("Device Management Repository data source configuration " + "is null and thus, is not initialized"); } JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); if (jndiConfig != null) { if (log.isDebugEnabled()) { log.debug("Initializing Device Management Repository data source using the JNDI " + "Lookup Definition"); } List<JNDILookupDefinition.JNDIProperty> jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>(); for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { jndiProperties.put(prop.getName(), prop.getValue()); } dataSource = PolicyManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); } else { dataSource = PolicyManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); } } return dataSource; } public static void beginTransaction() throws PolicyManagerDAOException { try { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); currentConnection.set(conn); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while retrieving config.datasource connection", e); } } public static Connection getConnection() throws PolicyManagerDAOException { if (currentConnection.get() == null) { try { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); currentConnection.set(conn); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while retrieving data source connection", e); } } return currentConnection.get(); } public static void closeConnection() throws PolicyManagerDAOException { Connection con = currentConnection.get(); try { con.close(); } catch (SQLException e) { log.error("Error occurred while close the connection"); } currentConnection.remove(); } public static void commitTransaction() throws PolicyManagerDAOException { try { Connection conn = currentConnection.get(); if (conn != null) { conn.commit(); } else { if (log.isDebugEnabled()) { log.debug("Datasource connection associated with the current thread is null, hence commit " + "has not been attempted"); } } } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while committing the transaction", e); } finally { closeConnection(); } } public static void rollbackTransaction() throws PolicyManagerDAOException { try { Connection conn = currentConnection.get(); if (conn != null) { conn.rollback(); } else { if (log.isDebugEnabled()) { log.debug("Datasource connection associated with the current thread is null, hence rollback " + "has not been attempted"); } } } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while rollbacking the transaction", e); } finally { closeConnection(); } } }
apache-2.0
LamdaFu/statzall
statzall-core/src/test/java/statzall/codec/StreamCalcKryoTest.java
539
package statzall.codec; import static org.junit.Assert.*; import org.junit.Test; import statzall.Cast; import statzall.StreamCalc; import statzall.codec.StreamCalcKryo; public class StreamCalcKryoTest { @Test public void test() { StreamCalc calc = new StreamCalc(10, 10); StreamCalcKryo target = new StreamCalcKryo(); calc.add(1D, 2D, 3D, 4D, 5D, 6D, 7D, 8D, 9D); byte[] buff = target.write(calc); StreamCalc read = target.read(buff); assertEquals(9.0D, Cast.as(read.snapshot().get("q009"), Double.class), 0.0D); } }
apache-2.0
ppavlidis/aspiredb
aspiredb/src/main/java/ubc/pavlab/aspiredb/shared/query/AspireDbFilterConfig.java
971
/* * The aspiredb project * * Copyright (c) 2012 University of British Columbia * * 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 ubc.pavlab.aspiredb.shared.query; import java.io.Serializable; import org.directwebremoting.annotations.DataTransferObject; @DataTransferObject(javascript = "AspireDbFilterConfig") public abstract class AspireDbFilterConfig implements Serializable { private static final long serialVersionUID = 2621587187020538685L; }
apache-2.0
tectronics/hyracks
algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/properties/AbstractGroupingProperty.java
3116
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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.hyracks.algebricks.core.algebra.properties; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hyracks.algebricks.common.utils.ListSet; import org.apache.hyracks.algebricks.core.algebra.base.EquivalenceClass; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; public abstract class AbstractGroupingProperty { protected Set<LogicalVariable> columnSet; public AbstractGroupingProperty(Set<LogicalVariable> columnSet) { this.columnSet = columnSet; } public Set<LogicalVariable> getColumnSet() { return columnSet; } public final void normalizeGroupingColumns(Map<LogicalVariable, EquivalenceClass> equivalenceClasses, List<FunctionalDependency> fds) { replaceGroupingColumnsByEqClasses(equivalenceClasses); applyFDsToGroupingColumns(fds); } private void replaceGroupingColumnsByEqClasses(Map<LogicalVariable, EquivalenceClass> equivalenceClasses) { if (equivalenceClasses == null || equivalenceClasses.isEmpty()) { return; } Set<LogicalVariable> norm = new ListSet<LogicalVariable>(); for (LogicalVariable v : columnSet) { EquivalenceClass ec = equivalenceClasses.get(v); if (ec == null) { norm.add(v); } else { if (ec.representativeIsConst()) { // trivially satisfied, so the var. can be removed } else { norm.add(ec.getVariableRepresentative()); } } } columnSet = norm; } private void applyFDsToGroupingColumns(List<FunctionalDependency> fds) { // the set of vars. is unordered // so we try all FDs on all variables (incomplete algo?) if (fds == null || fds.isEmpty()) { return; } Set<LogicalVariable> norm = new ListSet<LogicalVariable>(); for (LogicalVariable v : columnSet) { boolean isImpliedByAnFD = false; for (FunctionalDependency fdep : fds) { if (columnSet.containsAll(fdep.getHead()) && fdep.getTail().contains(v)) { isImpliedByAnFD = true; norm.addAll(fdep.getHead()); break; } } if (!isImpliedByAnFD) { norm.add(v); } } columnSet = norm; } }
apache-2.0
reTHINK-project/dev-registry-domain
server/src/main/java/domainregistry/exception/HypertiesNotFoundException.java
701
/** * Copyright 2015-2016 INESC-ID * * 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 domainregistry; public class HypertiesNotFoundException extends RuntimeException{ }
apache-2.0
bobmcwhirter/drools
drools-core/src/main/java/org/drools/reteoo/RuleRemovalContext.java
2187
/* * Copyright 2008 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created on Feb 6, 2008 */ package org.drools.reteoo; import java.io.Serializable; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; import java.util.HashMap; import java.util.Map; import org.drools.common.BaseNode; /** * This context class is used during rule removal to ensure * network consistency. * * @author etirelli * */ public class RuleRemovalContext implements Externalizable { private Map visitedNodes; public RuleRemovalContext() { this.visitedNodes = new HashMap(); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { visitedNodes = (Map) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( visitedNodes ); } /** * We need to track tuple source nodes that we visit * to avoid multiple removal in case of subnetworks * * @param node */ public void visitTupleSource(LeftTupleSource node) { this.visitedNodes.put( new Integer( node.getId() ), node ); } /** * We need to track tuple source nodes that we visit * to avoid multiple removal in case of subnetworks * * @param node * @return */ public boolean alreadyVisited(LeftTupleSource node) { return this.visitedNodes.containsKey( new Integer( node.getId() ) ); } public void clear() { this.visitedNodes.clear(); } }
apache-2.0
Legioth/vaadin
server/src/main/java/com/vaadin/data/Result.java
6251
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.data; import java.io.Serializable; import java.util.Objects; import java.util.Optional; import com.vaadin.server.SerializableConsumer; import com.vaadin.server.SerializableFunction; import com.vaadin.server.SerializableSupplier; /** * Represents the result of an operation that might fail, such as type * conversion. A result may contain either a value, signifying a successful * operation, or an error message in case of a failure. * <p> * Result instances are created using the factory methods {@link #ok(R)} and * {@link #error(String)}, denoting success and failure respectively. * <p> * Unless otherwise specified, {@code Result} method arguments cannot be null. * * @param <R> * the result value type */ public interface Result<R> extends Serializable { /** * Returns a successful result wrapping the given value. * * @param <R> * the result value type * @param value * the result value, can be null * @return a successful result */ public static <R> Result<R> ok(R value) { return new SimpleResult<>(value, null); } /** * Returns a failure result wrapping the given error message. * * @param <R> * the result value type * @param message * the error message * @return a failure result */ public static <R> Result<R> error(String message) { Objects.requireNonNull(message, "message cannot be null"); return new SimpleResult<>(null, message); } /** * Returns a Result representing the result of invoking the given supplier. * If the supplier returns a value, returns a {@code Result.ok} of the * value; if an exception is thrown, returns the message in a * {@code Result.error}. * * @param <R> * the result value type * @param supplier * the supplier to run * @param onError * the function to provide the error message * @return the result of invoking the supplier */ public static <R> Result<R> of(SerializableSupplier<R> supplier, SerializableFunction<Exception, String> onError) { Objects.requireNonNull(supplier, "supplier cannot be null"); Objects.requireNonNull(onError, "onError cannot be null"); try { return ok(supplier.get()); } catch (Exception e) { return error(onError.apply(e)); } } /** * If this Result has a value, returns a Result of applying the given * function to the value. Otherwise, returns a Result bearing the same error * as this one. Note that any exceptions thrown by the mapping function are * not wrapped but allowed to propagate. * * @param <S> * the type of the mapped value * @param mapper * the mapping function * @return the mapped result */ public default <S> Result<S> map(SerializableFunction<R, S> mapper) { return flatMap(value -> ok(mapper.apply(value))); } /** * If this Result has a value, applies the given Result-returning function * to the value. Otherwise, returns a Result bearing the same error as this * one. Note that any exceptions thrown by the mapping function are not * wrapped but allowed to propagate. * * @param <S> * the type of the mapped value * @param mapper * the mapping function * @return the mapped result */ public <S> Result<S> flatMap(SerializableFunction<R, Result<S>> mapper); /** * Invokes either the first callback or the second one, depending on whether * this Result denotes a success or a failure, respectively. * * @param ifOk * the function to call if success * @param ifError * the function to call if failure */ public void handle(SerializableConsumer<R> ifOk, SerializableConsumer<String> ifError); /** * Applies the {@code consumer} if result is not an error. * * @param consumer * consumer to apply in case it's not an error */ public default void ifOk(SerializableConsumer<R> consumer) { handle(consumer, error -> { }); } /** * Applies the {@code consumer} if result is an error. * * @param consumer * consumer to apply in case it's an error */ public default void ifError(SerializableConsumer<String> consumer) { handle(value -> { }, consumer); } /** * Checks if the result denotes an error. * * @return <code>true</code> if the result denotes an error, * <code>false</code> otherwise */ public boolean isError(); /** * Returns an Optional of the result message, or an empty Optional if none. * * @return the optional message */ public Optional<String> getMessage(); /** * Return the value, if the result denotes success, otherwise throw an * exception to be created by the provided supplier. * * @param <X> * Type of the exception to be thrown * @param exceptionProvider * The provider which will return the exception to be thrown * based on the given error message * @return the value * @throws X * if this result denotes an error */ public <X extends Throwable> R getOrThrow( SerializableFunction<String, ? extends X> exceptionProvider) throws X; }
apache-2.0
cibuddy/cibuddy
drivers/hid/src/test/java/com/cibuddy/hid/test/HIDManagerTest.java
2419
package com.cibuddy.hid.test; import com.codeminders.hidapi.ClassPathLibraryLoader; import com.codeminders.hidapi.HIDDeviceInfo; import com.codeminders.hidapi.HIDManager; import java.io.IOException; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; /** * A simple test to see if the native libraries could be loaded. * * @author Mirko Jahn <mirkojahn@gmail.com> * @version 1.0 */ @Ignore public class HIDManagerTest { /** * Loads the native libraries before the test execution. * @since 1.0 */ @BeforeClass public static void beforeEverything() { // load the native libraries automatically (only once per JVM instance) ClassPathLibraryLoader.loadNativeHIDLibrary(); } /** * Test how many devices are found if run twice. * * Listing all devices twice and checking if the lists are identical. If not, * most likely one device is still occupied by the first request (Windows is * supposed to behave like that in some cases). You might as well have just * removed/added the HID device during the test run. * * @throws IOException in case access to the driver was not possible * @throws InterruptedException */ @Test public void testListDevices() throws IOException, InterruptedException { HIDManager manager = HIDManager.getInstance(); HIDDeviceInfo[] firstRun = printDevices(manager); System.out.println("Second run: Checking for HID devices again..."); HIDDeviceInfo[] secondRun = printDevices(manager); Assert.assertArrayEquals("The list of found HID devices is NOT equal. Make sure you didn't connect/disconnect a device while running the test", firstRun, secondRun); manager.release(); } /** * Main method, just printing all connected devices. * * @param args - not used. */ private static HIDDeviceInfo[] printDevices(HIDManager manager) throws IOException{ HIDDeviceInfo[] devs = manager.listDevices(); System.out.println("HID Devices:\n\n"); for(int i=0;i<devs.length;i++) { System.out.println(""+i+".\t"+devs[i]); System.out.println("---------------------------------------------\n"); } System.gc(); return devs; } }
apache-2.0
OpenGamma/Strata
modules/product/src/main/java/com/opengamma/strata/product/swap/RateCalculationSwapLeg.java
28501
/* * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.product.swap; import java.io.Serializable; import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.joda.beans.Bean; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaBean; import org.joda.beans.MetaProperty; import org.joda.beans.gen.BeanDefinition; import org.joda.beans.gen.DerivedProperty; import org.joda.beans.gen.PropertyDefinition; import org.joda.beans.impl.direct.DirectFieldsBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.ReferenceDataNotFoundException; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.basics.date.AdjustableDate; import com.opengamma.strata.basics.date.DayCount; import com.opengamma.strata.basics.index.Index; import com.opengamma.strata.basics.schedule.PeriodicSchedule; import com.opengamma.strata.basics.schedule.Schedule; import com.opengamma.strata.product.common.PayReceive; /** * A rate swap leg defined using a parameterized schedule and calculation. * <p> * This defines a single swap leg paying a rate, such as an interest rate. * The rate may be fixed or floating, see {@link FixedRateCalculation}, * {@link IborRateCalculation} and {@link OvernightRateCalculation}. * <p> * Interest is calculated based on <i>accrual periods</i> which follow a regular schedule * with optional initial and final stubs. Coupon payments are based on <i>payment periods</i> * which are typically the same as the accrual periods. * If the payment period is longer than the accrual period then compounding may apply. * The schedule of periods is defined using {@link PeriodicSchedule}, {@link PaymentSchedule}, * {@link NotionalSchedule} and {@link ResetSchedule}. * <p> * If the schedule needs to be manually specified, or there are other unusual calculation * rules then the {@link RatePeriodSwapLeg} class should be used instead. */ @BeanDefinition public final class RateCalculationSwapLeg implements ScheduledSwapLeg, ImmutableBean, Serializable { /** * Whether the leg is pay or receive. * <p> * A value of 'Pay' implies that the resulting amount is paid to the counterparty. * A value of 'Receive' implies that the resulting amount is received from the counterparty. * Note that negative interest rates can result in a payment in the opposite * direction to that implied by this indicator. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final PayReceive payReceive; /** * The accrual schedule. * <p> * This is used to define the accrual periods. * These are used directly or indirectly to determine other dates in the swap. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final PeriodicSchedule accrualSchedule; /** * The payment schedule. * <p> * This is used to define the payment periods, including any compounding. * The payment period dates are based on the accrual schedule. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private final PaymentSchedule paymentSchedule; /** * The notional schedule. * <p> * The notional amount schedule, which can vary during the lifetime of the swap. * In most cases, the notional amount is not exchanged, with only the net difference being exchanged. * However, in certain cases, initial, final or intermediate amounts are exchanged. */ @PropertyDefinition(validate = "notNull") private final NotionalSchedule notionalSchedule; /** * The interest rate accrual calculation. * <p> * Different kinds of swap leg are determined by the subclass used here. * See {@link FixedRateCalculation}, {@link IborRateCalculation} and {@link OvernightRateCalculation}. */ @PropertyDefinition(validate = "notNull") private final RateCalculation calculation; //------------------------------------------------------------------------- @Override @DerivedProperty public SwapLegType getType() { return calculation.getType(); } @Override @DerivedProperty public AdjustableDate getStartDate() { return accrualSchedule.calculatedStartDate(); } @Override @DerivedProperty public AdjustableDate getEndDate() { return accrualSchedule.calculatedEndDate(); } @Override @DerivedProperty public Currency getCurrency() { return notionalSchedule.getCurrency(); } @Override public void collectCurrencies(ImmutableSet.Builder<Currency> builder) { builder.add(getCurrency()); calculation.collectCurrencies(builder); notionalSchedule.getFxReset().ifPresent(fxReset -> builder.add(fxReset.getReferenceCurrency())); } @Override public void collectIndices(ImmutableSet.Builder<Index> builder) { calculation.collectIndices(builder); notionalSchedule.getFxReset().ifPresent(fxReset -> builder.add(fxReset.getIndex())); } //------------------------------------------------------------------------- /** * Returns an instance based on this leg with the start date replaced. * <p> * This uses {@link PeriodicSchedule#replaceStartDate(LocalDate)}. * * @throws IllegalArgumentException if the start date cannot be replaced with the proposed start date */ @Override public RateCalculationSwapLeg replaceStartDate(LocalDate adjustedStartDate) { return toBuilder().accrualSchedule(accrualSchedule.replaceStartDate(adjustedStartDate)).build(); } /** * Converts this swap leg to the equivalent {@code ResolvedSwapLeg}. * <p> * An {@link ResolvedSwapLeg} represents the same data as this leg, but with * a complete schedule of dates defined using {@link RatePaymentPeriod}. * * @return the equivalent resolved swap leg * @throws ReferenceDataNotFoundException if an identifier cannot be resolved in the reference data * @throws RuntimeException if unable to resolve due to an invalid swap schedule or definition */ @Override public ResolvedSwapLeg resolve(ReferenceData refData) { DayCount dayCount = calculation.getDayCount(); Schedule resolvedAccruals = accrualSchedule.createSchedule(refData); Schedule resolvedPayments = paymentSchedule.createSchedule(resolvedAccruals, refData); List<RateAccrualPeriod> accrualPeriods = calculation.createAccrualPeriods(resolvedAccruals, resolvedPayments, refData); List<NotionalPaymentPeriod> payPeriods = paymentSchedule.createPaymentPeriods( resolvedAccruals, resolvedPayments, accrualPeriods, dayCount, notionalSchedule, payReceive, refData); LocalDate startDate = accrualPeriods.get(0).getStartDate(); ImmutableList<SwapPaymentEvent> payEvents = notionalSchedule.createEvents(payPeriods, startDate, refData); return new ResolvedSwapLeg(getType(), payReceive, payPeriods, payEvents, getCurrency()); } //------------------------- AUTOGENERATED START ------------------------- /** * The meta-bean for {@code RateCalculationSwapLeg}. * @return the meta-bean, not null */ public static RateCalculationSwapLeg.Meta meta() { return RateCalculationSwapLeg.Meta.INSTANCE; } static { MetaBean.register(RateCalculationSwapLeg.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; /** * Returns a builder used to create an instance of the bean. * @return the builder, not null */ public static RateCalculationSwapLeg.Builder builder() { return new RateCalculationSwapLeg.Builder(); } private RateCalculationSwapLeg( PayReceive payReceive, PeriodicSchedule accrualSchedule, PaymentSchedule paymentSchedule, NotionalSchedule notionalSchedule, RateCalculation calculation) { JodaBeanUtils.notNull(payReceive, "payReceive"); JodaBeanUtils.notNull(accrualSchedule, "accrualSchedule"); JodaBeanUtils.notNull(paymentSchedule, "paymentSchedule"); JodaBeanUtils.notNull(notionalSchedule, "notionalSchedule"); JodaBeanUtils.notNull(calculation, "calculation"); this.payReceive = payReceive; this.accrualSchedule = accrualSchedule; this.paymentSchedule = paymentSchedule; this.notionalSchedule = notionalSchedule; this.calculation = calculation; } @Override public RateCalculationSwapLeg.Meta metaBean() { return RateCalculationSwapLeg.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets whether the leg is pay or receive. * <p> * A value of 'Pay' implies that the resulting amount is paid to the counterparty. * A value of 'Receive' implies that the resulting amount is received from the counterparty. * Note that negative interest rates can result in a payment in the opposite * direction to that implied by this indicator. * @return the value of the property, not null */ @Override public PayReceive getPayReceive() { return payReceive; } //----------------------------------------------------------------------- /** * Gets the accrual schedule. * <p> * This is used to define the accrual periods. * These are used directly or indirectly to determine other dates in the swap. * @return the value of the property, not null */ @Override public PeriodicSchedule getAccrualSchedule() { return accrualSchedule; } //----------------------------------------------------------------------- /** * Gets the payment schedule. * <p> * This is used to define the payment periods, including any compounding. * The payment period dates are based on the accrual schedule. * @return the value of the property, not null */ @Override public PaymentSchedule getPaymentSchedule() { return paymentSchedule; } //----------------------------------------------------------------------- /** * Gets the notional schedule. * <p> * The notional amount schedule, which can vary during the lifetime of the swap. * In most cases, the notional amount is not exchanged, with only the net difference being exchanged. * However, in certain cases, initial, final or intermediate amounts are exchanged. * @return the value of the property, not null */ public NotionalSchedule getNotionalSchedule() { return notionalSchedule; } //----------------------------------------------------------------------- /** * Gets the interest rate accrual calculation. * <p> * Different kinds of swap leg are determined by the subclass used here. * See {@link FixedRateCalculation}, {@link IborRateCalculation} and {@link OvernightRateCalculation}. * @return the value of the property, not null */ public RateCalculation getCalculation() { return calculation; } //----------------------------------------------------------------------- /** * Returns a builder that allows this bean to be mutated. * @return the mutable builder, not null */ public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { RateCalculationSwapLeg other = (RateCalculationSwapLeg) obj; return JodaBeanUtils.equal(payReceive, other.payReceive) && JodaBeanUtils.equal(accrualSchedule, other.accrualSchedule) && JodaBeanUtils.equal(paymentSchedule, other.paymentSchedule) && JodaBeanUtils.equal(notionalSchedule, other.notionalSchedule) && JodaBeanUtils.equal(calculation, other.calculation); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(payReceive); hash = hash * 31 + JodaBeanUtils.hashCode(accrualSchedule); hash = hash * 31 + JodaBeanUtils.hashCode(paymentSchedule); hash = hash * 31 + JodaBeanUtils.hashCode(notionalSchedule); hash = hash * 31 + JodaBeanUtils.hashCode(calculation); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(320); buf.append("RateCalculationSwapLeg{"); buf.append("payReceive").append('=').append(JodaBeanUtils.toString(payReceive)).append(',').append(' '); buf.append("accrualSchedule").append('=').append(JodaBeanUtils.toString(accrualSchedule)).append(',').append(' '); buf.append("paymentSchedule").append('=').append(JodaBeanUtils.toString(paymentSchedule)).append(',').append(' '); buf.append("notionalSchedule").append('=').append(JodaBeanUtils.toString(notionalSchedule)).append(',').append(' '); buf.append("calculation").append('=').append(JodaBeanUtils.toString(calculation)).append(',').append(' '); buf.append("type").append('=').append(JodaBeanUtils.toString(getType())).append(',').append(' '); buf.append("startDate").append('=').append(JodaBeanUtils.toString(getStartDate())).append(',').append(' '); buf.append("endDate").append('=').append(JodaBeanUtils.toString(getEndDate())).append(',').append(' '); buf.append("currency").append('=').append(JodaBeanUtils.toString(getCurrency())); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code RateCalculationSwapLeg}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code payReceive} property. */ private final MetaProperty<PayReceive> payReceive = DirectMetaProperty.ofImmutable( this, "payReceive", RateCalculationSwapLeg.class, PayReceive.class); /** * The meta-property for the {@code accrualSchedule} property. */ private final MetaProperty<PeriodicSchedule> accrualSchedule = DirectMetaProperty.ofImmutable( this, "accrualSchedule", RateCalculationSwapLeg.class, PeriodicSchedule.class); /** * The meta-property for the {@code paymentSchedule} property. */ private final MetaProperty<PaymentSchedule> paymentSchedule = DirectMetaProperty.ofImmutable( this, "paymentSchedule", RateCalculationSwapLeg.class, PaymentSchedule.class); /** * The meta-property for the {@code notionalSchedule} property. */ private final MetaProperty<NotionalSchedule> notionalSchedule = DirectMetaProperty.ofImmutable( this, "notionalSchedule", RateCalculationSwapLeg.class, NotionalSchedule.class); /** * The meta-property for the {@code calculation} property. */ private final MetaProperty<RateCalculation> calculation = DirectMetaProperty.ofImmutable( this, "calculation", RateCalculationSwapLeg.class, RateCalculation.class); /** * The meta-property for the {@code type} property. */ private final MetaProperty<SwapLegType> type = DirectMetaProperty.ofDerived( this, "type", RateCalculationSwapLeg.class, SwapLegType.class); /** * The meta-property for the {@code startDate} property. */ private final MetaProperty<AdjustableDate> startDate = DirectMetaProperty.ofDerived( this, "startDate", RateCalculationSwapLeg.class, AdjustableDate.class); /** * The meta-property for the {@code endDate} property. */ private final MetaProperty<AdjustableDate> endDate = DirectMetaProperty.ofDerived( this, "endDate", RateCalculationSwapLeg.class, AdjustableDate.class); /** * The meta-property for the {@code currency} property. */ private final MetaProperty<Currency> currency = DirectMetaProperty.ofDerived( this, "currency", RateCalculationSwapLeg.class, Currency.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "payReceive", "accrualSchedule", "paymentSchedule", "notionalSchedule", "calculation", "type", "startDate", "endDate", "currency"); /** * Restricted constructor. */ private Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -885469925: // payReceive return payReceive; case 304659814: // accrualSchedule return accrualSchedule; case -1499086147: // paymentSchedule return paymentSchedule; case 1447860727: // notionalSchedule return notionalSchedule; case -934682935: // calculation return calculation; case 3575610: // type return type; case -2129778896: // startDate return startDate; case -1607727319: // endDate return endDate; case 575402001: // currency return currency; } return super.metaPropertyGet(propertyName); } @Override public RateCalculationSwapLeg.Builder builder() { return new RateCalculationSwapLeg.Builder(); } @Override public Class<? extends RateCalculationSwapLeg> beanType() { return RateCalculationSwapLeg.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code payReceive} property. * @return the meta-property, not null */ public MetaProperty<PayReceive> payReceive() { return payReceive; } /** * The meta-property for the {@code accrualSchedule} property. * @return the meta-property, not null */ public MetaProperty<PeriodicSchedule> accrualSchedule() { return accrualSchedule; } /** * The meta-property for the {@code paymentSchedule} property. * @return the meta-property, not null */ public MetaProperty<PaymentSchedule> paymentSchedule() { return paymentSchedule; } /** * The meta-property for the {@code notionalSchedule} property. * @return the meta-property, not null */ public MetaProperty<NotionalSchedule> notionalSchedule() { return notionalSchedule; } /** * The meta-property for the {@code calculation} property. * @return the meta-property, not null */ public MetaProperty<RateCalculation> calculation() { return calculation; } /** * The meta-property for the {@code type} property. * @return the meta-property, not null */ public MetaProperty<SwapLegType> type() { return type; } /** * The meta-property for the {@code startDate} property. * @return the meta-property, not null */ public MetaProperty<AdjustableDate> startDate() { return startDate; } /** * The meta-property for the {@code endDate} property. * @return the meta-property, not null */ public MetaProperty<AdjustableDate> endDate() { return endDate; } /** * The meta-property for the {@code currency} property. * @return the meta-property, not null */ public MetaProperty<Currency> currency() { return currency; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -885469925: // payReceive return ((RateCalculationSwapLeg) bean).getPayReceive(); case 304659814: // accrualSchedule return ((RateCalculationSwapLeg) bean).getAccrualSchedule(); case -1499086147: // paymentSchedule return ((RateCalculationSwapLeg) bean).getPaymentSchedule(); case 1447860727: // notionalSchedule return ((RateCalculationSwapLeg) bean).getNotionalSchedule(); case -934682935: // calculation return ((RateCalculationSwapLeg) bean).getCalculation(); case 3575610: // type return ((RateCalculationSwapLeg) bean).getType(); case -2129778896: // startDate return ((RateCalculationSwapLeg) bean).getStartDate(); case -1607727319: // endDate return ((RateCalculationSwapLeg) bean).getEndDate(); case 575402001: // currency return ((RateCalculationSwapLeg) bean).getCurrency(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code RateCalculationSwapLeg}. */ public static final class Builder extends DirectFieldsBeanBuilder<RateCalculationSwapLeg> { private PayReceive payReceive; private PeriodicSchedule accrualSchedule; private PaymentSchedule paymentSchedule; private NotionalSchedule notionalSchedule; private RateCalculation calculation; /** * Restricted constructor. */ private Builder() { } /** * Restricted copy constructor. * @param beanToCopy the bean to copy from, not null */ private Builder(RateCalculationSwapLeg beanToCopy) { this.payReceive = beanToCopy.getPayReceive(); this.accrualSchedule = beanToCopy.getAccrualSchedule(); this.paymentSchedule = beanToCopy.getPaymentSchedule(); this.notionalSchedule = beanToCopy.getNotionalSchedule(); this.calculation = beanToCopy.getCalculation(); } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case -885469925: // payReceive return payReceive; case 304659814: // accrualSchedule return accrualSchedule; case -1499086147: // paymentSchedule return paymentSchedule; case 1447860727: // notionalSchedule return notionalSchedule; case -934682935: // calculation return calculation; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case -885469925: // payReceive this.payReceive = (PayReceive) newValue; break; case 304659814: // accrualSchedule this.accrualSchedule = (PeriodicSchedule) newValue; break; case -1499086147: // paymentSchedule this.paymentSchedule = (PaymentSchedule) newValue; break; case 1447860727: // notionalSchedule this.notionalSchedule = (NotionalSchedule) newValue; break; case -934682935: // calculation this.calculation = (RateCalculation) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public Builder set(MetaProperty<?> property, Object value) { super.set(property, value); return this; } @Override public RateCalculationSwapLeg build() { return new RateCalculationSwapLeg( payReceive, accrualSchedule, paymentSchedule, notionalSchedule, calculation); } //----------------------------------------------------------------------- /** * Sets whether the leg is pay or receive. * <p> * A value of 'Pay' implies that the resulting amount is paid to the counterparty. * A value of 'Receive' implies that the resulting amount is received from the counterparty. * Note that negative interest rates can result in a payment in the opposite * direction to that implied by this indicator. * @param payReceive the new value, not null * @return this, for chaining, not null */ public Builder payReceive(PayReceive payReceive) { JodaBeanUtils.notNull(payReceive, "payReceive"); this.payReceive = payReceive; return this; } /** * Sets the accrual schedule. * <p> * This is used to define the accrual periods. * These are used directly or indirectly to determine other dates in the swap. * @param accrualSchedule the new value, not null * @return this, for chaining, not null */ public Builder accrualSchedule(PeriodicSchedule accrualSchedule) { JodaBeanUtils.notNull(accrualSchedule, "accrualSchedule"); this.accrualSchedule = accrualSchedule; return this; } /** * Sets the payment schedule. * <p> * This is used to define the payment periods, including any compounding. * The payment period dates are based on the accrual schedule. * @param paymentSchedule the new value, not null * @return this, for chaining, not null */ public Builder paymentSchedule(PaymentSchedule paymentSchedule) { JodaBeanUtils.notNull(paymentSchedule, "paymentSchedule"); this.paymentSchedule = paymentSchedule; return this; } /** * Sets the notional schedule. * <p> * The notional amount schedule, which can vary during the lifetime of the swap. * In most cases, the notional amount is not exchanged, with only the net difference being exchanged. * However, in certain cases, initial, final or intermediate amounts are exchanged. * @param notionalSchedule the new value, not null * @return this, for chaining, not null */ public Builder notionalSchedule(NotionalSchedule notionalSchedule) { JodaBeanUtils.notNull(notionalSchedule, "notionalSchedule"); this.notionalSchedule = notionalSchedule; return this; } /** * Sets the interest rate accrual calculation. * <p> * Different kinds of swap leg are determined by the subclass used here. * See {@link FixedRateCalculation}, {@link IborRateCalculation} and {@link OvernightRateCalculation}. * @param calculation the new value, not null * @return this, for chaining, not null */ public Builder calculation(RateCalculation calculation) { JodaBeanUtils.notNull(calculation, "calculation"); this.calculation = calculation; return this; } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(320); buf.append("RateCalculationSwapLeg.Builder{"); buf.append("payReceive").append('=').append(JodaBeanUtils.toString(payReceive)).append(',').append(' '); buf.append("accrualSchedule").append('=').append(JodaBeanUtils.toString(accrualSchedule)).append(',').append(' '); buf.append("paymentSchedule").append('=').append(JodaBeanUtils.toString(paymentSchedule)).append(',').append(' '); buf.append("notionalSchedule").append('=').append(JodaBeanUtils.toString(notionalSchedule)).append(',').append(' '); buf.append("calculation").append('=').append(JodaBeanUtils.toString(calculation)).append(',').append(' '); buf.append("type").append('=').append(JodaBeanUtils.toString(null)).append(',').append(' '); buf.append("startDate").append('=').append(JodaBeanUtils.toString(null)).append(',').append(' '); buf.append("endDate").append('=').append(JodaBeanUtils.toString(null)).append(',').append(' '); buf.append("currency").append('=').append(JodaBeanUtils.toString(null)); buf.append('}'); return buf.toString(); } } //-------------------------- AUTOGENERATED END -------------------------- }
apache-2.0
goodev/android-discourse
userVoiceSDK/src/main/java/com/uservoice/uservoicesdk/ui/Utils.java
5192
package com.uservoice.uservoicesdk.ui; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.support.v4.app.FragmentActivity; import android.util.TypedValue; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebSettings.PluginState; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import com.uservoice.uservoicesdk.R; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.activity.TopicActivity; import com.uservoice.uservoicesdk.dialog.ArticleDialogFragment; import com.uservoice.uservoicesdk.dialog.SuggestionDialogFragment; import com.uservoice.uservoicesdk.model.Article; import com.uservoice.uservoicesdk.model.BaseModel; import com.uservoice.uservoicesdk.model.Suggestion; import com.uservoice.uservoicesdk.model.Topic; import java.util.Locale; public class Utils { @SuppressLint("SetJavaScriptEnabled") public static void displayArticle(WebView webView, Article article, Context context) { String styles = "iframe, img { width: 100%; }"; if (isDarkTheme(context)) { webView.setBackgroundColor(Color.BLACK); styles += "body { background-color: #000000; color: #F6F6F6; } a { color: #0099FF; }"; } String html = String.format("<html><head><meta charset=\"utf-8\"><link rel=\"stylesheet\" type=\"text/css\" href=\"http://cdn.uservoice.com/stylesheets/vendor/typeset.css\"/><style>%s</style></head><body class=\"typeset\" style=\"font-family: sans-serif; margin: 1em\"><h3>%s</h3>%s</body></html>", styles, article.getTitle(), article.getHtml()); webView.setWebChromeClient(new WebChromeClient()); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setPluginState(PluginState.ON); webView.loadUrl(String.format("data:text/html;charset=utf-8,%s", Uri.encode(html))); } public static boolean isDarkTheme(Context context) { TypedValue tv = new TypedValue(); float[] hsv = new float[3]; context.getTheme().resolveAttribute(android.R.attr.textColorPrimary, tv, true); Color.colorToHSV(context.getResources().getColor(tv.resourceId), hsv); return hsv[2] > 0.5f; } @SuppressLint("DefaultLocale") public static String getQuantityString(View view, int id, int count) { return String.format("%,d %s", count, view.getContext().getResources().getQuantityString(id, count)); } public static void displayInstantAnswer(View view, BaseModel model) { TextView title = (TextView) view.findViewById(R.id.uv_title); TextView detail = (TextView) view.findViewById(R.id.uv_detail); View suggestionDetails = view.findViewById(R.id.uv_suggestion_details); ImageView image = (ImageView) view.findViewById(R.id.uv_icon); if (model instanceof Article) { Article article = (Article) model; image.setImageResource(R.drawable.uv_article); title.setText(article.getTitle()); if (article.getTopicName() != null) { detail.setVisibility(View.VISIBLE); detail.setText(article.getTopicName()); } else { detail.setVisibility(View.GONE); } suggestionDetails.setVisibility(View.GONE); } else if (model instanceof Suggestion) { Suggestion suggestion = (Suggestion) model; image.setImageResource(R.drawable.uv_idea); title.setText(suggestion.getTitle()); detail.setVisibility(View.VISIBLE); detail.setText(suggestion.getForumName()); if (suggestion.getStatus() != null) { View statusColor = suggestionDetails.findViewById(R.id.uv_suggestion_status_color); TextView status = (TextView) suggestionDetails.findViewById(R.id.uv_suggestion_status); int color = Color.parseColor(suggestion.getStatusColor()); suggestionDetails.setVisibility(View.VISIBLE); status.setText(suggestion.getStatus().toUpperCase(Locale.getDefault())); status.setTextColor(color); statusColor.setBackgroundColor(color); } else { suggestionDetails.setVisibility(View.GONE); } } } public static void showModel(FragmentActivity context, BaseModel model) { if (model instanceof Article) { ArticleDialogFragment fragment = new ArticleDialogFragment((Article) model); fragment.show(context.getSupportFragmentManager(), "ArticleDialogFragment"); } else if (model instanceof Suggestion) { SuggestionDialogFragment fragment = new SuggestionDialogFragment((Suggestion) model); fragment.show(context.getSupportFragmentManager(), "SuggestionDialogFragment"); } else if (model instanceof Topic) { Session.getInstance().setTopic((Topic) model); context.startActivity(new Intent(context, TopicActivity.class)); } } }
apache-2.0
mikouaj/finsight
finsight-backend/src/main/java/pl/surreal/finance/transaction/resources/TransactionResource.java
11611
/* Copyright 2016 Mikolaj Stefaniak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 pl.surreal.finance.transaction.resources; import java.io.InputStream; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Link; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.hibernate.exception.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.annotation.Timed; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.LongParam; import io.swagger.annotations.Api; import pl.surreal.finance.transaction.api.AccountApi; import pl.surreal.finance.transaction.api.CardApi; import pl.surreal.finance.transaction.api.CardOperationApi; import pl.surreal.finance.transaction.api.ImportResult; import pl.surreal.finance.transaction.api.ImportType; import pl.surreal.finance.transaction.api.LabelResultApi; import pl.surreal.finance.transaction.api.TransactionApi; import pl.surreal.finance.transaction.api.TransferApi; import pl.surreal.finance.transaction.core.CardOperation; import pl.surreal.finance.transaction.core.Label; import pl.surreal.finance.transaction.core.Transaction; import pl.surreal.finance.transaction.core.Transfer; import pl.surreal.finance.transaction.db.LabelDAO; import pl.surreal.finance.transaction.db.TransactionDAO; import pl.surreal.finance.transaction.labeler.ITransactionLabeler; import pl.surreal.finance.transaction.parser.IParserFactory; import pl.surreal.finance.transaction.parser.ITransactionParser; import pl.surreal.finance.transaction.parser.ParserSupportedType; @Path("/transactions") @Api(value = "transactions") @Produces(MediaType.APPLICATION_JSON) public class TransactionResource { private static final Logger LOGGER = LoggerFactory.getLogger(TransactionResource.class); private TransactionDAO transactionDAO; private LabelDAO labelDAO; private IParserFactory parserFactory; private ITransactionLabeler transactionLabeler; @Context private UriInfo uriInfo; public TransactionResource(TransactionDAO transactionDAO,LabelDAO labelDAO,IParserFactory parserFactory,ITransactionLabeler transactionLabeler) { this.transactionDAO = transactionDAO; this.parserFactory = parserFactory; this.transactionLabeler = transactionLabeler; this.labelDAO = labelDAO; } private TransactionApi mapDomainToApi(Transaction transaction) { TransactionApi transactionApi = new TransactionApi(); transactionApi.setId(transaction.getId()); transactionApi.setDate(transaction.getAccountingDate()); transactionApi.setAmount(transaction.getAccountingAmount()); transactionApi.setAccountingAmount(transaction.getAccountingAmount()); transactionApi.setCurrency(transaction.getCurrency()); transactionApi.setTitle(transaction.getTitle()); transactionApi.setType(transaction.getClass().getSimpleName()); List<Long> labelIds = new ArrayList<>(); for(Label label : transaction.getLabels()) { labelIds.add(label.getId()); } transactionApi.setLabelIds(labelIds); if(transaction instanceof CardOperation) { CardOperation cardOperTrans = (CardOperation)transaction; CardOperationApi cardOperApi = new CardOperationApi(); if(cardOperTrans.getCard()!=null) { cardOperApi.setCard(new CardApi(cardOperTrans.getCard().getNumber(),(cardOperTrans.getCard().getName()))); } cardOperApi.setDestination(cardOperTrans.getDestination()); transactionApi.setDetails(cardOperApi); } else if(transaction instanceof Transfer) { Transfer transferTrans = (Transfer)transaction; TransferApi transferApi = new TransferApi(); transferApi.setDescription(transferTrans.getDescription()); transferApi.setInternal(transferTrans.isInternal()); transferApi.setDirection(transferTrans.getDirection().toString()); if(transferTrans.getDstAccount()!=null) { transferApi.setDstAccount(new AccountApi(transferTrans.getDstAccount().getNumber(),transferTrans.getDstAccount().getName())); } if(transferTrans.getSrcAccount()!=null) { transferApi.setSrcAccount(new AccountApi(transferTrans.getSrcAccount().getNumber(),transferTrans.getSrcAccount().getName())); } transactionApi.setDetails(transferApi); } return transactionApi; } private Transaction mapApiToDomain(TransactionApi transactionApi,Transaction transaction) throws NotFoundException { Objects.requireNonNull(transaction); List<Label> labels = new ArrayList<>(); for(Long labelId : transactionApi.getLabelIds()) { Label label = labelDAO.findById(labelId).orElseThrow(() -> new NotFoundException("Label "+labelId+" not found.")); labels.add(label); } transaction.setLabels(labels); return transaction; } @GET @UnitOfWork @Timed public List<TransactionApi> get( @QueryParam("first") @Min(0) Integer first, @QueryParam("max") @Min(0) Integer max, @QueryParam("label") @Min(0) Integer labelId, @QueryParam("dateFrom") @Pattern(regexp="\\d{4}-\\d{2}-\\d{2}") String dateFromString, @QueryParam("dateTo") @Pattern(regexp="\\d{4}-\\d{2}-\\d{2}") String dateToString) { MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters(); HashMap<String,Object> queryAttributes = new HashMap<>(); for(String queryParam : queryParams.keySet()) { Object attrToAdd = queryParams.getFirst(queryParam); if(queryParam.equals("dateFrom") || queryParam.equals("dateTo")) { try { attrToAdd = new SimpleDateFormat("yyyy-MM-dd").parse((String)attrToAdd); } catch (ParseException e) { LOGGER.debug("Can't parse date string {}",dateFromString); continue; } } if(queryParam.equals("label")) { List<String> labelIDs = queryParams.get("label"); List<Label> labels = new ArrayList<>(); for(String id : labelIDs) { Label label = labelDAO.findById(Long.parseLong(id)).orElseThrow(() -> new NotFoundException("Label "+id+" not found.")); labels.add(label); } attrToAdd = labels; } queryAttributes.put(queryParam,attrToAdd); } ArrayList<TransactionApi> apiTransactions = new ArrayList<>(); for(Transaction transaction : transactionDAO.findAll(queryAttributes)) { TransactionApi transactionApi = mapDomainToApi(transaction); apiTransactions.add(transactionApi); } return apiTransactions; } @GET @Path("/{id}") @UnitOfWork public TransactionApi getById(@PathParam("id") LongParam id) { Transaction transaction = transactionDAO.findById(id.get()).orElseThrow(() -> new NotFoundException("Not found.")); TransactionApi transactionApi = mapDomainToApi(transaction); return transactionApi; } @PUT @Path("/{id}") @UnitOfWork public TransactionApi replace(@PathParam("id") LongParam id, TransactionApi transactionApi) { Transaction transaction = transactionDAO.findById(id.get()).orElseThrow(() -> new NotFoundException("Transaction not found.")); mapApiToDomain(transactionApi, transaction); transactionDAO.create(transaction); return transactionApi; } @POST @Path("/import") @Consumes(MediaType.MULTIPART_FORM_DATA) @UnitOfWork(transactional=false) @Timed public Response importTransactions( @NotNull @FormDataParam("file") InputStream uploadedInputStream, @NotNull @FormDataParam("file") FormDataContentDisposition fileDetail, @NotNull @FormDataParam("type") String fileType, @NotNull @FormDataParam("baseResourceId") String baseResourceId) { ITransactionParser parser = parserFactory.getParser(uploadedInputStream,fileType,baseResourceId).orElseThrow(()->new InternalServerErrorException("Can't configure parser for a given file type")); ImportResult result = importTransactions(parser); result.setFileName(fileDetail.getFileName()); return Response.status(200).entity(result).build(); } @GET @Path("/import") public List<ImportType> getImportTypes() { ArrayList<ImportType> importTypes = new ArrayList<>(); for(ParserSupportedType type : parserFactory.getSupportedTypes()) { try { Class<?> resourceClass = Class.forName("pl.surreal.finance.transaction.resources."+type.getBaseResourceClass().getSimpleName()+"Resource"); URI uri = uriInfo.getBaseUriBuilder().path(resourceClass).build(); ImportType importType = new ImportType(type.getId(),type.getDescription(),Link.fromUri(uri).rel("describedby").type(type.getBaseResourceClass().getSimpleName()).build()); importTypes.add(importType); } catch(Exception e) { LOGGER.warn("getImportCapabilities : can't add supported type due to '{}'",e.toString()); e.printStackTrace(); } } return importTypes; } @POST @Path("/runAllRules") @UnitOfWork public LabelResultApi runAllRules() { int transactionCount=0; int labelsCount=0; for(pl.surreal.finance.transaction.core.Transaction t: transactionDAO.findAll()) { int appliedCount = transactionLabeler.label(t); if(appliedCount>0) { transactionCount++; labelsCount+=appliedCount; transactionDAO.create(t); } } return new LabelResultApi(transactionCount,labelsCount); } @POST @Path("/runRule/{id}") @UnitOfWork public LabelResultApi runRule(@PathParam("id") LongParam id) { int transactionCount=0; int labelsCount=0; for(pl.surreal.finance.transaction.core.Transaction t: transactionDAO.findAll()) { try { int appliedCount = transactionLabeler.label(t,id.get()); if(appliedCount>0) { transactionCount++; labelsCount+=appliedCount; transactionDAO.create(t); } } catch(NoSuchElementException ex) { throw new NotFoundException(ex.getMessage()); } } return new LabelResultApi(transactionCount,labelsCount); } private ImportResult importTransactions(ITransactionParser parser) { ImportResult result = new ImportResult(); while(parser.hasNext()) { Optional<pl.surreal.finance.transaction.core.Transaction> optional = parser.getNext(); result.incProcessed(); if(optional.isPresent()) { try { transactionDAO.create(optional.get()); result.incImported(); } catch(ConstraintViolationException ex) { LOGGER.warn("importCSV: constraint violation '{}'",ex.getMessage()); result.incContraintViolations(); continue; } } else { result.incNulls(); } } parser.close(); return result; } }
apache-2.0
Vam85/gwt-createjs
gwt-easeljs/src/com/voisintech/easeljs/display/MovieClip.java
69
package com.voisintech.easeljs.display; public class MovieClip { }
apache-2.0
HuangLS/neo4j
advanced/management/src/main/java/org/neo4j/management/HighAvailability.java
2055
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.management; import org.neo4j.jmx.Description; import org.neo4j.jmx.ManagementInterface; @ManagementInterface( name = HighAvailability.NAME ) @Description( "Information about an instance participating in a HA cluster" ) public interface HighAvailability { final String NAME = "High Availability"; @Description( "The identifier used to identify this server in the HA cluster" ) String getInstanceId(); @Description( "Whether this instance is available or not" ) boolean isAvailable(); @Description( "Whether this instance is alive or not" ) boolean isAlive(); @Description( "The role this instance has in the cluster" ) String getRole(); @Description( "The time when the data on this instance was last updated from the master" ) String getLastUpdateTime(); @Description( "The latest transaction id present in this instance's store" ) long getLastCommittedTxId(); @Description( "Information about all instances in this cluster" ) ClusterMemberInfo[] getInstancesInCluster(); @Description( "(If this is a slave) Update the database on this " + "instance with the latest transactions from the master" ) String update(); }
apache-2.0
EMostafaAli/HlaListener
src/main/java/ca/mali/customcontrol/DimensionsListController.java
6175
/* * Copyright (c) 2015-2016, Mostafa Ali (engabdomostafa@gmail.com) * 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. * * 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. */ package ca.mali.customcontrol; import ca.mali.fomparser.DimensionFDD; import ca.mali.fomparser.FddObjectModel; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.CheckBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.CheckBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.util.Callback; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; /** * @author Mostafa Ali <engabdomostafa@gmail.com> */ public class DimensionsListController extends VBox { //Logger private static final Logger logger = LogManager.getLogger(); @FXML private TableView<DimensionState> DimensionTableView; @FXML private TableColumn<DimensionState, String> DimensionTableColumn; @FXML private TableColumn CheckTableColumn; CheckBox cb = new CheckBox(); ObservableList<DimensionState> dimensions = FXCollections.observableArrayList(); public DimensionsListController() { logger.entry(); FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/customcontrol/DimensionsList.fxml")); fxmlLoader.setController(this); fxmlLoader.setRoot(this); try { fxmlLoader.load(); } catch (IOException ex) { logger.log(Level.FATAL, ex.getMessage(), ex); } logger.exit(); } public void setFddObjectModel(FddObjectModel fddObjectModel) { logger.entry(); if (fddObjectModel != null) { fddObjectModel.getDimensions().values().stream().forEach((value) -> dimensions.add(new DimensionState(value))); DimensionTableView.setItems(dimensions); dimensions.forEach((interaction) -> interaction.onProperty().addListener((observable, oldValue, newValue) -> { if (!newValue) { cb.setSelected(false); } else if (dimensions.stream().allMatch(a -> a.isOn())) { cb.setSelected(true); } })); DimensionTableColumn.setCellValueFactory(new PropertyValueFactory<>("DimensionName")); CheckTableColumn.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<DimensionState, Boolean>, ObservableValue<Boolean>>() { @Override public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<DimensionState, Boolean> param) { return param.getValue().onProperty(); } }); CheckTableColumn.setCellFactory(CheckBoxTableCell.forTableColumn(CheckTableColumn)); cb.setUserData(CheckTableColumn); cb.setOnAction((ActionEvent event) -> { CheckBox cb1 = (CheckBox) event.getSource(); TableColumn tc = (TableColumn) cb1.getUserData(); DimensionTableView.getItems().stream().forEach((item) -> item.setOn(cb1.isSelected())); }); CheckTableColumn.setGraphic(cb); } logger.exit(); } public List<DimensionFDD> getDimensions() { return dimensions.stream().filter(DimensionState::isOn).map(a -> a.dimension).collect(Collectors.toList()); } public static class DimensionState { private final ReadOnlyStringWrapper DimensionName = new ReadOnlyStringWrapper(); private final BooleanProperty on = new SimpleBooleanProperty(); private final DimensionFDD dimension; public DimensionState(DimensionFDD dimension) { this.dimension = dimension; DimensionName.set(dimension.getName()); } public String getDimensionName() { return DimensionName.get(); } public ReadOnlyStringProperty dimensionNameProperty() { return DimensionName.getReadOnlyProperty(); } public boolean isOn() { return on.get(); } public void setOn(boolean value) { on.set(value); } public BooleanProperty onProperty() { return on; } @Override public String toString() { return dimension.getName(); } } }
apache-2.0
ManfredTremmel/gwt-bean-validators
gwt-bean-validators/src/main/java/de/knightsoftnet/validators/client/data/PhoneRegionCode504Constants.java
1101
/* * 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 de.knightsoftnet.validators.client.data; import com.google.gwt.i18n.client.Constants; import java.util.Map; /** * set of phone country region codes. * * @author Manfred Tremmel * */ public interface PhoneRegionCode504Constants extends Constants { Map<String, String> phoneRegionCodes504(); }
apache-2.0
duftler/clouddriver
clouddriver-kubernetes/src/main/java/com/netflix/spinnaker/clouddriver/kubernetes/provider/KubernetesModelUtil.java
3696
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.clouddriver.kubernetes.provider; import com.netflix.spinnaker.clouddriver.model.HealthState; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @Slf4j public class KubernetesModelUtil { public static long translateTime(String time) { return KubernetesModelUtil.translateTime(time, "yyyy-MM-dd'T'HH:mm:ssX"); } public static long translateTime(String time, String format) { try { return StringUtils.isNotEmpty(time) ? (new SimpleDateFormat(format).parse(time)).getTime() : 0; } catch (ParseException e) { log.error("Failed to parse kubernetes timestamp", e); return 0; } } public static HealthState getHealthState(List<Map<String, Object>> health) { return someUpRemainingUnknown(health) ? HealthState.Up : someSucceededRemainingUnknown(health) ? HealthState.Succeeded : anyStarting(health) ? HealthState.Starting : anyDown(health) ? HealthState.Down : anyFailed(health) ? HealthState.Failed : anyOutOfService(health) ? HealthState.OutOfService : HealthState.Unknown; } private static boolean stateEquals(Map<String, Object> health, HealthState state) { Object healthState = health.get("state"); return healthState != null && healthState.equals(state.name()); } private static boolean someUpRemainingUnknown(List<Map<String, Object>> healthsList) { List<Map<String, Object>> knownHealthList = healthsList.stream() .filter(h -> !stateEquals(h, HealthState.Unknown)) .collect(Collectors.toList()); return !knownHealthList.isEmpty() && knownHealthList.stream().allMatch(h -> stateEquals(h, HealthState.Up)); } private static boolean someSucceededRemainingUnknown(List<Map<String, Object>> healthsList) { List<Map<String, Object>> knownHealthList = healthsList.stream() .filter(h -> !stateEquals(h, HealthState.Unknown)) .collect(Collectors.toList()); return !knownHealthList.isEmpty() && knownHealthList.stream().allMatch(h -> stateEquals(h, HealthState.Succeeded)); } private static boolean anyDown(List<Map<String, Object>> healthsList) { return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Down)); } private static boolean anyStarting(List<Map<String, Object>> healthsList) { return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Starting)); } private static boolean anyFailed(List<Map<String, Object>> healthsList) { return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Failed)); } private static boolean anyOutOfService(List<Map<String, Object>> healthsList) { return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.OutOfService)); } }
apache-2.0
astefanutti/camel-cdi
envs/se/src/test/java/org/apache/camel/cdi/se/MultiCamelContextReusedRouteTest.java
4298
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.cdi.se; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.cdi.CdiCamelExtension; import org.apache.camel.cdi.ContextName; import org.apache.camel.cdi.Uri; import org.apache.camel.cdi.se.bean.FirstCamelContextBean; import org.apache.camel.cdi.se.bean.SecondNamedCamelContextBean; import org.apache.camel.component.mock.MockEndpoint; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.util.concurrent.TimeUnit; import static org.apache.camel.cdi.se.expression.ExchangeExpression.fromCamelContext; import static org.apache.camel.component.mock.MockEndpoint.assertIsSatisfied; @RunWith(Arquillian.class) public class MultiCamelContextReusedRouteTest { @Deployment public static Archive<?> deployment() { return ShrinkWrap.create(JavaArchive.class) // Camel CDI .addPackage(CdiCamelExtension.class.getPackage()) // Test classes .addClasses(FirstCamelContextBean.class, SecondNamedCamelContextBean.class) // Bean archive deployment descriptor .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } @Inject @ContextName("first") private CamelContext firstCamelContext; @Inject @ContextName("first") @Uri("direct:inbound") private ProducerTemplate firstInbound; @Inject @ContextName("first") @Uri("mock:outbound") private MockEndpoint firstOutbound; @Inject @ContextName("second") private CamelContext secondCamelContext; @Inject @ContextName("second") @Uri("direct:inbound") private ProducerTemplate secondInbound; @Inject @ContextName("second") @Uri("mock:outbound") private MockEndpoint secondOutbound; @Test public void sendMessageToFirstCamelContextInbound() throws InterruptedException { firstOutbound.expectedMessageCount(1); firstOutbound.expectedBodiesReceived("test-first"); firstOutbound.expectedHeaderReceived("context", "test"); firstOutbound.message(0).exchange().matches(fromCamelContext("first")); firstInbound.sendBody("test-first"); assertIsSatisfied(2L, TimeUnit.SECONDS, firstOutbound); } @Test public void sendMessageToSecondCamelContextInbound() throws InterruptedException { secondOutbound.expectedMessageCount(1); secondOutbound.expectedBodiesReceived("test-second"); secondOutbound.expectedHeaderReceived("context", "test"); secondOutbound.message(0).exchange().matches(fromCamelContext("second")); secondInbound.sendBody("test-second"); assertIsSatisfied(2L, TimeUnit.SECONDS, secondOutbound); } @ContextName("first") @ContextName("second") static class ReusedRouteBuilder extends RouteBuilder { @Override public void configure() { from("direct:inbound").setHeader("context").constant("test").to("mock:outbound"); } } }
apache-2.0
StephanieMak/word2vec-query-expansion
src/main/java/com/radialpoint/word2vec/Vectors.java
4960
/* * Copyright 2014 Radialpoint SafeCare 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.radialpoint.word2vec; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; /** * This class stores the mapping of String->array of float that constitutes each vector. * * The class can serialize to/from a stream. * * The ConvertVectors allows to transform the C binary vectors into instances of this class. */ public class Vectors { /** * The vectors themselves. */ protected float[][] vectors; /** * The words associated with the vectors */ protected String[] vocabVects; /** * Size of each vector */ protected int size; /** * Inverse map, word-> index */ protected Map<String, Integer> vocab; /** * Package-level constructor, used by the ConvertVectors program. * * @param vectors * , it cannot be empty * @param vocabVects * , the length should match vectors */ Vectors(float[][] vectors, String[] vocabVects) throws VectorsException { this.vectors = vectors; this.size = vectors[0].length; if (vectors.length != vocabVects.length) throw new VectorsException("Vectors and vocabulary size mismatch"); this.vocabVects = vocabVects; this.vocab = new HashMap<String, Integer>(); for (int i = 0; i < vocabVects.length; i++) vocab.put(vocabVects[i], i); } /** * Initialize a Vectors instance from an open input stream. This method closes the stream. * * @param is * the open stream * @throws IOException * if there are problems reading from the stream */ public Vectors(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int words = dis.readInt(); int size = dis.readInt(); this.size = size; this.vectors = new float[words][]; this.vocabVects = new String[words]; for (int i = 0; i < words; i++) { this.vocabVects[i] = dis.readUTF(); float[] vector = new float[size]; for (int j = 0; j < size; j++) vector[j] = dis.readFloat(); this.vectors[i] = vector; } this.vocab = new HashMap<String, Integer>(); for (int i = 0; i < vocabVects.length; i++) vocab.put(vocabVects[i], i); dis.close(); } /** * Writes this vector to an open output stream. This method closes the stream. * * @param os * the stream to write to * @throws IOException * if there are problems writing to the stream */ public void writeTo(OutputStream os) throws IOException { DataOutputStream dos = new DataOutputStream(os); dos.writeInt(this.vectors.length); dos.writeInt(this.size); for (int i = 0; i < vectors.length; i++) { dos.writeUTF(this.vocabVects[i]); for (int j = 0; j < size; j++) dos.writeFloat(this.vectors[i][j]); } dos.close(); } public float[][] getVectors() { return vectors; } public float[] getVector(int i) { return vectors[i]; } public float[] getVector(String term) throws OutOfVocabularyException { Integer idx = vocab.get(term); if (idx == null) throw new OutOfVocabularyException("Unknown term '" + term + "'"); return vectors[idx]; } public int getIndex(String term) throws OutOfVocabularyException { Integer idx = vocab.get(term); if (idx == null) throw new OutOfVocabularyException("Unknown term '" + term + "'"); return idx; } public Integer getIndexOrNull(String term) { return vocab.get(term); } public String getTerm(int index) { return vocabVects[index]; } public Map<String, Integer> getVocabulary() { return vocab; } public boolean hasTerm(String term) { return vocab.containsKey(term); } public int vectorSize() { return size; } public int wordCount() { return vectors.length; } }
apache-2.0
evandor/skysail
skysail.server.queryfilter/src/io/skysail/server/queryfilter/parser/LdapParser.java
9977
package io.skysail.server.queryfilter.parser; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.osgi.framework.InvalidSyntaxException; import org.osgi.service.component.annotations.Component; import io.skysail.server.domain.jvm.FieldFacet; import io.skysail.server.filter.ExprNode; import io.skysail.server.filter.FilterParser; import io.skysail.server.queryfilter.nodes.AndNode; import io.skysail.server.queryfilter.nodes.EqualityNode; import io.skysail.server.queryfilter.nodes.GreaterNode; import io.skysail.server.queryfilter.nodes.IsInNode; import io.skysail.server.queryfilter.nodes.LessNode; import io.skysail.server.queryfilter.nodes.NotNode; import io.skysail.server.queryfilter.nodes.OrNode; import io.skysail.server.queryfilter.nodes.PresentNode; import io.skysail.server.queryfilter.nodes.SubstringNode; import lombok.ToString; import lombok.extern.slf4j.Slf4j; /** * @author org.osgi.framework.FrameworkUtil.ExprNode.Parser * */ @Component @Slf4j @ToString public class LdapParser implements FilterParser { private char[] filterChars; private int pos; @Override public ExprNode parse(String filterstring) { filterChars = filterstring.toCharArray(); pos = 0; ExprNode filter; try { filter = parseFilter(filterstring); sanityCheck(filterstring); return filter; } catch (ArrayIndexOutOfBoundsException | InvalidSyntaxException e) { log.error(e.getMessage(),e); } return null; } /* e.g. (buchungstag;YYYY=2006) */ @SuppressWarnings("unchecked") @Override public Set<String> getSelected(FieldFacet facet, Map<String, String> lines, String filterParamValue) { return (Set<String>) parse(filterParamValue).accept(n -> n.getSelected(facet, lines)); } private ExprNode parseFilter(String filterstring) throws InvalidSyntaxException { skipWhiteSpace(); if (filterChars[pos] != '(') { throw new InvalidSyntaxException("Missing '(': " + filterstring.substring(pos), filterstring); } pos++; ExprNode filter = parseFiltercomp(filterstring); skipWhiteSpace(); if (filterChars[pos] != ')') { throw new InvalidSyntaxException("Missing ')': " + filterstring.substring(pos), filterstring); } pos++; skipWhiteSpace(); return filter; } private ExprNode parseFiltercomp(String filterstring) throws InvalidSyntaxException { skipWhiteSpace(); char c = filterChars[pos]; switch (c) { case '&': { pos++; return parseAnd(filterstring); } case '|': { pos++; return parseOr(filterstring); } case '!': { pos++; return parseNot(filterstring); } } return parseItem(filterstring); } private ExprNode parseAnd(String filterstring) throws InvalidSyntaxException { int lookahead = pos; skipWhiteSpace(); if (filterChars[pos] != '(') { pos = lookahead - 1; return parseItem(filterstring); } List<ExprNode> operands = new ArrayList<>(10); while (filterChars[pos] == '(') { ExprNode child = parseFilter(filterstring); operands.add(child); } return new AndNode(operands); } private ExprNode parseOr(String filterstring) throws InvalidSyntaxException { int lookahead = pos; skipWhiteSpace(); if (filterChars[pos] != '(') { pos = lookahead - 1; return parseItem(filterstring); } List<ExprNode> operands = new ArrayList<>(10); while (filterChars[pos] == '(') { ExprNode child = parseFilter(filterstring); operands.add(child); } return new OrNode(operands); } private ExprNode parseNot(String filterstring) throws InvalidSyntaxException { int lookahead = pos; skipWhiteSpace(); if (filterChars[pos] != '(') { pos = lookahead - 1; return parseItem(filterstring); } ExprNode child = parseFilter(filterstring); return new NotNode(child); } private ExprNode parseItem(String filterstring) throws InvalidSyntaxException { String attr = parseAttr(filterstring); skipWhiteSpace(); switch (filterChars[pos]) { case '~': { if (filterChars[pos + 1] == '=') { pos += 2; return null; } break; } case '>': { if (filterChars[pos + 1] == '=') { pos += 2; throw new InvalidSyntaxException("Invalid operator: >= not implemented", filterstring); } else { pos += 1; return new GreaterNode(attr, Float.valueOf((String)parseSubstring())); } } case '<': { if (filterChars[pos + 1] == '=') { pos += 2; throw new InvalidSyntaxException("Invalid operator: <= not implemented", filterstring); } else { pos += 1; return new LessNode(attr, Float.valueOf((String)parseSubstring())); } } case '=': { if (filterChars[pos + 1] == '*') { int oldpos = pos; pos += 2; skipWhiteSpace(); if (filterChars[pos] == ')') { return new PresentNode(attr, null); } pos = oldpos; } pos++; Object string = parseSubstring(); if (string instanceof String) { return new EqualityNode(attr, (String) string); } if (string instanceof String[]) { String[] value = (String[]) string; if (value.length == 3) { return new SubstringNode(attr, value[1]); } else if (value.length == 2) { if (value[0] == null) { return new SubstringNode(attr, value[1]); } else if (value[1] == null) { return new SubstringNode(attr, value[0]); } } } return null; } case '\u00A7': { // paragraph or section symbol, "element of", "is in", // not standard LDAP syntax! will replace this whole // thing with a ANTLR-based grammar pos++; Object string = parseSubstring(); if (string instanceof String) { return new IsInNode(attr, (String) string); } return null; } } throw new InvalidSyntaxException("Invalid operator: " + filterstring.substring(pos), filterstring); } private String parseAttr(String filterstring) throws InvalidSyntaxException { skipWhiteSpace(); int begin = pos; int end = pos; char c = filterChars[pos]; while (c != '~' && c != '\u00A7' && c != '<' && c != '>' && c != '=' && c != '(' && c != ')') { pos++; if (!Character.isWhitespace(c)) { end = pos; } c = filterChars[pos]; } int length = end - begin; if (length == 0) { throw new InvalidSyntaxException("Missing attr: " + filterstring.substring(pos), filterstring); } return new String(filterChars, begin, length); } private Object parseSubstring() throws InvalidSyntaxException { StringBuilder sb = new StringBuilder(filterChars.length - pos); List<String> operands = new ArrayList<>(10); boolean isMethod = false; parseloop: while (true) { char c = filterChars[pos]; switch (c) { case ')': { if (!isMethod) { if (sb.length() > 0) { operands.add(sb.toString()); } break parseloop; } else { isMethod = false; pos++; sb.append(")"); break; } } case '(': { isMethod = true; pos += 1; sb.append("("); break; } case '*': { if (sb.length() > 0) { operands.add(sb.toString()); } sb.setLength(0); operands.add(null); pos++; break; } case '\\': { pos++; c = filterChars[pos]; /* fall through into default */ } default: { sb.append(c); pos++; break; } } } int size = operands.size(); if (size == 0) { return ""; } if (size == 1) { Object single = operands.get(0); if (single != null) { return single; } } return operands.toArray(new String[size]); } private void skipWhiteSpace() { for (int length = filterChars.length; (pos < length) && Character.isWhitespace(filterChars[pos]);) { pos++; } } private void sanityCheck(String filterstring) throws InvalidSyntaxException { if (pos != filterChars.length) { throw new InvalidSyntaxException("Extraneous trailing characters: " + filterstring.substring(pos), filterstring); } } }
apache-2.0
jon-stumpf/traccar
test/org/traccar/protocol/TelicProtocolDecoderTest.java
4381
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; public class TelicProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { TelicProtocolDecoder decoder = new TelicProtocolDecoder(new TelicProtocol()); verifyNull(decoder, text( "0026355565071347499|206|01|001002008")); verifyPosition(decoder, text( "052028495198,160917073641,0,160917073642,43879,511958,3,24,223,17,,,-3,142379,,0010,00,64,205,0,0499")); verifyPosition(decoder, text( "01302849516,160917073503,0,160917073504,43907,512006,3,11,160,14,,,-7,141811,,0010,00,64,206,0,0499")); verifyPosition(decoder, text( "002135556507134749999,010817171138,0,010817171138,004560973,50667173,3,0,0,11,1,1,100,958071,20601,000000,00,4142,0000,0000,0208,10395,0")); verifyPosition(decoder, text( "442045993198,290317131935,0,290317131935,269158,465748,3,26,183,,,,184,85316567,226,01,00,68,218")); verifyPosition(decoder, text( "673091036017,290317131801,0,290317131801,262214,450536,3,40,199,8,,,154,19969553,,0011,00,59,240,0,0406")); verifyPosition(decoder, text( "092020621198,280317084155,0,280317084156,259762,444356,3,42,278,9,,,89,56793311,,0110,00,67,0,,0400")); verifyPosition(decoder, text( "502091227598,280317084149,0,280317084149,261756,444358,3,33,286,9,,,77,3143031,,0010,00,171,240,0,0406")); verifyPosition(decoder, text( "232027997498,230317083900,0,230317083900,260105,444112,3,22,259,,,,111,61110817,226,01,00,255,218,00000000000000")); verifyPosition(decoder, text( "072027997498,230317082635,0,230317082635,260332,444265,3,28,165,,,,124,61107582,226,01,00,255,219,00000000000000")); verifyNull(decoder, text( "0026203393|226|10|002004010")); verifyPosition(decoder, text( "003020339325,190317083052,0,180317103127,259924,445133,3,0,0,9,,,93,12210141,,0010,00,40,240,0,0406")); verifyNull(decoder, text( "0026296218SCCE01_SCCE|226|10|0267")); verifyNull(decoder, text( "1242022592TTUV0100,0201,351266000022592,170403114305,0115859,480323,3,30,5,9,3,4,650,250000000,26202,1001,0001,211,233,111,0")); verifyPosition(decoder, text( "123002259213,170403114305,1234,170403114305,0115859,480323,3,30,5,9,3,4,650,250000000,26202,1001,0001,211,233,111,0,600")); verifyNull(decoder, text( "0044296218TLOC0267,00,011009000296218,190317083036,255178,445072,3,0,82,,,,168,14741296,,00,00,0,217")); verifyPosition(decoder, text( "003097061325,220616044200,0,220616044200,247169,593911,3,48,248,8,,,50,1024846,,1111,00,48,0,51,0406")); verifyPosition(decoder, text( "003097061325,210216112630,0,210216001405,246985,594078,3,0,283,12,,,23,4418669,,0010,00,117,0,0,0108")); verifyPosition(decoder, text( "592078222222,010100030200,0,240516133500,222222,222222,3,0,0,5,,,37,324,,1010,00,48,0,0,0406")); verifyPosition(decoder, text( "002017297899,220216111100,0,220216111059,014306446,46626713,3,7,137,7,,,448,266643,,0000,00,0,206,0,0407")); verifyPosition(decoder, text( "003097061325,210216112630,0,210216001405,246985,594078,3,0,283,12,,,23,4418669,,0010,00,117,0,0,0108")); verifyNull(decoder, text( "0026970613|248|01|004006011")); verifyPosition(decoder, text( "032097061399,210216112800,0,210216112759,246912,594076,3,47,291,10,,,46,4419290,,0010,00,100,0,0,0108")); verifyPosition(decoder, text( "002017297899,190216202500,0,190216202459,014221890,46492170,3,0,0,6,,,1034,43841,,0000,00,0,209,0,0407")); verifyPosition(decoder, text( "182043672999,010100001301,0,270613041652,166653,475341,3,0,355,6,2,1,231,8112432,23201,01,00,217,0,0,0,0,7"), position("2013-06-27 04:16:52.000", true, 47.53410, 16.66530)); verifyPosition(decoder, text( "182043672999,010100001301,0,270613041652,166653,475341,3,0,355,6,2,1,231,8112432,23201,01,00,217,0,0,0,0,7")); } }
apache-2.0
KMANTER/StopMyLine2016
client/StopTheLine-android/gen/com/skm/stl/R.java
567
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.skm.stl; public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/Volume.java
8673
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ecs.model; import java.io.Serializable; /** * <p> * A data volume used in a task definition. * </p> */ public class Volume implements Serializable, Cloneable { /** * <p> * The name of the volume. Up to 255 letters (uppercase and lowercase), * numbers, hyphens, and underscores are allowed. This name is referenced in * the <code>sourceVolume</code> parameter of container definition * <code>mountPoints</code>. * </p> */ private String name; /** * <p> * The contents of the <code>host</code> parameter determine whether your * data volume persists on the host container instance and where it is * stored. If the host parameter is empty, then the Docker daemon assigns a * host path for your data volume, but the data is not guaranteed to persist * after the containers associated with it stop running. * </p> */ private HostVolumeProperties host; /** * <p> * The name of the volume. Up to 255 letters (uppercase and lowercase), * numbers, hyphens, and underscores are allowed. This name is referenced in * the <code>sourceVolume</code> parameter of container definition * <code>mountPoints</code>. * </p> * * @param name * The name of the volume. Up to 255 letters (uppercase and * lowercase), numbers, hyphens, and underscores are allowed. This * name is referenced in the <code>sourceVolume</code> parameter of * container definition <code>mountPoints</code>. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the volume. Up to 255 letters (uppercase and lowercase), * numbers, hyphens, and underscores are allowed. This name is referenced in * the <code>sourceVolume</code> parameter of container definition * <code>mountPoints</code>. * </p> * * @return The name of the volume. Up to 255 letters (uppercase and * lowercase), numbers, hyphens, and underscores are allowed. This * name is referenced in the <code>sourceVolume</code> parameter of * container definition <code>mountPoints</code>. */ public String getName() { return this.name; } /** * <p> * The name of the volume. Up to 255 letters (uppercase and lowercase), * numbers, hyphens, and underscores are allowed. This name is referenced in * the <code>sourceVolume</code> parameter of container definition * <code>mountPoints</code>. * </p> * * @param name * The name of the volume. Up to 255 letters (uppercase and * lowercase), numbers, hyphens, and underscores are allowed. This * name is referenced in the <code>sourceVolume</code> parameter of * container definition <code>mountPoints</code>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Volume withName(String name) { setName(name); return this; } /** * <p> * The contents of the <code>host</code> parameter determine whether your * data volume persists on the host container instance and where it is * stored. If the host parameter is empty, then the Docker daemon assigns a * host path for your data volume, but the data is not guaranteed to persist * after the containers associated with it stop running. * </p> * * @param host * The contents of the <code>host</code> parameter determine whether * your data volume persists on the host container instance and where * it is stored. If the host parameter is empty, then the Docker * daemon assigns a host path for your data volume, but the data is * not guaranteed to persist after the containers associated with it * stop running. */ public void setHost(HostVolumeProperties host) { this.host = host; } /** * <p> * The contents of the <code>host</code> parameter determine whether your * data volume persists on the host container instance and where it is * stored. If the host parameter is empty, then the Docker daemon assigns a * host path for your data volume, but the data is not guaranteed to persist * after the containers associated with it stop running. * </p> * * @return The contents of the <code>host</code> parameter determine whether * your data volume persists on the host container instance and * where it is stored. If the host parameter is empty, then the * Docker daemon assigns a host path for your data volume, but the * data is not guaranteed to persist after the containers associated * with it stop running. */ public HostVolumeProperties getHost() { return this.host; } /** * <p> * The contents of the <code>host</code> parameter determine whether your * data volume persists on the host container instance and where it is * stored. If the host parameter is empty, then the Docker daemon assigns a * host path for your data volume, but the data is not guaranteed to persist * after the containers associated with it stop running. * </p> * * @param host * The contents of the <code>host</code> parameter determine whether * your data volume persists on the host container instance and where * it is stored. If the host parameter is empty, then the Docker * daemon assigns a host path for your data volume, but the data is * not guaranteed to persist after the containers associated with it * stop running. * @return Returns a reference to this object so that method calls can be * chained together. */ public Volume withHost(HostVolumeProperties host) { setHost(host); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: " + getName() + ","); if (getHost() != null) sb.append("Host: " + getHost()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Volume == false) return false; Volume other = (Volume) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getHost() == null ^ this.getHost() == null) return false; if (other.getHost() != null && other.getHost().equals(this.getHost()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getHost() == null) ? 0 : getHost().hashCode()); return hashCode; } @Override public Volume clone() { try { return (Volume) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
rajeevanv89/developer-studio
esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/policies/TransactionMediatorOutputConnectorItemSemanticEditPolicy.java
3894
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies; import java.util.Iterator; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.ReorientRelationshipRequest; import org.eclipse.gmf.runtime.notation.Edge; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.EsbLinkCreateCommand; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands.EsbLinkReorientCommand; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts.EsbLinkEditPart; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry; import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes; /** * @generated */ public class TransactionMediatorOutputConnectorItemSemanticEditPolicy extends EsbBaseItemSemanticEditPolicy { /** * @generated */ public TransactionMediatorOutputConnectorItemSemanticEditPolicy() { super(EsbElementTypes.TransactionMediatorOutputConnector_3119); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { View view = (View) getHost().getModel(); CompositeTransactionalCommand cmd = new CompositeTransactionalCommand( getEditingDomain(), null); cmd.setTransactionNestingEnabled(false); for (Iterator<?> it = view.getSourceEdges().iterator(); it.hasNext();) { Edge outgoingLink = (Edge) it.next(); if (EsbVisualIDRegistry.getVisualID(outgoingLink) == EsbLinkEditPart.VISUAL_ID) { DestroyElementRequest r = new DestroyElementRequest( outgoingLink.getElement(), false); cmd.add(new DestroyElementCommand(r)); cmd.add(new DeleteCommand(getEditingDomain(), outgoingLink)); continue; } } EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$ if (annotation == null) { // there are indirectly referenced children, need extra commands: false addDestroyShortcutsCommand(cmd, view); // delete host element cmd.add(new DestroyElementCommand(req)); } else { cmd.add(new DeleteCommand(getEditingDomain(), view)); } return getGEFWrapper(cmd.reduce()); } /** * @generated */ protected Command getCreateRelationshipCommand(CreateRelationshipRequest req) { Command command = req.getTarget() == null ? getStartCreateRelationshipCommand(req) : getCompleteCreateRelationshipCommand(req); return command != null ? command : super .getCreateRelationshipCommand(req); } /** * @generated */ protected Command getStartCreateRelationshipCommand( CreateRelationshipRequest req) { if (EsbElementTypes.EsbLink_4001 == req.getElementType()) { return getGEFWrapper(new EsbLinkCreateCommand(req, req.getSource(), req.getTarget())); } return null; } /** * @generated */ protected Command getCompleteCreateRelationshipCommand( CreateRelationshipRequest req) { if (EsbElementTypes.EsbLink_4001 == req.getElementType()) { return null; } return null; } /** * Returns command to reorient EClass based link. New link target or source * should be the domain model element associated with this node. * * @generated */ protected Command getReorientRelationshipCommand( ReorientRelationshipRequest req) { switch (getVisualID(req)) { case EsbLinkEditPart.VISUAL_ID: return getGEFWrapper(new EsbLinkReorientCommand(req)); } return super.getReorientRelationshipCommand(req); } }
apache-2.0
vergnes/spring-social-weibo
src/main/java/org/springframework/social/weibo/api/impl/json/TrendsWrapperMixin.java
1429
/* * Copyright 2011 France Telecom R&D Beijing Co., Ltd 北京法国电信研发中心有限公司 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.weibo.api.impl.json; import java.util.Date; import java.util.SortedSet; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.springframework.social.weibo.api.Trends.Trend; /** * Annotated mixin to add Jackson annotations to TrendsWrapper. * * @author edva8332 */ @JsonIgnoreProperties(ignoreUnknown = true) abstract class TrendsWrapperMixin { @JsonProperty("trends") @JsonDeserialize(using = TrendsDeserializer.class) SortedSet<Trend> trends; @JsonProperty("as_of") @JsonDeserialize(using = DateInSecondsDeserializer.class) Date asOf; }
apache-2.0
timstoner/stackexchangeimporter
src/main/java/com/example/stackexchange/util/SiteUtils.java
504
package com.example.stackexchange.util; import java.nio.file.Path; import java.nio.file.Paths; public class SiteUtils { private static String siteName; public static String getSiteName(String dir) { if (siteName == null) { Path path = Paths.get(dir); Path parent = path.getParent(); Path name = parent.getName(parent.getNameCount() - 1); siteName = name.toString(); } return siteName; } public static void setSiteName(String siteName) { SiteUtils.siteName = siteName; } }
apache-2.0
weiwenqiang/GitHub
MVP/BookReader-master/app/src/main/java/com/justwayward/reader/ui/fragment/FindFragment.java
3463
/** * Copyright 2016 JustWayward Team * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.justwayward.reader.ui.fragment; import android.content.Intent; import android.net.Uri; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.justwayward.reader.R; import com.justwayward.reader.base.BaseFragment; import com.justwayward.reader.bean.support.FindBean; import com.justwayward.reader.common.OnRvItemClickListener; import com.justwayward.reader.component.AppComponent; import com.justwayward.reader.ui.activity.SubjectBookListActivity; import com.justwayward.reader.ui.activity.TopCategoryListActivity; import com.justwayward.reader.ui.activity.TopRankActivity; import com.justwayward.reader.ui.adapter.FindAdapter; import com.justwayward.reader.view.SupportDividerItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /** * 发现 * * @author yuyh. * @date 16/9/1. */ public class FindFragment extends BaseFragment implements OnRvItemClickListener<FindBean> { @Bind(R.id.recyclerview) RecyclerView mRecyclerView; private FindAdapter mAdapter; private List<FindBean> mList = new ArrayList<>(); @Override public int getLayoutResId() { return R.layout.fragment_find; } @Override public void initDatas() { mList.clear(); mList.add(new FindBean("排行榜", R.drawable.home_find_rank)); mList.add(new FindBean("主题书单", R.drawable.home_find_topic)); mList.add(new FindBean("分类", R.drawable.home_find_category)); mList.add(new FindBean("官方QQ群", R.drawable.home_find_listen)); } @Override public void configViews() { mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mRecyclerView.addItemDecoration(new SupportDividerItemDecoration(mContext, LinearLayoutManager.VERTICAL, true)); mAdapter = new FindAdapter(mContext, mList, this); mRecyclerView.setAdapter(mAdapter); } @Override protected void setupActivityComponent(AppComponent appComponent) { } @Override public void attachView() { } @Override public void onItemClick(View view, int position, FindBean data) { switch (position) { case 0: TopRankActivity.startActivity(activity); break; case 1: SubjectBookListActivity.startActivity(activity); break; case 2: startActivity(new Intent(activity, TopCategoryListActivity.class)); break; case 3: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://jq.qq.com/?_wv=1027&k=46qbql8"))); break; default: break; } } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p281/Production5628.java
1891
package org.gradle.test.performance.mediummonolithicjavaproject.p281; public class Production5628 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
apache-2.0
ruspl-afed/dbeaver
plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/tools/MySQLScriptExecuteWizard.java
3895
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * Copyright (C) 2011-2012 Eugene Fradkin (eugene.fradkin@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.mysql.tools; import org.jkiss.dbeaver.ext.mysql.MySQLConstants; import org.jkiss.dbeaver.ext.mysql.MySQLDataSourceProvider; import org.jkiss.dbeaver.ext.mysql.MySQLMessages; import org.jkiss.dbeaver.ext.mysql.MySQLServerHome; import org.jkiss.dbeaver.ext.mysql.model.MySQLCatalog; import org.jkiss.dbeaver.ui.dialogs.tools.AbstractScriptExecuteWizard; import org.jkiss.dbeaver.utils.RuntimeUtils; import org.jkiss.utils.CommonUtils; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; class MySQLScriptExecuteWizard extends AbstractScriptExecuteWizard<MySQLCatalog, MySQLCatalog> { enum LogLevel { Normal, Verbose, Debug } private LogLevel logLevel; private boolean noBeep; private boolean isImport; private MySQLScriptExecuteWizardPageSettings mainPage; public MySQLScriptExecuteWizard(MySQLCatalog catalog, boolean isImport) { super(Collections.singleton(catalog), isImport ? MySQLMessages.tools_script_execute_wizard_db_import : MySQLMessages.tools_script_execute_wizard_execute_script); this.isImport = isImport; this.logLevel = LogLevel.Normal; this.noBeep = true; this.mainPage = new MySQLScriptExecuteWizardPageSettings(this); } public LogLevel getLogLevel() { return logLevel; } public void setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; } public boolean isImport() { return isImport; } @Override public boolean isVerbose() { return logLevel == LogLevel.Verbose || logLevel == LogLevel.Debug; } @Override public void addPages() { addPage(mainPage); super.addPages(); } @Override public void fillProcessParameters(List<String> cmd, MySQLCatalog arg) throws IOException { String dumpPath = RuntimeUtils.getHomeBinary(getClientHome(), MySQLConstants.BIN_FOLDER, "mysql").getAbsolutePath(); //$NON-NLS-1$ cmd.add(dumpPath); if (logLevel == LogLevel.Debug) { cmd.add("--debug-info"); //$NON-NLS-1$ } if (noBeep) { cmd.add("--no-beep"); //$NON-NLS-1$ } } @Override protected void setupProcessParameters(ProcessBuilder process) { if (!CommonUtils.isEmpty(getToolUserPassword())) { process.environment().put(MySQLConstants.ENV_VARIABLE_MYSQL_PWD, getToolUserPassword()); } } @Override public MySQLServerHome findServerHome(String clientHomeId) { return MySQLDataSourceProvider.getServerHome(clientHomeId); } @Override public Collection<MySQLCatalog> getRunInfo() { return getDatabaseObjects(); } @Override protected List<String> getCommandLine(MySQLCatalog arg) throws IOException { List<String> cmd = MySQLToolScript.getMySQLToolCommandLine(this, arg); cmd.add(arg.getName()); return cmd; } }
apache-2.0
skekre98/apex-mlhr
library/src/test/java/com/datatorrent/lib/script/JavaScriptOperatorTest.java
2038
/** * 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.datatorrent.lib.script; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import com.datatorrent.lib.testbench.CollectorTestSink; import com.datatorrent.lib.util.TestUtils; /** * Functional tests for {@link com.datatorrent.lib.script.JavaScriptOperator}. */ public class JavaScriptOperatorTest { @Test public void testJavaOperator() { // Create bash operator instance (calculate suqare). JavaScriptOperator oper = new JavaScriptOperator(); oper.addSetupScript("function square() { return val*val;}"); oper.setInvoke("square"); oper.setPassThru(true); oper.setup(null); CollectorTestSink<Object> sink = new CollectorTestSink<Object>(); TestUtils.setSink(oper.result, sink); // Add input sample data. HashMap<String, Object> tuple = new HashMap<String, Object>(); tuple.put("val", 2); // Process operator. oper.beginWindow(0); oper.inBindings.process(tuple); oper.endWindow(); // Validate value. Assert.assertEquals("number emitted tuples", 1, sink.collectedTuples.size()); for (Object o : sink.collectedTuples) { // count is 12 Assert.assertEquals("4.0 is expected", (Double) o, 4.0, 0); } } }
apache-2.0
nobdy/mybatis-plus
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/plugins/paginationInterceptor/PaginationInterceptorTest.java
3569
package com.baomidou.mybatisplus.test.plugins.paginationInterceptor; import java.io.Reader; import java.sql.Connection; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.test.plugins.RandomUtils; import com.baomidou.mybatisplus.test.plugins.paginationInterceptor.entity.PageUser; import com.baomidou.mybatisplus.test.plugins.paginationInterceptor.mapper.PageUserMapper; import com.baomidou.mybatisplus.test.plugins.paginationInterceptor.service.PageUserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/plugins/paginationInterceptor.xml" }) public class PaginationInterceptorTest { @Autowired private SqlSessionTemplate sqlSessionTemplate; @Autowired private PageUserService pageUserService; @Autowired private PageUserMapper pageUserMapper; private int current; private int size; @Before public void setUp() throws Exception { SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(); Connection conn = session.getConnection(); Reader reader = Resources.getResourceAsReader("com/baomidou/mybatisplus/test/plugins/paginationInterceptor/CreateDB.sql"); ScriptRunner runner = new ScriptRunner(conn); runner.setLogWriter(null); runner.runScript(reader); reader.close(); session.close(); // 随机当前页和分页大小 size = RandomUtils.nextInt(1, 50); current = RandomUtils.nextInt(1, 200 / size); System.err.println("当前页为:" + current + " 分页大小为" + size); } @Test public void pageSimpleTest() { // 最基础分页 Page<PageUser> page1 = new Page<>(current, size); Page<PageUser> result1 = pageUserService.selectPage(page1); Assert.assertTrue(!result1.getRecords().isEmpty()); } @Test public void pageOrderByTest() { // 带OrderBy Page<PageUser> page2 = new Page<>(current, size, "name"); Page<PageUser> result2 = pageUserService.selectPage(page2); Assert.assertTrue(!result2.getRecords().isEmpty()); // 没有orderby但是设置了倒叙 Page<PageUser> page3 = new Page<>(current, size); page3.setAsc(false); Page<PageUser> result3 = pageUserService.selectPage(page3); Assert.assertTrue(!result3.getRecords().isEmpty()); // 有orderby设置了倒叙 Page<PageUser> page4 = new Page<>(current, size, "name"); page3.setAsc(false); Page<PageUser> result4 = pageUserService.selectPage(page4); Assert.assertTrue(!result4.getRecords().isEmpty()); } @Test public void pageCountTest() { // 设置不count Page<PageUser> page = new Page<>(current, size); page.setSearchCount(false); Page<PageUser> result = pageUserService.selectPage(page); Assert.assertTrue(result.getTotal() == 0); } @Test public void rowBoundTest() { System.err.println("测试原生RowBounds分页"); int offset = RandomUtils.nextInt(1, 190); int limit = RandomUtils.nextInt(1,20); RowBounds rowBounds = new RowBounds(offset, limit); List<PageUser> result = pageUserMapper.selectPage(rowBounds, null); Assert.assertTrue(!result.isEmpty()); } }
apache-2.0
mountain-pass/hyperstate
hyperstate-core/src/main/java/au/com/mountainpass/hyperstate/core/Link.java
3050
package au.com.mountainpass.hyperstate.core; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.eclipse.jdt.annotation.Nullable; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.MediaType; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import au.com.mountainpass.hyperstate.core.entities.CreatedEntity; import au.com.mountainpass.hyperstate.core.entities.DeletedEntity; import au.com.mountainpass.hyperstate.core.entities.EntityWrapper; import au.com.mountainpass.hyperstate.core.entities.UpdatedEntity; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class Link extends Titled { @Nullable private MediaType representationFormat = MediaTypes.SIREN_JSON; private Address address; public Link(@JsonProperty("href") Address address, @JsonProperty("title") final String title, @JsonProperty("class") final String... classes) { super(title, classes); this.address = address; } public Link() { } public Link(Address address) { this.address = address; } @JsonProperty("type") public MediaType getRepresentationFormat() { return representationFormat == null ? MediaTypes.SIREN_JSON : representationFormat; } public <T extends EntityWrapper<?>> CompletableFuture<T> resolve( Class<T> type) { return address.get(type); } public <T extends EntityWrapper<?>> CompletableFuture<T> resolve( ParameterizedTypeReference<T> type) { return address.get(type); } @JsonIgnore public String getPath() { return address.getPath(); } public CompletableFuture<EntityWrapper<?>> get( Map<String, Object> filteredParameters) { return address.get(filteredParameters); } public CompletableFuture<DeletedEntity> delete( Map<String, Object> filteredParameters) { return address.delete(filteredParameters); } public CompletableFuture<CreatedEntity> create( Map<String, Object> filteredParameters) { return address.create(filteredParameters); } public CompletableFuture<UpdatedEntity> update( Map<String, Object> filteredParameters) { return address.update(filteredParameters); } public CompletableFuture<EntityWrapper<?>> get() { return address.get(); } @JsonIgnore public <T extends EntityWrapper<?>> CompletableFuture<T> get( Class<T> type) { return address.get(type); } /** * @return the address */ @JsonUnwrapped public Address getAddress() { return address; } /** * @param address * the address to set */ public void setAddress(Address address) { this.address = address; } }
apache-2.0
yiding-he/redisfx
src/main/java/com/hyd/redisfx/RedisFxApp.java
1099
package com.hyd.redisfx; import com.hyd.fx.Fxml; import com.hyd.fx.app.AppLogo; import com.hyd.fx.app.AppPrimaryStage; import com.hyd.redisfx.fx.BackgroundExecutor; import com.hyd.redisfx.i18n.I18n; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class RedisFxApp extends Application { public static void main(String[] args) { launch(RedisFxApp.class); } @Override public void start(Stage primaryStage) throws Exception { AppPrimaryStage.setPrimaryStage(primaryStage); AppLogo.setStageLogo(primaryStage); primaryStage.setTitle("RedisFX"); primaryStage.setScene(new Scene(getRoot())); primaryStage.setOnCloseRequest(event -> BackgroundExecutor.shutdown()); primaryStage.show(); } public Parent getRoot() throws Exception { FXMLLoader fxmlLoader = Fxml.load("/fxml/Main.fxml", I18n.UI_MAIN_BUNDLE); return fxmlLoader.<BorderPane>getRoot(); } }
apache-2.0
mattdelsordo/Rate-A-Dog
app/src/main/java/com/mdelsordo/rate_a_dog/util/BitmapHelper.java
3767
package com.mdelsordo.rate_a_dog.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.net.Uri; import android.util.Log; import android.widget.Toast; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Created by mdelsord on 7/25/17. * Contains methods to load bitmaps that avoid outofmemoryerrors */ public class BitmapHelper { private static final String TAG = "BitmapHelper"; public static Bitmap decodeStream(Context context, Uri uri, int min_dim){ try{ Bitmap b = null; //Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; InputStream is = context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(is, null, o); is.close(); int scale = 1; if (o.outHeight > min_dim || o.outWidth > min_dim) { scale = (int)Math.pow(2, (int) Math.ceil(Math.log(min_dim / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } //Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; is = context.getContentResolver().openInputStream(uri); b = BitmapFactory.decodeStream(is, null, o2); is.close(); return b; }catch(IOException e){ Logger.e(TAG, "File not found."); Toast.makeText(context, "ERROR: File not found.", Toast.LENGTH_LONG).show(); return null; } } public static Bitmap getBitmap(Context context, Uri uri, int reqWidth, int reqHeight){ try{ Logger.i(TAG, "Dimensions: " + reqWidth + " " + reqHeight); InputStream stream = context.getContentResolver().openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap test1 = BitmapFactory.decodeStream(stream, new Rect(), options); if(test1 == null) Logger.e(TAG, "Test1 null"); //calculate sample size BitmapFactory.Options options2 = new BitmapFactory.Options(); options2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); //decode bitmap Bitmap test2 = BitmapFactory.decodeStream(stream, new Rect(), options2); if(test2 == null ) Logger.e(TAG, "test2 null"); return test2; }catch (FileNotFoundException e){ Logger.e(TAG, "File not found."); Toast.makeText(context, "ERROR: File not found.", Toast.LENGTH_LONG).show(); return null; } } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){ //raw dimensions of image final int height = options.outHeight; final int width = options.outWidth; Logger.i(TAG, "image dims: " + width + " " + height); int inSampleSize = 1; if(height > reqHeight || width > reqWidth){ final int halfHeight = height / 2; final int halfWidth = width / 2; //Calculate the largest inSampleSize that is a power of 2 and keeps both //height and width larger than the requested height and width while((halfHeight/inSampleSize)> reqHeight && (halfWidth/inSampleSize) > reqWidth){ inSampleSize *=2; } } Logger.i(TAG, "Sample size: " + inSampleSize); return inSampleSize; } }
apache-2.0
slipperyseal/B9
src/main/java/net/catchpole/B9/codec/transcoder/MapTranscoder.java
1451
package net.catchpole.B9.codec.transcoder; import net.catchpole.B9.codec.stream.BitInputStream; import net.catchpole.B9.codec.stream.BitOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; class MapTranscoder implements TypeTranscoder<Map>, FieldInterceptor<Map> { private ObjectArrayTranscoder objectArrayTranscoder; public MapTranscoder(ObjectArrayTranscoder objectArrayTranscoder) { this.objectArrayTranscoder = objectArrayTranscoder; } public Map read(BitInputStream in) throws IOException { Object[] all = objectArrayTranscoder.read(in); Map value = new HashMap(); for (int x=0;x<all.length;x+=2) { value.put(all[x],all[x+1]); } return value; } public void write(BitOutputStream out, Map value) throws IOException { Object[] values = new Object[value.size()*2]; int x=0; Set<Map.Entry> entrySet = value.entrySet(); for (Map.Entry entry : entrySet) { values[x++] = entry.getKey(); values[x++] = entry.getValue(); } objectArrayTranscoder.write(out, values); } public Map intercept(Map currentValue, Map newValue) { if (currentValue != null && currentValue.isEmpty()) { currentValue.putAll(newValue); return currentValue; } else { return newValue; } } }
apache-2.0
machadolucas/watchout
src/main/java/com/riskvis/entity/Transports.java
3527
package com.riskvis.entity; // Generated May 12, 2014 11:45:38 PM by Hibernate Tools 4.0.0 import static javax.persistence.GenerationType.IDENTITY; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; /** * Transports generated by hbm2java */ @Entity @Table(name = "transports", catalog = "test") public class Transports extends AbstractEntity implements java.io.Serializable { private static final long serialVersionUID = -2787847957235299023L; private Integer idtransports; private String name; private String description; private byte[] icon; private Set<PlacesHasTransports> placesHasTransportses = new HashSet<PlacesHasTransports>( 0); private Set<Transportationrisks> transportationriskses = new HashSet<Transportationrisks>( 0); public Transports() { } public Transports(String name) { this.name = name; } public Transports(String name, String description, byte[] icon, Set<PlacesHasTransports> placesHasTransportses, Set<Transportationrisks> transportationriskses) { this.name = name; this.description = description; this.icon = icon; this.placesHasTransportses = placesHasTransportses; this.transportationriskses = transportationriskses; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "idtransports", unique = true, nullable = false) public Integer getIdtransports() { return this.idtransports; } public void setIdtransports(Integer idtransports) { this.idtransports = idtransports; } @Column(name = "name", nullable = false, length = 45) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "description", length = 512) public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @Column(name = "icon") public byte[] getIcon() { return this.icon; } public void setIcon(byte[] icon) { this.icon = icon; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "transports") public Set<PlacesHasTransports> getPlacesHasTransportses() { return this.placesHasTransportses; } public void setPlacesHasTransportses( Set<PlacesHasTransports> placesHasTransportses) { this.placesHasTransportses = placesHasTransportses; } @OneToMany(fetch = FetchType.EAGER, mappedBy = "transports") @Cascade({ CascadeType.DELETE }) public Set<Transportationrisks> getTransportationriskses() { return this.transportationriskses; } public void setTransportationriskses( Set<Transportationrisks> transportationriskses) { this.transportationriskses = transportationriskses; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((idtransports == null) ? 0 : idtransports.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Transports other = (Transports) obj; if (idtransports == null) { if (other.idtransports != null) return false; } else if (!idtransports.equals(other.idtransports)) return false; return true; } }
apache-2.0
sgasiewska/java_dla_testerow
mantis-tests/src/test/java/jdt/mantis/appmanager/HttpSession.java
2863
package jdt.mantis.appmanager; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HttpSession { private CloseableHttpClient httpclient; private ApplicationManager app; public HttpSession(ApplicationManager app) { //powstaje nowa sesja this.app = app; //powstaje nowy klient (sesja) do pracy po protokole http, objekt wysyłający zapotrzebowania na serwer httpclient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); } public boolean login(String username, String password) throws IOException { //adres na jajki wysylane jest zapytanie HttpPost post = new HttpPost(app.getProperty("web.baseUrl") + "login.php"); List<NameValuePair> params = new ArrayList<NameValuePair>(); //inicjalizacja zbioru parametrow params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("secure_session", "on")); params.add(new BasicNameValuePair("return", "index.php")); //parametry zapakowują się zgodnie z określonymi zasadami i lokują się we wczesniej strworzone zapytanie post.setEntity(new UrlEncodedFormEntity(params)); //wysyłka zapytania httpclient.execute(post) a wynikiem jest odp od serwera CloseableHttpResponse response = httpclient.execute(post); //Analizujemy odp od serwera String body = getTextFrom(response); //sprawdzanie czy uzytkownik sie zalogowal, czy kod strony zawiera taka linijke return body.contains(String.format("<span class=\"user-info\">%s</span>", username)); } //metoda do otrzymywania tekstu z odp serwera private String getTextFrom(CloseableHttpResponse response) throws IOException { try { return EntityUtils.toString(response.getEntity()); } finally { response.close(); } } //jaki uzytkownik jest teraz zalogowany public boolean isLoggedInAs(String username) throws IOException { //wchodzimy na strone glowna HttpGet get = new HttpGet(app.getProperty("web.baseUrl") + "/index.php"); // wykonujemy zapytanie i otzymujemy odpowiedz CloseableHttpResponse response = httpclient.execute(get); String body = getTextFrom(response); return body.contains(String.format("<span class=\"user-info\">%s</span>", username)); } }
apache-2.0
taoshujian/exampleJava
src/main/java/tsj/example/java/project/tsj/net/mindview/util/Print.java
683
//: net/mindview/util/Print.java // Print methods that can be used without // qualifiers, using Java SE5 static imports: package tsj.example.java.project.tsj.net.mindview.util; import java.io.*; public class Print { // Print with a newline: public static void print(Object obj) { System.out.println(obj); } // Print a newline by itself: public static void print() { System.out.println(); } // Print with no line break: public static void printnb(Object obj) { System.out.print(obj); } // The new Java SE5 printf() (from C): public static PrintStream printf(String format, Object... args) { return System.out.printf(format, args); } } ///:~
apache-2.0
GSSBuse/GSSB
src/main/java/com/thinkgem/jeesite/modules/sys/service/gbj/GbjUserSoldCommentsReplyService.java
1961
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.service.gbj; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestParam; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.service.CrudService; import com.thinkgem.jeesite.modules.sys.dao.gbj.GbjUserSoldCommentsReplyDao; import com.thinkgem.jeesite.modules.sys.entity.gbj.GbjUserSoldCommentsReply; /** * 卖标信息评论回复管理Service * * @author snnu * @version 2018-01-18 */ @Service @Transactional(readOnly = true) public class GbjUserSoldCommentsReplyService extends CrudService<GbjUserSoldCommentsReplyDao, GbjUserSoldCommentsReply> { @Autowired GbjUserSoldCommentsReplyDao gbjUserSoldCommentsReplyDao; public GbjUserSoldCommentsReply get(String id) { return super.get(id); } public List<GbjUserSoldCommentsReply> findList(GbjUserSoldCommentsReply gbjUserSoldCommentsReply) { return super.findList(gbjUserSoldCommentsReply); } public Page<GbjUserSoldCommentsReply> findPage(Page<GbjUserSoldCommentsReply> page, GbjUserSoldCommentsReply gbjUserSoldCommentsReply) { return super.findPage(page, gbjUserSoldCommentsReply); } @Transactional(readOnly = false) public void save(GbjUserSoldCommentsReply gbjUserSoldCommentsReply) { super.save(gbjUserSoldCommentsReply); } @Transactional(readOnly = false) public void delete(GbjUserSoldCommentsReply gbjUserSoldCommentsReply) { super.delete(gbjUserSoldCommentsReply); } public List<GbjUserSoldCommentsReply> findDomainArticleSoldReplyCommentsList(@RequestParam("id") String id) { return gbjUserSoldCommentsReplyDao.findDomainArticleSoldReplyCommentsList(id); } }
apache-2.0
syphr42/libmythtv-java
protocol/src/main/java/org/syphr/mythtv/protocol/impl/Command63QueryRemoteEncoderCancelNextRecording.java
1753
/* * Copyright 2011-2012 Gregory P. Moyer * * 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.syphr.mythtv.protocol.impl; import org.syphr.mythtv.commons.exception.ProtocolException; import org.syphr.mythtv.commons.socket.CommandUtils; import org.syphr.mythtv.commons.translate.Translator; /* default */class Command63QueryRemoteEncoderCancelNextRecording extends AbstractCommand63QueryRemoteEncoder<Void> { private final boolean cancel; public Command63QueryRemoteEncoderCancelNextRecording(Translator translator, Parser parser, int recorderId, boolean cancel) { super(translator, parser, recorderId); this.cancel = cancel; } @Override protected String getSubCommand() throws ProtocolException { return getParser().combineArguments("CANCEL_NEXT_RECORDING", cancel ? "1" : "0"); } @Override protected Void parseResponse(String response) throws ProtocolException { CommandUtils.expectOk(response); return null; } }
apache-2.0
kunickiaj/datacollector
hdfs-protolib/src/main/java/com/streamsets/pipeline/stage/destination/hdfs/HdfsTargetConfigBean.java
33768
/* * Copyright 2017 StreamSets 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.streamsets.pipeline.stage.destination.hdfs; import com.codahale.metrics.Counter; import com.codahale.metrics.Meter; import com.google.common.annotations.VisibleForTesting; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDefBean; import com.streamsets.pipeline.api.Stage; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.Target; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.api.el.ELEval; import com.streamsets.pipeline.api.el.ELEvalException; import com.streamsets.pipeline.api.el.ELVars; import com.streamsets.pipeline.api.el.SdcEL; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.config.TimeZoneChooserValues; import com.streamsets.pipeline.lib.el.DataUtilEL; import com.streamsets.pipeline.lib.el.RecordEL; import com.streamsets.pipeline.lib.el.TimeEL; import com.streamsets.pipeline.lib.el.TimeNowEL; import com.streamsets.pipeline.lib.hdfs.common.Errors; import com.streamsets.pipeline.lib.hdfs.common.HdfsBaseConfigBean; import com.streamsets.pipeline.stage.destination.hdfs.writer.ActiveRecordWriters; import com.streamsets.pipeline.stage.destination.hdfs.writer.RecordWriterManager; import com.streamsets.pipeline.stage.destination.lib.DataGeneratorFormatConfig; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.security.UserGroupInformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.time.ZoneId; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; public class HdfsTargetConfigBean extends HdfsBaseConfigBean { private static final Logger LOG = LoggerFactory.getLogger(HdfsTargetConfigBean.class); private static final int MEGA_BYTE = 1024 * 1024; @Override protected String getConfigBeanPrefix() { return "hdfsTargetConfigBean."; } @ConfigDef( required = false, type = ConfigDef.Type.STRING, defaultValue = "sdc-${sdc:id()}", label = "Files Prefix", description = "File name prefix", displayPosition = 105, group = "OUTPUT_FILES", displayMode = ConfigDef.DisplayMode.ADVANCED, elDefs = SdcEL.class ) public String uniquePrefix; @ConfigDef( required = false, type = ConfigDef.Type.STRING, label = "Files Suffix", description = "File name suffix e.g.'txt'", displayPosition = 106, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES", dependsOn = "fileType", triggeredByValue = {"TEXT", "SEQUENCE_FILE"} ) public String fileNameSuffix; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "Directory in Header", description = "The directory is defined by the '" + HdfsTarget.TARGET_DIRECTORY_HEADER + "' record header attribute instead of the Directory Template configuration property.", displayPosition = 107, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) public boolean dirPathTemplateInHeader; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "/tmp/out/${YYYY()}-${MM()}-${DD()}-${hh()}", label = "Directory Template", description = "Template for the creation of output directories. Valid variables are ${YYYY()}, ${MM()}, ${DD()}, " + "${hh()}, ${mm()}, ${ss()} and {record:value(“/field”)} for values in a field. Directories are " + "created based on the smallest time unit variable used.", displayPosition = 110, displayMode = ConfigDef.DisplayMode.BASIC, group = "OUTPUT_FILES", elDefs = {RecordEL.class, TimeEL.class, ExtraTimeEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT, dependsOn = "dirPathTemplateInHeader", triggeredByValue = "false" ) public String dirPathTemplate; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "UTC", label = "Data Time Zone", description = "Time zone to use to resolve directory paths", displayPosition = 120, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) @ValueChooserModel(TimeZoneChooserValues.class) public String timeZoneID; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "${time:now()}", label = "Time Basis", description = "Time basis to use for a record. Enter an expression that evaluates to a datetime. To use the " + "processing time, enter ${time:now()}. To use field values, use '${record:value(\"<filepath>\")}'.", displayPosition = 130, group = "OUTPUT_FILES", displayMode = ConfigDef.DisplayMode.ADVANCED, elDefs = {RecordEL.class, TimeEL.class, TimeNowEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT ) public String timeDriver; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, defaultValue = "0", label = "Max Records in File", description = "Number of records that triggers the creation of a new file. Use 0 to opt out.", displayPosition = 140, group = "OUTPUT_FILES", min = 0, displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "fileType", triggeredByValue = {"TEXT", "SEQUENCE_FILE"} ) public long maxRecordsPerFile; @ConfigDef( required = true, type = ConfigDef.Type.NUMBER, defaultValue = "0", label = "Max File Size (MB)", description = "Exceeding this size triggers the creation of a new file. Use 0 to opt out.", displayPosition = 150, group = "OUTPUT_FILES", min = 0, displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "fileType", triggeredByValue = {"TEXT", "SEQUENCE_FILE"} ) public long maxFileSize; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "${1 * HOURS}", label = "Idle Timeout", description = "Maximum time for a file to remain idle. After no records are written to a file for the" + " specified time, the destination closes the file. Enter a number to specify a value in seconds. You" + " can also use the MINUTES or HOURS constants in an expression. Use -1 to opt out of a timeout.", group = "OUTPUT_FILES", displayPosition = 155, elDefs = {TimeEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT, displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "fileType", triggeredByValue = {"TEXT", "SEQUENCE_FILE"} ) public String idleTimeout; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "NONE", label = "Compression Codec", description = "", displayPosition = 160, group = "OUTPUT_FILES", displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "fileType", triggeredByValue = {"TEXT", "SEQUENCE_FILE"} ) @ValueChooserModel(CompressionChooserValues.class) public CompressionMode compression; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "", label = "Compression Codec Class", description = "Use the full class name", displayPosition = 170, group = "OUTPUT_FILES", displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "compression", triggeredByValue = "OTHER" ) public String otherCompression; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "TEXT", label = "File Type", description = "", displayPosition = 100, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) @ValueChooserModel(FileTypeChooserValues.class) public HdfsFileType fileType; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "${uuid()}", label = "Sequence File Key", description = "Record key for creating Hadoop sequence files. Valid options are " + "'${record:value(\"<field-path>\")}' or '${uuid()}'", displayPosition = 180, group = "OUTPUT_FILES", dependsOn = "fileType", triggeredByValue = "SEQUENCE_FILE", displayMode = ConfigDef.DisplayMode.ADVANCED, evaluation = ConfigDef.Evaluation.EXPLICIT, elDefs = {RecordEL.class, DataUtilEL.class} ) public String keyEl; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "BLOCK", label = "Compression Type", description = "Compression type if using a CompressionCodec", displayPosition = 190, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES", dependsOn = "fileType", triggeredByValue = "SEQUENCE_FILE" ) @ValueChooserModel(HdfsSequenceFileCompressionTypeChooserValues.class) public HdfsSequenceFileCompressionType seqFileCompressionType; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "${1 * HOURS}", label = "Late Record Time Limit (secs)", description = "Time limit (in seconds) for a record to be written to the corresponding directory, if the " + "limit is exceeded the record will be written to the current late records file. " + "If a number is used it is considered seconds, it can be multiplied by 'MINUTES' or 'HOURS', ie: " + "'${30 * MINUTES}'", displayPosition = 200, group = "LATE_RECORDS", displayMode = ConfigDef.DisplayMode.ADVANCED, elDefs = {TimeEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT ) public String lateRecordsLimit; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "false", label = "Use Roll Attribute", description = "Closes the current file and creates a new file when processing a record with the specified roll attribute", displayPosition = 204, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) public boolean rollIfHeader; @ConfigDef( required = true, type = ConfigDef.Type.STRING, defaultValue = "roll", label = "Roll Attribute Name", description = "Name of the roll attribute", displayPosition = 205, group = "OUTPUT_FILES", displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "rollIfHeader", triggeredByValue = "true" ) public String rollHeaderName; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, defaultValue = "SEND_TO_ERROR", label = "Late Record Handling", description = "Action for records considered late.", displayPosition = 210, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "LATE_RECORDS" ) @ValueChooserModel(LateRecordsActionChooserValues.class) public LateRecordsAction lateRecordsAction; @ConfigDef( required = false, type = ConfigDef.Type.STRING, defaultValue = "/tmp/late/${YYYY()}-${MM()}-${DD()}", label = "Late Record Directory Template", description = "Template for the creation of late record directories. Valid variables are ${YYYY()}, ${MM()}, " + "${DD()}, ${hh()}, ${mm()}, ${ss()}.", displayPosition = 220, group = "LATE_RECORDS", dependsOn = "lateRecordsAction", triggeredByValue = "SEND_TO_LATE_RECORDS_FILE", displayMode = ConfigDef.DisplayMode.ADVANCED, elDefs = {RecordEL.class, TimeEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT ) public String lateRecordsDirPathTemplate; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Data Format", description = "Data Format", displayPosition = 1, group = "DATA_FORMAT" ) @ValueChooserModel(DataFormatChooserValues.class) public DataFormat dataFormat; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, defaultValue = "true", label = "Validate Permissions", description = "When checked, the destination creates a test file in configured target directory to verify access privileges.", displayPosition = 230, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) public boolean hdfsPermissionCheck; //Optional if empty file is created with default umask. @ConfigDef( required = false, type = ConfigDef.Type.STRING, elDefs = {RecordEL.class}, evaluation = ConfigDef.Evaluation.EXPLICIT, label = "Permissions Expression", description = "Expression that determines the target file permissions." + "Should be a octal/symbolic representation of the permissions.", displayPosition = 460, group = "DATA_FORMAT", displayMode = ConfigDef.DisplayMode.ADVANCED, dependsOn = "dataFormat", triggeredByValue = "WHOLE_FILE" ) public String permissionEL = ""; @ConfigDef( required = true, type = ConfigDef.Type.BOOLEAN, label = "Skip file recovery", defaultValue = "false", description = "Set to true to skip finding old temporary files that were written to and automatically recover them.", displayPosition = 1000, displayMode = ConfigDef.DisplayMode.ADVANCED, group = "OUTPUT_FILES" ) public boolean skipOldTempFileRecovery = false; @ConfigDefBean(groups = {"DATA_FORMAT"}) public DataGeneratorFormatConfig dataGeneratorFormatConfig; //private members private long lateRecordsLimitSecs; private long idleTimeSecs = -1; private ActiveRecordWriters currentWriters; private ActiveRecordWriters lateWriters; private ELEval timeDriverElEval; private CompressionCodec compressionCodec; private Counter toHdfsRecordsCounter; private Meter toHdfsRecordsMeter; private Counter lateRecordsCounter; private Meter lateRecordsMeter; //public API public void init(final Stage.Context context, List<Stage.ConfigIssue> issues) { boolean hadoopFSValidated = validateHadoopFS(context, issues); String fileNameEL = ""; lateRecordsLimitSecs = initTimeConfigs(context, "lateRecordsLimit", lateRecordsLimit, Groups.LATE_RECORDS, false, Errors.HADOOPFS_10, issues); if (idleTimeout != null && !idleTimeout.isEmpty()) { idleTimeSecs = initTimeConfigs(context, "idleTimeout", idleTimeout, Groups.OUTPUT_FILES, true, Errors.HADOOPFS_52, issues); } if (maxFileSize < 0) { issues.add( context.createConfigIssue( Groups.LATE_RECORDS.name(), getConfigBeanPrefix() + "maxFileSize", Errors.HADOOPFS_08 ) ); } if (maxRecordsPerFile < 0) { issues.add( context.createConfigIssue( Groups.LATE_RECORDS.name(), getConfigBeanPrefix() + "maxRecordsPerFile", Errors.HADOOPFS_09 ) ); } if (uniquePrefix == null) { uniquePrefix = ""; } if (fileNameSuffix == null) { fileNameSuffix = ""; } else { //File Suffix should not contain '/' or start with '.' if(fileType != HdfsFileType.WHOLE_FILE && (fileNameSuffix.startsWith(".") || fileNameSuffix.contains("/"))) { issues.add( context.createConfigIssue( Groups.HADOOP_FS.name(), getConfigBeanPrefix() + "fileNameSuffix", Errors.HADOOPFS_57 ) ); } } dataGeneratorFormatConfig.init( context, dataFormat, Groups.OUTPUT_FILES.name(), getConfigBeanPrefix() + "dataGeneratorFormatConfig", issues ); if (dataFormat == DataFormat.WHOLE_FILE || fileType == HdfsFileType.WHOLE_FILE) { validateStageForWholeFileFormat(context, issues); fileNameEL = dataGeneratorFormatConfig.fileNameEL; } SequenceFile.CompressionType compressionType = (seqFileCompressionType != null) ? seqFileCompressionType.getType() : null; try { switch (compression) { case OTHER: try { Class klass = Thread.currentThread().getContextClassLoader().loadClass(otherCompression); if (CompressionCodec.class.isAssignableFrom(klass)) { compressionCodec = ((Class<? extends CompressionCodec> ) klass).newInstance(); } else { throw new StageException(Errors.HADOOPFS_04, otherCompression); } } catch (Exception ex1) { throw new StageException(Errors.HADOOPFS_05, otherCompression, ex1.toString(), ex1); } break; case NONE: break; default: try { compressionCodec = compression.getCodec().newInstance(); } catch (IllegalAccessException | InstantiationException ex) { LOG.info("Error: " + ex.getMessage(), ex.toString(), ex); issues.add(context.createConfigIssue(Groups.OUTPUT_FILES.name(), null, Errors.HADOOPFS_48, ex.toString(), ex)); } break; } if (compressionCodec != null) { if (compressionCodec instanceof Configurable) { ((Configurable) compressionCodec).setConf(hdfsConfiguration); } } } catch (StageException ex) { LOG.info("Validation Error: " + ex.getMessage(), ex.toString(), ex); issues.add(context.createConfigIssue(Groups.OUTPUT_FILES.name(), null, ex.getErrorCode(), ex.toString(), ex)); } if(hadoopFSValidated){ try { // Creating RecordWriterManager for dirPathTemplate RecordWriterManager mgr = new RecordWriterManager( fs, hdfsConfiguration, uniquePrefix, fileNameSuffix, dirPathTemplateInHeader, dirPathTemplate, TimeZone.getTimeZone(ZoneId.of(timeZoneID)), lateRecordsLimitSecs, maxFileSize * MEGA_BYTE, maxRecordsPerFile, fileType, compressionCodec, compressionType, keyEl, rollIfHeader, rollHeaderName, fileNameEL, dataGeneratorFormatConfig.wholeFileExistsAction, permissionEL, dataGeneratorFormatConfig.getDataGeneratorFactory(), (Target.Context) context, "dirPathTemplate" ); if (idleTimeSecs > 0) { mgr.setIdleTimeoutSeconds(idleTimeSecs); } // We're skipping all hdfs-target-directory related validations if we're getting the configuration from header if(dirPathTemplateInHeader) { currentWriters = new ActiveRecordWriters(mgr); } else { // validate if the dirPathTemplate can be resolved by Els constants if (mgr.validateDirTemplate( Groups.OUTPUT_FILES.name(), "dirPathTemplate", getConfigBeanPrefix() + "dirPathTemplate", issues )) { String newDirPath = mgr.getDirPath(new Date()).toString(); if (validateHadoopDir( // permission check on the output directory context, getConfigBeanPrefix() + "dirPathTemplate", Groups.OUTPUT_FILES.name(), newDirPath, issues )) { currentWriters = new ActiveRecordWriters(mgr); } } } } catch (Exception ex) { LOG.info("Validation Error: " + Errors.HADOOPFS_11.getMessage(), ex.toString(), ex); issues.add(context.createConfigIssue(Groups.OUTPUT_FILES.name(), null, Errors.HADOOPFS_11, ex.toString(), ex)); } // Creating RecordWriterManager for Late Records if(lateRecordsDirPathTemplate != null && !lateRecordsDirPathTemplate.isEmpty()) { try { RecordWriterManager mgr = new RecordWriterManager( fs, hdfsConfiguration, uniquePrefix, fileNameSuffix, false, // Late records doesn't support "template directory" to be in header lateRecordsDirPathTemplate, TimeZone.getTimeZone(ZoneId.of(timeZoneID)), lateRecordsLimitSecs, maxFileSize * MEGA_BYTE, maxRecordsPerFile, fileType, compressionCodec, compressionType, keyEl, false, null, fileNameEL, dataGeneratorFormatConfig.wholeFileExistsAction, permissionEL, dataGeneratorFormatConfig.getDataGeneratorFactory(), (Target.Context) context, "lateRecordsDirPathTemplate" ); if (idleTimeSecs > 0) { mgr.setIdleTimeoutSeconds(idleTimeSecs); } // validate if the lateRecordsDirPathTemplate can be resolved by Els constants if (mgr.validateDirTemplate( Groups.OUTPUT_FILES.name(), "lateRecordsDirPathTemplate", getConfigBeanPrefix() + "lateRecordsDirPathTemplate", issues )) { String newLateRecordPath = mgr.getDirPath(new Date()).toString(); if (lateRecordsAction == LateRecordsAction.SEND_TO_LATE_RECORDS_FILE && lateRecordsDirPathTemplate != null && !lateRecordsDirPathTemplate.isEmpty() && validateHadoopDir( // permission check on the late record directory context, getConfigBeanPrefix() + "lateRecordsDirPathTemplate", Groups.LATE_RECORDS.name(), newLateRecordPath, issues )) { lateWriters = new ActiveRecordWriters(mgr); } } } catch (Exception ex) { issues.add(context.createConfigIssue(Groups.LATE_RECORDS.name(), null, Errors.HADOOPFS_17, ex.toString(), ex)); } } } timeDriverElEval = context.createELEval("timeDriver"); try { ELVars variables = context.createELVars(); RecordEL.setRecordInContext(variables, context.createRecord("validationConfigs")); TimeNowEL.setTimeNowInContext(variables, new Date()); context.parseEL(timeDriver); timeDriverElEval.eval(variables, timeDriver, Date.class); } catch (ELEvalException ex) { issues.add( context.createConfigIssue( Groups.OUTPUT_FILES.name(), getConfigBeanPrefix() + "timeDriver", Errors.HADOOPFS_19, ex.toString(), ex ) ); } if(rollIfHeader && (rollHeaderName == null || rollHeaderName.isEmpty())) { issues.add( context.createConfigIssue( Groups.OUTPUT_FILES.name(), getConfigBeanPrefix() + "rollHeaderName", Errors.HADOOPFS_51 ) ); } if (issues.isEmpty()) { try { userUgi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { getCurrentWriters().commitOldFiles(fs); if (getLateWriters() != null) { getLateWriters().commitOldFiles(fs); } return null; } }); } catch (Exception ex) { LOG.error("Exception while initializing bean configuration", ex); issues.add(context.createConfigIssue(null, null, Errors.HADOOPFS_23, ex.toString(), ex)); } toHdfsRecordsCounter = context.createCounter("toHdfsRecords"); toHdfsRecordsMeter = context.createMeter("toHdfsRecords"); lateRecordsCounter = context.createCounter("lateRecords"); lateRecordsMeter = context.createMeter("lateRecords"); } if (issues.isEmpty()) { try { // Recover previously written files (promote all _tmp_ to their final form). // // We want to run the recovery only if // * Not preview // * This is not a WHOLE_FILE since it doesn't make sense there (tmp files will be discarded instead) // * User explicitly did not disabled the recovery in configuration // * We do have the directory template available (e.g. it's not in header) // * Only for the first runner, since it would be empty operation for the others recoveryOldTempFile(context); } catch (Exception ex) { LOG.error(Errors.HADOOPFS_59.getMessage(), ex.toString(), ex); issues.add( context.createConfigIssue( Groups.OUTPUT_FILES.name(), getConfigBeanPrefix() + "dirPathTemplate", Errors.HADOOPFS_59, ex.toString(), ex ) ); } } } public void destroy() { LOG.info("Destroy"); try { if(userUgi != null) { userUgi.doAs((PrivilegedExceptionAction<Void>) () -> { try { //Don't close the whole files on destroy, we should only do it after //the file is copied (i.e after a record is written, the file will be closed) //For resume cases(i.e file copied fully but not renamed/ file partially copied) //we will overwrite the _tmp file and start copying from scratch if (currentWriters != null) { if (dataFormat != DataFormat.WHOLE_FILE) { currentWriters.closeAll(); } currentWriters.getWriterManager().issueCachedEvents(); } if (lateWriters != null) { if (dataFormat != DataFormat.WHOLE_FILE) { lateWriters.closeAll(); } lateWriters.getWriterManager().issueCachedEvents(); } } finally { if(fs != null) { fs.close(); fs = null; } } return null; }); } } catch (Exception ex) { LOG.warn("Error while closing FileSystem URI='{}': {}", hdfsUri, ex.toString(), ex); } } private long initTimeConfigs( Stage.Context context, String configName, String configuredValue, Groups configGroup, boolean allowNegOne, Errors errorCode, List<Stage.ConfigIssue> issues) { long timeInSecs = 0; try { ELEval timeEvaluator = context.createELEval(configName); context.parseEL(configuredValue); timeInSecs = timeEvaluator.eval(context.createELVars(), configuredValue, Long.class); if (timeInSecs <= 0 && (!allowNegOne || timeInSecs != -1)) { issues.add( context.createConfigIssue( configGroup.name(), getConfigBeanPrefix() + configName, errorCode ) ); } } catch (Exception ex) { issues.add( context.createConfigIssue( configGroup.name(), getConfigBeanPrefix() + configName, Errors.HADOOPFS_06, configuredValue, ex.toString(), ex ) ); } return timeInSecs; } Counter getToHdfsRecordsCounter() { return toHdfsRecordsCounter; } Meter getToHdfsRecordsMeter() { return toHdfsRecordsMeter; } Counter getLateRecordsCounter() { return lateRecordsCounter; } Meter getLateRecordsMeter() { return lateRecordsMeter; } String getTimeDriver() { return timeDriver; } ELEval getTimeDriverElEval() { return timeDriverElEval; } UserGroupInformation getUGI() { return userUgi; } protected ActiveRecordWriters getCurrentWriters() { return currentWriters; } protected ActiveRecordWriters getLateWriters() { return lateWriters; } @VisibleForTesting Configuration getHdfsConfiguration() { return hdfsConfiguration; } @VisibleForTesting CompressionCodec getCompressionCodec() throws StageException { return compressionCodec; } @VisibleForTesting long getLateRecordLimitSecs() { return lateRecordsLimitSecs; } //private implementation protected void validateStageForWholeFileFormat(Stage.Context context, List<Stage.ConfigIssue> issues) { maxFileSize = 0; maxRecordsPerFile = 1; idleTimeout = "-1"; if (fileType != HdfsFileType.WHOLE_FILE) { issues.add( context.createConfigIssue( Groups.OUTPUT_FILES.name(), getConfigBeanPrefix() + "fileType", Errors.HADOOPFS_53, fileType, HdfsFileType.WHOLE_FILE.getLabel(), DataFormat.WHOLE_FILE.getLabel() ) ); } if (dataFormat != DataFormat.WHOLE_FILE) { issues.add( context.createConfigIssue( Groups.DATA_FORMAT.name(), getConfigBeanPrefix() + "dataFormat", Errors.HADOOPFS_60, dataFormat.name(), DataFormat.WHOLE_FILE.getLabel(), HdfsFileType.WHOLE_FILE.getLabel() ) ); } } protected boolean validateHadoopDir(final Stage.Context context, final String configName, final String configGroup, String dirPathTemplate, final List<Stage.ConfigIssue> issues) { if (!dirPathTemplate.startsWith("/")) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_40)); return false; } // User can opt out canary write to HDFS if(!hdfsPermissionCheck) { return true; } final AtomicBoolean ok = new AtomicBoolean(true); dirPathTemplate = (dirPathTemplate.isEmpty()) ? "/" : dirPathTemplate; try { final Path dir = new Path(dirPathTemplate); userUgi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { // Based on whether the target directory exists or not, we'll do different check if (!fs.exists(dir)) { // Target directory doesn't exists, we'll try to create directory a directory and then drop it Path workDir = dir; // We don't want to pollute HDFS with random directories, so we'll create exactly one directory under // another already existing directory on the template path. (e.g. if template is /a/b/c/d and only /a // exists, then we will create new dummy directory in /a during this test). while(!fs.exists(workDir)) { workDir = workDir.getParent(); } // Sub-directory to be created in existing directory workDir = new Path(workDir, "_sdc-dummy-" + UUID.randomUUID().toString()); try { if (fs.mkdirs(workDir)) { LOG.info("Creating dummy directory to validate permissions {}", workDir.toString()); fs.delete(workDir, true); ok.set(true); } else { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_41)); ok.set(false); } } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_42, ex.toString())); ok.set(false); } } else { // Target directory exists, we will just create empty test file and then immediately drop it try { Path dummy = new Path(dir, "_sdc-dummy-" + UUID.randomUUID().toString()); fs.create(dummy).close(); fs.delete(dummy, false); ok.set(true); } catch (IOException ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_43, ex.toString())); ok.set(false); } } return null; } }); } catch (Exception ex) { issues.add(context.createConfigIssue(configGroup, configName, Errors.HADOOPFS_44, ex.toString())); ok.set(false); } return ok.get(); } @Override protected FileSystem createFileSystem() throws Exception { try { return userUgi.doAs(new PrivilegedExceptionAction<FileSystem>() { @Override public FileSystem run() throws Exception { return FileSystem.newInstance(new URI(hdfsUri), hdfsConfiguration); } }); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { Throwable cause = ex.getCause(); if (cause instanceof Exception) { throw (Exception)cause; } throw ex; } } private void recoveryOldTempFile(Stage.Context context) throws IOException, InterruptedException { if(!context.isPreview() && dataFormat != DataFormat.WHOLE_FILE && !skipOldTempFileRecovery && !dirPathTemplateInHeader && context.getRunnerId() == 0) { userUgi.doAs((PrivilegedExceptionAction<Void>) () -> { getCurrentWriters().getWriterManager().handleAlreadyExistingFiles(); return null; }); } } }
apache-2.0
jexp/idea2
platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java
6502
/* * 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.application.options.colors; import com.intellij.ui.ListScrollingUtil; import com.intellij.util.EventDispatcher; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashSet; import java.util.Set; public class OptionsPanelImpl extends JPanel implements OptionsPanel { private final JList myOptionsList; private final ColorAndFontDescriptionPanel myOptionsPanel; private final ColorAndFontOptions myOptions; private final SchemesPanel mySchemesProvider; private final String myCategoryName; private final EventDispatcher<ColorAndFontSettingsListener> myDispatcher = EventDispatcher.create(ColorAndFontSettingsListener.class); public OptionsPanelImpl(ColorAndFontDescriptionPanel optionsPanel, ColorAndFontOptions options, SchemesPanel schemesProvider, String categoryName) { super(new BorderLayout()); myOptions = options; mySchemesProvider = schemesProvider; myCategoryName = categoryName; optionsPanel.addActionListener(new ActionListener(){ public void actionPerformed(final ActionEvent e) { myDispatcher.getMulticaster().settingsChanged(); } }); myOptionsList = new JList(); myOptionsList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!mySchemesProvider.areSchemesLoaded()) return; processListValueChanged(); } }); myOptionsList.setCellRenderer(new DefaultListCellRenderer(){ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof ColorAndFontDescription) { setIcon(((ColorAndFontDescription)value).getIcon()); setToolTipText(((ColorAndFontDescription)value).getToolTip()); } return component; } }); myOptionsList.setModel(new DefaultListModel()); myOptionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPane = new JScrollPane(myOptionsList); scrollPane.setPreferredSize(new Dimension(230, 60)); JPanel north = new JPanel(new BorderLayout()); north.add(scrollPane, BorderLayout.WEST); north.add(optionsPanel, BorderLayout.CENTER); myOptionsPanel = optionsPanel; add(north, BorderLayout.NORTH); } public void addListener(ColorAndFontSettingsListener listener) { myDispatcher.addListener(listener); } private void processListValueChanged() { Object selectedValue = myOptionsList.getSelectedValue(); ColorAndFontDescription description = (ColorAndFontDescription)selectedValue; ColorAndFontDescriptionPanel optionsPanel = myOptionsPanel; if (description == null) { optionsPanel.resetDefault(); return; } optionsPanel.reset(description); myDispatcher.getMulticaster().selectedOptionChanged(description); } private void fillOptionsList() { int selIndex = myOptionsList.getSelectedIndex(); DefaultListModel listModel = (DefaultListModel)myOptionsList.getModel(); listModel.removeAllElements(); EditorSchemeAttributeDescriptor[] descriptions = myOptions.getCurrentDescriptions(); for (EditorSchemeAttributeDescriptor description : descriptions) { if (description.getGroup().equals(myCategoryName)) { listModel.addElement(description); } } if (selIndex >= 0) { myOptionsList.setSelectedIndex(selIndex); } ListScrollingUtil.ensureSelectionExists(myOptionsList); Object selected = myOptionsList.getSelectedValue(); if (selected instanceof EditorSchemeAttributeDescriptor) { myDispatcher.getMulticaster().selectedOptionChanged(selected); } } public JPanel getPanel() { return this; } public void updateOptionsList() { fillOptionsList(); processListValueChanged(); } public Runnable showOption(final String option) { DefaultListModel model = (DefaultListModel)myOptionsList.getModel(); for (int i = 0; i < model.size(); i++) { Object o = model.get(i); if (o instanceof EditorSchemeAttributeDescriptor) { String type = ((EditorSchemeAttributeDescriptor)o).getType(); if (type.toLowerCase().contains(option.toLowerCase())) { final int i1 = i; return new Runnable() { public void run() { ListScrollingUtil.selectItem(myOptionsList, i1); } }; } } } return null; } public void applyChangesToScheme() { Object selectedValue = myOptionsList.getSelectedValue(); if (selectedValue instanceof ColorAndFontDescription) { myOptionsPanel.apply((ColorAndFontDescription)selectedValue,myOptions.getSelectedScheme()); } } public void selectOption(final String typeToSelect) { DefaultListModel model = (DefaultListModel)myOptionsList.getModel(); for (int i = 0; i < model.size(); i++) { Object o = model.get(i); if (o instanceof EditorSchemeAttributeDescriptor) { if (typeToSelect.equals(((EditorSchemeAttributeDescriptor)o).getType())) { ListScrollingUtil.selectItem(myOptionsList, i); return; } } } } public Set<String> processListOptions() { HashSet<String> result = new HashSet<String>(); EditorSchemeAttributeDescriptor[] descriptions = myOptions.getCurrentDescriptions(); for (EditorSchemeAttributeDescriptor description : descriptions) { if (description.getGroup().equals(myCategoryName)) { result.add(description.toString()); } } return result; } }
apache-2.0
nowshad-sust/ImageMatching-RGB
src/compare/FilePicker.java
2982
//simple GUI for the Matching program package compare; //importing requird libraries import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class FilePicker extends JPanel { //declaring required variables private String textFieldLabel; private String buttonLabel; private JLabel label; public static JTextField textField; private JButton browseButton; private JFileChooser fileChooser; public static String fileName, outputDestination, filePath; private int mode; public static final int MODE_OPEN = 1; public static final int MODE_SAVE = 2; public static JLabel categoryLabel; //Constructor for the UI public FilePicker(String textFieldLabel, String buttonLabel) { this.textFieldLabel = textFieldLabel; this.buttonLabel = buttonLabel; fileChooser = new JFileChooser(); label = new JLabel(textFieldLabel); textField = new JTextField(30); browseButton = new JButton(buttonLabel); browseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { browseButtonActionPerformed(evt); } }); add(label); add(textField); add(browseButton); } //browse button click event private void browseButtonActionPerformed(ActionEvent evt) { if (mode == MODE_OPEN) { if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { textField.setText(fileChooser.getSelectedFile().getAbsolutePath()); } } else if (mode == MODE_SAVE) { if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { textField.setText(fileChooser.getSelectedFile().getAbsolutePath()); } } this.filePath = getSelectedFilePath(); } //adding required filter for browsing files public void addFileTypeFilter(String extension, String description) { FileTypeFilter filter = new FileTypeFilter(extension, description); fileChooser.addChoosableFileFilter(filter); } //browsing mode public void setMode(int mode) { this.mode = mode; } //get file path of the selected file public static String getSelectedFilePath() { return textField.getText(); } //get the file Chooser public JFileChooser getFileChooser() { return this.fileChooser; } }
apache-2.0
machado-rev/htmlcoinj
core/src/main/java/com/bushstar/htmlcoinj/jni/NativeWalletEventListener.java
1933
/** * Copyright 2013 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.bushstar.htmlcoinj.jni; import com.bushstar.htmlcoinj.core.ECKey; import com.bushstar.htmlcoinj.core.Transaction; import com.bushstar.htmlcoinj.core.Wallet; import com.bushstar.htmlcoinj.core.WalletEventListener; import com.bushstar.htmlcoinj.script.Script; import java.math.BigInteger; import java.util.List; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. */ public class NativeWalletEventListener implements WalletEventListener { public long ptr; @Override public native void onCoinsReceived(Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance); @Override public native void onCoinsSent(Wallet wallet, Transaction tx, BigInteger prevBalance, BigInteger newBalance); @Override public native void onReorganize(Wallet wallet); @Override public native void onTransactionConfidenceChanged(Wallet wallet, Transaction tx); @Override public native void onWalletChanged(Wallet wallet); @Override public native void onKeysAdded(Wallet wallet, List<ECKey> keys); @Override public native void onScriptsAdded(Wallet wallet, List<Script> scripts); }
apache-2.0
ribeirux/jalphanode
core/src/main/java/org/jalphanode/scheduler/ScheduleIterator.java
1080
/** * Copyright 2011 Pedro Ribeiro * * 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.jalphanode.scheduler; import java.util.Date; /** * Iterator which builds the next execution time. * * @author ribeirux * @version $Revision$ */ public interface ScheduleIterator { /** * Builds the next execution time according the specified {@code date}. * * @param date the date to begin the search for the next valid date * * @return the next execution date */ Date next(Date date); }
apache-2.0
roncoo/roncoo-pay
roncoo-pay-service/src/main/java/com/roncoo/pay/reconciliation/service/impl/RpAccountCheckBatchServiceImpl.java
2174
/* * Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.pay.reconciliation.service.impl; import com.roncoo.pay.common.core.page.PageBean; import com.roncoo.pay.common.core.page.PageParam; import com.roncoo.pay.reconciliation.dao.RpAccountCheckBatchDao; import com.roncoo.pay.reconciliation.entity.RpAccountCheckBatch; import com.roncoo.pay.reconciliation.service.RpAccountCheckBatchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * 对账批次接口实现 . * * 龙果学院:www.roncoo.com * * @author:shenjialong */ @Service("rpAccountCheckBatchService") public class RpAccountCheckBatchServiceImpl implements RpAccountCheckBatchService { @Autowired private RpAccountCheckBatchDao rpAccountCheckBatchDao; @Override public void saveData(RpAccountCheckBatch rpAccountCheckBatch) { rpAccountCheckBatchDao.insert(rpAccountCheckBatch); } @Override public void updateData(RpAccountCheckBatch rpAccountCheckBatch) { rpAccountCheckBatchDao.update(rpAccountCheckBatch); } @Override public RpAccountCheckBatch getDataById(String id) { return rpAccountCheckBatchDao.getById(id); } @Override public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) { return rpAccountCheckBatchDao.listPage(pageParam, paramMap); } /** * 根据条件查询实体 * * @param paramMap */ public List<RpAccountCheckBatch> listBy(Map<String, Object> paramMap) { return rpAccountCheckBatchDao.listBy(paramMap); } }
apache-2.0
KleeGroup/vertigo-quarto
vertigo-quarto-api/src/main/java/io/vertigo/quarto/publisher/PublisherManager.java
1636
/** * vertigo - simple java starter * * Copyright (C) 2013-2017, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com) * KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France * * 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.vertigo.quarto.publisher; import java.net.URL; import io.vertigo.dynamo.file.model.VFile; import io.vertigo.lang.Manager; import io.vertigo.quarto.publisher.model.PublisherData; /** * Gestionnaire centralisé des éditions. * Le choix du type d'édition est fait par l'appelant qui fournit les paramètres adaptés à son besoin. * * @author pchretien, npiedeloup */ public interface PublisherManager extends Manager { /** * Création d'une nouvelle édition. * @param fileName Nom du document à générer (! pas son emplacement de stockage !) * @param modelFileURL Chemin vers le fichier model * @param data Données à fusionner avec le model * @return Tache permettant la production d'un document au format passé en paramètre */ VFile publish(String fileName, URL modelFileURL, PublisherData data); }
apache-2.0
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/homekit/HMHomeManager.java
9411
/* Copyright 2014-2016 Intel Corporation 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 apple.homekit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSError; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.homekit.protocol.HMHomeManagerDelegate; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCBlock; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * Manages collection of one or more homes. * <p> * This class is responsible for managing a collection of homes. */ @Generated @Library("HomeKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class HMHomeManager extends NSObject { static { NatJ.register(); } @Generated protected HMHomeManager(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native HMHomeManager alloc(); @Owned @Generated @Selector("allocWithZone:") public static native HMHomeManager allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native HMHomeManager new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); /** * Adds a new home to the collection. * * @param homeName Name of the home to create and add to the collection. * @param completion Block that is invoked once the request is processed. * The NSError provides more information on the status of the request, error * will be nil on success. */ @Generated @Selector("addHomeWithName:completionHandler:") public native void addHomeWithNameCompletionHandler(String homeName, @ObjCBlock(name = "call_addHomeWithNameCompletionHandler") Block_addHomeWithNameCompletionHandler completion); /** * Delegate that receives updates on the collection of homes. */ @Generated @Selector("delegate") @MappedReturn(ObjCObjectMapper.class) public native HMHomeManagerDelegate delegate(); /** * Array of HMHome objects that represents the homes associated with the home manager. * <p> * When a new home manager is created, this array is initialized as an empty array. It is * not guaranteed to be filled with the list of homes, represented as HMHome objects, * until the homeManagerDidUpdateHomes: delegate method has been invoked. */ @Generated @Selector("homes") public native NSArray<? extends HMHome> homes(); @Generated @Selector("init") public native HMHomeManager init(); /** * The primary home for this collection. */ @Generated @Selector("primaryHome") public native HMHome primaryHome(); /** * Removes an existing home from the collection. * * @param home Home object that needs to be removed from the collection. * @param completion Block that is invoked once the request is processed. * The NSError provides more information on the status of the request, error * will be nil on success. */ @Generated @Selector("removeHome:completionHandler:") public native void removeHomeCompletionHandler(HMHome home, @ObjCBlock(name = "call_removeHomeCompletionHandler") Block_removeHomeCompletionHandler completion); /** * Delegate that receives updates on the collection of homes. */ @Generated @Selector("setDelegate:") public native void setDelegate_unsafe(@Mapped(ObjCObjectMapper.class) HMHomeManagerDelegate value); /** * Delegate that receives updates on the collection of homes. */ @Generated public void setDelegate(@Mapped(ObjCObjectMapper.class) HMHomeManagerDelegate value) { Object __old = delegate(); if (value != null) { org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value); } setDelegate_unsafe(value); if (__old != null) { org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old); } } /** * This method is used to change the primary home. * * @param home New primary home. * @param completion Block that is invoked once the request is processed. * The NSError provides more information on the status of the request, error * will be nil on success. */ @Generated @Selector("updatePrimaryHome:completionHandler:") public native void updatePrimaryHomeCompletionHandler(HMHome home, @ObjCBlock(name = "call_updatePrimaryHomeCompletionHandler") Block_updatePrimaryHomeCompletionHandler completion); @Runtime(ObjCRuntime.class) @Generated public interface Block_addHomeWithNameCompletionHandler { @Generated void call_addHomeWithNameCompletionHandler(HMHome home, NSError error); } @Runtime(ObjCRuntime.class) @Generated public interface Block_removeHomeCompletionHandler { @Generated void call_removeHomeCompletionHandler(NSError error); } @Runtime(ObjCRuntime.class) @Generated public interface Block_updatePrimaryHomeCompletionHandler { @Generated void call_updatePrimaryHomeCompletionHandler(NSError error); } /** * The current authorization status of the application. * <p> * The authorization is managed by the system, there is no need to explicitly request authorization. */ @Generated @Selector("authorizationStatus") @NUInt public native long authorizationStatus(); }
apache-2.0
actuaryzhang/spark
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExternalShuffleClient.java
7360
/* * 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.spark.network.shuffle; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import com.codahale.metrics.MetricSet; import com.google.common.collect.Lists; import org.apache.spark.network.client.RpcResponseCallback; import org.apache.spark.network.shuffle.protocol.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.spark.network.TransportContext; import org.apache.spark.network.client.TransportClient; import org.apache.spark.network.client.TransportClientBootstrap; import org.apache.spark.network.client.TransportClientFactory; import org.apache.spark.network.crypto.AuthClientBootstrap; import org.apache.spark.network.sasl.SecretKeyHolder; import org.apache.spark.network.server.NoOpRpcHandler; import org.apache.spark.network.util.TransportConf; /** * Client for reading shuffle blocks which points to an external (outside of executor) server. * This is instead of reading shuffle blocks directly from other executors (via * BlockTransferService), which has the downside of losing the shuffle data if we lose the * executors. */ public class ExternalShuffleClient extends ShuffleClient { private static final Logger logger = LoggerFactory.getLogger(ExternalShuffleClient.class); private final TransportConf conf; private final boolean authEnabled; private final SecretKeyHolder secretKeyHolder; private final long registrationTimeoutMs; protected TransportClientFactory clientFactory; protected String appId; /** * Creates an external shuffle client, with SASL optionally enabled. If SASL is not enabled, * then secretKeyHolder may be null. */ public ExternalShuffleClient( TransportConf conf, SecretKeyHolder secretKeyHolder, boolean authEnabled, long registrationTimeoutMs) { this.conf = conf; this.secretKeyHolder = secretKeyHolder; this.authEnabled = authEnabled; this.registrationTimeoutMs = registrationTimeoutMs; } protected void checkInit() { assert appId != null : "Called before init()"; } /** * Initializes the ShuffleClient, specifying this Executor's appId. * Must be called before any other method on the ShuffleClient. */ public void init(String appId) { this.appId = appId; TransportContext context = new TransportContext(conf, new NoOpRpcHandler(), true, true); List<TransportClientBootstrap> bootstraps = Lists.newArrayList(); if (authEnabled) { bootstraps.add(new AuthClientBootstrap(conf, appId, secretKeyHolder)); } clientFactory = context.createClientFactory(bootstraps); } @Override public void fetchBlocks( String host, int port, String execId, String[] blockIds, BlockFetchingListener listener, DownloadFileManager downloadFileManager) { checkInit(); logger.debug("External shuffle fetch from {}:{} (executor id {})", host, port, execId); try { RetryingBlockFetcher.BlockFetchStarter blockFetchStarter = (blockIds1, listener1) -> { TransportClient client = clientFactory.createClient(host, port); new OneForOneBlockFetcher(client, appId, execId, blockIds1, listener1, conf, downloadFileManager).start(); }; int maxRetries = conf.maxIORetries(); if (maxRetries > 0) { // Note this Fetcher will correctly handle maxRetries == 0; we avoid it just in case there's // a bug in this code. We should remove the if statement once we're sure of the stability. new RetryingBlockFetcher(conf, blockFetchStarter, blockIds, listener).start(); } else { blockFetchStarter.createAndStart(blockIds, listener); } } catch (Exception e) { logger.error("Exception while beginning fetchBlocks", e); for (String blockId : blockIds) { listener.onBlockFetchFailure(blockId, e); } } } @Override public MetricSet shuffleMetrics() { checkInit(); return clientFactory.getAllMetrics(); } /** * Registers this executor with an external shuffle server. This registration is required to * inform the shuffle server about where and how we store our shuffle files. * * @param host Host of shuffle server. * @param port Port of shuffle server. * @param execId This Executor's id. * @param executorInfo Contains all info necessary for the service to find our shuffle files. */ public void registerWithShuffleServer( String host, int port, String execId, ExecutorShuffleInfo executorInfo) throws IOException, InterruptedException { checkInit(); try (TransportClient client = clientFactory.createClient(host, port)) { ByteBuffer registerMessage = new RegisterExecutor(appId, execId, executorInfo).toByteBuffer(); client.sendRpcSync(registerMessage, registrationTimeoutMs); } } public Future<Integer> removeBlocks( String host, int port, String execId, String[] blockIds) throws IOException, InterruptedException { checkInit(); CompletableFuture<Integer> numRemovedBlocksFuture = new CompletableFuture<>(); ByteBuffer removeBlocksMessage = new RemoveBlocks(appId, execId, blockIds).toByteBuffer(); final TransportClient client = clientFactory.createClient(host, port); client.sendRpc(removeBlocksMessage, new RpcResponseCallback() { @Override public void onSuccess(ByteBuffer response) { try { BlockTransferMessage msgObj = BlockTransferMessage.Decoder.fromByteBuffer(response); numRemovedBlocksFuture.complete(((BlocksRemoved) msgObj).numRemovedBlocks); } catch (Throwable t) { logger.warn("Error trying to remove RDD blocks " + Arrays.toString(blockIds) + " via external shuffle service from executor: " + execId, t); numRemovedBlocksFuture.complete(0); } finally { client.close(); } } @Override public void onFailure(Throwable e) { logger.warn("Error trying to remove RDD blocks " + Arrays.toString(blockIds) + " via external shuffle service from executor: " + execId, e); numRemovedBlocksFuture.complete(0); client.close(); } }); return numRemovedBlocksFuture; } @Override public void close() { checkInit(); if (clientFactory != null) { clientFactory.close(); clientFactory = null; } } }
apache-2.0
universum-studios/android_fragments
library-base/src/test/java/universum/studios/android/fragment/annotation/handler/BaseAnnotationHandlersTest.java
2753
/* * ************************************************************************************************* * Copyright 2016 Universum Studios * ************************************************************************************************* * 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 universum.studios.android.fragment.annotation.handler; import androidx.fragment.app.Fragment; import org.junit.Test; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import universum.studios.android.fragment.annotation.FragmentAnnotations; import universum.studios.android.test.local.RobolectricTestCase; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.notNullValue; /** * @author Martin Albedinsky */ public final class BaseAnnotationHandlersTest extends RobolectricTestCase { @Override public void beforeTest() throws Exception { super.beforeTest(); // Ensure that we have always annotations processing enabled. FragmentAnnotations.setEnabled(true); } @Test(expected = UnsupportedOperationException.class) public void testInstantiation() { // Act: new BaseAnnotationHandlers(); } @Test(expected = InvocationTargetException.class) public void testInstantiationWithAccessibleConstructor() throws Exception { // Arrange: final Constructor<BaseAnnotationHandlers> constructor = BaseAnnotationHandlers.class.getDeclaredConstructor(); constructor.setAccessible(true); // Act: constructor.newInstance(); } @Test public void testObtainFragmentHandler() { // Act: final FragmentAnnotationHandler handler = BaseAnnotationHandlers.obtainFragmentHandler(TestFragment.class); // Assert: assertThat(handler, is(notNullValue())); assertThat(handler, instanceOf(BaseAnnotationHandlers.FragmentHandler.class)); } public static final class TestFragment extends Fragment {} }
apache-2.0
davidmoten/rtree
src/main/java/com/github/davidmoten/rtree/RTree.java
34613
package com.github.davidmoten.rtree; import static com.github.davidmoten.rtree.geometry.Geometries.rectangle; import static java.util.Optional.of; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.guavamini.annotations.VisibleForTesting; import com.github.davidmoten.rtree.geometry.Circle; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.HasGeometry; import com.github.davidmoten.rtree.geometry.Intersects; import com.github.davidmoten.rtree.geometry.Line; import com.github.davidmoten.rtree.geometry.Point; import com.github.davidmoten.rtree.geometry.Rectangle; import com.github.davidmoten.rtree.internal.Comparators; import com.github.davidmoten.rtree.internal.NodeAndEntries; import com.github.davidmoten.rtree.internal.operators.OperatorBoundedPriorityQueue; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; /** * Immutable in-memory 2D R-Tree with configurable splitter heuristic. * * @param <T> * the entry value type * @param <S> * the entry geometry type */ public final class RTree<T, S extends Geometry> { public static final Rectangle ZERO_RECTANGLE = rectangle(0, 0, 0, 0); private final Optional<? extends Node<T, S>> root; private final Context<T, S> context; /** * Benchmarks show that this is a good choice for up to O(10,000) entries when * using Quadratic splitter (Guttman). */ public static final int MAX_CHILDREN_DEFAULT_GUTTMAN = 4; /** * Benchmarks show that this is the sweet spot for up to O(10,000) entries when * using R*-tree heuristics. */ public static final int MAX_CHILDREN_DEFAULT_STAR = 4; /** * Current size in Entries of the RTree. */ private final int size; private static final Func2<Optional<Rectangle>, Entry<Object, Geometry>, Optional<Rectangle>> RECTANGLE_ACCUMULATOR = (rectangle, entry) -> rectangle.map(value -> Optional.of(value.add(entry.geometry().mbr()))) .orElseGet(() -> Optional.of(entry.geometry().mbr())); /** * Constructor. * * @param root * the root node of the tree if present * @param context * options for the R-tree */ private RTree(Optional<? extends Node<T, S>> root, int size, Context<T, S> context) { this.root = root; this.size = size; this.context = context; } private RTree() { this(Optional.empty(), 0, null); } /** * Constructor. * * @param root * the root node of the R-tree * @param context * options for the R-tree */ private RTree(Node<T, S> root, int size, Context<T, S> context) { this(of(root), size, context); } static <T, S extends Geometry> RTree<T, S> create(Optional<? extends Node<T, S>> root, int size, Context<T, S> context) { return new RTree<T, S>(root, size, context); } /** * Returns a new Builder instance for {@link RTree}. Defaults to * maxChildren=128, minChildren=64, splitter=QuadraticSplitter. * * @param <T> * the value type of the entries in the tree * @param <S> * the geometry type of the entries in the tree * @return a new RTree instance */ public static <T, S extends Geometry> RTree<T, S> create() { return new Builder().create(); } /** * Construct an Rtree through STR bulk loading. Default to maxChildren=128, * minChildren=64 and fill nodes by a factor of 0.7 * * @param entries * entries to add to the R-tree * * @param <T> * the value type of the entries in the tree * @param <S> * the geometry type of the entries in the tree * @return a new RTree instance */ public static <T, S extends Geometry> RTree<T, S> create(List<Entry<T, S>> entries) { return new Builder().create(entries); } /** * The tree is scanned for depth and the depth returned. This involves recursing * down to the leaf level of the tree to get the current depth. Should be * <code>log(n)</code> in complexity. * * @return depth of the R-tree */ public int calculateDepth() { return calculateDepth(root); } private static <T, S extends Geometry> int calculateDepth(Optional<? extends Node<T, S>> root) { return root.map(node -> calculateDepth(node, 0)).orElse(0); } private static <T, S extends Geometry> int calculateDepth(Node<T, S> node, int depth) { if (node instanceof Leaf) { return depth + 1; } else { return calculateDepth(((NonLeaf<T, S>) node).child(0), depth + 1); } } /** * When the number of children in an R-tree node drops below this number the * node is deleted and the children are added on to the R-tree again. * * @param minChildren * less than this number of children in a node triggers a node * deletion and redistribution of its members * @return builder */ public static Builder minChildren(int minChildren) { return new Builder().minChildren(minChildren); } /** * Sets the max number of children in an R-tree node. * * @param maxChildren * max number of children in an R-tree node * @return builder */ public static Builder maxChildren(int maxChildren) { return new Builder().maxChildren(maxChildren); } /** * Sets the {@link Splitter} to use when maxChildren is reached. * * @param splitter * the splitter algorithm to use * @return builder */ public static Builder splitter(Splitter splitter) { return new Builder().splitter(splitter); } /** * Sets the node {@link Selector} which decides which branches to follow when * inserting or searching. * * @param selector * determines which branches to follow when inserting or searching * @return builder */ public static Builder selector(Selector selector) { return new Builder().selector(selector); } /** * Sets the splitter to {@link SplitterRStar} and selector to * {@link SelectorRStar} and defaults to minChildren=10. * * @return builder */ public static Builder star() { return new Builder().star(); } /** * RTree Builder. */ public static class Builder { /** * According to http://dbs.mathematik.uni-marburg.de/publications/myPapers * /1990/BKSS90.pdf (R*-tree paper), best filling ratio is 0.4 for both * quadratic split and R*-tree split. */ private static final double DEFAULT_FILLING_FACTOR = 0.4; private static final double DEFAULT_LOADING_FACTOR = 0.7; private Optional<Integer> maxChildren = Optional.empty(); private Optional<Integer> minChildren = Optional.empty(); private Splitter splitter = new SplitterQuadratic(); private Selector selector = new SelectorMinimalAreaIncrease(); private double loadingFactor; private boolean star = false; private Factory<Object, Geometry> factory = Factories.defaultFactory(); private Builder() { loadingFactor = DEFAULT_LOADING_FACTOR; } /** * The factor is used as the fill ratio during bulk loading. * * @param factor * loading factor * @return this */ public Builder loadingFactor(double factor) { this.loadingFactor = factor; return this; } /** * When the number of children in an R-tree node drops below this number the * node is deleted and the children are added on to the R-tree again. * * @param minChildren * less than this number of children in a node triggers a * redistribution of its children. * @return builder */ public Builder minChildren(int minChildren) { this.minChildren = of(minChildren); return this; } /** * Sets the max number of children in an R-tree node. * * @param maxChildren * max number of children in R-tree node. * @return builder */ public Builder maxChildren(int maxChildren) { this.maxChildren = of(maxChildren); return this; } /** * Sets the {@link Splitter} to use when maxChildren is reached. * * @param splitter * node splitting method to use * @return builder */ public Builder splitter(Splitter splitter) { this.splitter = splitter; return this; } /** * Sets the node {@link Selector} which decides which branches to follow when * inserting or searching. * * @param selector * selects the branch to follow when inserting or searching * @return builder */ public Builder selector(Selector selector) { this.selector = selector; return this; } /** * Sets the splitter to {@link SplitterRStar} and selector to * {@link SelectorRStar} and defaults to minChildren=10. * * @return builder */ public Builder star() { selector = new SelectorRStar(); splitter = new SplitterRStar(); star = true; return this; } @SuppressWarnings("unchecked") public Builder factory(Factory<?, ? extends Geometry> factory) { // TODO could change the signature of Builder to have types to // support this method but would be breaking change for existing // clients this.factory = (Factory<Object, Geometry>) factory; return this; } /** * Builds the {@link RTree}. * * @param <T> * value type * @param <S> * geometry type * @return RTree */ @SuppressWarnings("unchecked") public <T, S extends Geometry> RTree<T, S> create() { setDefaultCapacity(); return new RTree<T, S>(Optional.<Node<T, S>>empty(), 0, new Context<T, S>(minChildren.get(), maxChildren.get(), selector, splitter, (Factory<T, S>) factory)); } /** * Create an RTree by bulk loading, using the STR method. STR: a simple and * efficient algorithm for R-tree packing * http://ieeexplore.ieee.org/abstract/document/582015/ * <p> * Note: this method mutates the input entries, the internal order of the List * may be changed. * </p> * * @param entries * entries to be added to the r-tree * @return a loaded RTree */ @SuppressWarnings("unchecked") public <T, S extends Geometry> RTree<T, S> create(List<Entry<T, S>> entries) { setDefaultCapacity(); Context<T, S> context = new Context<T, S>(minChildren.get(), maxChildren.get(), selector, splitter, (Factory<T, S>) factory); return packingSTR(entries, true, entries.size(), context); } private void setDefaultCapacity() { if (!maxChildren.isPresent()) { if (star) { maxChildren = Optional.of(MAX_CHILDREN_DEFAULT_STAR); } else { maxChildren = Optional.of(MAX_CHILDREN_DEFAULT_GUTTMAN); } } if (!minChildren.isPresent()) { minChildren = Optional.of((int) Math.round(maxChildren.get() * DEFAULT_FILLING_FACTOR)); } } @SuppressWarnings("unchecked") private <T, S extends Geometry> RTree<T, S> packingSTR(List<? extends HasGeometry> objects, boolean isLeaf, int size, Context<T, S> context) { int capacity = (int) Math.round(maxChildren.get() * loadingFactor); int nodeCount = (int) Math.ceil(1.0 * objects.size() / capacity); if (nodeCount == 0) { return create(); } else if (nodeCount == 1) { Node<T, S> root; if (isLeaf) { root = context.factory().createLeaf((List<Entry<T, S>>) objects, context); } else { root = context.factory().createNonLeaf((List<Node<T, S>>) objects, context); } return new RTree<T, S>(of(root), size, context); } int nodePerSlice = (int) Math.ceil(Math.sqrt(nodeCount)); int sliceCapacity = nodePerSlice * capacity; int sliceCount = (int) Math.ceil(1.0 * objects.size() / sliceCapacity); Collections.sort(objects, new MidComparator((short) 0)); List<Node<T, S>> nodes = new ArrayList<Node<T, S>>(nodeCount); for (int s = 0; s < sliceCount; s++) { @SuppressWarnings("rawtypes") List slice = objects.subList(s * sliceCapacity, Math.min((s + 1) * sliceCapacity, objects.size())); Collections.sort(slice, new MidComparator((short) 1)); for (int i = 0; i < slice.size(); i += capacity) { if (isLeaf) { List<Entry<T, S>> entries = slice.subList(i, Math.min(slice.size(), i + capacity)); Node<T, S> leaf = context.factory().createLeaf(entries, context); nodes.add(leaf); } else { List<Node<T, S>> children = slice.subList(i, Math.min(slice.size(), i + capacity)); Node<T, S> nonleaf = context.factory().createNonLeaf(children, context); nodes.add(nonleaf); } } } return packingSTR(nodes, false, size, context); } private static final class MidComparator implements Comparator<HasGeometry> { private final short dimension; // leave space for multiple dimensions, 0 for x, 1 for y, // ... public MidComparator(short dim) { dimension = dim; } @Override public int compare(HasGeometry o1, HasGeometry o2) { return Double.compare(mid(o1), mid(o2)); } private double mid(HasGeometry o) { Rectangle mbr = o.geometry().mbr(); if (dimension == 0) return (mbr.x1() + mbr.x2()) / 2; else return (mbr.y1() + mbr.y2()) / 2; } } } /** * Returns an immutable copy of the RTree with the addition of given entry. * * @param entry * item to add to the R-tree. * @return a new immutable R-tree including the new entry */ @SuppressWarnings("unchecked") public RTree<T, S> add(Entry<? extends T, ? extends S> entry) { if (root.isPresent()) { List<Node<T, S>> nodes = root.get().add(entry); Node<T, S> node; if (nodes.size() == 1) node = nodes.get(0); else { node = context.factory().createNonLeaf(nodes, context); } return new RTree<T, S>(node, size + 1, context); } else { Leaf<T, S> node = context.factory().createLeaf(Lists.newArrayList((Entry<T, S>) entry), context); return new RTree<T, S>(node, size + 1, context); } } /** * Returns an immutable copy of the RTree with the addition of an entry * comprised of the given value and Geometry. * * @param value * the value of the {@link Entry} to be added * @param geometry * the geometry of the {@link Entry} to be added * @return a new immutable R-tree including the new entry */ public RTree<T, S> add(T value, S geometry) { return add(context.factory().createEntry(value, geometry)); } /** * Returns an immutable RTree with the current entries and the additional * entries supplied as a parameter. * * @param entries * entries to add * @return R-tree with entries added */ public RTree<T, S> add(Iterable<Entry<T, S>> entries) { RTree<T, S> tree = this; for (Entry<T, S> entry : entries) tree = tree.add(entry); return tree; } /** * Returns the Observable sequence of trees created by progressively adding * entries. * * @param entries * the entries to add * @return a sequence of trees */ public Observable<RTree<T, S>> add(Observable<Entry<T, S>> entries) { return entries.scan(this, (tree, entry) -> tree.add(entry)); } /** * Returns the Observable sequence of trees created by progressively deleting * entries. * * @param entries * the entries to add * @param all * if true delete all matching otherwise just first matching * @return a sequence of trees */ public Observable<RTree<T, S>> delete(Observable<Entry<T, S>> entries, final boolean all) { return entries.scan(this, new Func2<RTree<T, S>, Entry<T, S>, RTree<T, S>>() { @Override public RTree<T, S> call(RTree<T, S> tree, Entry<T, S> entry) { return tree.delete(entry, all); } }); } /** * Returns a new R-tree with the given entries deleted. If <code>all</code> is * false deletes only one if exists. If <code>all</code> is true deletes all * matching entries. * * @param entries * entries to delete * @param all * if false deletes one if exists else deletes all * @return R-tree with entries deleted */ public RTree<T, S> delete(Iterable<Entry<T, S>> entries, boolean all) { RTree<T, S> tree = this; for (Entry<T, S> entry : entries) tree = tree.delete(entry, all); return tree; } /** * Returns a new R-tree with the given entries deleted but only one matching * occurence of each entry is deleted. * * @param entries * entries to delete * @return R-tree with entries deleted up to one matching occurence per entry */ public RTree<T, S> delete(Iterable<Entry<T, S>> entries) { RTree<T, S> tree = this; for (Entry<T, S> entry : entries) tree = tree.delete(entry); return tree; } /** * If <code>all</code> is false deletes one entry matching the given value and * Geometry. If <code>all</code> is true deletes all entries matching the given * value and geometry. This method has no effect if the entry is not present. * The entry must match on both value and geometry to be deleted. * * @param value * the value of the {@link Entry} to be deleted * @param geometry * the geometry of the {@link Entry} to be deleted * @param all * if false deletes one if exists else deletes all * @return a new immutable R-tree without one or many instances of the specified * entry if it exists otherwise returns the original RTree object */ public RTree<T, S> delete(T value, S geometry, boolean all) { return delete(context.factory().createEntry(value, geometry), all); } /** * Deletes maximum one entry matching the given value and geometry. This method * has no effect if the entry is not present. The entry must match on both value * and geometry to be deleted. * * @param value * the value to be matched for deletion * @param geometry * the geometry to be matched for deletion * @return an immutable RTree without one entry (if found) matching the given * value and geometry */ public RTree<T, S> delete(T value, S geometry) { return delete(context.factory().createEntry(value, geometry), false); } /** * Deletes one or all matching entries depending on the value of * <code>all</code>. If multiple copies of the entry are in the R-tree only one * will be deleted if all is false otherwise all matching entries will be * deleted. The entry must match on both value and geometry to be deleted. * * @param entry * the {@link Entry} to be deleted * @param all * if true deletes all matches otherwise deletes first found * @return a new immutable R-tree without one instance of the specified entry */ public RTree<T, S> delete(Entry<? extends T, ? extends S> entry, boolean all) { if (root.isPresent()) { NodeAndEntries<T, S> nodeAndEntries = root.get().delete(entry, all); if (nodeAndEntries.node().isPresent() && nodeAndEntries.node().get() == root.get()) return this; else return new RTree<T, S>(nodeAndEntries.node(), size - nodeAndEntries.countDeleted() - nodeAndEntries.entriesToAdd().size(), context).add(nodeAndEntries.entriesToAdd()); } else return this; } /** * Deletes one entry if it exists, returning an immutable copy of the RTree * without that entry. If multiple copies of the entry are in the R-tree only * one will be deleted. The entry must match on both value and geometry to be * deleted. * * @param entry * the {@link Entry} to be deleted * @return a new immutable R-tree without one instance of the specified entry */ public RTree<T, S> delete(Entry<? extends T, ? extends S> entry) { return delete(entry, false); } /** * <p> * Returns an Observable sequence of {@link Entry} that satisfy the given * condition. Note that this method is well-behaved only if: * * * <p> * {@code condition(g)} is true for {@link Geometry} g implies * {@code condition(r)} is true for the minimum bounding rectangles of the * ancestor nodes. * * <p> * {@code distance(g) < D} is an example of such a condition. * * * @param condition * return Entries whose geometry satisfies the given condition * @return sequence of matching entries */ @VisibleForTesting Observable<Entry<T, S>> search(Func1<? super Geometry, Boolean> condition) { return root .map(node -> Observable.unsafeCreate(new OnSubscribeSearch<>(node, condition))) .orElseGet(Observable::empty); } /** * Returns a predicate function that indicates if {@link Geometry} intersects * with a given rectangle. * * @param r * the rectangle to check intersection with * @return whether the geometry and the rectangle intersect */ public static Func1<Geometry, Boolean> intersects(final Rectangle r) { return g -> g.intersects(r); } /** * Returns the always true predicate. See {@link RTree#entries()} for example * use. */ private static final Func1<Geometry, Boolean> ALWAYS_TRUE = rectangle -> true; /** * Returns an {@link Observable} sequence of all {@link Entry}s in the R-tree * whose minimum bounding rectangle intersects with the given rectangle. * * @param r * rectangle to check intersection with the entry mbr * @return entries that intersect with the rectangle r */ public Observable<Entry<T, S>> search(final Rectangle r) { return search(intersects(r)); } /** * Returns an {@link Observable} sequence of all {@link Entry}s in the R-tree * whose minimum bounding rectangle intersects with the given point. * * @param p * point to check intersection with the entry mbr * @return entries that intersect with the point p */ public Observable<Entry<T, S>> search(final Point p) { return search(p.mbr()); } public Observable<Entry<T, S>> search(Circle circle) { return search(circle, Intersects.geometryIntersectsCircle); } public Observable<Entry<T, S>> search(Line line) { return search(line, Intersects.geometryIntersectsLine); } /** * Returns an {@link Observable} sequence of all {@link Entry}s in the R-tree * whose minimum bounding rectangles are strictly less than maxDistance from the * given rectangle. * * @param r * rectangle to measure distance from * @param maxDistance * entries returned must be within this distance from rectangle r * @return the sequence of matching entries */ public Observable<Entry<T, S>> search(final Rectangle r, final double maxDistance) { return search(g -> g.distance(r) < maxDistance); } /** * Returns the intersections with the the given (arbitrary) geometry using an * intersection function to filter the search results returned from a search of * the mbr of <code>g</code>. * * @param <R> * type of geometry being searched for intersection with * @param g * geometry being searched for intersection with * @param intersects * function to determine if the two geometries intersect * @return a sequence of entries that intersect with g */ public <R extends Geometry> Observable<Entry<T, S>> search(final R g, final Func2<? super S, ? super R, Boolean> intersects) { return search(g.mbr()).filter(entry -> intersects.call(entry.geometry(), g)); } /** * Returns all entries strictly less than <code>maxDistance</code> from the * given geometry. Because the geometry may be of an arbitrary type it is * necessary to also pass a distance function. * * @param <R> * type of the geometry being searched for * @param g * geometry to search for entries within maxDistance of * @param maxDistance * strict max distance that entries must be from g * @param distance * function to calculate the distance between geometries of type S * and R. * @return entries strictly less than maxDistance from g */ public <R extends Geometry> Observable<Entry<T, S>> search(final R g, final double maxDistance, final Func2<? super S, ? super R, Double> distance) { // just use the mbr initially return search(entry -> entry.distance(g.mbr()) < maxDistance) // refine with distance function .filter(entry -> distance.call(entry.geometry(), g) < maxDistance); } /** * Returns an {@link Observable} sequence of all {@link Entry}s in the R-tree * whose minimum bounding rectangles are within maxDistance from the given * point. * * @param p * point to measure distance from * @param maxDistance * entries returned must be within this distance from point p * @return the sequence of matching entries */ public Observable<Entry<T, S>> search(final Point p, final double maxDistance) { return search(p.mbr(), maxDistance); } /** * Returns the nearest k entries (k=maxCount) to the given rectangle where the * entries are strictly less than a given maximum distance from the rectangle. * * @param r * rectangle * @param maxDistance * max distance of returned entries from the rectangle * @param maxCount * max number of entries to return * @return nearest entries to maxCount, in ascending order of distance */ public Observable<Entry<T, S>> nearest(final Rectangle r, final double maxDistance, int maxCount) { return search(r, maxDistance).lift(new OperatorBoundedPriorityQueue<Entry<T, S>>(maxCount, Comparators.<T, S>ascendingDistance(r))); } /** * Returns the nearest k entries (k=maxCount) to the given point where the * entries are strictly less than a given maximum distance from the point. * * @param p * point * @param maxDistance * max distance of returned entries from the point * @param maxCount * max number of entries to return * @return nearest entries to maxCount, in ascending order of distance */ public Observable<Entry<T, S>> nearest(final Point p, final double maxDistance, int maxCount) { return nearest(p.mbr(), maxDistance, maxCount); } /** * Returns all entries in the tree as an {@link Observable} sequence. * * @return all entries in the R-tree */ public Observable<Entry<T, S>> entries() { return search(ALWAYS_TRUE); } /** * Returns a {@link Visualizer} for an image of given width and height and * restricted to the given view of the coordinates. The points in the view are * scaled to match the aspect ratio defined by the width and height. * * @param width * of the image in pixels * @param height * of the image in pixels * @param view * using the coordinate system of the entries * @return visualizer */ @SuppressWarnings("unchecked") public Visualizer visualize(int width, int height, Rectangle view) { return new Visualizer((RTree<?, Geometry>) this, width, height, view); } /** * Returns a {@link Visualizer} for an image of given width and height and * restricted to the the smallest view that fully contains the coordinates. The * points in the view are scaled to match the aspect ratio defined by the width * and height. * * @param width * of the image in pixels * @param height * of the image in pixels * @return visualizer */ public Visualizer visualize(int width, int height) { return visualize(width, height, calculateMaxView(this)); } private Rectangle calculateMaxView(RTree<T, S> tree) { @SuppressWarnings("unchecked") Func2<Optional<Rectangle>, Entry<T, S>, Optional<Rectangle>> ra = // (Func2<Optional<Rectangle>, Entry<T, S>, Optional<Rectangle>>) // (Func2<?,?,?>) // RECTANGLE_ACCUMULATOR; return tree.entries() .reduce(Optional.empty(), ra) .toBlocking().single() .orElse(ZERO_RECTANGLE); } public Optional<? extends Node<T, S>> root() { return root; } /** * If the RTree has no entries returns {@link Optional#absent} otherwise returns * the minimum bounding rectangle of all entries in the RTree. * * @return minimum bounding rectangle of all entries in RTree */ public Optional<Rectangle> mbr() { return root.map(r -> r.geometry().mbr()); } /** * Returns true if and only if the R-tree is empty of entries. * * @return is R-tree empty */ public boolean isEmpty() { return size == 0; } /** * Returns the number of entries in the RTree. * * @return the number of entries */ public int size() { return size; } /** * Returns a {@link Context} containing the configuration of the RTree at the * time of instantiation. * * @return the configuration of the RTree prior to instantiation */ public Context<T, S> context() { return context; } /** * Returns a human readable form of the RTree. Here's an example: * * <pre> * mbr=Rectangle [x1=10.0, y1=4.0, x2=62.0, y2=85.0] * mbr=Rectangle [x1=28.0, y1=4.0, x2=34.0, y2=85.0] * entry=Entry [value=2, geometry=Point [x=29.0, y=4.0]] * entry=Entry [value=1, geometry=Point [x=28.0, y=19.0]] * entry=Entry [value=4, geometry=Point [x=34.0, y=85.0]] * mbr=Rectangle [x1=10.0, y1=45.0, x2=62.0, y2=63.0] * entry=Entry [value=5, geometry=Point [x=62.0, y=45.0]] * entry=Entry [value=3, geometry=Point [x=10.0, y=63.0]] * </pre> * * @return a string representation of the RTree */ public String asString() { if (!root.isPresent()) return ""; else return asString(root.get(), ""); } private static final String MARGIN_INCREMENT = " "; private String asString(Node<T, S> node, String margin) { StringBuilder s = new StringBuilder(); s.append(margin); s.append("mbr="); s.append(node.geometry()); s.append('\n'); if (node instanceof NonLeaf) { NonLeaf<T, S> n = (NonLeaf<T, S>) node; for (int i = 0; i < n.count(); i++) { Node<T, S> child = n.child(i); s.append(asString(child, margin + MARGIN_INCREMENT)); } } else { Leaf<T, S> leaf = (Leaf<T, S>) node; for (Entry<T, S> entry : leaf.entries()) { s.append(margin); s.append(MARGIN_INCREMENT); s.append("entry="); s.append(entry); s.append('\n'); } } return s.toString(); } }
apache-2.0
stephraleigh/flowable-engine
modules/flowable-dmn-engine/src/main/java/org/flowable/dmn/engine/impl/cmd/ExecuteDecisionWithAuditTrailCmd.java
2903
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.dmn.engine.impl.cmd; import java.util.Map; import org.flowable.dmn.api.DecisionExecutionAuditContainer; import org.flowable.dmn.api.DmnDecisionTable; import org.flowable.dmn.engine.DmnEngineConfiguration; import org.flowable.dmn.engine.impl.ExecuteDecisionBuilderImpl; import org.flowable.dmn.engine.impl.util.CommandContextUtil; import org.flowable.dmn.model.Decision; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.impl.interceptor.Command; import org.flowable.engine.common.impl.interceptor.CommandContext; /** * @author Tijs Rademakers * @author Yvo Swillens */ public class ExecuteDecisionWithAuditTrailCmd extends AbstractExecuteDecisionCmd implements Command<DecisionExecutionAuditContainer> { private static final long serialVersionUID = 1L; public ExecuteDecisionWithAuditTrailCmd(ExecuteDecisionBuilderImpl decisionBuilder) { super(decisionBuilder); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, Map<String, Object> variables) { super(decisionKey, variables); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables) { this(decisionKey, variables); executeDecisionInfo.setParentDeploymentId(parentDeploymentId); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables, String tenantId) { this(decisionKey, parentDeploymentId, variables); executeDecisionInfo.setTenantId(tenantId); } public DecisionExecutionAuditContainer execute(CommandContext commandContext) { if (getDecisionKey() == null) { throw new FlowableIllegalArgumentException("decisionKey is null"); } DmnEngineConfiguration dmnEngineConfiguration = CommandContextUtil.getDmnEngineConfiguration(); DmnDecisionTable decisionTable = resolveDecisionTable(dmnEngineConfiguration.getDeploymentManager()); Decision decision = resolveDecision(dmnEngineConfiguration.getDeploymentManager(), decisionTable); DecisionExecutionAuditContainer executionResult = dmnEngineConfiguration.getRuleEngineExecutor().execute(decision, executeDecisionInfo); return executionResult; } }
apache-2.0
enternoescape/opendct
src/main/java/opendct/tuning/discovery/DiscoveredDeviceParent.java
2882
/* * Copyright 2016 The OpenDCT Authors. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opendct.tuning.discovery; import opendct.config.options.DeviceOptions; import java.net.InetAddress; public interface DiscoveredDeviceParent extends DeviceOptions { /** * The unique name of this capture device parent. * <p/> * This should always return exactly the same name every time this device is detected. This is * used to verify that we are not potentially loading a duplicate device. * * @return The unchangeable unique name of this capture device. */ public String getName(); /** * The friendly/modifiable name of this capture device parent. * <p/> * This can be the same as the unique name, but this value should be user assignable. * * @return The modifiable name of this capture device parent. */ public String getFriendlyName(); /** * The unique id of this capture device parent. * <p/> * This ID must be exactly the same every time this device is detected. This is used to verify * that we are not potentially loading a duplicate device. * * @return The unique ID for this capture device. */ public int getParentId(); /** * Is this a network device? * * @return <i>true</i> if this is a network device. */ public boolean isNetworkDevice(); /** * Returns the local IP address to be used when streaming to this computer. * <p/> * Return <i>null</i> if this is not a network device. * * @return Returns the local IP address if this is a network device or <i>null</i>. */ public InetAddress getLocalAddress(); /** * Returns the current IP address of the capture device parent. * <p/> * Return <i>null</i> if this is not a network device. * * @return Returns the remote IP address if this is a network device or <i>null</i>. */ public InetAddress getRemoteAddress(); /** * Returns the unique IDs of all child devices for this parent device. * <p/> * This list is allowed to expand. When a capture device is detected, the device parent should * always be added first. * * @return An array of the child devices by unique ID. */ public int[] getChildDevices(); }
apache-2.0