text
stringlengths 7
1.01M
|
|---|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ds_project;
/**
*
* @author Aili
*/
public class DS_Project {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
|
package com.swroom.service;
/**
* 目标类(业务层)
* Created by Ray on 2016/5/4.
*/
public class SomeServiceImpl implements ISomeService {
@Override
public void doSome() {
System.out.println("执行doSome方法");
}
@Override
public String doSecond() {
System.out.println("执行doSecond方法");
return null;
}
}
|
package com.galois.fiveui;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Function;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author bjones
*/
public class BasicCrawlerController {
private String seed;
private String tmpDir;
private int depth;
private int maxFetch;
private int politeness;
private int threads;
private Function<String, Boolean> predicate;
/**
* Initialize a basic web crawler controller.
*
* @param seed URL to start the crawl
* @param domain string that all crawled page URLs must start with
* @param depth maximum depth to crawl
* @param maxFetch maximum number of pages to crawl
* @param politeness time in milliseconds to wait before making requests on same domain
* @param threads number of concurrent threads to use while crawling
* @param tmpDir temporary directory to store intermediate crawl data
* (must exist and be read/write before crawl starts)
*/
public BasicCrawlerController (String seed, final String domain, int depth, int maxFetch,
int politeness, int threads, String tmpDir) {
this.seed = seed;
this.predicate = new Function<String, Boolean>() {
public Boolean apply(String s) {
return s.startsWith(domain);
}
};
this.depth = depth;
this.maxFetch = maxFetch;
this.politeness = politeness;
this.threads = threads;
this.tmpDir = tmpDir;
}
/**
* Initialize a basic web crawler controller.
*
* @param seed URL to start the crawl
* @param pred a Function<String, Boolean> to be used as a predicate that all crawled URLs must pass
* @param depth maximum depth to crawl
* @param maxFetch maximum number of pages to crawl
* @param politeness time in milliseconds to wait before making requests on same domain
* @param threads number of concurrent threads to use while crawling
* @param tmpDir temporary directory to store intermediate crawl data
* (must exist and be read/write before crawl starts)
*/
public BasicCrawlerController (String seed, Function<String, Boolean> pred, int depth, int maxFetch,
int politeness, int threads, String tmpDir) {
this.seed = seed;
this.predicate = pred;
this.depth = depth;
this.maxFetch = maxFetch;
this.politeness = politeness;
this.threads = threads;
this.tmpDir = tmpDir;
}
public List<String> go() throws Exception {
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = this.tmpDir;
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = this.threads;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(this.politeness);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(this.depth);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(this.maxFetch);
/*
* Delete the temporary crawl storage after we're done.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
//robotstxtConfig.setEnabled(false); // uncomment if you want to ignore robots.txt
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
// add a seed URL
controller.addSeed(this.seed);
/*
* Setup storage for data collection by the BasicCrawler class
*/
List<String> store = new ArrayList<String>();
BasicCrawler.configure(this.predicate, store);
/*
* Start the crawl. This is a blocking operation.
*/
try {
controller.start(BasicCrawler.class, numberOfCrawlers);
} finally {
controller.Shutdown();
}
/*
* Extract and return data collected by BasicCrawler
*/
return store;
}
}
|
/******************************************************************************
Copyright 2019 EMBL - European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific
language governing permissions and limitations under the
License.
*/
package org.gentar.biology.gene_list;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.hateoas.server.core.Relation;
import java.util.List;
@Relation(collectionRelation = "records")
@Data
public class ListRecordDTO
{
private Long id;
private String note;
private Boolean visible;
private List<GeneByListRecordDTO> genes;
private List<String> recordTypes;
// Internal field to help the correct mapping of the recordTypes
@JsonIgnore
private String consortiumName;
@JsonProperty("projects")
private List<ProjectByGeneSummaryDTO> projectByGeneSummaryDTOS;
}
|
package com.neuedu.lab.model.po;
public class Department {
private String department_id;
private String department_name;
private String department_type;
private String department_cat;
public String getDepartment_id() {
return department_id;
}
public void setDepartment_id(String department_id) {
this.department_id = department_id;
}
public String getDepartment_name() {
return department_name;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
public String getDepartment_type() {
return department_type;
}
public void setDepartment_type(String department_type) {
this.department_type = department_type;
}
public String getDepartment_cat() {
return department_cat;
}
public void setDepartment_cat(String department_cat) {
this.department_cat = department_cat;
}
}
|
package hrv.lib.hrv.calc.manipulator.window;
import hrv.lib.hrv.RRData;
import hrv.lib.hrv.calc.manipulator.HRVDataManipulator;
public class NoWindow implements HRVDataManipulator {
@Override
public RRData manipulate(RRData data) {
return data;
}
}
|
/*
* Copyright 2012-2016 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 jetbrains.jetpad.hybrid.testapp.model;
public class EmptyExpr extends Expr {
}
|
/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
package net.hydromatic.optiq;
import org.eigenbase.reltype.RelDataType;
import org.eigenbase.reltype.RelDataTypeFactory;
/**
* Parameter to a {@link TableFunction}.
*/
public interface Parameter {
/**
* Zero-based ordinal of this parameter within the member's parameter
* list.
*
* @return Parameter ordinal
*/
int getOrdinal();
/**
* Name of the parameter.
*
* @return Parameter name
*/
String getName();
/**
* Returns the type of this parameter.
*
* @param typeFactory Type factory to be used to create the type
*
* @return Parameter type.
*/
RelDataType getType(RelDataTypeFactory typeFactory);
}
// End Parameter.java
|
package com.byron.line.component.rocketmq.listener;
import com.alibaba.fastjson.JSONObject;
import com.byron.line.common.ctx.SpringApplicationContext;
import com.byron.line.domain.Company;
import com.byron.line.req.TestReq;
import com.byron.line.service.CompanyService;
import lombok.Data;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @desc: 訂單状态更改消費者監聽中心
* 主要處理玩家充值失效訂單
* @author: byron
* @createtime: 5/22/20183:38 PM
* @modify by: ${user}
* @modify time: 5/22/20183:38 PM
* @desc of modify:
* @throws:
*/
@Component
@Data
public class TradeNoConsumeListener implements MessageListenerConcurrently {
private static final Logger log = LoggerFactory.getLogger(TradeNoConsumeListener.class);
private CompanyService companyService;
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
log.info("----------訂單状态更改消費者消費消息--------------");
list.stream().forEach(messageExt -> {
log.info("----------處理消息----------");
log.info("消息內容:{}",messageExt);
try {
String json = new String(messageExt.getBody());
TestReq testReq = JSONObject.parseObject(json, TestReq.class);
companyService = (CompanyService) SpringApplicationContext.getBean("TestService");
companyService.insertCompany(new Company());
} catch (Exception e){
log.info("消費者處理消息拋出異常:{}",e);
}
});
log.info("----------訂單状态更改消費者消費消息處理完成----------");
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
|
package net.minecraft.client.renderer.entity.layers;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.entity.RenderEnderman;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.util.ResourceLocation;
public class LayerEndermanEyes implements LayerRenderer
{
private static final ResourceLocation field_177203_a = new ResourceLocation("textures/entity/enderman/enderman_eyes.png");
private final RenderEnderman field_177202_b;
private static final String __OBFID = "CL_00002418";
public LayerEndermanEyes(RenderEnderman p_i46117_1_)
{
this.field_177202_b = p_i46117_1_;
}
public void func_177201_a(EntityEnderman p_177201_1_, float p_177201_2_, float p_177201_3_, float p_177201_4_, float p_177201_5_, float p_177201_6_, float p_177201_7_, float p_177201_8_)
{
this.field_177202_b.bindTexture(field_177203_a);
GlStateManager.enableBlend();
GlStateManager.disableAlpha();
GlStateManager.blendFunc(1, 1);
GlStateManager.disableLighting();
if (p_177201_1_.isInvisible())
{
GlStateManager.depthMask(false);
}
else
{
GlStateManager.depthMask(true);
}
char var9 = 61680;
int var10 = var9 % 65536;
int var11 = var9 / 65536;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)var10 / 1.0F, (float)var11 / 1.0F);
GlStateManager.enableLighting();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.field_177202_b.getMainModel().render(p_177201_1_, p_177201_2_, p_177201_3_, p_177201_5_, p_177201_6_, p_177201_7_, p_177201_8_);
this.field_177202_b.func_177105_a(p_177201_1_, p_177201_4_);
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
}
public boolean shouldCombineTextures()
{
return false;
}
public void doRenderLayer(EntityLivingBase p_177141_1_, float p_177141_2_, float p_177141_3_, float p_177141_4_, float p_177141_5_, float p_177141_6_, float p_177141_7_, float p_177141_8_)
{
this.func_177201_a((EntityEnderman)p_177141_1_, p_177141_2_, p_177141_3_, p_177141_4_, p_177141_5_, p_177141_6_, p_177141_7_, p_177141_8_);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.test.runtime.minicluster;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.testkit.JavaTestKit;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.messages.JobManagerMessages;
import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class LocalFlinkMiniClusterITCase {
static ActorSystem system;
@BeforeClass
public static void setup() {
system = ActorSystem.create("Testkit", AkkaUtils.getDefaultAkkaConfig());
}
@AfterClass
public static void teardown() {
JavaTestKit.shutdownActorSystem(system);
system = null;
}
@Test
public void testLocalFlinkMiniClusterWithMultipleTaskManagers() {
LocalFlinkMiniCluster miniCluster = null;
final int numTMs = 3;
final int numSlots = 14;
try{
Configuration config = new Configuration();
config.setInteger(ConfigConstants.LOCAL_INSTANCE_MANAGER_NUMBER_TASK_MANAGER, numTMs);
config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, numSlots);
miniCluster = new LocalFlinkMiniCluster(config, true);
final ActorRef jm = miniCluster.getJobManager();
new JavaTestKit(system) {{
new Within(TestingUtils.TESTING_DURATION()) {
@Override
protected void run() {
jm.tell(JobManagerMessages.getRequestNumberRegisteredTaskManager(),
getRef());
expectMsgEquals(TestingUtils.TESTING_DURATION(), numTMs);
jm.tell(JobManagerMessages.getRequestTotalNumberOfSlots(), getRef());
expectMsgEquals(TestingUtils.TESTING_DURATION(), numTMs*numSlots);
}
};
}};
} finally {
if (miniCluster != null) {
miniCluster.stop();
}
}
}
}
|
/* 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.content.engine;
import org.flowable.content.api.ContentManagementService;
import org.flowable.content.api.ContentService;
public interface ContentEngine {
/**
* the version of the flowable content library
*/
public static String VERSION = "6.2.0.0";
/**
* The name as specified in 'content-engine-name' in the flowable.content.cfg.xml configuration file. The default name for a process engine is 'default
*/
String getName();
void close();
ContentManagementService getContentManagementService();
ContentService getContentService();
ContentEngineConfiguration getContentEngineConfiguration();
}
|
/*
* 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.quotas;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.SnapshotDescription;
import org.apache.hadoop.hbase.client.SnapshotType;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.quotas.SnapshotQuotaObserverChore.SnapshotWithSize;
import org.apache.hadoop.hbase.quotas.SpaceQuotaHelperForTests.NoFilesToDischarge;
import org.apache.hadoop.hbase.quotas.SpaceQuotaHelperForTests.SpaceQuotaSnapshotPredicate;
import org.apache.hadoop.hbase.regionserver.HStore;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.collect.HashMultimap;
import org.apache.hbase.thirdparty.com.google.common.collect.Iterables;
import org.apache.hbase.thirdparty.com.google.common.collect.Multimap;
/**
* Test class for the {@link SnapshotQuotaObserverChore}.
*/
@Category(MediumTests.class)
public class TestSnapshotQuotaObserverChore {
private static final Logger LOG = LoggerFactory.getLogger(TestSnapshotQuotaObserverChore.class);
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static final AtomicLong COUNTER = new AtomicLong();
@Rule
public TestName testName = new TestName();
private Connection conn;
private Admin admin;
private SpaceQuotaHelperForTests helper;
private HMaster master;
private SnapshotQuotaObserverChore testChore;
@BeforeClass
public static void setUp() throws Exception {
Configuration conf = TEST_UTIL.getConfiguration();
SpaceQuotaHelperForTests.updateConfigForQuotas(conf);
// Clean up the compacted files faster than normal (15s instead of 2mins)
conf.setInt("hbase.hfile.compaction.discharger.interval", 15 * 1000);
TEST_UTIL.startMiniCluster(1);
}
@AfterClass
public static void tearDown() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
@Before
public void setup() throws Exception {
conn = TEST_UTIL.getConnection();
admin = TEST_UTIL.getAdmin();
helper = new SpaceQuotaHelperForTests(TEST_UTIL, testName, COUNTER);
master = TEST_UTIL.getHBaseCluster().getMaster();
helper.removeAllQuotas(conn);
testChore = new SnapshotQuotaObserverChore(
TEST_UTIL.getConnection(), TEST_UTIL.getConfiguration(), master.getFileSystem(), master,
null);
}
@Test
public void testSnapshotSizePersistence() throws IOException {
final Admin admin = TEST_UTIL.getAdmin();
final TableName tn = TableName.valueOf("quota_snapshotSizePersistence");
if (admin.tableExists(tn)) {
admin.disableTable(tn);
admin.deleteTable(tn);
}
HTableDescriptor desc = new HTableDescriptor(tn);
desc.addFamily(new HColumnDescriptor(QuotaTableUtil.QUOTA_FAMILY_USAGE));
admin.createTable(desc);
Multimap<TableName,SnapshotWithSize> snapshotsWithSizes = HashMultimap.create();
try (Table table = conn.getTable(tn)) {
// Writing no values will result in no records written.
verify(table, () -> {
testChore.persistSnapshotSizes(table, snapshotsWithSizes);
assertEquals(0, count(table));
});
verify(table, () -> {
TableName originatingTable = TableName.valueOf("t1");
snapshotsWithSizes.put(originatingTable, new SnapshotWithSize("ss1", 1024L));
snapshotsWithSizes.put(originatingTable, new SnapshotWithSize("ss2", 4096L));
testChore.persistSnapshotSizes(table, snapshotsWithSizes);
assertEquals(2, count(table));
assertEquals(1024L, extractSnapshotSize(table, originatingTable, "ss1"));
assertEquals(4096L, extractSnapshotSize(table, originatingTable, "ss2"));
});
snapshotsWithSizes.clear();
verify(table, () -> {
snapshotsWithSizes.put(TableName.valueOf("t1"), new SnapshotWithSize("ss1", 1024L));
snapshotsWithSizes.put(TableName.valueOf("t2"), new SnapshotWithSize("ss2", 4096L));
snapshotsWithSizes.put(TableName.valueOf("t3"), new SnapshotWithSize("ss3", 8192L));
testChore.persistSnapshotSizes(table, snapshotsWithSizes);
assertEquals(3, count(table));
assertEquals(1024L, extractSnapshotSize(table, TableName.valueOf("t1"), "ss1"));
assertEquals(4096L, extractSnapshotSize(table, TableName.valueOf("t2"), "ss2"));
assertEquals(8192L, extractSnapshotSize(table, TableName.valueOf("t3"), "ss3"));
});
}
}
@Test
public void testSnapshotsFromTables() throws Exception {
TableName tn1 = helper.createTableWithRegions(1);
TableName tn2 = helper.createTableWithRegions(1);
TableName tn3 = helper.createTableWithRegions(1);
// Set a space quota on table 1 and 2 (but not 3)
admin.setQuota(QuotaSettingsFactory.limitTableSpace(
tn1, SpaceQuotaHelperForTests.ONE_GIGABYTE, SpaceViolationPolicy.NO_INSERTS));
admin.setQuota(QuotaSettingsFactory.limitTableSpace(
tn2, SpaceQuotaHelperForTests.ONE_GIGABYTE, SpaceViolationPolicy.NO_INSERTS));
// Create snapshots on each table (we didn't write any data, so just skipflush)
admin.snapshot(new SnapshotDescription(tn1 + "snapshot", tn1, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(tn2 + "snapshot", tn2, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(tn3 + "snapshot", tn3, SnapshotType.SKIPFLUSH));
Multimap<TableName,String> mapping = testChore.getSnapshotsToComputeSize();
assertEquals(2, mapping.size());
assertEquals(1, mapping.get(tn1).size());
assertEquals(tn1 + "snapshot", mapping.get(tn1).iterator().next());
assertEquals(1, mapping.get(tn2).size());
assertEquals(tn2 + "snapshot", mapping.get(tn2).iterator().next());
admin.snapshot(new SnapshotDescription(tn2 + "snapshot1", tn2, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(tn3 + "snapshot1", tn3, SnapshotType.SKIPFLUSH));
mapping = testChore.getSnapshotsToComputeSize();
assertEquals(3, mapping.size());
assertEquals(1, mapping.get(tn1).size());
assertEquals(tn1 + "snapshot", mapping.get(tn1).iterator().next());
assertEquals(2, mapping.get(tn2).size());
assertEquals(
new HashSet<String>(Arrays.asList(tn2 + "snapshot", tn2 + "snapshot1")), mapping.get(tn2));
}
@Test
public void testSnapshotsFromNamespaces() throws Exception {
NamespaceDescriptor ns = NamespaceDescriptor.create("snapshots_from_namespaces").build();
admin.createNamespace(ns);
TableName tn1 = helper.createTableWithRegions(ns.getName(), 1);
TableName tn2 = helper.createTableWithRegions(ns.getName(), 1);
TableName tn3 = helper.createTableWithRegions(1);
// Set a space quota on the namespace
admin.setQuota(QuotaSettingsFactory.limitNamespaceSpace(
ns.getName(), SpaceQuotaHelperForTests.ONE_GIGABYTE, SpaceViolationPolicy.NO_INSERTS));
// Create snapshots on each table (we didn't write any data, so just skipflush)
admin.snapshot(new SnapshotDescription(
tn1.getQualifierAsString() + "snapshot", tn1, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(
tn2.getQualifierAsString() + "snapshot", tn2, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(
tn3.getQualifierAsString() + "snapshot", tn3, SnapshotType.SKIPFLUSH));
Multimap<TableName,String> mapping = testChore.getSnapshotsToComputeSize();
assertEquals(2, mapping.size());
assertEquals(1, mapping.get(tn1).size());
assertEquals(tn1.getQualifierAsString() + "snapshot", mapping.get(tn1).iterator().next());
assertEquals(1, mapping.get(tn2).size());
assertEquals(tn2.getQualifierAsString() + "snapshot", mapping.get(tn2).iterator().next());
admin.snapshot(new SnapshotDescription(
tn2.getQualifierAsString() + "snapshot1", tn2, SnapshotType.SKIPFLUSH));
admin.snapshot(new SnapshotDescription(
tn3.getQualifierAsString() + "snapshot2", tn3, SnapshotType.SKIPFLUSH));
mapping = testChore.getSnapshotsToComputeSize();
assertEquals(3, mapping.size());
assertEquals(1, mapping.get(tn1).size());
assertEquals(tn1.getQualifierAsString() + "snapshot", mapping.get(tn1).iterator().next());
assertEquals(2, mapping.get(tn2).size());
assertEquals(
new HashSet<String>(Arrays.asList(tn2.getQualifierAsString() + "snapshot",
tn2.getQualifierAsString() + "snapshot1")), mapping.get(tn2));
}
@Test
public void testSnapshotSize() throws Exception {
// Create a table and set a quota
TableName tn1 = helper.createTableWithRegions(5);
admin.setQuota(QuotaSettingsFactory.limitTableSpace(
tn1, SpaceQuotaHelperForTests.ONE_GIGABYTE, SpaceViolationPolicy.NO_INSERTS));
// Write some data and flush it
helper.writeData(tn1, 256L * SpaceQuotaHelperForTests.ONE_KILOBYTE);
admin.flush(tn1);
final long snapshotSize = TEST_UTIL.getMiniHBaseCluster().getRegions(tn1).stream()
.flatMap(r -> r.getStores().stream()).mapToLong(HStore::getHFilesSize).sum();
// Wait for the Master chore to run to see the usage (with a fudge factor)
TEST_UTIL.waitFor(30_000, new SpaceQuotaSnapshotPredicate(conn, tn1) {
@Override
boolean evaluate(SpaceQuotaSnapshot snapshot) throws Exception {
return snapshot.getUsage() == snapshotSize;
}
});
// Create a snapshot on the table
final String snapshotName = tn1 + "snapshot";
admin.snapshot(new SnapshotDescription(snapshotName, tn1, SnapshotType.SKIPFLUSH));
// Get the snapshots
Multimap<TableName,String> snapshotsToCompute = testChore.getSnapshotsToComputeSize();
assertEquals(
"Expected to see the single snapshot: " + snapshotsToCompute, 1, snapshotsToCompute.size());
// Get the size of our snapshot
Multimap<TableName,SnapshotWithSize> snapshotsWithSize = testChore.computeSnapshotSizes(
snapshotsToCompute);
assertEquals(1, snapshotsWithSize.size());
SnapshotWithSize sws = Iterables.getOnlyElement(snapshotsWithSize.get(tn1));
assertEquals(snapshotName, sws.getName());
// The snapshot should take up no space since the table refers to it completely
assertEquals(0, sws.getSize());
// Write some more data, flush it, and then major_compact the table
helper.writeData(tn1, 256L * SpaceQuotaHelperForTests.ONE_KILOBYTE);
admin.flush(tn1);
TEST_UTIL.compact(tn1, true);
// Test table should reflect it's original size since ingest was deterministic
TEST_UTIL.waitFor(30_000, new SpaceQuotaSnapshotPredicate(conn, tn1) {
private final long regionSize = TEST_UTIL.getMiniHBaseCluster().getRegions(tn1).stream()
.flatMap(r -> r.getStores().stream()).mapToLong(HStore::getHFilesSize).sum();
@Override
boolean evaluate(SpaceQuotaSnapshot snapshot) throws Exception {
LOG.debug("Current usage=" + snapshot.getUsage() + " snapshotSize=" + snapshotSize);
// The usage of table space consists of region size and snapshot size
return closeInSize(snapshot.getUsage(), snapshotSize + regionSize,
SpaceQuotaHelperForTests.ONE_KILOBYTE);
}
});
// Wait for no compacted files on the regions of our table
TEST_UTIL.waitFor(30_000, new NoFilesToDischarge(TEST_UTIL.getMiniHBaseCluster(), tn1));
// Still should see only one snapshot
snapshotsToCompute = testChore.getSnapshotsToComputeSize();
assertEquals(
"Expected to see the single snapshot: " + snapshotsToCompute, 1, snapshotsToCompute.size());
snapshotsWithSize = testChore.computeSnapshotSizes(
snapshotsToCompute);
assertEquals(1, snapshotsWithSize.size());
sws = Iterables.getOnlyElement(snapshotsWithSize.get(tn1));
assertEquals(snapshotName, sws.getName());
// The snapshot should take up the size the table originally took up
assertEquals(snapshotSize, sws.getSize());
}
@Test
public void testPersistingSnapshotsForNamespaces() throws Exception {
Multimap<TableName,SnapshotWithSize> snapshotsWithSizes = HashMultimap.create();
TableName tn1 = TableName.valueOf("ns1:tn1");
TableName tn2 = TableName.valueOf("ns1:tn2");
TableName tn3 = TableName.valueOf("ns2:tn1");
TableName tn4 = TableName.valueOf("ns2:tn2");
TableName tn5 = TableName.valueOf("tn1");
snapshotsWithSizes.put(tn1, new SnapshotWithSize("", 1024L));
snapshotsWithSizes.put(tn2, new SnapshotWithSize("", 1024L));
snapshotsWithSizes.put(tn3, new SnapshotWithSize("", 512L));
snapshotsWithSizes.put(tn4, new SnapshotWithSize("", 1024L));
snapshotsWithSizes.put(tn5, new SnapshotWithSize("", 3072L));
Map<String,Long> nsSizes = testChore.groupSnapshotSizesByNamespace(snapshotsWithSizes);
assertEquals(3, nsSizes.size());
assertEquals(2048L, (long) nsSizes.get("ns1"));
assertEquals(1536L, (long) nsSizes.get("ns2"));
assertEquals(3072L, (long) nsSizes.get(NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR));
}
private long count(Table t) throws IOException {
try (ResultScanner rs = t.getScanner(new Scan())) {
long sum = 0;
for (Result r : rs) {
while (r.advance()) {
sum++;
}
}
return sum;
}
}
private long extractSnapshotSize(
Table quotaTable, TableName tn, String snapshot) throws IOException {
Get g = QuotaTableUtil.makeGetForSnapshotSize(tn, snapshot);
Result r = quotaTable.get(g);
assertNotNull(r);
CellScanner cs = r.cellScanner();
cs.advance();
Cell c = cs.current();
assertNotNull(c);
return QuotaTableUtil.extractSnapshotSize(
c.getValueArray(), c.getValueOffset(), c.getValueLength());
}
private void verify(Table t, IOThrowingRunnable test) throws IOException {
admin.disableTable(t.getName());
admin.truncateTable(t.getName(), false);
test.run();
}
@FunctionalInterface
private interface IOThrowingRunnable {
void run() throws IOException;
}
/**
* Computes if {@code size2} is within {@code delta} of {@code size1}, inclusive.
*/
boolean closeInSize(long size1, long size2, long delta) {
long lower = size1 - delta;
long upper = size1 + delta;
return lower <= size2 && size2 <= upper;
}
}
|
// 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
//
// 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.uicd.backend.core.uicdactions;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.uicd.backend.core.constants.ContentMatchType;
import com.google.uicd.backend.core.constants.ContextStorageType;
import com.google.uicd.backend.core.constants.ElementSelectorType;
import com.google.uicd.backend.core.constants.ScreenContentSearchType;
import com.google.uicd.backend.core.devicesdriver.AndroidDeviceDriver;
import com.google.uicd.backend.core.exceptions.UicdDeviceHttpConnectionResetException;
import com.google.uicd.backend.core.uicdactions.jsondbignores.BaseSantinizer.ScreenContentValidationActionSantinizer;
import com.google.uicd.backend.core.xmlparser.Bounds;
import com.google.uicd.backend.core.xmlparser.NodeContext;
import com.google.uicd.backend.core.xmlparser.Position;
import com.google.uicd.backend.core.xmlparser.TextValidator;
import com.google.uicd.backend.core.xmlparser.XmlHelper;
import com.google.uicd.backend.core.xmlparser.XmlParser;
import java.util.List;
import java.util.Optional;
/** ScreenContentValidationAction */
@JsonDeserialize(converter = ScreenContentValidationActionSantinizer.class)
public class ScreenContentValidationAction extends ValidationAction {
protected boolean isOcrMode;
// node context for advanced search
protected NodeContext savedNodeContext;
@JsonIgnore protected NodeContext foundNodeContext;
@JsonIgnore protected PositionHelper positionHelper;
@JsonIgnore protected String validateInfo;
private ContextStorageType contextStorageType = ContextStorageType.CONTEXT_BASED;
private ScreenContentSearchType screenContentSearchType;
private String selectedText;
private ElementSelectorType selectedType;
private Bounds selectedBound;
public ScreenContentValidationAction() {
this.positionHelper = new PositionHelper();
}
public ScreenContentValidationAction(ValidationReqDetails validationReqDetails) {
this.selectedBound = validationReqDetails.getSelectedBounds();
this.selectedType = validationReqDetails.getElementSelectorType();
this.stopType = validationReqDetails.getStopType();
this.screenContentSearchType = validationReqDetails.getScreenContentSearchType();
this.setName(this.getClass().getSimpleName());
this.selectedText = validationReqDetails.getContentData();
this.contextStorageType = validationReqDetails.getContextStorageType();
this.isOcrMode = validationReqDetails.isOcrMode();
if (validationReqDetails.getNodeContext().isPresent()) {
this.savedNodeContext = validationReqDetails.getNodeContext().get();
}
if (validationReqDetails.getContextStorageType() == ContextStorageType.TEXT_BASED) {
TextValidator textValidator =
new TextValidator(this.selectedText, validationReqDetails.getContentMatchType());
this.setTextValidator(textValidator);
}
this.positionHelper = new PositionHelper();
}
protected void clear() {
super.clear();
foundNodeContext = new NodeContext();
}
@Override
public String getDisplay() {
return String.format("Screen Validate:(%s)", selectedText)
+ String.format("Stop Type:" + this.stopType);
}
@Override
public void updateAction(BaseAction baseAction) {
super.updateAction(baseAction);
if (baseAction instanceof ScreenContentValidationAction) {
ScreenContentValidationAction otherAction = (ScreenContentValidationAction) baseAction;
this.selectedText = otherAction.selectedText;
this.selectedType = otherAction.selectedType;
this.stopType = otherAction.stopType;
this.screenContentSearchType = otherAction.screenContentSearchType;
this.textValidator = otherAction.textValidator;
this.contextStorageType = otherAction.contextStorageType;
this.isOcrMode = otherAction.isOcrMode;
}
}
public Bounds getSelectedBound() {
return selectedBound;
}
public String getSelectedText() {
return selectedText;
}
private boolean validateBasedOnOCR(
String targetText, ActionContext actionContext, AndroidDeviceDriver androidDeviceDriver) {
Position pos =
positionHelper.getPositionFromScreenByORC(targetText, androidDeviceDriver, actionContext);
if (pos.isValidPos()) {
validateInfo =
String.format("Found targetText: %s at Position %s", targetText, pos);
} else {
validateInfo = "Can not find text by OCR";
}
return pos.isValidPos();
}
@Override
protected boolean validateRaw(
ActionContext actionContext, AndroidDeviceDriver androidDeviceDriver)
throws UicdDeviceHttpConnectionResetException {
String targetText =
actionContext.expandUicdGlobalVariable(
this.selectedText, androidDeviceDriver.getDeviceId());
if (isOcrMode) {
logger.info("Using ocr mode: searching for text: " + targetText);
return validateBasedOnOCR(targetText, actionContext, androidDeviceDriver);
}
if (this.textValidator == null) {
createDefaultTextValidator();
}
// Create a copy of textValidator, so that it won't change the original one,
// we should only "expand the variable when the actionContext exists.
TextValidator localTextValidator =
new TextValidator(
actionContext.expandUicdGlobalVariable(
this.textValidator.getPatternValue(), androidDeviceDriver.getDeviceId()),
this.textValidator.getContentMatchType());
List<String> xmls = androidDeviceDriver.fetchCurrentXML();
// first we validate content
if (savedNodeContext == null || this.contextStorageType != ContextStorageType.CONTEXT_BASED) {
XmlParser xmlParser =
new XmlParser(
xmls, androidDeviceDriver.getWidthRatio(), androidDeviceDriver.getHeightRatio());
Optional<NodeContext> candidateNode = Optional.empty();
int distanceThreshold = getDistanceThreshold(androidDeviceDriver);
if (selectedType == ElementSelectorType.RESOURCE_ID) {
candidateNode =
xmlParser.findNodeContextByResourceIdAndBounds(
localTextValidator, this.selectedBound, distanceThreshold);
} else if (selectedType == ElementSelectorType.DISPLAY_TEXT) {
candidateNode =
xmlParser.findNodeContextByTextValidatorAndBounds(
localTextValidator, this.selectedBound, distanceThreshold);
}
if (!candidateNode.isPresent()) {
return false;
} else {
foundNodeContext = candidateNode.get();
}
} else {
foundNodeContext =
XmlHelper.getMatchNodeContent(
xmls,
this.savedNodeContext,
androidDeviceDriver.getWidthRatio(),
androidDeviceDriver.getHeightRatio());
if (foundNodeContext == null) {
return false;
}
if (savedNodeContext.getLeafNodeContext() != null) {
if (foundNodeContext.getLeafNodeContext() == null) {
return false;
}
if (!savedNodeContext
.getLeafNodeContext()
.getFirstText()
.equalsIgnoreCase(foundNodeContext.getLeafNodeContext().getFirstText())) {
return false;
}
}
if (selectedType == ElementSelectorType.CHECK) {
if (foundNodeContext.findNodeByCheckStatus(Boolean.parseBoolean(targetText)) == null) {
return false;
}
} else if (foundNodeContext.findNodeByText(targetText) == null) {
return false;
}
}
// simple mode, we can also verify the location
if (savedNodeContext == null) {
int distanceThreshold = getDistanceThreshold(androidDeviceDriver);
if (foundNodeContext.getBounds().getCenter().getDistance(selectedBound.getCenter())
> distanceThreshold) {
return false;
}
}
return true;
}
private int getDistanceThreshold(AndroidDeviceDriver androidDeviceDriver) {
int distanceThreshold = 0;
if (screenContentSearchType == ScreenContentSearchType.AROUND) {
distanceThreshold = (int) (300 / androidDeviceDriver.getHeightRatio());
} else if (screenContentSearchType == ScreenContentSearchType.STRICT) {
distanceThreshold = (int) (100 / androidDeviceDriver.getHeightRatio());
} else {
distanceThreshold = (int) (10000 / androidDeviceDriver.getHeightRatio());
}
return distanceThreshold;
}
@Override
protected ActionExecutionResult genActionExecutionResults(
AndroidDeviceDriver androidDeviceDriver, ActionContext actionContext) {
ActionExecutionResult actionExecutionResult = new ActionExecutionResult();
String targetText;
if (savedNodeContext != null) {
targetText = savedNodeContext.getDisplayEstimate();
} else {
targetText = selectedText;
}
String foundsText = "";
if (selectedType == ElementSelectorType.RESOURCE_ID) {
foundsText = foundNodeContext == null ? "unknown" : foundNodeContext.getResourceId();
} else {
foundsText = foundNodeContext == null ? "unknown" : foundNodeContext.getDisplayEstimate();
}
String logContent;
if (isOcrMode) {
logContent =
String.format(
"Validation Result: %b. StopType: %s. %s",
this.validationResult, this.stopType, this.validateInfo);
} else {
logContent =
String.format(
"Validation Result: %b. StopType: %s. Looking for %s: %s of %s, found node: %s,",
this.validationResult,
this.stopType,
selectedType,
selectedText,
targetText,
foundsText);
}
actionExecutionResult.setRegularOutput(logContent);
actionExecutionResult.setActionId(this.getActionId().toString());
actionExecutionResult.setPlayStatus(this.playStatus);
logger.info(logContent);
return actionExecutionResult;
}
private void createDefaultTextValidator() {
TextValidator textValidator =
new TextValidator(this.selectedText, ContentMatchType.fromString("Equals"));
this.setTextValidator(textValidator);
}
public ElementSelectorType getSelectedType() {
return selectedType;
}
public NodeContext getSavedNodeContext() {
return savedNodeContext;
}
public ScreenContentSearchType getScreenContentSearchType() {
return screenContentSearchType;
}
}
|
/*
* Copyright (c) 2017, 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.mdm.qsg;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.wso2.mdm.qsg.dto.EMMQSGConfig;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import org.wso2.mdm.qsg.utils.Constants;
import org.wso2.mdm.qsg.utils.HTTPInvoker;
import java.util.HashMap;
/**
* This class holds the methods to create policies.
*/
public class PolicyOperations {
public static boolean createPasscodePolicy(String policyName, String deviceType) {
HashMap<String, String> headers = new HashMap<String, String>();
String policyEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/policies";
//Set the policy payload
JSONObject policyData = new JSONObject();
policyData.put("policyName", policyName);
policyData.put("description", "Passcode Policy");
policyData.put("compliance", "enforce");
policyData.put("ownershipType", "ANY");
policyData.put("active", false);
JSONObject profile = new JSONObject();
profile.put("profileName", "passcode");
profile.put("deviceType", deviceType);
JSONArray featureList = new JSONArray();
JSONObject feature = new JSONObject();
feature.put("featureCode", "PASSCODE_POLICY");
feature.put("deviceType", deviceType);
JSONObject featureContent = new JSONObject();
featureContent.put("allowSimple", false);
featureContent.put("requireAlphanumeric", true);
featureContent.put("minLength", "5");
featureContent.put("minComplexChars", "2");
featureContent.put("maxPINAgeInDays", 7);
featureContent.put("pinHistory", 7);
featureContent.put("maxFailedAttempts", null);
feature.put("content", featureContent);
featureList.add(feature);
profile.put("profileFeaturesList", featureList);
JSONArray roles = new JSONArray();
roles.add(Constants.EMM_USER_ROLE);
policyData.put("profile", profile);
policyData.put("roles", roles);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse
httpResponse = HTTPInvoker
.sendHTTPPostWithOAuthSecurity(policyEndpoint, policyData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
return true;
}
return false;
}
}
|
/**
* Copyright (c) Istituto Nazionale di Fisica Nucleare, 2018.
*
* 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.italiangrid.storm.webdav.oauth.authzserver;
import org.springframework.security.core.Authentication;
public interface TokenIssuerService {
TokenResponseDTO createAccessToken(AccessTokenRequest tokenRequest,
Authentication authentication);
}
|
package test10;
/*
* @author Sridhar Gopinath - g.sridhar53@gmail.com
*
* Course project,
* Principles of Programming Course, Fall - 2016,
* Computer Science and Automation (CSA),
* Indian Institute of Science (IISc),
* Bangalore
*/
/*
* Test 10: Complicated loops and conditionals
*/
public class Main {
public static void main(String[] args) {
int x = args[0].length();
int y = 0;
if (x < 3) {
if (x == 2)
y = y + 1;
else {
if (x == 1)
y = y + 2;
}
}
while (x < 10) {
if (x == 5) {
x++;
continue;
}
if (x == 9)
break;
x++;
}
if (x < 5) {
while (x < 10) {
if (x == 6)
System.err.println(x);
else if (x == 7)
System.err.println(x + 1);
else
System.err.println(x - 1);
}
System.exit(0);
}
System.err.println(x);
return;
}
}
|
package com.massoftware.service.fondos;
import com.massoftware.ui.components.UIUtils;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.KeyModifier;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.component.textfield.TextField;
@PageTitle("Conceptos")
@Route("TiposComprobantesConceptos")
public class UITiposComprobantesConceptosView extends VerticalLayout {
// autowidth
// filtro en formlayout
// ctrol + b buscar -- en la view no en la grid
// ctrol + n nuevo -- en la view no en la grid
// boton info
// tarjeta info
// responsive
// botonera no ordenable no movible
// Binder
private TiposComprobantesConceptosFiltro lastFilter;
private TiposComprobantesConceptosFiltro filter;
private Binder<TiposComprobantesConceptosFiltro> binder;
// Filter control
private HorizontalLayout filterRow1;
// EJEMPLOS
//private NumberField numeroFrom;
//private NumberField numeroTo;
//private TextField nombre;
private TextField codigo;
private TextField nombre;
private Button newBTN;
private Button findBTN;
// Grid
private UITiposComprobantesConceptosGrid grid;
public UITiposComprobantesConceptosView() throws Exception {
buildBinder();
buildFilterRows();
buildGrid();
this.setHeightFull();
this.search();
}
private void buildBinder() {
filter = new TiposComprobantesConceptosFiltro();
binder = new Binder<>(TiposComprobantesConceptosFiltro.class);
binder.setBean(filter);
}
private void buildFilterRows() throws Exception {
// Controls ------------------------
//-------------------------------------------------------------------
// Código
codigo = new TextField();
codigo.setPlaceholder("Código");
codigo.setPrefixComponent(VaadinIcon.SEARCH.create());
codigo.setWidthFull();
codigo.setClearButtonVisible(true);
codigo.setAutoselect(true);
codigo.addFocusShortcut(Key.DIGIT_1, KeyModifier.ALT);
binder.forField(codigo)
.bind(TiposComprobantesConceptosFiltro::getCodigo, TiposComprobantesConceptosFiltro::setCodigo);
codigo.addKeyPressListener(Key.ENTER, event -> {
search();
});
codigo.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().toString().trim().length() == 0) {
search();
}
});
codigo.addBlurListener(event -> {
search();
});
//-------------------------------------------------------------------
// Nombre
nombre = new TextField();
nombre.setPlaceholder("Nombre");
nombre.setPrefixComponent(VaadinIcon.SEARCH.create());
nombre.setWidthFull();
nombre.setClearButtonVisible(true);
nombre.setAutoselect(true);
nombre.addFocusShortcut(Key.DIGIT_2, KeyModifier.ALT);
binder.forField(nombre)
.bind(TiposComprobantesConceptosFiltro::getNombre, TiposComprobantesConceptosFiltro::setNombre);
nombre.addKeyPressListener(Key.ENTER, event -> {
search();
});
nombre.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().toString().trim().length() == 0) {
search();
}
});
nombre.addBlurListener(event -> {
search();
});
/* EJEMPLOS
// Nº banco (desde)
numeroFrom = new NumberField();
numeroFrom.setMin(1);
numeroFrom.setMax(Integer.MAX_VALUE);
numeroFrom.setPlaceholder("nº desde");
numeroFrom.setPrefixComponent(VaadinIcon.SEARCH.create());
numeroFrom.setClearButtonVisible(true);
numeroFrom.addFocusShortcut(Key.DIGIT_1, KeyModifier.ALT);
binder.forField(numeroFrom).withConverter(new DoubleToIntegerConverter())
.withValidator(value -> (value != null) ? value > 1 : true, "El valor tiene que ser >= 1")
.withValidator(value -> (value != null) ? value <= Integer.MAX_VALUE : true,
"El valor tiene que ser <= " + Integer.MAX_VALUE)
.bind(BancosFiltro::getNumeroFrom, BancosFiltro::setNumeroFrom);
numeroFrom.addKeyPressListener(Key.ENTER, event -> {
search();
});
numeroFrom.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().toString().trim().length() == 0) {
search();
}
});
numeroFrom.addBlurListener(event -> {
search();
});
// Nº banco (hasta)
numeroTo = new NumberField();
numeroTo.setMin(1);
numeroTo.setMax(Integer.MAX_VALUE);
numeroTo.setPlaceholder("nº hasta");
numeroTo.setPrefixComponent(VaadinIcon.SEARCH.create());
numeroTo.setClearButtonVisible(true);
numeroTo.addFocusShortcut(Key.DIGIT_2, KeyModifier.ALT);
binder.forField(numeroTo).withConverter(new DoubleToIntegerConverter())
.withValidator(value -> (value != null) ? value > 1 : true, "El valor tiene que ser >= 1")
.withValidator(value -> (value != null) ? value <= Integer.MAX_VALUE : true,
"El valor tiene que ser <= " + Integer.MAX_VALUE)
.bind(BancosFiltro::getNumeroTo, BancosFiltro::setNumeroTo);
numeroTo.addKeyPressListener(Key.ENTER, event -> {
search();
});
numeroTo.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().toString().trim().length() == 0) {
search();
}
});
numeroTo.addBlurListener(event -> {
search();
});
// Vigente
ComboBox<FBoolean> vigente = new ComboBox<>();
vigente.setPlaceholder("Vigente: Todos");
FBoolean valueVigente = new FBoolean("Vigente: ", null, "Todos");
vigente.setItems(valueVigente, new FBoolean("Vigente: ", true, "Si"), new FBoolean("Vigente: ", false, "No"));
vigente.setValue(valueVigente);
binder.bind(vigente, BancosFiltro::getVigenteX, BancosFiltro::setVigenteX);
vigente.addValueChangeListener(event -> {
search();
});
vigente.addBlurListener(event -> {
search();
});
// Nombre
nombre = new TextField();
nombre.setPlaceholder("nombre");
nombre.setPrefixComponent(VaadinIcon.SEARCH.create());
nombre.setWidthFull();
nombre.setClearButtonVisible(true);
nombre.setAutoselect(true);
nombre.addFocusShortcut(Key.DIGIT_3, KeyModifier.ALT);
binder.bind(nombre, BancosFiltro::getNombre, BancosFiltro::setNombre);
nombre.addKeyPressListener(Key.ENTER, event -> {
search();
});
nombre.addValueChangeListener(event -> {
if (event.getValue() == null || event.getValue().toString().trim().length() == 0) {
search();
}
});
nombre.addBlurListener(event -> {
search();
});
*/
//-------------------------------------------------------------------
// Button New ítem
newBTN = new Button();
UIUtils.setTooltip("Nuevo", newBTN);
newBTN.setIcon(VaadinIcon.PLUS.create());
// Button Search ítem's
findBTN = new Button();
UIUtils.setTooltip("Buscar", findBTN);
findBTN.setIcon(VaadinIcon.SEARCH.create());
findBTN.addClickListener(event -> {
search();
});
// Layout ------------------------
filterRow1 = new HorizontalLayout();
filterRow1.setWidthFull();
add(filterRow1);
//filterRow1.add(newBTN, numeroFrom, numeroTo, vigente, nombre, findBTN);
filterRow1.add(newBTN, codigo, nombre, findBTN);
//-------------------------------------------------------------------
}
private void buildGrid() throws Exception {
// grid = new UITiposComprobantesConceptosGrid(AppCX.services().buildTipoComprobanteConceptoService(), filter);
grid = new UITiposComprobantesConceptosGrid(new TipoComprobanteConceptoService(), filter);
// grid.addFocusShortcut(Key.DIGIT_1, KeyModifier.ALT);
grid.setWidthFull();
// grid.setHeightFull();
add(grid);
grid.focus();
}
private void search() {
binder.validate();
if (this.filter.equals(this.lastFilter) == false) {
this.lastFilter = (TiposComprobantesConceptosFiltro) this.filter.clone();
if (binder.isValid()) {
grid.refreshAll();
} else {
Notification.show("Uno o mas valores del filtro son incorrectos.");
}
}
}
private static final long serialVersionUID = 882456696439273826L;
}
|
/*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.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.camunda.bpm.engine.impl;
import org.camunda.bpm.engine.batch.BatchQuery;
import org.camunda.bpm.engine.query.QueryProperty;
/**
* Contains the possible properties that can be used in a {@link BatchQuery}.
*
*/
public interface BatchQueryProperty {
QueryProperty ID = new QueryPropertyImpl("ID_");
QueryProperty TENANT_ID = new QueryPropertyImpl("TENANT_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.
*
* Copyright 2012-2018 the original author or authors.
*/
package org.assertj.swing.lock;
import static edu.umd.cs.mtc.TestFramework.runOnce;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import edu.umd.cs.mtc.MultithreadedTestCase;
/**
* Tests for {@link ScreenLock#acquire(Object)}.
*
* @author Alex Ruiz
*/
public class ScreenLock_acquire_Test extends MultithreadedTestCase {
private ScreenLock lock;
private Object owner;
@Override
public void initialize() {
lock = new ScreenLock();
owner = new Object();
}
public void thread1() {
lock.acquire(owner);
assertThat(lock.acquiredBy(owner)).isTrue();
}
@Override
public void finish() {
if (lock.acquiredBy(owner)) {
lock.release(owner);
}
}
@Test
public void should_Not_Block_If_Current_Owner_Tries_To_Acquire_Lock_Again() throws Throwable {
runOnce(new ScreenLock_acquire_Test());
}
}
|
/*
* 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.netbeans.modules.search.matcher;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.netbeans.api.queries.FileEncodingQuery;
import org.netbeans.api.search.SearchPattern;
import org.netbeans.api.search.provider.SearchListener;
import org.netbeans.modules.search.Constants;
import org.netbeans.modules.search.MatchingObject.Def;
import org.netbeans.modules.search.TextDetail;
import org.netbeans.modules.search.TextRegexpUtil;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.util.Exceptions;
/**
* Multi-line matcher for big files that uses file-mapped memory.
*
* @author jhavlin
*/
public class MultiLineMappedMatcherBig extends AbstractMatcher {
private static int SIZE_LIMIT = 10 * 1024 * 1024;
private static int LINE_LIMIT = 4 * 1024;
private SearchPattern searchPattern;
private Pattern pattern;
private int fileMatches = 0;
private int itemMatches = 0;
private volatile boolean terminated = false;
public MultiLineMappedMatcherBig(SearchPattern searchPattern) {
this.searchPattern = searchPattern;
this.pattern = TextRegexpUtil.makeTextPattern(searchPattern);
}
@Override
protected Def checkMeasuredInternal(FileObject file,
SearchListener listener) {
Charset charset = FileEncodingQuery.getEncoding(file);
LongCharSequence longSequence = null;
try {
File f = FileUtil.toFile(file);
longSequence = new LongCharSequence(f, charset);
List<TextDetail> textDetails = matchWholeFile(longSequence, file);
if (textDetails == null) {
return null;
} else {
Def def = new Def(file, charset, textDetails);
return def;
}
} catch (Exception ex) {
listener.generalError(ex);
return null;
} finally {
if (longSequence != null) {
longSequence.close();
}
}
}
/**
* Perform pattern matching inside the whole file.
*
* @param cb Character buffer.
* @param fo File object.
*/
private List<TextDetail> matchWholeFile(CharSequence cb, FileObject fo)
throws DataObjectNotFoundException {
Matcher textMatcher = pattern.matcher(cb);
DataObject dataObject = null;
MultiLineMappedMatcherSmall.LineInfoHelper lineInfoHelper =
new MultiLineMappedMatcherSmall.LineInfoHelper(cb);
List<TextDetail> textDetails = null;
while (textMatcher.find()) {
if (textDetails == null) {
textDetails = new LinkedList<TextDetail>();
dataObject = DataObject.find(fo);
fileMatches++;
}
itemMatches++;
TextDetail ntd = new TextDetail(dataObject, searchPattern);
lineInfoHelper.findAndSetPositionInfo(ntd, textMatcher.start(),
textMatcher.end(), textMatcher.group());
textDetails.add(ntd);
if (fileMatches >= Constants.COUNT_LIMIT
|| itemMatches
>= Constants.DETAILS_COUNT_LIMIT) {
break;
}
}
return textDetails;
}
@Override
public void terminate() {
terminated = true;
}
/**
* Character sequence for matching content of very big files.
*/
private class LongCharSequence implements CharSequence {
private long fileSize;
private FileInputStream fileInputStream;
private FileChannel fileChannel;
/**
* At which character in the file the current buffer starts (counting
* from 0).
*/
private int charBufferStartsAt = -1;
/**
* At which character in the file the current buffer ends (counting from
* 0).
*/
private int charBufferEndsAt = -1;
/**
* Current buffer with character data. It shows a part of backing file.
*
* The part starts at charBufferStartsAt and ends at charBufferStartsAt
* + charBuffer.limit().
*/
private CharBuffer charBuffer = null;
/**
* Buffer with bytes from the file. The data between its current
* position and its limit has not been decoded yet. If it is null, no
* undecoded bytes are remaining.
*/
private MappedByteBuffer byteBuffer;
/**
* Decoder for file encoding.
*/
private CharsetDecoder decoder = null;
/**
* Total lengh of the character sequence. Value -1 means "unknown".
*/
private int length = -1;
/**
* Number of already decoded bytes;
*/
private long decodedBytes = 0;
/**
* Some variables for internal statistics. Usefull when debugging.
*/
/**
* Overflow indicated by the last ending decode or flush command.
*/
private boolean overflow = false;
private int shifts = 0;
private int maps = 0;
/**
* Current state of this sequence
*/
private State state = State.STANDARD;
public LongCharSequence(File file, Charset charset)
throws FileNotFoundException {
decoder = prepareDecoder(charset);
fileInputStream = new FileInputStream(file);
fileChannel = fileInputStream.getChannel();
fileSize = file.length();
charBuffer = CharBuffer.allocate((int) Math.min(fileSize,
SIZE_LIMIT));
}
/**
* Reset the character sequence - to read the file from the beginning.
*/
public void reset() {
decoder.reset();
decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
decodedBytes = 0;
charBuffer.clear();
charBufferStartsAt = -1;
charBufferEndsAt = -1;
overflow = false;
state = State.STANDARD;
if (byteBuffer != null) {
MatcherUtils.unmap(byteBuffer);
byteBuffer = null;
}
}
/**
* Compute lenght of this sequence - quite expensive operation, indeed.
*/
@Override
public synchronized int length() {
if (length == -1) {
try {
if (charBufferStartsAt == -1) {
reset();
}
while (shiftBuffer()) {
if (terminated) {
throw new TerminatedException();
}
// call to decode the whole file
}
length = charBufferStartsAt + charBuffer.limit();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
return length;
}
/**
* Get character at an index.
*/
@Override
public synchronized char charAt(int index) {
if (terminated) {
throw new TerminatedException();
}
if (isInBuffer(index)) {
return getFromBuffer(index);
} else {
if (index > length()) {
throw new IndexOutOfBoundsException();
}
if (index < charBufferStartsAt || charBufferStartsAt == -1) {
reset();
}
try {
while (shiftBuffer()) {
if (isInBuffer(index)) {
return getFromBuffer(index);
}
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
throw new IllegalStateException(
"Cannot get character."); //NOI18N
}
/**
* Shift buffer window to the following part of the file.
*
* Current buffer, buffer start and read bytes are updated. Current
* buffer position will be set to 0 and its limit to number of available
* characters.
*
* @return True if the buffer was shifted, false if end of the file was
* reached (the buffer was been shifted).
*/
private boolean shiftBuffer() throws IOException {
shifts++;
boolean res;
if (state == State.FLUSHED) {
assert overflow == false;
res = false;
} else if (state == State.STANDARD) {
assert overflow == false;
res = shiftBufferStandard();
} else if (state == State.ENDING) {
assert overflow == true;
res = shiftBufferEnding();
} else if (state == State.FLUSHING) {
assert overflow == true;
res = shiftBufferFlushing();
} else {
throw new IllegalStateException();
}
updateBufferBounds();
return res;
}
private boolean shiftBufferStandard() throws IllegalStateException,
IOException {
if (byteBuffer == null || byteBuffer.remaining() == 0) {
if (byteBuffer != null) {
MatcherUtils.unmap(byteBuffer);
}
long size = Math.min(SIZE_LIMIT, fileSize - decodedBytes);
byteBuffer = fileChannel.map(
FileChannel.MapMode.READ_ONLY,
decodedBytes,
size);
maps++;
}
long origByteBufPosition = byteBuffer.position();
int origCharBufLimit = charBufferStartsAt == -1
? 0
: charBuffer.limit();
charBuffer.clear();
CoderResult res;
res = decoder.decode(byteBuffer, charBuffer, false);
charBufferStartsAt = charBufferStartsAt == -1
? 0
: charBufferStartsAt + origCharBufLimit;
decodedBytes += byteBuffer.position() - origByteBufPosition;
if (res.isOverflow()) {
/*
* To much bytes for char buffer, will read from the same buffer
* the next time again.
*/
if (origByteBufPosition == byteBuffer.position()) {
throw new IllegalStateException("Neverending loop?");
}
charBuffer.flip();
return true;
} else if (decodedBytes < fileSize) {
/*
* Not at the end of file, will need new byte buffer.
*/
charBuffer.flip();
MatcherUtils.unmap(byteBuffer);
byteBuffer = null;
return true;
} else {
/*
* All bytes decoded, end and flush decoder.
*/
state = State.ENDING;
return shiftBufferEnding();
}
}
/**
* Called when state is ENDING. All bytes were read and passed to
* decoder.
*
* If overflow flag is on, the char buffer is cleared before decoding.
*/
private boolean shiftBufferEnding() {
assert state == State.ENDING;
if (overflow) {
charBufferStartsAt = charBufferStartsAt + charBuffer.limit();
charBuffer.clear();
}
CoderResult res = decoder.decode(byteBuffer, charBuffer, true);
if (res.isOverflow()) {
charBuffer.flip();
overflow = true;
return true;
} else {
overflow = false;
state = State.FLUSHING;
return shiftBufferFlushing();
}
}
/**
* Called when ending decode method was called and the doceder method
* should be flushed.
*
* If overflow flag is on, the char buffer is cleared before decoding.
*/
private boolean shiftBufferFlushing() {
assert state == State.FLUSHING;
if (overflow) {
charBufferStartsAt = charBufferStartsAt + charBuffer.limit();
charBuffer.clear();
}
CoderResult res = decoder.flush(charBuffer);
charBuffer.flip();
if (res.isOverflow()) {
overflow = true;
} else {
overflow = false;
state = State.FLUSHED;
}
return true;
}
@Override
public synchronized CharSequence subSequence(int start, int end) {
if (end - start < LINE_LIMIT) {
StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++) {
sb.append(charAt(i));
}
return sb.toString();
} else {
throw new IllegalArgumentException(
"Long subSequences are not supported."); //NOI18N
}
}
@Override
public synchronized String toString() {
return subSequence(0, length()).toString();
}
/**
* Close and release all resources.
*/
public void close() {
if (fileChannel != null) {
try {
fileChannel.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
if (byteBuffer != null) {
MatcherUtils.unmap(byteBuffer);
}
}
/**
* Is character on the specified index in the current buffer?
*/
private boolean isInBuffer(int index) {
return index >= charBufferStartsAt
&& index < charBufferEndsAt;
}
/**
* Get character on the specified index from the current buffer.
*/
private char getFromBuffer(int index) {
return charBuffer.charAt(index - charBufferStartsAt);
}
/**
* Update char buffer start and end offset.
*/
private void updateBufferBounds() {
if (charBufferStartsAt == -1) {
charBufferEndsAt = -1;
} else {
charBufferEndsAt = charBufferStartsAt + charBuffer.limit();
}
}
}
/**
* State of long character sequence.
*/
private enum State {
STANDARD, ENDING, FLUSHING, FLUSHED
}
class TerminatedException extends RuntimeException {
}
}
|
package com.ironaviation.traveller.di.component.my.travel;
import com.ironaviation.traveller.common.AppComponent;
import com.ironaviation.traveller.di.module.my.travel.BalancePayModule;
import com.ironaviation.traveller.mvp.ui.my.travel.BalancePayActivity;
import com.jess.arms.di.scope.ActivityScope;
import dagger.Component;
/**
* 通过Template生成对应页面的MVP和Dagger代码,请注意输入框中输入的名字必须相同
* 由于每个项目包结构都不一定相同,所以每生成一个文件需要自己导入import包名,可以在设置中设置自动导入包名
* 请在对应包下按以下顺序生成对应代码,Contract->Model->Presenter->Activity->Module->Component
* 因为生成Activity时,Module和Component还没生成,但是Activity中有它们的引用,所以会报错,但是不用理会
* 继续将Module和Component生成完后,编译一下项目再回到Activity,按提示修改一个方法名即可
* 如果想生成Fragment的相关文件,则将上面构建顺序中的Activity换为Fragment,并将Component中inject方法的参数改为此Fragment
*/
/**
* Created by flq on 2017/6/16.
*/
@ActivityScope
@Component(modules = BalancePayModule.class, dependencies = AppComponent.class)
public interface BalancePayComponent {
void inject(BalancePayActivity activity);
}
|
package org.frameworkset.tran.es.input.db;
/**
* Copyright 2008 biaoping.yin
* <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.
*/
import com.frameworkset.common.poolman.ConfigSQLExecutor;
import org.frameworkset.tran.BaseDataTran;
import org.frameworkset.tran.DataTranPlugin;
import org.frameworkset.tran.ESDataImportException;
import org.frameworkset.tran.TranResultSet;
import org.frameworkset.tran.context.ImportContext;
import org.frameworkset.tran.db.output.AsynDBOutPutDataTran;
import org.frameworkset.tran.db.output.DBOutPutContext;
import org.frameworkset.tran.es.input.ESInputPlugin;
import org.frameworkset.tran.schedule.Status;
import org.frameworkset.tran.schedule.TaskContext;
import org.frameworkset.tran.util.TranUtil;
import java.util.concurrent.CountDownLatch;
/**
* <p>Description: </p>
* <p></p>
* <p>Copyright (c) 2018</p>
* @Date 2019/10/9 14:35
* @author biaoping.yin
* @version 1.0
*/
public class ES2DBDataTranPlugin extends ESInputPlugin implements DataTranPlugin {
protected ConfigSQLExecutor executor;
protected DBOutPutContext dbOutPutContext;
public ES2DBDataTranPlugin(ImportContext importContext,ImportContext targetImportContext){
super( importContext, targetImportContext);
dbOutPutContext = (DBOutPutContext) targetImportContext;
}
@Override
public void beforeInit() {
super.beforeInit();
if(dbOutPutContext.getTargetDBConfig() != null)
{
this.initDS(dbOutPutContext.getTargetDBConfig());
}
if(importContext.getDbConfig() != null) {
this.initDS(importContext.getDbConfig());
}
initOtherDSes(importContext.getConfigs());
}
@Override
public void afterInit(){
executor = TranUtil.initTargetSQLInfo(dbOutPutContext,dbOutPutContext.getTargetDBConfig() != null?dbOutPutContext.getTargetDBConfig():importContext.getDbConfig());
}
protected BaseDataTran createBaseDataTran(TaskContext taskContext, TranResultSet jdbcResultSet, CountDownLatch countDownLatch, Status currentStatus){
AsynDBOutPutDataTran asynDBOutPutDataTran = new AsynDBOutPutDataTran( taskContext,jdbcResultSet,importContext, targetImportContext,countDownLatch, currentStatus);
asynDBOutPutDataTran.init();
return asynDBOutPutDataTran;
}
public void doImportData(TaskContext taskContext) throws ESDataImportException{
if(dbOutPutContext.getBatchHandler() != null){
doBatchHandler( taskContext);
}
else{
super.doImportData( taskContext);
}
}
protected void doBatchHandler(TaskContext taskContext){
ESDirectExporterScrollHandler esDirectExporterScrollHandler = new ESDirectExporterScrollHandler(importContext,targetImportContext,
executor);
try {
if (!isIncreamentImport()) {
commonImportData( taskContext,esDirectExporterScrollHandler);
} else {
increamentImportData( taskContext,esDirectExporterScrollHandler);
}
} catch (ESDataImportException e) {
throw e;
} catch (Exception e) {
throw new ESDataImportException(e);
}
}
}
|
/*
* Copyright 2012-2017 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.springframework.boot.context.properties.source;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySource.StubPropertySource;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* Adapter to convert Spring's {@link MutablePropertySources} to
* {@link ConfigurationPropertySource ConfigurationPropertySources}.
*
* @author Phillip Webb
*/
class SpringConfigurationPropertySources
implements Iterable<ConfigurationPropertySource> {
private final MutablePropertySources sources;
private volatile PropertySourcesKey lastKey;
private volatile List<ConfigurationPropertySource> adaptedSources;
SpringConfigurationPropertySources(MutablePropertySources sources) {
Assert.notNull(sources, "Sources must not be null");
this.sources = sources;
}
@Override
public Iterator<ConfigurationPropertySource> iterator() {
checkForChanges();
return this.adaptedSources.iterator();
}
private void checkForChanges() {
PropertySourcesKey lastKey = this.lastKey;
PropertySourcesKey currentKey = new PropertySourcesKey(this.sources);
if (!currentKey.equals(lastKey)) {
onChange(this.sources);
this.lastKey = currentKey;
}
}
private void onChange(MutablePropertySources sources) {
this.adaptedSources = streamPropertySources(sources)
.map(SpringConfigurationPropertySource::from)
.collect(Collectors.toList());
}
private Stream<PropertySource<?>> streamPropertySources(
Iterable<PropertySource<?>> sources) {
return StreamSupport.stream(sources.spliterator(), false).flatMap(this::flatten)
.filter(this::isIncluded);
}
private Stream<PropertySource<?>> flatten(PropertySource<?> source) {
if (source.getSource() instanceof ConfigurableEnvironment) {
return streamPropertySources(
((ConfigurableEnvironment) source.getSource()).getPropertySources());
}
return Stream.of(source);
}
private boolean isIncluded(PropertySource<?> source) {
return !(source instanceof StubPropertySource)
&& !(source instanceof ConfigurationPropertySourcesPropertySource);
}
private static class PropertySourcesKey {
private final List<PropertySourceKey> keys = new ArrayList<>();
PropertySourcesKey(MutablePropertySources sources) {
sources.forEach(this::addKey);
}
private void addKey(PropertySource<?> source) {
this.keys.add(new PropertySourceKey(source));
}
@Override
public int hashCode() {
return this.keys.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.keys.equals(((PropertySourcesKey) obj).keys);
}
}
private static class PropertySourceKey {
private final String name;
private final Class<?> type;
PropertySourceKey(PropertySource<?> source) {
this.name = source.getName();
this.type = source.getClass();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ObjectUtils.nullSafeHashCode(this.name);
result = prime * result + ObjectUtils.nullSafeHashCode(this.type);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
PropertySourceKey other = (PropertySourceKey) obj;
boolean result = true;
result = result && ObjectUtils.nullSafeEquals(this.name, other.name);
result = result && ObjectUtils.nullSafeEquals(this.type, other.type);
return result;
}
}
}
|
package com.capgemini.rebecca.repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class ConnectionFactory {
private EntityManager entityManager;
public ConnectionFactory() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("banco");
this.entityManager = factory.createEntityManager();
}
public EntityManager getConnection() {
return entityManager;
}
}
|
/*
* Copyright 2013-2018 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.databasemigrationservice.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.databasemigrationservice.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* TableStatisticsMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TableStatisticsMarshaller {
private static final MarshallingInfo<String> SCHEMANAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SchemaName").build();
private static final MarshallingInfo<String> TABLENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("TableName").build();
private static final MarshallingInfo<Long> INSERTS_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Inserts").build();
private static final MarshallingInfo<Long> DELETES_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Deletes").build();
private static final MarshallingInfo<Long> UPDATES_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Updates").build();
private static final MarshallingInfo<Long> DDLS_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Ddls").build();
private static final MarshallingInfo<Long> FULLLOADROWS_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("FullLoadRows").build();
private static final MarshallingInfo<Long> FULLLOADCONDTNLCHKFAILEDROWS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FullLoadCondtnlChkFailedRows").build();
private static final MarshallingInfo<Long> FULLLOADERRORROWS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FullLoadErrorRows").build();
private static final MarshallingInfo<java.util.Date> LASTUPDATETIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LastUpdateTime").build();
private static final MarshallingInfo<String> TABLESTATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("TableState").build();
private static final MarshallingInfo<Long> VALIDATIONPENDINGRECORDS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidationPendingRecords").build();
private static final MarshallingInfo<Long> VALIDATIONFAILEDRECORDS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidationFailedRecords").build();
private static final MarshallingInfo<Long> VALIDATIONSUSPENDEDRECORDS_BINDING = MarshallingInfo.builder(MarshallingType.LONG)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidationSuspendedRecords").build();
private static final MarshallingInfo<String> VALIDATIONSTATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidationState").build();
private static final MarshallingInfo<String> VALIDATIONSTATEDETAILS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ValidationStateDetails").build();
private static final TableStatisticsMarshaller instance = new TableStatisticsMarshaller();
public static TableStatisticsMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(TableStatistics tableStatistics, ProtocolMarshaller protocolMarshaller) {
if (tableStatistics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(tableStatistics.getSchemaName(), SCHEMANAME_BINDING);
protocolMarshaller.marshall(tableStatistics.getTableName(), TABLENAME_BINDING);
protocolMarshaller.marshall(tableStatistics.getInserts(), INSERTS_BINDING);
protocolMarshaller.marshall(tableStatistics.getDeletes(), DELETES_BINDING);
protocolMarshaller.marshall(tableStatistics.getUpdates(), UPDATES_BINDING);
protocolMarshaller.marshall(tableStatistics.getDdls(), DDLS_BINDING);
protocolMarshaller.marshall(tableStatistics.getFullLoadRows(), FULLLOADROWS_BINDING);
protocolMarshaller.marshall(tableStatistics.getFullLoadCondtnlChkFailedRows(), FULLLOADCONDTNLCHKFAILEDROWS_BINDING);
protocolMarshaller.marshall(tableStatistics.getFullLoadErrorRows(), FULLLOADERRORROWS_BINDING);
protocolMarshaller.marshall(tableStatistics.getLastUpdateTime(), LASTUPDATETIME_BINDING);
protocolMarshaller.marshall(tableStatistics.getTableState(), TABLESTATE_BINDING);
protocolMarshaller.marshall(tableStatistics.getValidationPendingRecords(), VALIDATIONPENDINGRECORDS_BINDING);
protocolMarshaller.marshall(tableStatistics.getValidationFailedRecords(), VALIDATIONFAILEDRECORDS_BINDING);
protocolMarshaller.marshall(tableStatistics.getValidationSuspendedRecords(), VALIDATIONSUSPENDEDRECORDS_BINDING);
protocolMarshaller.marshall(tableStatistics.getValidationState(), VALIDATIONSTATE_BINDING);
protocolMarshaller.marshall(tableStatistics.getValidationStateDetails(), VALIDATIONSTATEDETAILS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
/*
* Copyright © 2014 Cask Data, 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 co.cask.cdap.internal.pipeline;
import co.cask.cdap.pipeline.Pipeline;
import co.cask.cdap.pipeline.Stage;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
/**
* Abstract implementation of {@link Pipeline}.
*
* @param <T> Type of object produced by this pipeline.
*/
public abstract class AbstractPipeline<T> implements Pipeline<T> {
/**
* List of stages in the pipeline.
*/
private List<Stage> stages = Lists.newLinkedList();
private Stage finalStage;
/**
* Adds a {@link Stage} to the {@link Pipeline}.
*
* @param stage to be added to this pipeline.
*/
@Override
public void addLast(Stage stage) {
stages.add(stage);
}
@Override
public void setFinally(Stage stage) {
this.finalStage = stage;
}
/**
* @return list of Stages.
*/
protected final List<Stage> getStages() {
return Collections.unmodifiableList(stages);
}
@Nullable
protected final Stage getFinalStage() {
return finalStage;
}
}
|
/*
* Copyright 2019 StreamThoughts.
*
* 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 io.streamthoughts.azkarra.http.handler;
import io.streamthoughts.azkarra.api.AzkarraStreamsService;
import io.undertow.server.HttpServerExchange;
public class StreamsDeleteHandler extends AbstractStreamHttpHandler implements WithApplication {
/**
* Creates a new {@link StreamsDeleteHandler} instance.
*
* @param service the {@link AzkarraStreamsService} instance.
*/
public StreamsDeleteHandler(final AzkarraStreamsService service) {
super(service);
}
/**
* {@inheritDoc}
*/
@Override
public void handleRequest(final HttpServerExchange exchange, final String applicationId) {
service.deleteStreams(applicationId);
}
}
|
package org.broadinstitute.hellbender.tools.walkers.haplotypecaller;
import com.google.common.base.Strings;
import htsjdk.samtools.util.Locatable;
import htsjdk.variant.variantcontext.*;
import org.apache.commons.lang3.tuple.Pair;
import org.broadinstitute.hellbender.utils.QualityUtils;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.haplotype.EventMap;
import org.broadinstitute.hellbender.utils.haplotype.Haplotype;
import org.broadinstitute.hellbender.utils.pileup.ReadPileup;
import org.broadinstitute.hellbender.utils.read.ArtificialReadUtils;
import org.broadinstitute.hellbender.utils.read.GATKRead;
import org.broadinstitute.hellbender.utils.smithwaterman.SWPairwiseAlignment;
import org.broadinstitute.hellbender.utils.test.BaseTest;
import org.broadinstitute.hellbender.utils.variant.GATKVCFConstants;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.*;
/**
* Unit tests for {@link HaplotypeCallerGenotypingEngine}.
*/
public final class HaplotypeCallerGenotypingEngineUnitTest extends BaseTest {
private class BasicGenotypingTestProvider extends TestDataProvider {
byte[] ref;
byte[] hap;
Map<Integer,Byte> expected;
public BasicGenotypingTestProvider(String refString, String hapString, Map<Integer, Byte> expected) {
super(BasicGenotypingTestProvider.class, String.format("Haplotype to VCF test: ref = %s, alignment = %s", refString,hapString));
ref = refString.getBytes();
hap = hapString.getBytes();
this.expected = expected;
}
public Map<Integer,VariantContext> calcAlignment() {
final SWPairwiseAlignment alignment = new SWPairwiseAlignment(ref, hap, new SWPairwiseAlignment.Parameters(3,-1,-4, -1));
final Haplotype h = new Haplotype(hap, false, alignment.getAlignmentStart2wrt1(), alignment.getCigar());
return new EventMap(h, ref, new SimpleInterval("4", 1, 1 + ref.length), "name");
}
public String toString() {
return "REF:" + new String(ref) + ",ALT:" + new String(hap);
}
}
@DataProvider(name = "BasicGenotypingTestProvider")
public Object[][] makeBasicGenotypingTests() {
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(1 + contextSize, (byte)'M');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "CGCTCGCATCGCGAGCATCGACTAGCCGATAG", map);
}
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(2 + contextSize, (byte)'M');
map.put(21 + contextSize, (byte)'M');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG", "ATCTCGCATCGCGAGCATCGCCTAGCCGATAG", map);
}
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(1 + contextSize, (byte)'M');
map.put(20 + contextSize, (byte)'I');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "CGCTCGCATCGCGAGCATCGACACTAGCCGATAG", map);
}
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(1 + contextSize, (byte)'M');
map.put(20 + contextSize, (byte)'D');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "CGCTCGCATCGCGAGCATCGCTAGCCGATAG", map);
}
for( int contextSize : new int[]{1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(1, (byte)'M');
map.put(20, (byte)'D');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider("AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "CGCTCGCATCGCGAGCATCGCTAGCCGATAG", map);
}
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(2 + contextSize, (byte)'M');
map.put(20 + contextSize, (byte)'I');
map.put(30 + contextSize, (byte)'D');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "ACCTCGCATCGCGAGCATCGTTACTAGCCGATG", map);
}
for( int contextSize : new int[]{0,1,5,9,24,36} ) {
Map<Integer, Byte> map = new HashMap<>();
map.put(1 + contextSize, (byte)'M');
map.put(20 + contextSize, (byte)'D');
map.put(28 + contextSize, (byte)'M');
final String context = Strings.repeat("G", contextSize);
new BasicGenotypingTestProvider(context + "AGCTCGCATCGCGAGCATCGACTAGCCGATAG" + context, "CGCTCGCATCGCGAGCATCGCTAGCCCATAG", map);
}
return BasicGenotypingTestProvider.getTests(BasicGenotypingTestProvider.class);
}
@Test(dataProvider = "BasicGenotypingTestProvider", enabled = true)
public void testHaplotypeToVCF(BasicGenotypingTestProvider cfg) {
Map<Integer,VariantContext> calculatedMap = cfg.calcAlignment();
Map<Integer,Byte> expectedMap = cfg.expected;
logger.warn(String.format("Test: %s", cfg.toString()));
if(!compareVCMaps(calculatedMap, expectedMap)) {
logger.warn("calc map = " + calculatedMap);
logger.warn("expected map = " + expectedMap);
}
Assert.assertTrue(compareVCMaps(calculatedMap, expectedMap),"" + cfg);
}
@Test(dataProvider="AddMiscellaneousDataProvider", enabled=false)
public void testAddMiscellaneousAllele(final String readBases, final int readOffset,
final String ref, final int refOffset,
final String referenceAllele, final String[] alternatives, final double[] likelihoods, final double[] expected) {
final byte baseQual = (byte)30;
final byte[] baseQuals = Utils.dupBytes(baseQual, readBases.length());
final GATKRead read = ArtificialReadUtils.createArtificialRead(readBases.getBytes(), baseQuals, readBases.length() + "M");
final Locatable loc = new SimpleInterval("20",refOffset,refOffset);
final ReadPileup pileup = new ReadPileup(loc, Collections.singletonList(read),readOffset);
final VariantContextBuilder vcb = new VariantContextBuilder();
final GenotypeBuilder gb = new GenotypeBuilder();
final List<String> alleleStrings = new ArrayList<>( 1 + alternatives.length);
alleleStrings.add(referenceAllele);
alleleStrings.addAll(Arrays.asList(alternatives));
gb.AD(new int[] { 1 });
gb.DP(1);
gb.PL(likelihoods);
vcb.alleles(alleleStrings);
vcb.loc("20",refOffset,refOffset + referenceAllele.length() -1);
vcb.genotypes(gb.make());
final VariantContext vc = vcb.make();
final VariantContext updatedVc = null; // GenotypingEngine.addMiscellaneousAllele(vc,pileup,ref.getBytes(),0);
final GenotypeLikelihoods updatedLikelihoods = updatedVc.getGenotype(0).getLikelihoods();
Assert.assertEquals(updatedLikelihoods.getAsVector().length, expected.length);
final double[] updatedLikelihoodsArray = updatedVc.getGenotype(0).getLikelihoods().getAsVector();
for (int i = 0; i < updatedLikelihoodsArray.length; i++) {
Assert.assertEquals(updatedLikelihoodsArray[i],expected[i],0.0001);
}
Allele altAllele = null;
for (final Allele allele : updatedVc.getAlleles())
if (allele.isSymbolic() && allele.getBaseString().equals(GATKVCFConstants.NON_REF_SYMBOLIC_ALLELE_NAME))
altAllele = allele;
Assert.assertNotNull(altAllele);
}
@DataProvider(name="AddMiscellaneousDataProvider")
public Iterator<Object[]> addMiscellaneousAlleleDataProvider() {
return Arrays.asList(ADD_MISCELLANEOUS_ALLELE_DATA).iterator();
}
private static final double MATCH_LnLK = QualityUtils.qualToProbLog10((byte)30);
private static final double MISS_LnLK = QualityUtils.qualToErrorProbLog10((byte)30);
private static final Object[][] ADD_MISCELLANEOUS_ALLELE_DATA = new Object[][] {
new Object[] {"ACTG", 0,"ACTGTGAGTATTCC",0,"A",new String[]{}, new double[] {MATCH_LnLK * MATCH_LnLK}, 6,
new double[] {MATCH_LnLK * MATCH_LnLK,MATCH_LnLK * MISS_LnLK, MISS_LnLK * MISS_LnLK}}
};
/**
* Private function to compare Map of VCs, it only checks the types and start locations of the VariantContext
*/
private boolean compareVCMaps(Map<Integer, VariantContext> calc, Map<Integer, Byte> expected) {
if( !calc.keySet().equals(expected.keySet()) ) { return false; } // sanity check
for( Integer loc : expected.keySet() ) {
Byte type = expected.get(loc);
switch( type ) {
case 'I':
if( !calc.get(loc).isSimpleInsertion() ) { return false; }
break;
case 'D':
if( !calc.get(loc).isSimpleDeletion() ) { return false; }
break;
case 'M':
if( !(calc.get(loc).isMNP() || calc.get(loc).isSNP()) ) { return false; }
break;
default:
return false;
}
}
return true;
}
@DataProvider(name = "CreateHaplotypeMappingProvider")
public Object[][] makeCreateHaplotypeMappingData() {
List<Object[]> tests = new ArrayList<Object[]>();
final Set<Haplotype> haplotypes = new HashSet<>();
final Allele ref = Allele.create("A", true);
final Allele altC = Allele.create("C", false);
final Allele altT = Allele.create("T", false);
final Haplotype AtoC1 = new Haplotype("AACAA".getBytes());
final VariantContext vc1 = new VariantContextBuilder().chr("20").start(3).stop(3).alleles(Arrays.asList(ref, altC)).make();
AtoC1.setEventMap(new EventMap(Arrays.asList(vc1)));
AtoC1.getEventMap().put(3, vc1);
haplotypes.add(AtoC1);
final Haplotype AtoC2 = new Haplotype("AAACA".getBytes());
final VariantContext vc2 = new VariantContextBuilder().chr("20").start(4).stop(4).alleles(Arrays.asList(ref, altT)).make();
AtoC2.setEventMap(new EventMap(Arrays.asList(vc2)));
AtoC2.getEventMap().put(4, vc2);
haplotypes.add(AtoC2);
tests.add(new Object[]{vc1, haplotypes, AtoC1});
tests.add(new Object[]{vc2, haplotypes, AtoC2});
tests.add(new Object[]{new VariantContextBuilder().chr("20").start(1).stop(1).alleles(Arrays.asList(ref, altT)).make(), haplotypes, null});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider="CreateHaplotypeMappingProvider")
public void testCreateHaplotypeMapping(final VariantContext vc, final Set<Haplotype> haplotypes, final Haplotype expected) {
final Map<VariantContext, Set<Haplotype>> mapping = HaplotypeCallerGenotypingEngine.constructHaplotypeMapping(Arrays.asList(vc), haplotypes);
final Set<Haplotype> actual = mapping.get(vc);
if ( expected == null )
Assert.assertTrue(actual.isEmpty(), actual.toString());
else {
Assert.assertEquals(actual.size(), 1);
Assert.assertEquals(actual.iterator().next(), expected);
}
}
@DataProvider(name = "ConstructPhaseSetMappingProvider")
public Object[][] makeConstructPhaseSetMappingData() {
List<Object[]> tests = new ArrayList<Object[]>();
final Allele ref = Allele.create("A", true);
final Allele altC = Allele.create("C", false);
final Allele altT = Allele.create("T", false);
final VariantContext vc1 = new VariantContextBuilder().chr("20").start(1).stop(1).alleles(Arrays.asList(ref, altC)).make();
final VariantContext vc2 = new VariantContextBuilder().chr("20").start(2).stop(2).alleles(Arrays.asList(ref, altC)).make();
final VariantContext vc3 = new VariantContextBuilder().chr("20").start(3).stop(3).alleles(Arrays.asList(ref, altT)).make();
final VariantContext vc4 = new VariantContextBuilder().chr("20").start(4).stop(4).alleles(Arrays.asList(ref, altC)).make();
final List<VariantContext> calls = Arrays.asList(vc2, vc3, vc4);
final Haplotype pos1 = new Haplotype("CAAAA".getBytes());
pos1.setEventMap(new EventMap(Arrays.asList(vc1)));
pos1.getEventMap().put(1, vc1);
final Haplotype pos2 = new Haplotype("ACAAA".getBytes());
pos2.setEventMap(new EventMap(Arrays.asList(vc2)));
pos2.getEventMap().put(2, vc2);
final Haplotype pos3 = new Haplotype("AACAA".getBytes());
pos3.setEventMap(new EventMap(Arrays.asList(vc3)));
pos3.getEventMap().put(3, vc3);
final Haplotype pos4 = new Haplotype("AAACA".getBytes());
pos4.setEventMap(new EventMap(Arrays.asList(vc4)));
pos4.getEventMap().put(4, vc4);
final Haplotype pos24 = new Haplotype("ACACA".getBytes());
pos24.setEventMap(new EventMap(Arrays.asList(vc2, vc4)));
pos24.getEventMap().put(2, vc2);
pos24.getEventMap().put(4, vc4);
final Haplotype pos34 = new Haplotype("AACCA".getBytes());
pos34.setEventMap(new EventMap(Arrays.asList(vc3, vc4)));
pos34.getEventMap().put(3, vc3);
pos34.getEventMap().put(4, vc4);
final Haplotype pos234 = new Haplotype("ACCCA".getBytes());
pos234.setEventMap(new EventMap(Arrays.asList(vc2, vc3, vc4)));
pos234.getEventMap().put(2, vc2);
pos234.getEventMap().put(3, vc3);
pos234.getEventMap().put(4, vc4);
final Map<VariantContext, Set<Haplotype>> haplotypeMap = new HashMap<>();
// test no phased variants #1
final Set<Haplotype> haplotypes2 = new HashSet<>();
haplotypes2.add(pos2);
haplotypeMap.put(vc2, haplotypes2);
tests.add(new Object[]{Arrays.asList(vc2), new HashMap<>(haplotypeMap), 2, 0, 0, 0, 0});
// test no phased variants #2
final Set<Haplotype> haplotypes3 = new HashSet<>();
haplotypes3.add(pos3);
haplotypeMap.put(vc3, haplotypes3);
tests.add(new Object[]{Arrays.asList(vc2, vc3), new HashMap<>(haplotypeMap), 3, 0, 0, 0, 0});
// test opposite phase
tests.add(new Object[]{Arrays.asList(vc2, vc3), new HashMap<>(haplotypeMap), 2, 2, 1, 1, 1});
// test no phased variants #3
final Set<Haplotype> haplotypes4 = new HashSet<>();
haplotypes4.add(pos4);
haplotypeMap.put(vc4, haplotypes4);
tests.add(new Object[]{calls, new HashMap<>(haplotypeMap), 3, 0, 0, 0, 0});
// test mixture
final Set<Haplotype> haplotypes24 = new HashSet<>();
haplotypes24.add(pos24);
haplotypeMap.put(vc2, haplotypes24);
haplotypeMap.put(vc4, haplotypes24);
tests.add(new Object[]{calls, new HashMap<>(haplotypeMap), 2, 3, 1, 2, 1});
// test 2 hets
haplotypeMap.remove(vc3);
tests.add(new Object[]{Arrays.asList(vc2, vc4), new HashMap<>(haplotypeMap), 1, 2, 1, 2, 0});
// test 2 with opposite phase
final Set<Haplotype> haplotypes1 = new HashSet<>();
haplotypes1.add(pos1);
haplotypeMap.put(vc1, haplotypes1);
tests.add(new Object[]{Arrays.asList(vc1, vc2, vc4), new HashMap<>(haplotypeMap), 2, 3, 1, 1, 2});
// test homs around a het
final Set<Haplotype> haplotypes2hom = new HashSet<>();
haplotypes2hom.add(pos24);
haplotypes2hom.add(pos234);
final Set<Haplotype> haplotypes4hom = new HashSet<>();
haplotypes4hom.add(pos24);
haplotypes4hom.add(pos234);
final Set<Haplotype> haplotypes3het = new HashSet<>();
haplotypes3het.add(pos234);
haplotypeMap.put(vc2, haplotypes2hom);
haplotypeMap.put(vc3, haplotypes3het);
haplotypeMap.put(vc4, haplotypes4hom);
tests.add(new Object[]{calls, new HashMap<>(haplotypeMap), 2, 3, 1, 3, 0});
// test hets around a hom
final Set<Haplotype> haplotypes2het = new HashSet<>();
haplotypes2het.add(pos234);
final Set<Haplotype> haplotypes4het = new HashSet<>();
haplotypes4het.add(pos234);
final Set<Haplotype> haplotypes3hom = new HashSet<>();
haplotypes3hom.add(pos3);
haplotypes3hom.add(pos234);
haplotypeMap.put(vc2, haplotypes2het);
haplotypeMap.put(vc3, haplotypes3hom);
haplotypeMap.put(vc4, haplotypes4het);
tests.add(new Object[]{calls, new HashMap<>(haplotypeMap), 2, 3, 1, 3, 0});
// test no phased variants around a hom
final Set<Haplotype> haplotypes2incomplete = new HashSet<>();
haplotypes2incomplete.add(pos24);
final Set<Haplotype> haplotypes3incomplete = new HashSet<>();
haplotypes3incomplete.add(pos34);
final Set<Haplotype> haplotypes4complete = new HashSet<>();
haplotypes4complete.add(pos24);
haplotypes4complete.add(pos34);
haplotypes4complete.add(pos234);
haplotypeMap.put(vc2, haplotypes2incomplete);
haplotypeMap.put(vc3, haplotypes3incomplete);
haplotypeMap.put(vc4, haplotypes4complete);
tests.add(new Object[]{calls, new HashMap<>(haplotypeMap), 0, 0, 0, 0, 0});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider="ConstructPhaseSetMappingProvider")
public void testConstructPhaseSetMapping(final List<VariantContext> calls,
final Map<VariantContext, Set<Haplotype>> haplotypeMap,
final int totalHaplotypes,
final int expectedMapSize,
final int expectedNumGroups,
final int expectedNum01,
final int expectedNum10) {
final Map<VariantContext, Pair<Integer, String>> actualPhaseSetMapping = new HashMap<>();
final int actualNumGroups = HaplotypeCallerGenotypingEngine.constructPhaseSetMapping(calls, haplotypeMap, totalHaplotypes, actualPhaseSetMapping);
Assert.assertEquals(actualNumGroups, expectedNumGroups);
Assert.assertEquals(actualPhaseSetMapping.size(), expectedMapSize);
int num01 = 0, num10 = 0;
for ( final Pair<Integer, String> phase : actualPhaseSetMapping.values() ) {
if ( phase.getRight().equals("0|1") )
num01++;
else if ( phase.getRight().equals("1|0") )
num10++;
}
Assert.assertEquals(num01, expectedNum01);
Assert.assertEquals(num10, expectedNum10);
}
@DataProvider(name = "ConstructPhaseGroupsProvider")
public Object[][] makeConstructPhaseGroupsData() {
List<Object[]> tests = new ArrayList<>();
final Allele ref = Allele.create("A", true);
final Allele altC = Allele.create("C", false);
final Genotype g1 = new GenotypeBuilder().alleles(Arrays.asList(ref, altC)).make();
final VariantContext vc1 = new VariantContextBuilder().chr("20").start(1).stop(1).alleles(Arrays.asList(ref, altC)).genotypes(g1).make();
final Genotype g2 = new GenotypeBuilder().alleles(Arrays.asList(ref, altC)).make();
final VariantContext vc2 = new VariantContextBuilder().chr("20").start(2).stop(2).alleles(Arrays.asList(ref, altC)).genotypes(g2).make();
final Genotype g3 = new GenotypeBuilder().alleles(Arrays.asList(ref, altC)).make();
final VariantContext vc3 = new VariantContextBuilder().chr("20").start(3).stop(3).alleles(Arrays.asList(ref, altC)).genotypes(g3).make();
final List<VariantContext> calls = Arrays.asList(vc1, vc2, vc3);
// test no phased variants, empty map
final Map<VariantContext, Pair<Integer, String>> nonePhased1 = new HashMap<>();
tests.add(new Object[]{calls, nonePhased1, 0, 0, 0});
// test no phased variants, full map, exception expected
final Map<VariantContext, Pair<Integer, String>> nonePhased2 = new HashMap<>();
nonePhased2.put(vc1, Pair.of(0, "0/1"));
nonePhased2.put(vc2, Pair.of(1, "0/1"));
nonePhased2.put(vc3, Pair.of(2, "0/1"));
tests.add(new Object[]{calls, nonePhased2, 3, -1, -1});
// test 2 phased variants
final Map<VariantContext, Pair<Integer, String>> twoPhased = new HashMap<>();
twoPhased.put(vc1, Pair.of(0, "0/1"));
twoPhased.put(vc2, Pair.of(0, "0/1"));
tests.add(new Object[]{calls, twoPhased, 1, 1, 2});
// test all phased variants
final Map<VariantContext, Pair<Integer, String>> allPhased = new HashMap<>();
allPhased.put(vc1, Pair.of(0, "0/1"));
allPhased.put(vc2, Pair.of(0, "0/1"));
allPhased.put(vc3, Pair.of(0, "0/1"));
tests.add(new Object[]{calls, allPhased, 1, 1, 3});
return tests.toArray(new Object[][]{});
}
@Test(dataProvider="ConstructPhaseGroupsProvider")
public void testConstructPhaseGroups(final List<VariantContext> calls,
final Map<VariantContext, Pair<Integer, String>> phaseMap,
final int endIndex,
final int expectedNumGroups,
final int expectedGroupSize) {
final List<VariantContext> actualPhasedCalls;
try {
actualPhasedCalls = HaplotypeCallerGenotypingEngine.constructPhaseGroups(calls, phaseMap, endIndex);
} catch (IllegalStateException e) {
Assert.assertEquals(-1, expectedNumGroups);
return;
}
final Set<String> uniqueGroups = new HashSet<>();
int counter = 0;
for ( final VariantContext call : actualPhasedCalls ) {
for ( final Genotype g : call.getGenotypes() ) {
if ( g.hasExtendedAttribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_ID_KEY) ) {
uniqueGroups.add(g.getExtendedAttribute(GATKVCFConstants.HAPLOTYPE_CALLER_PHASING_ID_KEY).toString());
counter++;
}
}
}
Assert.assertEquals(uniqueGroups.size(), expectedNumGroups);
Assert.assertEquals(counter, expectedGroupSize);
}
@Test
public void testReduceNumberOfAlternativeAllelesBasedOnHaplotypesScores(){
// first have a list of alleles, one ref, several alt
final Allele ref = Allele.create("A", true);
final Allele altC = Allele.create("C", false);
final Allele altT = Allele.create("T", false);
final Allele altT2 = Allele.create("TT", false);
final Allele altG = Allele.create("G", false);
// then create several haplotypes, assign ad-hoc scores
final Haplotype hapRef = new Haplotype("AAAAA".getBytes());
hapRef.setScore(Double.MAX_VALUE);
// test case when both same best score and second best score are the same
final Haplotype hapT = new Haplotype("TAAAA".getBytes());
hapT.setScore(-2.0);
final Haplotype hapTAnother = new Haplotype("TAAAT".getBytes());
hapTAnother.setScore(-3.0);
final Haplotype hapT2 = new Haplotype("TTAAA".getBytes());
hapT2.setScore(-2.0);
final Haplotype hapT2Another = new Haplotype("TTAAT".getBytes());
hapT2Another.setScore(-3.0);
final Haplotype hapC = new Haplotype("CAAAA".getBytes());
hapC.setScore(-3.0);
// for case when there's tie in highest haplotype score
final Haplotype hapG = new Haplotype("GAAAA".getBytes());
hapG.setScore(-3.0);
final Haplotype hapGAnother = new Haplotype("GAAAG".getBytes());
hapGAnother.setScore(-5.0);
final Map<Allele, List<Haplotype>> alleleMapper = new LinkedHashMap<>();
alleleMapper.put(ref, Arrays.asList(hapRef));
alleleMapper.put(altC, Arrays.asList(hapC));
alleleMapper.put(altT, Arrays.asList(hapT, hapTAnother));
alleleMapper.put(altT2, Arrays.asList(hapT2, hapT2Another));
alleleMapper.put(altG, Arrays.asList(hapG, hapGAnother));
List<Allele> allelesToKeep = HaplotypeCallerGenotypingEngine.whichAllelesToKeepBasedonHapScores(alleleMapper, 5);
Assert.assertEquals(allelesToKeep.size(), 5);
Iterator<Allele> it = allelesToKeep.iterator();
Assert.assertEquals(it.next(), ref);
Assert.assertEquals(it.next(), altC);
Assert.assertEquals(it.next(), altT);
Assert.assertEquals(it.next(), altT2);
Assert.assertEquals(it.next(), altG);
allelesToKeep = HaplotypeCallerGenotypingEngine.whichAllelesToKeepBasedonHapScores(alleleMapper, 4);
Assert.assertEquals(allelesToKeep.size(), 4);
it = allelesToKeep.iterator();
Assert.assertEquals(it.next(), ref);
Assert.assertEquals(it.next(), altT);
Assert.assertEquals(it.next(), altT2);
Assert.assertEquals(it.next(), altG);
allelesToKeep = HaplotypeCallerGenotypingEngine.whichAllelesToKeepBasedonHapScores(alleleMapper, 3);
Assert.assertEquals(allelesToKeep.size(), 3);
it = allelesToKeep.iterator();
Assert.assertEquals(it.next(), ref);
Assert.assertEquals(it.next(), altT);
Assert.assertEquals(it.next(), altT2);
allelesToKeep = HaplotypeCallerGenotypingEngine.whichAllelesToKeepBasedonHapScores(alleleMapper, 2);
Assert.assertEquals(allelesToKeep.size(), 2);
it = allelesToKeep.iterator();
Assert.assertEquals(it.next(), ref);
Assert.assertEquals(it.next(), altT);
allelesToKeep = HaplotypeCallerGenotypingEngine.whichAllelesToKeepBasedonHapScores(alleleMapper, 1);
Assert.assertEquals(allelesToKeep.size(), 1);
it = allelesToKeep.iterator();
Assert.assertEquals(it.next(), ref);
}
@Test
public void testRemoveExcessiveAltAlleleFromVC(){
final VariantContext originalVC = new VariantContextBuilder("source", "1", 1000000, 1000000, Arrays.asList(Allele.create("A", true), Allele.create("T", false), Allele.create("C", false), Allele.create("G", false))).make();
final VariantContext reducedVC = HaplotypeCallerGenotypingEngine.removeExcessAltAllelesFromVC(originalVC, Arrays.asList(Allele.create("A", true), Allele.create("T", false), Allele.create("C", false)));
Assert.assertEquals(reducedVC.getNAlleles(), 3);
Assert.assertTrue(reducedVC.getAlleles().containsAll(Arrays.asList(Allele.create("A", true), Allele.create("T", false), Allele.create("C", false))));
}
}
|
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* MimeType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201611;
public class MimeType implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected MimeType(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final java.lang.String _ASP = "ASP";
public static final java.lang.String _AUDIO_AIFF = "AUDIO_AIFF";
public static final java.lang.String _AUDIO_BASIC = "AUDIO_BASIC";
public static final java.lang.String _AUDIO_FLAC = "AUDIO_FLAC";
public static final java.lang.String _AUDIO_MID = "AUDIO_MID";
public static final java.lang.String _AUDIO_MP3 = "AUDIO_MP3";
public static final java.lang.String _AUDIO_MP4 = "AUDIO_MP4";
public static final java.lang.String _AUDIO_MPEG_URL = "AUDIO_MPEG_URL";
public static final java.lang.String _AUDIO_MS_WMA = "AUDIO_MS_WMA";
public static final java.lang.String _AUDIO_OGG = "AUDIO_OGG";
public static final java.lang.String _AUDIO_REAL_AUDIO_PLUGIN = "AUDIO_REAL_AUDIO_PLUGIN";
public static final java.lang.String _AUDIO_WAV = "AUDIO_WAV";
public static final java.lang.String _BINARY = "BINARY";
public static final java.lang.String _DASH = "DASH";
public static final java.lang.String _DIRECTOR = "DIRECTOR";
public static final java.lang.String _FLASH = "FLASH";
public static final java.lang.String _GRAPHIC_CONVERTER = "GRAPHIC_CONVERTER";
public static final java.lang.String _JAVASCRIPT = "JAVASCRIPT";
public static final java.lang.String _JSON = "JSON";
public static final java.lang.String _IMAGE_BITMAP = "IMAGE_BITMAP";
public static final java.lang.String _IMAGE_BMP = "IMAGE_BMP";
public static final java.lang.String _IMAGE_GIF = "IMAGE_GIF";
public static final java.lang.String _IMAGE_JPEG = "IMAGE_JPEG";
public static final java.lang.String _IMAGE_PHOTOSHOP = "IMAGE_PHOTOSHOP";
public static final java.lang.String _IMAGE_PNG = "IMAGE_PNG";
public static final java.lang.String _IMAGE_TIFF = "IMAGE_TIFF";
public static final java.lang.String _IMAGE_WBMP = "IMAGE_WBMP";
public static final java.lang.String _M3U8 = "M3U8";
public static final java.lang.String _MAC_BIN_HEX_40 = "MAC_BIN_HEX_40";
public static final java.lang.String _MS_EXCEL = "MS_EXCEL";
public static final java.lang.String _MS_POWERPOINT = "MS_POWERPOINT";
public static final java.lang.String _MS_WORD = "MS_WORD";
public static final java.lang.String _OCTET_STREAM = "OCTET_STREAM";
public static final java.lang.String _PDF = "PDF";
public static final java.lang.String _POSTSCRIPT = "POSTSCRIPT";
public static final java.lang.String _RN_REAL_MEDIA = "RN_REAL_MEDIA";
public static final java.lang.String _RFC_822 = "RFC_822";
public static final java.lang.String _RTF = "RTF";
public static final java.lang.String _TEXT_CALENDAR = "TEXT_CALENDAR";
public static final java.lang.String _TEXT_CSS = "TEXT_CSS";
public static final java.lang.String _TEXT_CSV = "TEXT_CSV";
public static final java.lang.String _TEXT_HTML = "TEXT_HTML";
public static final java.lang.String _TEXT_JAVA = "TEXT_JAVA";
public static final java.lang.String _TEXT_PLAIN = "TEXT_PLAIN";
public static final java.lang.String _VIDEO_3GPP = "VIDEO_3GPP";
public static final java.lang.String _VIDEO_3GPP2 = "VIDEO_3GPP2";
public static final java.lang.String _VIDEO_AVI = "VIDEO_AVI";
public static final java.lang.String _VIDEO_FLV = "VIDEO_FLV";
public static final java.lang.String _VIDEO_MP4 = "VIDEO_MP4";
public static final java.lang.String _VIDEO_MP4V_ES = "VIDEO_MP4V_ES";
public static final java.lang.String _VIDEO_MPEG = "VIDEO_MPEG";
public static final java.lang.String _VIDEO_MS_ASF = "VIDEO_MS_ASF";
public static final java.lang.String _VIDEO_MS_WM = "VIDEO_MS_WM";
public static final java.lang.String _VIDEO_MS_WMV = "VIDEO_MS_WMV";
public static final java.lang.String _VIDEO_MS_WVX = "VIDEO_MS_WVX";
public static final java.lang.String _VIDEO_OGG = "VIDEO_OGG";
public static final java.lang.String _VIDEO_QUICKTIME = "VIDEO_QUICKTIME";
public static final java.lang.String _VIDEO_WEBM = "VIDEO_WEBM";
public static final java.lang.String _XAML = "XAML";
public static final java.lang.String _XHTML = "XHTML";
public static final java.lang.String _XML = "XML";
public static final java.lang.String _ZIP = "ZIP";
public static final MimeType UNKNOWN = new MimeType(_UNKNOWN);
public static final MimeType ASP = new MimeType(_ASP);
public static final MimeType AUDIO_AIFF = new MimeType(_AUDIO_AIFF);
public static final MimeType AUDIO_BASIC = new MimeType(_AUDIO_BASIC);
public static final MimeType AUDIO_FLAC = new MimeType(_AUDIO_FLAC);
public static final MimeType AUDIO_MID = new MimeType(_AUDIO_MID);
public static final MimeType AUDIO_MP3 = new MimeType(_AUDIO_MP3);
public static final MimeType AUDIO_MP4 = new MimeType(_AUDIO_MP4);
public static final MimeType AUDIO_MPEG_URL = new MimeType(_AUDIO_MPEG_URL);
public static final MimeType AUDIO_MS_WMA = new MimeType(_AUDIO_MS_WMA);
public static final MimeType AUDIO_OGG = new MimeType(_AUDIO_OGG);
public static final MimeType AUDIO_REAL_AUDIO_PLUGIN = new MimeType(_AUDIO_REAL_AUDIO_PLUGIN);
public static final MimeType AUDIO_WAV = new MimeType(_AUDIO_WAV);
public static final MimeType BINARY = new MimeType(_BINARY);
public static final MimeType DASH = new MimeType(_DASH);
public static final MimeType DIRECTOR = new MimeType(_DIRECTOR);
public static final MimeType FLASH = new MimeType(_FLASH);
public static final MimeType GRAPHIC_CONVERTER = new MimeType(_GRAPHIC_CONVERTER);
public static final MimeType JAVASCRIPT = new MimeType(_JAVASCRIPT);
public static final MimeType JSON = new MimeType(_JSON);
public static final MimeType IMAGE_BITMAP = new MimeType(_IMAGE_BITMAP);
public static final MimeType IMAGE_BMP = new MimeType(_IMAGE_BMP);
public static final MimeType IMAGE_GIF = new MimeType(_IMAGE_GIF);
public static final MimeType IMAGE_JPEG = new MimeType(_IMAGE_JPEG);
public static final MimeType IMAGE_PHOTOSHOP = new MimeType(_IMAGE_PHOTOSHOP);
public static final MimeType IMAGE_PNG = new MimeType(_IMAGE_PNG);
public static final MimeType IMAGE_TIFF = new MimeType(_IMAGE_TIFF);
public static final MimeType IMAGE_WBMP = new MimeType(_IMAGE_WBMP);
public static final MimeType M3U8 = new MimeType(_M3U8);
public static final MimeType MAC_BIN_HEX_40 = new MimeType(_MAC_BIN_HEX_40);
public static final MimeType MS_EXCEL = new MimeType(_MS_EXCEL);
public static final MimeType MS_POWERPOINT = new MimeType(_MS_POWERPOINT);
public static final MimeType MS_WORD = new MimeType(_MS_WORD);
public static final MimeType OCTET_STREAM = new MimeType(_OCTET_STREAM);
public static final MimeType PDF = new MimeType(_PDF);
public static final MimeType POSTSCRIPT = new MimeType(_POSTSCRIPT);
public static final MimeType RN_REAL_MEDIA = new MimeType(_RN_REAL_MEDIA);
public static final MimeType RFC_822 = new MimeType(_RFC_822);
public static final MimeType RTF = new MimeType(_RTF);
public static final MimeType TEXT_CALENDAR = new MimeType(_TEXT_CALENDAR);
public static final MimeType TEXT_CSS = new MimeType(_TEXT_CSS);
public static final MimeType TEXT_CSV = new MimeType(_TEXT_CSV);
public static final MimeType TEXT_HTML = new MimeType(_TEXT_HTML);
public static final MimeType TEXT_JAVA = new MimeType(_TEXT_JAVA);
public static final MimeType TEXT_PLAIN = new MimeType(_TEXT_PLAIN);
public static final MimeType VIDEO_3GPP = new MimeType(_VIDEO_3GPP);
public static final MimeType VIDEO_3GPP2 = new MimeType(_VIDEO_3GPP2);
public static final MimeType VIDEO_AVI = new MimeType(_VIDEO_AVI);
public static final MimeType VIDEO_FLV = new MimeType(_VIDEO_FLV);
public static final MimeType VIDEO_MP4 = new MimeType(_VIDEO_MP4);
public static final MimeType VIDEO_MP4V_ES = new MimeType(_VIDEO_MP4V_ES);
public static final MimeType VIDEO_MPEG = new MimeType(_VIDEO_MPEG);
public static final MimeType VIDEO_MS_ASF = new MimeType(_VIDEO_MS_ASF);
public static final MimeType VIDEO_MS_WM = new MimeType(_VIDEO_MS_WM);
public static final MimeType VIDEO_MS_WMV = new MimeType(_VIDEO_MS_WMV);
public static final MimeType VIDEO_MS_WVX = new MimeType(_VIDEO_MS_WVX);
public static final MimeType VIDEO_OGG = new MimeType(_VIDEO_OGG);
public static final MimeType VIDEO_QUICKTIME = new MimeType(_VIDEO_QUICKTIME);
public static final MimeType VIDEO_WEBM = new MimeType(_VIDEO_WEBM);
public static final MimeType XAML = new MimeType(_XAML);
public static final MimeType XHTML = new MimeType(_XHTML);
public static final MimeType XML = new MimeType(_XML);
public static final MimeType ZIP = new MimeType(_ZIP);
public java.lang.String getValue() { return _value_;}
public static MimeType fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
MimeType enumeration = (MimeType)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static MimeType fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(MimeType.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201611", "MimeType"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
/**
* netcell-gui - A Swing GUI for netcell ESB
* Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.segoia.netcell.gui.components;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JPanel;
public abstract class GraphFigure extends JPanel implements MouseMotionListener, MouseListener{
/**
*
*/
private static final long serialVersionUID = 2927651624942635151L;
private Map<String,AnchorEdge> anchorEdges = new LinkedHashMap<String, AnchorEdge>();
private String id;
/* dragging */
private Point pressedOffset;
private int boxWrapperSize = 15;
public GraphFigure(){
this.addMouseMotionListener(this);
this.addMouseListener(this);
}
public List<Anchor> getAvailableAnchors(){
List<Anchor> anchors = new ArrayList<Anchor>();
for(AnchorEdge edge : anchorEdges.values()){
anchors.add(edge.getNextPreferedAnchor());
}
return anchors;
}
protected Rectangle enlargeBounds(Rectangle bounds) {
bounds.x-= boxWrapperSize;
bounds.y-= boxWrapperSize;
bounds.width += 2*boxWrapperSize;
bounds.height += 2*boxWrapperSize;
return bounds;
}
public Anchor getNextAvailableAnchor(String edgeId) {
return anchorEdges.get(edgeId).getNextPreferedAnchor();
}
public void setLocation(Point p){
super.setLocation(p);
updateAnchors();
}
public void setLocation(int x, int y){
super.setLocation(x, y);
updateAnchors();
}
public void setSize(Dimension d){
super.setSize(d);
updateAnchors();
}
public void setSize(int w, int h){
super.setSize(w,h);
updateAnchors();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void addAnchorEdge(AnchorEdge e){
anchorEdges.put(e.getId(), e);
}
/**
* @return the anchorEdges
*/
public Map<String, AnchorEdge> getAnchorEdges() {
return anchorEdges;
}
/**
* @param anchorEdges the anchorEdges to set
*/
public void setAnchorEdges(Map<String, AnchorEdge> anchorEdges) {
this.anchorEdges = anchorEdges;
}
protected abstract void updateAnchors();
protected abstract Rectangle getEnlargedBounds();
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
pressedOffset = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
Point newPos = e.getPoint();
int dx = newPos.x - pressedOffset.x;
int dy = newPos.y - pressedOffset.y;
Point newLocation = getLocation();
newLocation.translate(dx, dy);
setLocation(newLocation);
updateAnchors();
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* @return the boxWrapperSize
*/
public int getBoxWrapperSize() {
return boxWrapperSize;
}
}
|
/*
* Copyright (c) 2016 Couchbase, 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.couchbase.client.core.error.subdoc;
import com.couchbase.client.core.annotation.Stability;
import com.couchbase.client.core.error.CouchbaseException;
import com.couchbase.client.core.error.context.SubDocumentErrorContext;
/**
* Subdocument exception thrown when a macro has been requested when not using extended attributes.
* <p>
* This exception is deprecated because this case, while technically possible, should never be thrown in the first
* place to the user level because the SDK must catch this exception. It is never being thrown at this point.
*/
@Deprecated
public class XattrInvalidFlagComboException extends CouchbaseException {
public XattrInvalidFlagComboException(final SubDocumentErrorContext ctx) {
super("Need to specify xattr flag when requesting macro for path", ctx);
}
@Override
@Stability.Uncommitted
public SubDocumentErrorContext context() {
return (SubDocumentErrorContext) super.context();
}
}
|
package wolf.enums;
import wolf.interfaces.StringMiddle;
import wolf.interfaces.Visitor;
import wolf.node.TEscapeAlarm;
import wolf.node.TEscapeBackslash;
import wolf.node.TEscapeBackspace;
import wolf.node.TEscapeCarriageReturn;
import wolf.node.TEscapeDefault;
import wolf.node.TEscapeDoubleQuote;
import wolf.node.TEscapeFormfeed;
import wolf.node.TEscapeHexChar;
import wolf.node.TEscapeNewline;
import wolf.node.TEscapeOctalChar;
import wolf.node.TEscapeQuestionMark;
import wolf.node.TEscapeSingleQuote;
import wolf.node.TEscapeTab;
import wolf.node.TEscapeUnicodeChar;
import wolf.node.TEscapeVerticalTab;
/**
* Enumerated type representing different escape characters
* @author Kevin Dittmar
* @author William Ezekiel
* @author Joseph Alacqua
* @version Apr 3, 2016
*/
public enum EscapeChar implements StringMiddle {
ESCAPE_ALARM(TEscapeAlarm.class),
ESCAPE_BACKSPACE(TEscapeBackspace.class),
ESCAPE_FORMFEED(TEscapeFormfeed.class),
ESCAPE_CARRIAGE_RETURN(TEscapeCarriageReturn.class),
ESCAPE_NEWLINE(TEscapeNewline.class),
ESCAPE_TAB(TEscapeTab.class),
ESCAPE_VERTICAL_TAB(TEscapeVerticalTab.class),
ESCAPE_BACKSLASH(TEscapeBackslash.class),
ESCAPE_SINGLE_QUOTE(TEscapeSingleQuote.class),
ESCAPE_DOUBLE_QUOTE(TEscapeDoubleQuote.class),
ESCAPE_QUESTION_MARK(TEscapeQuestionMark.class),
ESCAPE_OCTAL_CHAR(TEscapeOctalChar.class),
ESCAPE_HEX_CHAR(TEscapeHexChar.class),
ESCAPE_UNICODE_CHAR(TEscapeUnicodeChar.class),
ESCAPE_DEFAULT(TEscapeDefault.class);
Class token_class;
/**
* Create an EscapeChar
* @param token_class the token class of the escape character
* to be represented.
*/
EscapeChar(Class token_class) {
this.token_class = token_class;
}
/**
* Accept a visitor
* @param v a visitor
*/
@Override
public void accept(Visitor v) {
// Do nothing.
}
}
|
// ========================================================================
// Copyright 2010 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.ims.oam.util;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
public class EditableLabel<T> extends Panel
{
private FormComponent<T> _editor;
private Component _label;
public EditableLabel(String id)
{
this(id, null);
}
public EditableLabel(String id, IModel<T> model)
{
super(id, model);
setOutputMarkupId(true);
_editor = newEditor(this, "editor", getDefaultModel());
add(_editor);
_label = newLabel(this, "label", getDefaultModel());
add(_label);
}
@Override
public final MarkupContainer setDefaultModel(IModel<?> model)
{
super.setDefaultModel(model);
getLabel().setDefaultModel(model);
getEditor().setDefaultModel(model);
return this;
}
public void setEditable(boolean editable)
{
getEditor().setVisible(editable);
getLabel().setVisible(!editable);
}
protected FormComponent<T> newEditor(MarkupContainer parent,
String componentId, IModel model)
{
TextField<T> editor = new TextField<T>(componentId, model);
editor.setOutputMarkupId(true);
editor.setVisible(false);
editor.setOutputMarkupPlaceholderTag(true);
return editor;
}
protected Component newLabel(MarkupContainer parent, String componentId,
IModel model)
{
Label label = new Label(componentId, model);
label.setOutputMarkupId(true);
label.setOutputMarkupPlaceholderTag(true);
return label;
}
protected final FormComponent<T> getEditor()
{
return _editor;
}
protected final Component getLabel()
{
return _label;
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, 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.hazelcast.quorum.impl;
import com.hazelcast.config.QuorumConfig;
import com.hazelcast.core.ManagedContext;
import com.hazelcast.core.Member;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import com.hazelcast.logging.ILogger;
import com.hazelcast.quorum.HeartbeatAware;
import com.hazelcast.quorum.PingAware;
import com.hazelcast.quorum.Quorum;
import com.hazelcast.quorum.QuorumEvent;
import com.hazelcast.quorum.QuorumException;
import com.hazelcast.quorum.QuorumFunction;
import com.hazelcast.quorum.QuorumService;
import com.hazelcast.quorum.QuorumType;
import com.hazelcast.spi.impl.operationservice.Operation;
import com.hazelcast.spi.impl.operationservice.ReadonlyOperation;
import com.hazelcast.spi.impl.operationservice.MutatingOperation;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationservice.QuorumCheckAwareOperation;
import com.hazelcast.spi.impl.eventservice.InternalEventService;
import java.util.Collection;
import static com.hazelcast.nio.ClassLoaderUtil.newInstance;
import static com.hazelcast.util.ExceptionUtil.rethrow;
/**
* {@link QuorumImpl} can be used to notify quorum service for a particular quorum result that originated externally.
* <p>
* IMPORTANT: The term "quorum" simply refers to the count of members in the cluster required for an operation to succeed.
* It does NOT refer to an implementation of Paxos or Raft protocols as used in many NoSQL and distributed systems.
* The mechanism it provides in Hazelcast protects the user in case the number of nodes in a cluster drops below the
* specified one.
*/
public class QuorumImpl implements Quorum {
private enum QuorumState {
INITIAL,
PRESENT,
ABSENT
}
private final NodeEngineImpl nodeEngine;
private final String quorumName;
private final int size;
private final QuorumConfig config;
private final InternalEventService eventService;
private final QuorumFunction quorumFunction;
private final boolean heartbeatAwareQuorumFunction;
private final boolean pingAwareQuorumFunction;
private final boolean membershipListenerQuorumFunction;
/**
* Current quorum state. Updated by single thread, read by multiple threads.
*/
private volatile QuorumState quorumState = QuorumState.INITIAL;
QuorumImpl(QuorumConfig config, NodeEngineImpl nodeEngine) {
this.nodeEngine = nodeEngine;
this.eventService = nodeEngine.getEventService();
this.config = config;
this.quorumName = config.getName();
this.size = config.getSize();
this.quorumFunction = initializeQuorumFunction();
this.heartbeatAwareQuorumFunction = (quorumFunction instanceof HeartbeatAware);
this.membershipListenerQuorumFunction = (quorumFunction instanceof MembershipListener);
this.pingAwareQuorumFunction = (quorumFunction instanceof PingAware);
}
/**
* Determines if the quorum is present for the given member collection, caches the result and publishes an event under
* the {@link #quorumName} topic if there was a change in presence.
* <p>
* <strong>This method is not thread safe and should not be called concurrently.</strong>
*
* @param members the members for which the presence is determined
*/
void update(Collection<Member> members) {
QuorumState previousQuorumState = quorumState;
QuorumState newQuorumState = QuorumState.ABSENT;
try {
boolean present = quorumFunction.apply(members);
newQuorumState = present ? QuorumState.PRESENT : QuorumState.ABSENT;
} catch (Exception e) {
ILogger logger = nodeEngine.getLogger(QuorumService.class);
logger.severe("Quorum function of quorum: " + quorumName + " failed! Quorum status is set to "
+ newQuorumState, e);
}
quorumState = newQuorumState;
if (previousQuorumState != newQuorumState) {
createAndPublishEvent(members, newQuorumState == QuorumState.PRESENT);
}
}
/**
* Notify a {@link HeartbeatAware} {@code QuorumFunction} that a heartbeat has been received from a member.
*
* @param member source member
* @param timestamp heartbeat's timestamp
*/
void onHeartbeat(Member member, long timestamp) {
if (!heartbeatAwareQuorumFunction) {
return;
}
((HeartbeatAware) quorumFunction).onHeartbeat(member, timestamp);
}
void onPing(Member member, boolean successful) {
if (!pingAwareQuorumFunction) {
return;
}
PingAware pingAware = (PingAware) quorumFunction;
if (successful) {
pingAware.onPingRestored(member);
} else {
pingAware.onPingLost(member);
}
}
void onMemberAdded(MembershipEvent event) {
if (!membershipListenerQuorumFunction) {
return;
}
((MembershipListener) quorumFunction).memberAdded(event);
}
void onMemberRemoved(MembershipEvent event) {
if (!membershipListenerQuorumFunction) {
return;
}
((MembershipListener) quorumFunction).memberRemoved(event);
}
public String getName() {
return quorumName;
}
public int getSize() {
return size;
}
public QuorumConfig getConfig() {
return config;
}
@Override
public boolean isPresent() {
return quorumState == QuorumState.PRESENT;
}
/**
* Indicates whether the {@link #quorumFunction} is {@link HeartbeatAware}. If so, then member heartbeats will be published
* to the {@link #quorumFunction}.
*
* @return {@code true} when the {@link #quorumFunction} implements {@link HeartbeatAware}, otherwise {@code false}
*/
boolean isHeartbeatAware() {
return heartbeatAwareQuorumFunction;
}
/**
* Indicates whether the {@link #quorumFunction} is {@link PingAware}. If so, then ICMP pings will be published
* to the {@link #quorumFunction}.
*
* @return {@code true} when the {@link #quorumFunction} implements {@link PingAware}, otherwise {@code false}
*/
boolean isPingAware() {
return pingAwareQuorumFunction;
}
/**
* Returns if quorum is needed for this operation.
* The quorum is determined by the {@link QuorumConfig#type} and by the type of the operation -
* {@link ReadonlyOperation} or {@link MutatingOperation}.
*
* @param op the operation which is to be executed
* @return if this quorum should be consulted for this operation
* @throws IllegalArgumentException if the quorum configuration type is not handled
*/
private boolean isQuorumNeeded(Operation op) {
QuorumType type = config.getType();
switch (type) {
case WRITE:
return isWriteOperation(op) && shouldCheckQuorum(op);
case READ:
return isReadOperation(op) && shouldCheckQuorum(op);
case READ_WRITE:
return (isReadOperation(op) || isWriteOperation(op)) && shouldCheckQuorum(op);
default:
throw new IllegalStateException("Unhandled quorum type: " + type);
}
}
/**
* Returns {@code true} if this operation is marked as a read-only operation.
* If this method returns {@code false}, the operation still might be
* read-only but is not marked as such.
*/
private static boolean isReadOperation(Operation op) {
return op instanceof ReadonlyOperation;
}
/**
* Returns {@code true} if this operation is marked as a mutating operation.
* If this method returns {@code false}, the operation still might be
* mutating but is not marked as such.
*/
private static boolean isWriteOperation(Operation op) {
return op instanceof MutatingOperation;
}
/**
* Returns {@code true} if the operation allows checking for quorum,
* {@code false} if the quorum check does not apply to this operation.
*/
private static boolean shouldCheckQuorum(Operation op) {
return !(op instanceof QuorumCheckAwareOperation) || ((QuorumCheckAwareOperation) op).shouldCheckQuorum();
}
/**
* Ensures that the quorum is present for the given operation. First checks if the quorum type defined by the configuration
* covers this operation and checks if the quorum is present. Dispatches an event under the {@link #quorumName} topic
* if membership changed after determining the quorum presence.
*
* @param op the operation for which the quorum should be present
* @throws QuorumException if the operation requires a quorum and the quorum is not present
*/
void ensureQuorumPresent(Operation op) {
if (!isQuorumNeeded(op)) {
return;
}
ensureQuorumPresent();
}
void ensureQuorumPresent() {
if (!isPresent()) {
throw newQuorumException();
}
}
private QuorumException newQuorumException() {
throw new QuorumException("Split brain protection exception: " + quorumName + " has failed!");
}
private void createAndPublishEvent(Collection<Member> memberList, boolean presence) {
QuorumEvent quorumEvent = new QuorumEvent(nodeEngine.getThisAddress(), size, memberList, presence);
eventService.publishEvent(QuorumServiceImpl.SERVICE_NAME, quorumName, quorumEvent, quorumEvent.hashCode());
}
private QuorumFunction initializeQuorumFunction() {
QuorumFunction quorumFunction = config.getQuorumFunctionImplementation();
if (quorumFunction == null && config.getQuorumFunctionClassName() != null) {
try {
quorumFunction = newInstance(nodeEngine.getConfigClassLoader(), config.getQuorumFunctionClassName());
} catch (Exception e) {
throw rethrow(e);
}
}
if (quorumFunction == null) {
quorumFunction = new MemberCountQuorumFunction(size);
}
ManagedContext managedContext = nodeEngine.getSerializationService().getManagedContext();
quorumFunction = (QuorumFunction) managedContext.initialize(quorumFunction);
return quorumFunction;
}
@Override
public String toString() {
return "QuorumImpl{"
+ "quorumName='" + quorumName + '\''
+ ", isPresent=" + isPresent()
+ ", size=" + size
+ ", config=" + config
+ ", quorumFunction=" + quorumFunction
+ '}';
}
}
|
/*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.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.pentaho.hadoop.mapreduce.converter.converters;
import org.apache.hadoop.io.BytesWritable;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.hadoop.mapreduce.converter.TypeConversionException;
import org.pentaho.hadoop.mapreduce.converter.spi.ITypeConverter;
/**
* Converts {@link org.apache.hadoop.io.BytesWritable} objects to {@link byte[]} objects
*/
public class BytesWritableToByteArrayConverter implements ITypeConverter<BytesWritable, byte[]> {
@Override
public boolean canConvert( Class from, Class to ) {
return BytesWritable.class.equals( from ) && byte[].class.equals( to );
}
@Override
public byte[] convert( ValueMetaInterface meta, BytesWritable obj ) throws TypeConversionException {
return obj.getBytes().clone();
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.AllocationConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSLeafQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FSQueue;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler;
import org.apache.hadoop.yarn.util.resource.Resources;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({FairSchedulerLeafQueueInfo.class})
public class FairSchedulerQueueInfo {
private int maxApps;
@XmlTransient
private float fractionMemUsed;
@XmlTransient
private float fractionMemSteadyFairShare;
@XmlTransient
private float fractionMemFairShare;
@XmlTransient
private float fractionMemMinShare;
@XmlTransient
private float fractionMemMaxShare;
private ResourceInfo minResources;
private ResourceInfo maxResources;
private ResourceInfo usedResources;
private ResourceInfo amUsedResources;
private ResourceInfo amMaxResources;
private ResourceInfo demandResources;
private ResourceInfo steadyFairResources;
private ResourceInfo fairResources;
private ResourceInfo clusterResources;
private ResourceInfo reservedResources;
private long pendingContainers;
private long allocatedContainers;
private long reservedContainers;
private String queueName;
private String schedulingPolicy;
private boolean preemptable;
private FairSchedulerQueueInfoList childQueues;
public FairSchedulerQueueInfo() {
}
public FairSchedulerQueueInfo(FSQueue queue, FairScheduler scheduler) {
AllocationConfiguration allocConf = scheduler.getAllocationConfiguration();
queueName = queue.getName();
schedulingPolicy = queue.getPolicy().getName();
clusterResources = new ResourceInfo(scheduler.getClusterResource());
amUsedResources = new ResourceInfo(Resource.newInstance(
queue.getMetrics().getAMResourceUsageMB(),
queue.getMetrics().getAMResourceUsageVCores()));
amMaxResources = new ResourceInfo(Resource.newInstance(
queue.getMetrics().getMaxAMShareMB(),
queue.getMetrics().getMaxAMShareVCores()));
usedResources = new ResourceInfo(queue.getResourceUsage());
demandResources = new ResourceInfo(queue.getDemand());
fractionMemUsed = (float)usedResources.getMemorySize() /
clusterResources.getMemorySize();
steadyFairResources = new ResourceInfo(queue.getSteadyFairShare());
fairResources = new ResourceInfo(queue.getFairShare());
minResources = new ResourceInfo(queue.getMinShare());
maxResources = new ResourceInfo(
Resources.componentwiseMin(queue.getMaxShare(),
scheduler.getClusterResource()));
reservedResources = new ResourceInfo(queue.getReservedResource());
fractionMemSteadyFairShare =
(float)steadyFairResources.getMemorySize() / clusterResources.getMemorySize();
fractionMemFairShare = (float) fairResources.getMemorySize()
/ clusterResources.getMemorySize();
fractionMemMinShare = (float)minResources.getMemorySize() / clusterResources.getMemorySize();
fractionMemMaxShare = (float)maxResources.getMemorySize() / clusterResources.getMemorySize();
maxApps = queue.getMaxRunningApps();
pendingContainers = queue.getMetrics().getPendingContainers();
allocatedContainers = queue.getMetrics().getAllocatedContainers();
reservedContainers = queue.getMetrics().getReservedContainers();
if (allocConf.isReservable(queueName) &&
!allocConf.getShowReservationAsQueues(queueName)) {
return;
}
preemptable = queue.isPreemptable();
childQueues = getChildQueues(queue, scheduler);
}
public long getPendingContainers() {
return pendingContainers;
}
public long getAllocatedContainers() {
return allocatedContainers;
}
public long getReservedContainers() {
return reservedContainers;
}
protected FairSchedulerQueueInfoList getChildQueues(FSQueue queue,
FairScheduler scheduler) {
// Return null to omit 'childQueues' field from the return value of
// REST API if it is empty. We omit the field to keep the consistency
// with CapacitySchedulerQueueInfo, which omits 'queues' field if empty.
Collection<FSQueue> children = queue.getChildQueues();
if (children.isEmpty()) {
return null;
}
FairSchedulerQueueInfoList list = new FairSchedulerQueueInfoList();
for (FSQueue child : children) {
if (child instanceof FSLeafQueue) {
list.addToQueueInfoList(
new FairSchedulerLeafQueueInfo((FSLeafQueue) child, scheduler));
} else {
list.addToQueueInfoList(
new FairSchedulerQueueInfo(child, scheduler));
}
}
return list;
}
/**
* Returns the steady fair share as a fraction of the entire cluster capacity.
*/
public float getSteadyFairShareMemoryFraction() {
return fractionMemSteadyFairShare;
}
/**
* Returns the fair share as a fraction of the entire cluster capacity.
*/
public float getFairShareMemoryFraction() {
return fractionMemFairShare;
}
/**
* Returns the steady fair share of this queue in megabytes.
*/
public ResourceInfo getSteadyFairShare() {
return steadyFairResources;
}
/**
* Returns the fair share of this queue in megabytes
*/
public ResourceInfo getFairShare() {
return fairResources;
}
public ResourceInfo getMinResources() {
return minResources;
}
public ResourceInfo getMaxResources() {
return maxResources;
}
public ResourceInfo getReservedResources() {
return reservedResources;
}
public int getMaxApplications() {
return maxApps;
}
public String getQueueName() {
return queueName;
}
public ResourceInfo getUsedResources() {
return usedResources;
}
/**
* @return the am used resource of this queue.
*/
public ResourceInfo getAMUsedResources() {
return amUsedResources;
}
/**
* @return the am max resource of this queue.
*/
public ResourceInfo getAMMaxResources() {
return amMaxResources;
}
/**
* @return the demand resource of this queue.
*/
public ResourceInfo getDemandResources() {
return demandResources;
}
/**
* Returns the queue's min share in as a fraction of the entire
* cluster capacity.
*/
public float getMinShareMemoryFraction() {
return fractionMemMinShare;
}
/**
* Returns the memory used by this queue as a fraction of the entire
* cluster capacity.
*/
public float getUsedMemoryFraction() {
return fractionMemUsed;
}
/**
* Returns the capacity of this queue as a fraction of the entire cluster
* capacity.
*/
public float getMaxResourcesFraction() {
return fractionMemMaxShare;
}
/**
* Returns the name of the scheduling policy used by this queue.
*/
public String getSchedulingPolicy() {
return schedulingPolicy;
}
public Collection<FairSchedulerQueueInfo> getChildQueues() {
return childQueues != null ? childQueues.getQueueInfoList() :
new ArrayList<FairSchedulerQueueInfo>();
}
public boolean isPreemptable() {
return preemptable;
}
}
|
package io.quarkus.deployment.steps;
import java.nio.file.Paths;
import org.apache.commons.io.FilenameUtils;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.HotDeploymentWatchedFileBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
import io.quarkus.deployment.builditem.RunTimeConfigurationDefaultBuildItem;
import io.quarkus.runtime.ConfigConfig;
import io.quarkus.runtime.LaunchMode;
public class ProfileBuildStep {
@BuildStep
RunTimeConfigurationDefaultBuildItem defaultProfile(LaunchModeBuildItem launchModeBuildItem) {
return new RunTimeConfigurationDefaultBuildItem("quarkus.profile",
getProfileValue(launchModeBuildItem.getLaunchMode()));
}
@BuildStep
void watchProfileSpecificFile(LaunchModeBuildItem launchModeBuildItem,
ConfigConfig config,
BuildProducer<HotDeploymentWatchedFileBuildItem> items) {
String activeProfile = getProfileValue(launchModeBuildItem.getLaunchMode());
String suffixedApplicationProperties = String.format("application-%s.properties", activeProfile);
items.produce(new HotDeploymentWatchedFileBuildItem(suffixedApplicationProperties));
items.produce(new HotDeploymentWatchedFileBuildItem(
Paths.get(String.format(".env-%s", activeProfile)).toAbsolutePath().toString()));
items.produce(new HotDeploymentWatchedFileBuildItem(Paths
.get(System.getProperty("user.dir"), "config", suffixedApplicationProperties).toAbsolutePath().toString()));
if (config.locations.isPresent()) {
for (String location : config.locations.get()) {
items.produce(new HotDeploymentWatchedFileBuildItem(appendProfileToFilename(location, activeProfile)));
}
}
}
private String appendProfileToFilename(String path, String activeProfile) {
String pathWithoutExtension = FilenameUtils.removeExtension(path);
return String.format("%s-%s.%s", pathWithoutExtension, activeProfile, FilenameUtils.getExtension(path));
}
private String getProfileValue(LaunchMode launchMode) {
if (launchMode == LaunchMode.DEVELOPMENT) {
return "dev";
} else if (launchMode == LaunchMode.TEST) {
return "test";
}
return "prod";
}
}
|
/*
* Copyright (c) 2009-2014, Peter Abeles. All Rights Reserved.
*
* This file is part of Efficient Java Matrix Library (EJML).
*
* 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.ejml.alg.dense.decomposition.svd.implicitqr;
import org.ejml.UtilEjml;
import org.ejml.alg.dense.decomposition.bidiagonal.BidiagonalDecompositionRow_D64;
import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;
import org.ejml.simple.SimpleMatrix;
import org.junit.Test;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Peter Abeles
*/
public class TestSvdImplicitQrAlgorithm {
private Random rand = new Random(234234);
/**
* Computes the singular values of a bidiagonal matrix that is all ones.
* From exercise 5.9.45 in Fundamentals of Matrix Computations.
*
*/
@Test
public void oneBidiagonalMatrix() {
SvdImplicitQrAlgorithm svd = new SvdImplicitQrAlgorithm(true);
for( int N = 5; N < 10; N++ ) {
double diag[] = new double[N];
double off[] = new double[N-1];
diag[0]=1;
for( int i = 0; i < N-1; i++ ) {
diag[i+1]=1;
off[i] = 1;
}
svd.setMatrix(N,N,diag,off);
assertTrue(svd.process());
for( int i = 0; i < N; i++ ) {
double val = 2.0*Math.cos( (i+1)*Math.PI/(2.0*N+1.0));
assertEquals(1,countNumFound(svd,val,1e-8));
}
}
}
/**
* A trivial case where all the elements are diagonal. It should do nothing here.
*/
@Test
public void knownDiagonal() {
double diag[] = new double[]{1,2,3,4,5};
double off[] = new double[diag.length-1];
SvdImplicitQrAlgorithm svd = new SvdImplicitQrAlgorithm(true);
svd.setMatrix(diag.length,diag.length,diag,off);
assertTrue(svd.process());
assertEquals(1,countNumFound(svd,5,1e-8));
assertEquals(1,countNumFound(svd,4,1e-8));
assertEquals(1,countNumFound(svd,3,1e-8));
assertEquals(1,countNumFound(svd,2,1e-8));
assertEquals(1,countNumFound(svd,1,1e-8));
}
/**
* Sees if it handles the case where there is a zero on the diagonal
*/
@Test
public void zeroOnDiagonal() {
double diag[] = new double[]{1,2,3,4,5,6};
double off[] = new double[]{2,2,2,2,2};
diag[2] = 0;
// A.print();
SvdImplicitQrAlgorithm svd = new SvdImplicitQrAlgorithm(false);
svd.setMatrix(6,6,diag,off);
assertTrue(svd.process());
assertEquals(1,countNumFound(svd,6.82550,1e-4));
assertEquals(1,countNumFound(svd,5.31496,1e-4));
assertEquals(1,countNumFound(svd,3.76347,1e-4));
assertEquals(1,countNumFound(svd,3.28207,1e-4));
assertEquals(1,countNumFound(svd,1.49265,1e-4));
assertEquals(1,countNumFound(svd,0.00000,1e-4));
}
@Test
public void knownCaseSquare() {
DenseMatrix64F A = UtilEjml.parseMatrix("-3 1 3 -3 0\n" +
" 2 -4 0 -2 0\n" +
" 1 -4 4 1 -3\n" +
" -1 -3 2 2 -4\n" +
" -5 3 1 3 1",5);
// A.print();
SvdImplicitQrAlgorithm svd = createHelper(A);
assertTrue(svd.process());
assertEquals(1,countNumFound(svd,9.3431,1e-3));
assertEquals(1,countNumFound(svd,7.4856,1e-3));
assertEquals(1,countNumFound(svd,4.9653,1e-3));
assertEquals(1,countNumFound(svd,1.8178,1e-3));
assertEquals(1,countNumFound(svd,1.6475,1e-3));
}
/**
* This makes sure the U and V matrices are being correctly by the push code.
*/
@Test
public void zeroOnDiagonalFull() {
for( int where = 0; where < 6; where++ ) {
double diag[] = new double[]{1,2,3,4,5,6};
double off[] = new double[]{2,2,2,2,2};
diag[where] = 0;
checkFullDecomposition(6, diag, off );
}
}
/**
* Decomposes a random matrix and see if the decomposition can reconstruct the original
*
*/
@Test
public void randomMatricesFullDecompose() {
for( int N = 2; N <= 20; N++ ) {
double diag[] = new double[N];
double off[] = new double[N];
diag[0] = rand.nextDouble();
for( int i = 1; i < N; i++ ) {
diag[i]=rand.nextDouble();
off[i-1] = rand.nextDouble();
}
checkFullDecomposition(N, diag,off);
}
}
/**
* Checks the full decomposing my multiplying the components together and seeing if it
* gets the original matrix again.
*/
private void checkFullDecomposition(int n, double diag[] , double off[] ) {
// a.print();
SvdImplicitQrAlgorithm svd = createHelper(n,n,diag.clone(),off.clone());
svd.setFastValues(true);
assertTrue(svd.process());
// System.out.println("Value total steps = "+svd.totalSteps);
svd.setFastValues(false);
double values[] = svd.diag.clone();
svd.setMatrix(n,n,diag.clone(),off.clone());
svd.setUt(CommonOps.identity(n));
svd.setVt(CommonOps.identity(n));
assertTrue(svd.process(values));
// System.out.println("Vector total steps = "+svd.totalSteps);
SimpleMatrix Ut = SimpleMatrix.wrap(svd.getUt());
SimpleMatrix Vt = SimpleMatrix.wrap(svd.getVt());
SimpleMatrix W = SimpleMatrix.diag(svd.diag);
//
// Ut.mult(W).mult(V).print();
SimpleMatrix A_found = Ut.transpose().mult(W).mult(Vt);
// A_found.print();
assertEquals(diag[0],A_found.get(0,0),1e-8);
for( int i = 0; i < n-1; i++ ) {
assertEquals(diag[i+1],A_found.get(i+1,i+1),1e-8);
assertEquals(off[i],A_found.get(i,i+1),1e-8);
}
}
public static SvdImplicitQrAlgorithm createHelper( DenseMatrix64F a ) {
BidiagonalDecompositionRow_D64 bidiag = new BidiagonalDecompositionRow_D64();
assertTrue(bidiag.decompose(a.copy()));
double diag[] = new double[a.numRows];
double off[] = new double[ diag.length-1 ];
bidiag.getDiagonal(diag,off);
return createHelper(a.numRows,a.numCols,diag,off);
}
public static SvdImplicitQrAlgorithm createHelper( int numRows , int numCols ,
double diag[] , double off[] ) {
SvdImplicitQrAlgorithm helper = new SvdImplicitQrAlgorithm();
helper.setMatrix(numRows,numCols,diag,off);
return helper;
}
/**
* Counts the number of times the specified eigenvalue appears.
*/
public int countNumFound( SvdImplicitQrAlgorithm alg , double val , double tol ) {
int total = 0;
for( int i = 0; i < alg.getNumberOfSingularValues(); i++ ) {
double a = Math.abs(alg.getSingularValue(i));
if( Math.abs(a-val) <= tol ) {
total++;
}
}
return total;
}
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.hibernate3;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* This interceptor binds a new Hibernate Session to the thread before a method
* call, closing and removing it afterwards in case of any method outcome.
* If there already is a pre-bound Session (e.g. from HibernateTransactionManager,
* or from a surrounding Hibernate-intercepted method), the interceptor simply
* participates in it.
*
* <p>Application code must retrieve a Hibernate Session via the
* {@code SessionFactoryUtils.getSession} method or - preferably -
* Hibernate's own {@code SessionFactory.getCurrentSession()} method, to be
* able to detect a thread-bound Session. Typically, the code will look like as follows:
*
* <pre>
* public void doSomeDataAccessAction() {
* Session session = this.sessionFactory.getCurrentSession();
* ...
* // No need to close the Session or translate exceptions!
* }</pre>
*
* Note that this interceptor automatically translates HibernateExceptions,
* via delegating to the {@code SessionFactoryUtils.convertHibernateAccessException}
* method that converts them to exceptions that are compatible with the
* {@code org.springframework.dao} exception hierarchy (like HibernateTemplate does).
* This can be turned off if the raw exceptions are preferred.
*
* <p>This class can be considered a declarative alternative to HibernateTemplate's
* callback approach. The advantages are:
* <ul>
* <li>no anonymous classes necessary for callback implementations;
* <li>the possibility to throw any application exceptions from within data access code.
* </ul>
*
* <p>The drawback is the dependency on interceptor configuration. However, note
* that this interceptor is usually <i>not</i> necessary in scenarios where the
* data access code always executes within transactions. A transaction will always
* have a thread-bound Session in the first place, so adding this interceptor to the
* configuration just adds value when fine-tuning Session settings like the flush mode
* - or when relying on exception translation.
*
* @author Juergen Hoeller
* @since 1.2
* @see org.hibernate.SessionFactory#getCurrentSession()
* @see HibernateTransactionManager
* @see HibernateTemplate
*/
public class HibernateInterceptor extends HibernateAccessor implements MethodInterceptor {
private boolean exceptionConversionEnabled = true;
/**
* Set whether to convert any HibernateException raised to a Spring DataAccessException,
* compatible with the {@code org.springframework.dao} exception hierarchy.
* <p>Default is "true". Turn this flag off to let the caller receive raw exceptions
* as-is, without any wrapping.
* @see org.springframework.dao.DataAccessException
*/
public void setExceptionConversionEnabled(boolean exceptionConversionEnabled) {
this.exceptionConversionEnabled = exceptionConversionEnabled;
}
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Session session = getSession();
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateInterceptor");
}
else {
if (sessionHolder != null) {
sessionHolder.addSession(session);
}
else {
TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
}
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
Object retVal = methodInvocation.proceed();
flushIfNecessary(session, existingTransaction);
return retVal;
}
catch (HibernateException ex) {
if (this.exceptionConversionEnabled) {
throw convertHibernateAccessException(ex);
}
else {
throw ex;
}
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
}
}
}
/**
* Return a Session for use by this interceptor.
* @see SessionFactoryUtils#getSession
*/
protected Session getSession() {
return SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
}
}
|
/*
* Copyright 2014 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.Es6ToEs3Util.CANNOT_CONVERT_YET;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
/**
* Converts {@code super.method()} calls and adds constructors to any classes that lack them.
*
* <p>This has to run before the main {@link Es6RewriteClass} pass. The super() constructor calls
* are not converted here, but rather in {@link Es6ConvertSuperConstructorCalls}, which runs later.
*/
public final class Es6ConvertSuper extends NodeTraversal.AbstractPostOrderCallback
implements HotSwapCompilerPass {
private final AbstractCompiler compiler;
private static final FeatureSet transpiledFeatures = FeatureSet.BARE_MINIMUM.with(Feature.SUPER);
public Es6ConvertSuper(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isClass()) {
boolean hasConstructor = false;
for (Node member = n.getLastChild().getFirstChild();
member != null;
member = member.getNext()) {
if (member.isMemberFunctionDef() && member.getString().equals("constructor")) {
hasConstructor = true;
break;
}
}
if (!hasConstructor) {
addSyntheticConstructor(n);
}
} else if (n.isSuper()) {
visitSuper(n, parent);
}
}
private void addSyntheticConstructor(Node classNode) {
Node superClass = classNode.getSecondChild();
Node classMembers = classNode.getLastChild();
Node memberDef;
if (superClass.isEmpty()) {
Node function = NodeUtil.emptyFunction();
compiler.reportChangeToChangeScope(function);
memberDef = IR.memberFunctionDef("constructor", function);
} else {
if (!superClass.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
Node body = IR.block();
// If a class is defined in an externs file or as an interface, it's only a stub, not an
// implementation that should be instantiated.
// A call to super() shouldn't actually exist for these cases and is problematic to
// transpile, so don't generate it.
if (!classNode.isFromExterns() && !isInterface(classNode)) {
Node exprResult = IR.exprResult(IR.call(
IR.getprop(IR.superNode(), IR.string("apply")),
IR.thisNode(),
IR.name("arguments")));
body.addChildToFront(exprResult);
}
Node constructor = IR.function(
IR.name(""),
IR.paramList(IR.name("var_args")),
body);
compiler.reportChangeToChangeScope(constructor);
memberDef = IR.memberFunctionDef("constructor", constructor);
JSDocInfoBuilder info = new JSDocInfoBuilder(false);
info.recordParameter(
"var_args",
new JSTypeExpression(
new Node(Token.ELLIPSIS, new Node(Token.QMARK)), "<Es6ConvertSuper>"));
memberDef.setJSDocInfo(info.build());
}
memberDef.useSourceInfoIfMissingFromForTree(classNode);
memberDef.makeNonIndexableRecursive();
classMembers.addChildToFront(memberDef);
compiler.reportChangeToEnclosingScope(memberDef);
}
private boolean isInterface(Node classNode) {
JSDocInfo classJsDocInfo = NodeUtil.getBestJSDocInfo(classNode);
return classJsDocInfo != null && classJsDocInfo.isInterface();
}
private void visitSuper(Node node, Node parent) {
checkState(node.isSuper());
Node exprRoot = node;
if (exprRoot.getParent().isGetElem() || exprRoot.getParent().isGetProp()) {
exprRoot = exprRoot.getParent();
}
Node enclosingMemberDef =
NodeUtil.getEnclosingNode(
exprRoot,
new Predicate<Node>() {
@Override
public boolean apply(Node n) {
switch (n.getToken()) {
case MEMBER_FUNCTION_DEF:
case GETTER_DEF:
case SETTER_DEF:
case COMPUTED_PROP:
return true;
default:
return false;
}
}
});
if (parent.isCall()) {
// super(...)
visitSuperCall(node, parent, enclosingMemberDef);
} else if (parent.isGetProp() || parent.isGetElem()) {
if (parent.getFirstChild() == node) {
if (parent.getParent().isCall() && NodeUtil.isInvocationTarget(parent)) {
// super.something(...) or super['something'](..)
visitSuperPropertyCall(node, parent, enclosingMemberDef);
} else {
// super.something or super['something']
visitSuperPropertyAccess(node, parent, enclosingMemberDef);
}
} else {
// super.something used in some other way
compiler.report(JSError.make(node, CANNOT_CONVERT_YET,
"Only calls to super or to a method of super are supported."));
}
} else if (parent.isNew()) {
throw new IllegalStateException("This should never happen. Did Es6SuperCheck fail to run?");
} else {
// some other use of super we don't support yet
compiler.report(JSError.make(node, CANNOT_CONVERT_YET,
"Only calls to super or to a method of super are supported."));
}
}
private void visitSuperCall(Node node, Node parent, Node enclosingMemberDef) {
checkState(parent.isCall(), parent);
checkState(node.isSuper(), node);
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
if (enclosingMemberDef.isMemberFunctionDef()
&& enclosingMemberDef.getString().equals("constructor")) {
// Calls to super() constructors will be transpiled by Es6ConvertSuperConstructorCalls later.
if (node.isFromExterns() || isInterface(clazz)) {
// If a class is defined in an externs file or as an interface, it's only a stub, not an
// implementation that should be instantiated.
// A call to super() shouldn't actually exist for these cases and is problematic to
// transpile, so just drop it.
Node enclosingStatement = NodeUtil.getEnclosingStatement(node);
Node enclosingStatementParent = enclosingStatement.getParent();
enclosingStatement.detach();
compiler.reportChangeToEnclosingScope(enclosingStatementParent);
}
// Calls to super() constructors will be transpiled by Es6ConvertSuperConstructorCalls
// later.
return;
} else {
// super can only be directly called in a constructor
throw new IllegalStateException("This should never happen. Did Es6SuperCheck fail to run?");
}
}
private void visitSuperPropertyCall(Node node, Node parent, Node enclosingMemberDef) {
checkState(parent.isGetProp() || parent.isGetElem(), parent);
checkState(node.isSuper(), node);
Node grandparent = parent.getParent();
checkState(grandparent.isCall());
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
Node callTarget = parent;
if (enclosingMemberDef.isStaticMember()) {
callTarget.replaceChild(node, superName.cloneTree());
callTarget = IR.getprop(callTarget.detach(), IR.string("call"));
grandparent.addChildToFront(callTarget);
grandparent.addChildAfter(IR.thisNode(), callTarget);
grandparent.useSourceInfoIfMissingFromForTree(parent);
} else {
String newPropName = Joiner.on('.').join(superName.getQualifiedName(), "prototype");
Node newProp = NodeUtil.newQName(compiler, newPropName);
node.replaceWith(newProp);
callTarget = IR.getprop(callTarget.detach(), IR.string("call"));
grandparent.addChildToFront(callTarget);
grandparent.addChildAfter(IR.thisNode(), callTarget);
grandparent.putBooleanProp(Node.FREE_CALL, false);
grandparent.useSourceInfoIfMissingFromForTree(parent);
}
compiler.reportChangeToEnclosingScope(grandparent);
}
private void visitSuperPropertyAccess(Node node, Node parent, Node enclosingMemberDef) {
checkState(parent.isGetProp() || parent.isGetElem(), parent);
checkState(node.isSuper(), node);
Node grandparent = parent.getParent();
if (NodeUtil.isLValue(parent)) {
// We don't support assigning to a super property
compiler.report(
JSError.make(parent, CANNOT_CONVERT_YET, "assigning to a super property"));
return;
}
Node clazz = NodeUtil.getEnclosingClass(node);
Node superName = clazz.getSecondChild();
if (!superName.isQualifiedName()) {
// This will be reported as an error in Es6ToEs3Converter.
return;
}
if (enclosingMemberDef.isStaticMember()) {
node.replaceWith(superName.cloneTree());
} else {
String newPropName = Joiner.on('.').join(superName.getQualifiedName(), "prototype");
Node newprop = NodeUtil.newQName(compiler, newPropName, node, "super");
node.replaceWith(newprop);
}
compiler.reportChangeToEnclosingScope(grandparent);
}
@Override
public void process(Node externs, Node root) {
// Might need to synthesize constructors for ambient classes in .d.ts externs
TranspilationPasses.processTranspile(compiler, externs, transpiledFeatures, this);
TranspilationPasses.processTranspile(compiler, root, transpiledFeatures, this);
TranspilationPasses.markFeaturesAsTranspiledAway(compiler, transpiledFeatures);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, transpiledFeatures, this);
TranspilationPasses.markFeaturesAsTranspiledAway(compiler, transpiledFeatures);
}
}
|
package models;
import java.util.List;
public class DocModel {
private List<ElementModel> elements;
private InfoModel info;
public List<ElementModel> getElements() {
return elements;
}
public InfoModel getInfoModel() {
return info;
}
}
|
package net.minecraft.command.server;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import java.util.List;
public class CommandListBans extends CommandBase {
private static final String __OBFID = "CL_00000596";
@Override
public String getCommandName() {
return "banlist";
}
@Override
public int getRequiredPermissionLevel() {
return 3;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_) {
return (MinecraftServer.getServer().getConfigurationManager().getBannedIPs().func_152689_b()
|| MinecraftServer.getServer().getConfigurationManager().func_152608_h().func_152689_b())
&& super.canCommandSenderUseCommand(p_71519_1_);
}
@Override
public String getCommandUsage(ICommandSender p_71518_1_) {
return "commands.banlist.usage";
}
@Override
public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) {
if (p_71515_2_.length >= 1 && p_71515_2_[0].equalsIgnoreCase("ips")) {
p_71515_1_.addChatMessage(
new ChatComponentTranslation("commands.banlist.ips", Integer.valueOf(MinecraftServer
.getServer().getConfigurationManager().getBannedIPs().func_152685_a().length)));
p_71515_1_.addChatMessage(new ChatComponentText(joinNiceString(
MinecraftServer.getServer().getConfigurationManager().getBannedIPs().func_152685_a())));
} else {
p_71515_1_.addChatMessage(new ChatComponentTranslation("commands.banlist.players",
Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().func_152608_h()
.func_152685_a().length)));
p_71515_1_.addChatMessage(new ChatComponentText(joinNiceString(
MinecraftServer.getServer().getConfigurationManager().func_152608_h().func_152685_a())));
}
}
@Override
public List addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) {
return p_71516_2_.length == 1 ? getListOfStringsMatchingLastWord(p_71516_2_, "players", "ips")
: null;
}
}
|
package org.vitrivr.cineast.core.features;
/**
* An Extraction and Retrieval module for 3D models that leverages Spherical Harmonics as proposed in [1]. This version
* uses low-resolution settings in terms of harmonics to consider.
*
* [1] Funkhouser, T., Min, P., Kazhdan, M., Chen, J., Halderman, A., Dobkin, D., & Jacobs, D. (2003).
* A search engine for 3D models. ACM Trans. Graph., 22(1), 83–105. http://doi.org/10.1145/588272.588279
*/
public class SphericalHarmonicsLow extends SphericalHarmonics {
/**
* Constructor for SphericalHarmonics feature module. Uses the values
* for grid_size proposed in [1] and harmonics up to l=5
*/
public SphericalHarmonicsLow() {
super("features_sphericalhlow", 64, 0,3);
}
}
|
/*
* 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.netbeans.modules.cpplite.debugger.breakpoints;
import java.net.MalformedURLException;
import java.net.URL;
import org.netbeans.api.debugger.Breakpoint;
import org.netbeans.api.debugger.Properties;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.URLMapper;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.text.Line;
/**
*
* @author Jan Jancura
*/
public class BreakpointsReader implements Properties.Reader {
@Override
public String [] getSupportedClassNames () {
return new String[] {
CPPLiteBreakpoint.class.getName (),
};
}
@Override
public Object read (String typeID, Properties properties) {
if (!(typeID.equals (CPPLiteBreakpoint.class.getName ())))
return null;
Line line = getLine (
properties.getString ("url", null),
properties.getInt ("lineNumber", 1));
if (line == null) return null;
CPPLiteBreakpoint b = new CPPLiteBreakpoint (line);
b.setGroupName(
properties.getString (Breakpoint.PROP_GROUP_NAME, "")
);
int hitCountFilter = properties.getInt(Breakpoint.PROP_HIT_COUNT_FILTER, 0);
Breakpoint.HIT_COUNT_FILTERING_STYLE hitCountFilteringStyle;
if (hitCountFilter > 0) {
hitCountFilteringStyle = Breakpoint.HIT_COUNT_FILTERING_STYLE.values()
[properties.getInt(Breakpoint.PROP_HIT_COUNT_FILTER+"_style", 0)]; // NOI18N
} else {
hitCountFilteringStyle = null;
}
b.setHitCountFilter(hitCountFilter, hitCountFilteringStyle);
if (properties.getBoolean (Breakpoint.PROP_ENABLED, true))
b.enable ();
else
b.disable ();
return b;
}
@Override
public void write (Object object, Properties properties) {
CPPLiteBreakpoint b = (CPPLiteBreakpoint) object;
FileObject fo = (FileObject) b.getLine ().getLookup ().
lookup (FileObject.class);
properties.setString("url", fo.toURL().toString());
properties.setInt (
"lineNumber",
b.getLine ().getLineNumber ()
);
properties.setString (
Breakpoint.PROP_GROUP_NAME,
b.getGroupName ()
);
properties.setBoolean (Breakpoint.PROP_ENABLED, b.isEnabled ());
properties.setInt(Breakpoint.PROP_HIT_COUNT_FILTER, b.getHitCountFilter());
Breakpoint.HIT_COUNT_FILTERING_STYLE style = b.getHitCountFilteringStyle();
properties.setInt(Breakpoint.PROP_HIT_COUNT_FILTER+"_style", style != null ? style.ordinal() : 0); // NOI18N
}
private Line getLine (String url, int lineNumber) {
FileObject file;
try {
file = URLMapper.findFileObject (new URL (url));
} catch (MalformedURLException e) {
return null;
}
if (file == null) return null;
DataObject dataObject;
try {
dataObject = DataObject.find (file);
} catch (DataObjectNotFoundException ex) {
return null;
}
if (dataObject == null) return null;
LineCookie lineCookie = dataObject.getLookup().lookup(LineCookie.class);
if (lineCookie == null) return null;
Line.Set ls = lineCookie.getLineSet ();
if (ls == null) return null;
try {
return ls.getCurrent (lineNumber);
} catch (IndexOutOfBoundsException e) {
} catch (IllegalArgumentException e) {
}
return null;
}
}
|
/*************************************************************************
* Copyright (c) 2019,2021 The Eclipse Foundation and others.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution, and is available at https://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*************************************************************************/
package org.eclipse.dash.licenses.tests;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.dash.licenses.ContentId;
import org.eclipse.dash.licenses.IContentData;
import org.eclipse.dash.licenses.LicenseSupport;
import org.eclipse.dash.licenses.clearlydefined.ClearlyDefinedContentData;
import org.eclipse.dash.licenses.clearlydefined.ClearlyDefinedSupport;
import org.eclipse.dash.licenses.tests.util.TestLicenseToolModule;
import org.eclipse.dash.licenses.util.JsonUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
class ClearlyDefinedSupportTests {
private ClearlyDefinedSupport clearlyDefined;
@BeforeEach
void setup() {
Injector injector = Guice.createInjector(new TestLicenseToolModule());
clearlyDefined = injector.getInstance(ClearlyDefinedSupport.class);
}
@Test
void testMatchApproved() {
List<IContentData> results = new ArrayList<>();
clearlyDefined.queryLicenseData(Collections.singleton(ContentId.getContentId("npm/npmjs/-/write/1.0.3")),
data -> results.add(data));
assertEquals(1, results.size());
IContentData write = results.get(0);
assertEquals("npm/npmjs/-/write/1.0.3", write.getId().toString());
assertEquals("clearlydefined", write.getAuthority());
assertEquals("MIT", write.getLicense());
assertEquals("https://clearlydefined.io/definitions/npm/npmjs/-/write/1.0.3", write.getUrl());
assertEquals(94, write.getScore());
assertEquals(LicenseSupport.Status.Approved, write.getStatus());
}
@Test
void testMatchRestricted() {
List<IContentData> results = new ArrayList<>();
clearlyDefined.queryLicenseData(
Collections.singleton(ContentId.getContentId("npm/npmjs/@yarnpkg/lockfile/1.1.0")),
data -> results.add(data));
assertEquals(1, results.size());
IContentData write = results.get(0);
assertEquals("npm/npmjs/@yarnpkg/lockfile/1.1.0", write.getId().toString());
assertEquals("clearlydefined", write.getAuthority());
assertEquals("BSD-2-Clause", write.getLicense());
assertEquals("https://clearlydefined.io/definitions/npm/npmjs/@yarnpkg/lockfile/1.1.0", write.getUrl());
assertEquals(53, write.getScore());
assertEquals(LicenseSupport.Status.Restricted, write.getStatus());
}
@Test
void testEmptyRequest() {
List<IContentData> results = new ArrayList<>();
clearlyDefined.queryLicenseData(Collections.emptySet(), data -> results.add(data));
assertTrue(results.isEmpty());
}
@Test
void testWithUnsupported() {
List<IContentData> results = new ArrayList<>();
clearlyDefined.queryLicenseData(Collections.singleton(ContentId.getContentId("p2/eclipseplugin/-/write/0.2.0")),
data -> results.add(data));
assertTrue(results.isEmpty());
}
@Nested
class TestServiceMethods {
@Test
void testAcceptable() {
// @formatter:off
String json =
"{\n" +
" \"licensed\": {\n" +
" \"declared\": \"EPL-2.0\", \n" +
" \"facets\": {\n" +
" \"core\": {\n" +
" \"discovered\": {\n" +
" \"expressions\": [\n" +
" \"EPL-2.0\",\n" +
" \"NONE\"\n" +
" ] \n" +
" }, \n" +
" \"files\": 4\n" +
" }\n" +
" }, \n" +
" \"score\": {\n" +
" \"total\": 80\n" +
" }\n" +
" }\n" +
"}\n";
// @formatter:on
ClearlyDefinedContentData data = new ClearlyDefinedContentData("id",
JsonUtils.readJson(new StringReader(json)));
assertTrue(clearlyDefined.isAccepted(data));
}
@Test
void testUnacceptableByScore() {
// @formatter:off
String json =
"{\n" +
" \"licensed\": {\n" +
" \"declared\": \"MIT\", \n" +
" \"facets\": {\n" +
" \"core\": {\n" +
" \"discovered\": {\n" +
" \"expressions\": [\n" +
" \"MIT\"\n" +
" ] \n" +
" }, \n" +
" \"files\": 4\n" +
" }\n" +
" }, \n" +
" \"score\": {\n" +
" \"total\": 50\n" +
" }\n" +
" }\n" +
"}\n";
// @formatter:on
ClearlyDefinedContentData data = new ClearlyDefinedContentData("id",
JsonUtils.readJson(new StringReader(json)));
assertFalse(clearlyDefined.isAccepted(data));
}
@Test
void testUnacceptableByDiscoveredLicense() {
// @formatter:off
String json =
"{\n" +
" \"licensed\": {\n" +
" \"declared\": \"EPL-2.0\", \n" +
" \"facets\": {\n" +
" \"core\": {\n" +
" \"discovered\": {\n" +
" \"expressions\": [\n" +
" \"MIT\",\n" +
" \"GPL-2.0\"\n" +
" ] \n" +
" }, \n" +
" \"files\": 4\n" +
" }\n" +
" }, \n" +
" \"score\": {\n" +
" \"total\": 80\n" +
" }\n" +
" }\n" +
"}\n";
// @formatter:on
ClearlyDefinedContentData data = new ClearlyDefinedContentData("id",
JsonUtils.readJson(new StringReader(json)));
assertFalse(clearlyDefined.isAccepted(data));
}
}
}
|
//====================================
// KYLE RUSSELL
// 13831056
// PDC Project
//====================================
package engine.models;
import com.google.gson.JsonArray;
import engine.core.database.Conditional;
import engine.core.database.Join;
import java.sql.SQLException;
public class DepartmentModel extends Model
{
public DepartmentModel()
{
super();
}
public DepartmentModel(Object id)
{
super(id);
}
public static JsonArray getUsersInDeptFiltered(int deptID)
{
try
{
JsonArray results = new User().builder()
.where("dept_id", "=", "" + deptID)
.select("username", "Username")
.select("users.firstname", "First name")
.select("users.lastname", "Last name")
.select("users.contact_ph", "Phone")
.select("users.contact_email", "Email")
.get();
return results;
}
catch(SQLException e)
{
return new JsonArray();
}
}
public static JsonArray getUsersInDept(int deptID)
{
try
{
JsonArray results = new User().builder()
.where("dept_id", "=", "" + deptID)
.get();
return results;
}
catch(SQLException e)
{
return new JsonArray();
}
}
public static JsonArray getAllDepartments()
{
try
{
JsonArray results = new DepartmentModel().builder().get();
return results;
}
catch(SQLException e)
{
return new JsonArray();
}
}
public static JsonArray getHOD(int deptID)
{
try
{
JsonArray results = new DepartmentModel().builder()
.join(new Join("department", "users", "dept_head", "username", Join.JoinType.INNERR_JOIN)
.filter(new Conditional("dept_id", "=", "" + deptID)))
.join("users", "role", "role_id", "id", Join.JoinType.INNERR_JOIN)
.select("users.*")
.select("role.name", "role_name")
.get();
return results;
}
catch(SQLException e)
{
return new JsonArray();
}
}
@Override
protected void initTable()
{
table = "department";
primaryKey = "id";
}
}
|
/*
* Copyright 2019 IIT Software GmbH
*
* IIT Software GmbH licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.swiftmq.amqp.v091.generated.confirm;
/**
* The Confirm method visitor.
*
* @author IIT Software GmbH, Bremen/Germany, (c) 2012, All Rights Reserved
* @version AMQP Version 091. Generation Date: Thu Apr 12 12:18:24 CEST 2012
**/
public interface ConfirmMethodVisitor {
/**
* Visitor method for a Select type object.
*
* @param impl a Select type object
*/
public void visit(Select impl);
/**
* Visitor method for a SelectOk type object.
*
* @param impl a SelectOk type object
*/
public void visit(SelectOk impl);
}
|
package org.sqlite;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/** These tests are designed to stress Statements on memory databases. */
public class DBMetaDataTest
{
private Connection conn;
private Statement stat;
private DatabaseMetaData meta;
@Before
public void connect() throws Exception {
conn = DriverManager.getConnection("jdbc:sqlite:");
stat = conn.createStatement();
stat.executeUpdate("create table test (id integer primary key, fn float default 0.0, sn not null);");
stat.executeUpdate("create view testView as select * from test;");
meta = conn.getMetaData();
}
@After
public void close() throws SQLException {
meta = null;
stat.close();
conn.close();
}
@Test
public void getTables() throws SQLException {
ResultSet rs = meta.getTables(null, null, null, null);
assertNotNull(rs);
stat.getGeneratedKeys().close();
stat.close();
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test"); // 3
assertEquals(rs.getString("TABLE_TYPE"), "TABLE"); // 4
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertEquals(rs.getString("TABLE_TYPE"), "VIEW");
rs.close();
rs = meta.getTables(null, null, "bob", null);
assertFalse(rs.next());
rs.close();
rs = meta.getTables(null, null, "test", null);
assertTrue(rs.next());
assertFalse(rs.next());
rs.close();
rs = meta.getTables(null, null, "test%", null);
assertTrue(rs.next());
assertTrue(rs.next());
rs.close();
rs = meta.getTables(null, null, null, new String[] { "table" });
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertFalse(rs.next());
rs.close();
rs = meta.getTables(null, null, null, new String[] { "view" });
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertFalse(rs.next());
rs.close();
}
@Test
public void getTableTypes() throws SQLException {
ResultSet rs = meta.getTableTypes();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_TYPE"), "GLOBAL TEMPORARY");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_TYPE"), "SYSTEM TABLE");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_TYPE"), "TABLE");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_TYPE"), "VIEW");
assertFalse(rs.next());
}
@Test
public void getTypeInfo() throws SQLException {
ResultSet rs = meta.getTypeInfo();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(rs.getString("TYPE_NAME"), "BLOB");
assertTrue(rs.next());
assertEquals(rs.getString("TYPE_NAME"), "INTEGER");
assertTrue(rs.next());
assertEquals(rs.getString("TYPE_NAME"), "NULL");
assertTrue(rs.next());
assertEquals(rs.getString("TYPE_NAME"), "REAL");
assertTrue(rs.next());
assertEquals(rs.getString("TYPE_NAME"), "TEXT");
assertFalse(rs.next());
}
@Test
public void getColumns() throws SQLException {
ResultSet rs = meta.getColumns(null, null, "test", "id");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertEquals(rs.getString("IS_NULLABLE"), "YES");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getInt("DATA_TYPE"), Types.INTEGER);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "test", "fn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertEquals(rs.getInt("DATA_TYPE"), Types.FLOAT);
assertEquals(rs.getString("IS_NULLABLE"), "YES");
assertEquals(rs.getString("COLUMN_DEF"), "0.0");
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "test", "sn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "sn");
assertEquals(rs.getString("IS_NULLABLE"), "NO");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertFalse(rs.next());
rs = meta.getColumns(null, null, "test", "%");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "sn");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "test", "%n");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "sn");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "test%", "%");
// TABLE "test"
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertEquals(rs.getString("COLUMN_NAME"), "sn");
// VIEW "testView"
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertEquals(rs.getString("COLUMN_NAME"), "sn");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "%", "%");
// TABLE "test"
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "test");
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "sn");
// VIEW "testView"
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "testView");
assertEquals(rs.getString("COLUMN_NAME"), "id");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "fn");
assertTrue(rs.next());
assertEquals(rs.getString("COLUMN_NAME"), "sn");
assertFalse(rs.next());
rs = meta.getColumns(null, null, "doesnotexist", "%");
assertFalse(rs.next());
assertEquals(24, rs.getMetaData().getColumnCount());
}
@Test
public void numberOfgetImportedKeysCols() throws SQLException {
stat.executeUpdate("create table parent (id1 integer, id2 integer, primary key(id1, id2))");
stat.executeUpdate("create table child1 (id1 integer, id2 integer, foreign key(id1) references parent(id1), foreign key(id2) references parent(id2))");
stat.executeUpdate("create table child2 (id1 integer, id2 integer, foreign key(id2, id1) references parent(id2, id1))");
ResultSet importedKeys = meta.getImportedKeys(null, null, "child1");
//child1: 1st fk (simple)
assertTrue(importedKeys.next());
assertEquals("parent", importedKeys.getString("PKTABLE_NAME"));
assertEquals("id2", importedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(importedKeys.getString("PK_NAME"));
assertNotNull(importedKeys.getString("FK_NAME"));
assertEquals("child1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("id2", importedKeys.getString("FKCOLUMN_NAME"));
//child1: 2nd fk (simple)
assertTrue(importedKeys.next());
assertEquals("parent", importedKeys.getString("PKTABLE_NAME"));
assertEquals("id1", importedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(importedKeys.getString("PK_NAME"));
assertNotNull(importedKeys.getString("FK_NAME"));
assertEquals("child1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("id1", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys = meta.getImportedKeys(null, null, "child2");
//child2: 1st fk (composite)
assertTrue(importedKeys.next());
assertEquals("parent", importedKeys.getString("PKTABLE_NAME"));
assertEquals("id2", importedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(importedKeys.getString("PK_NAME"));
assertNotNull(importedKeys.getString("FK_NAME"));
assertEquals("child2", importedKeys.getString("FKTABLE_NAME"));
assertEquals("id2", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("parent", importedKeys.getString("PKTABLE_NAME"));
assertEquals("id1", importedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(importedKeys.getString("PK_NAME"));
assertNotNull(importedKeys.getString("FK_NAME"));
assertEquals("child2", importedKeys.getString("FKTABLE_NAME"));
assertEquals("id1", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
}
@Test
public void numberOfgetExportedKeysCols() throws SQLException {
stat.executeUpdate("create table parent (id1 integer, id2 integer, primary key(id1, id2))");
stat.executeUpdate("create table child1 (id1 integer, id2 integer,\r\n foreign\tkey(id1) references parent(id1), foreign key(id2) references parent(id2))");
stat.executeUpdate("create table child2 (id1 integer, id2 integer, foreign key(id2, id1) references parent(id2, id1))");
ResultSet exportedKeys = meta.getExportedKeys(null, null, "parent");
//1st fk (simple) - child1
assertTrue(exportedKeys.next());
assertEquals("parent", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("id2", exportedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(exportedKeys.getString("PK_NAME"));
assertNotNull(exportedKeys.getString("FK_NAME"));
assertEquals("child1", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("id2", exportedKeys.getString("FKCOLUMN_NAME"));
//2nd fk (simple) - child1
assertTrue(exportedKeys.next());
assertEquals("parent", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("id1", exportedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(exportedKeys.getString("PK_NAME"));
assertNotNull(exportedKeys.getString("FK_NAME"));
assertEquals("child1", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("id1", exportedKeys.getString("FKCOLUMN_NAME"));
//3rd fk (composite) - child2
assertTrue(exportedKeys.next());
assertEquals("parent", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("id2", exportedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(exportedKeys.getString("PK_NAME"));
assertNotNull(exportedKeys.getString("FK_NAME"));
assertEquals("child2", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("id2", exportedKeys.getString("FKCOLUMN_NAME"));
assertTrue(exportedKeys.next());
assertEquals("parent", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("id1", exportedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(exportedKeys.getString("PK_NAME"));
assertNotNull(exportedKeys.getString("FK_NAME"));
assertEquals("child2", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("id1", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
}
@Test
public void getExportedKeysColsForNamedKeys() throws SQLException {
ResultSet exportedKeys;
// 1. Check for named primary keys
// SQL is deliberately in uppercase, to make sure case-sensitivity is maintained
stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
exportedKeys = meta.getExportedKeys(null, null, "PARENT1");
assertTrue(exportedKeys.next());
assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("ID1", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT", exportedKeys.getString("PK_NAME"));
assertEquals("", exportedKeys.getString("FK_NAME"));
assertEquals("CHILD1", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("ID1", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
// 2. Check for named foreign keys
// SQL is deliberately in mixed case, to make sure case-sensitivity is maintained
stat.executeUpdate("CREATE TABLE Parent2 (Id1 INTEGER, DATA1 INTEGER, PRIMARY KEY (Id1))");
stat.executeUpdate("CREATE TABLE Child2 (Id1 INTEGER, DATA2 INTEGER, CONSTRAINT FK_Child2 FOREIGN KEY(Id1) REFERENCES Parent2(Id1))");
exportedKeys = meta.getExportedKeys(null, null, "Parent2");
assertTrue(exportedKeys.next());
assertEquals("Parent2", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("Id1", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("", exportedKeys.getString("PK_NAME"));
assertEquals("FK_Child2", exportedKeys.getString("FK_NAME"));
assertEquals("Child2", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("Id1", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
}
@Test
public void getImportedKeysMultipleColumns()throws SQLException{
ResultSet importedKeys;
stat.executeUpdate("CREATE TABLE PONE ( ID_FIRST_ONE INTEGER NOT NULL, ID_SECOND_ONE INTEGER NOT NULL, ADDITIONAL_ONE TEXT, CONSTRAINT PONE_PK PRIMARY KEY (ID_FIRST_ONE, ID_SECOND_ONE) )");
stat.executeUpdate("CREATE TABLE PTWO ( ID_FIRST_TWO INTEGER NOT NULL, ID_SECOND_TWO INTEGER NOT NULL, ADDITIONAL_TWO TEXT, CONSTRAINT PTWO_PK PRIMARY KEY (ID_FIRST_TWO, ID_SECOND_TWO) )");
stat.executeUpdate("CREATE TABLE CHILD ( ID_CHILD INTEGER NOT NULL, ID_CHILD_TO_ONE INTEGER NOT NULL, ID_CHILD_TO_TWO INTEGER NOT NULL, CONSTRAINT CHILD_PK PRIMARY KEY (ID_CHILD, ID_CHILD_TO_ONE), CONSTRAINT PONE_FK01 FOREIGN KEY (ID_CHILD, ID_CHILD_TO_ONE) REFERENCES PONE (ID_FIRST_ONE, ID_SECOND_ONE) ON DELETE CASCADE, CONSTRAINT PTWO_FK02 FOREIGN KEY (ID_CHILD, ID_CHILD_TO_TWO) REFERENCES PTWO (ID_FIRST_TWO, ID_SECOND_TWO) )");
importedKeys = meta.getImportedKeys(null, null, "CHILD");
assertTrue(importedKeys.next());
assertEquals("PONE", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID_FIRST_ONE", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PONE_PK", importedKeys.getString("PK_NAME"));
assertEquals("PONE_FK01", importedKeys.getString("FK_NAME"));
assertEquals("CHILD", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID_CHILD", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("PONE", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID_SECOND_ONE", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PONE_PK", importedKeys.getString("PK_NAME"));
assertEquals("PONE_FK01", importedKeys.getString("FK_NAME"));
assertEquals("CHILD", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID_CHILD_TO_ONE", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("PTWO", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID_FIRST_TWO", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PTWO_PK", importedKeys.getString("PK_NAME"));
assertEquals("PTWO_FK02", importedKeys.getString("FK_NAME"));
assertEquals("CHILD", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID_CHILD", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("PTWO", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID_SECOND_TWO", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PTWO_PK", importedKeys.getString("PK_NAME"));
assertEquals("PTWO_FK02", importedKeys.getString("FK_NAME"));
assertEquals("CHILD", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID_CHILD_TO_TWO", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
}
@Test
public void getImportedKeysColsForNamedKeys() throws SQLException {
ResultSet importedKeys;
// 1. Check for named primary keys
// SQL is deliberately in uppercase, to make sure case-sensitivity is maintained
stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
importedKeys = meta.getImportedKeys(null, null, "CHILD1");
assertTrue(importedKeys.next());
assertEquals("PARENT1", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID1", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT", importedKeys.getString("PK_NAME"));
assertEquals("", importedKeys.getString("FK_NAME"));
assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
// 2. Check for named foreign keys
// SQL is deliberately in mixed case, to make sure case-sensitivity is maintained
stat.executeUpdate("CREATE TABLE Parent2 (Id1 INTEGER, DATA1 INTEGER, PRIMARY KEY (Id1))");
stat.executeUpdate("CREATE TABLE Child2 (Id1 INTEGER, DATA2 INTEGER, "
+ "CONSTRAINT FK_Child2 FOREIGN KEY(Id1) REFERENCES Parent2(Id1))");
importedKeys = meta.getImportedKeys(null, null, "Child2");
assertTrue(importedKeys.next());
assertEquals("Parent2", importedKeys.getString("PKTABLE_NAME"));
assertEquals("Id1", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("", importedKeys.getString("PK_NAME"));
assertEquals("FK_Child2", importedKeys.getString("FK_NAME"));
assertEquals("Child2", importedKeys.getString("FKTABLE_NAME"));
assertEquals("Id1", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
}
@Test
public void getImportedKeysColsForMixedCaseDefinition() throws SQLException {
ResultSet importedKeys;
// SQL is deliberately in mixed-case, to make sure case-sensitivity is maintained
stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT PRIMARY KEY (ID1))");
stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, DATA2 INTEGER, "
+ "CONSTRAINT FK_Parent1 FOREIGN KEY(ID1) REFERENCES Parent1(Id1))");
importedKeys = meta.getImportedKeys(null, null, "CHILD1");
assertTrue(importedKeys.next());
assertEquals("Parent1", importedKeys.getString("PKTABLE_NAME"));
assertEquals("Id1", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT", importedKeys.getString("PK_NAME"));
assertEquals("FK_Parent1", importedKeys.getString("FK_NAME"));
assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
}
@Test
public void getImportedKeysColsForMultipleImports() throws SQLException {
ResultSet importedKeys;
stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, DATA1 INTEGER, CONSTRAINT PK_PARENT1 PRIMARY KEY (ID1))");
stat.executeUpdate("CREATE TABLE PARENT2 (ID2 INTEGER, DATA2 INTEGER, CONSTRAINT PK_PARENT2 PRIMARY KEY (ID2))");
stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, ID2 INTEGER, "
+ "CONSTRAINT FK_PARENT1 FOREIGN KEY(ID1) REFERENCES PARENT1(ID1), "
+ "CONSTRAINT FK_PARENT2 FOREIGN KEY(ID2) REFERENCES PARENT2(ID2))");
importedKeys = meta.getImportedKeys(null, null, "CHILD1");
assertTrue(importedKeys.next());
assertEquals("PARENT1", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID1", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT1", importedKeys.getString("PK_NAME"));
assertEquals("FK_PARENT1", importedKeys.getString("FK_NAME"));
assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID1", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("PARENT2", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID2", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT2", importedKeys.getString("PK_NAME"));
assertEquals("FK_PARENT2", importedKeys.getString("FK_NAME"));
assertEquals("CHILD1", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID2", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
// Unnamed foreign keys and unnamed primary keys
stat.executeUpdate("CREATE TABLE PARENT3 (ID3 INTEGER, DATA3 INTEGER, PRIMARY KEY (ID3))");
stat.executeUpdate("CREATE TABLE PARENT4 (ID4 INTEGER, DATA4 INTEGER, CONSTRAINT PK_PARENT4 PRIMARY KEY (ID4))");
stat.executeUpdate("CREATE TABLE CHILD2 (ID3 INTEGER, ID4 INTEGER, "
+ "FOREIGN KEY(ID3) REFERENCES PARENT3(ID3), "
+ "CONSTRAINT FK_PARENT4 FOREIGN KEY(ID4) REFERENCES PARENT4(ID4))");
importedKeys = meta.getImportedKeys(null, null, "CHILD2");
assertTrue(importedKeys.next());
assertEquals("PARENT3", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID3", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("", importedKeys.getString("PK_NAME"));
assertEquals("", importedKeys.getString("FK_NAME"));
assertEquals("CHILD2", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID3", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("PARENT4", importedKeys.getString("PKTABLE_NAME"));
assertEquals("ID4", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT4", importedKeys.getString("PK_NAME"));
assertEquals("FK_PARENT4", importedKeys.getString("FK_NAME"));
assertEquals("CHILD2", importedKeys.getString("FKTABLE_NAME"));
assertEquals("ID4", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
}
@Test
public void getImportedKeysCols2() throws SQLException {
stat.executeUpdate("CREATE TABLE Authors (Id INTEGER NOT NULL, Name VARCHAR(20) NOT NULL, "
+ "CONSTRAINT PK_Authors PRIMARY KEY (Id)," +
" CONSTRAINT CHECK_UPPERCASE_Name CHECK (Name=UPPER(Name)))");
stat.executeUpdate("CREATE TABLE Books (Id INTEGER NOT NULL, Title VARCHAR(255) NOT NULL, PreviousEditionId INTEGER,"
+ "CONSTRAINT PK_Books PRIMARY KEY (Id), "
+ "CONSTRAINT FK_PreviousEdition FOREIGN KEY(PreviousEditionId) REFERENCES Books (Id))");
stat.executeUpdate("CREATE TABLE BookAuthors (BookId INTEGER NOT NULL, AuthorId INTEGER NOT NULL, "
+ "CONSTRAINT FK_Y_Book FOREIGN KEY (BookId) REFERENCES Books (Id), "
+ "CONSTRAINT FK_Z_Author FOREIGN KEY (AuthorId) REFERENCES Authors (Id)) ");
ResultSet importedKeys;
importedKeys = meta.getImportedKeys(null, null, "BookAuthors");
assertTrue(importedKeys.next());
assertEquals("Authors", importedKeys.getString("PKTABLE_NAME"));
assertEquals("Id", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_Authors", importedKeys.getString("PK_NAME"));
assertEquals("FK_Z_Author", importedKeys.getString("FK_NAME"));
assertEquals("BookAuthors", importedKeys.getString("FKTABLE_NAME"));
assertEquals("AuthorId", importedKeys.getString("FKCOLUMN_NAME"));
assertTrue(importedKeys.next());
assertEquals("Books", importedKeys.getString("PKTABLE_NAME"));
assertEquals("Id", importedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_Books", importedKeys.getString("PK_NAME"));
assertEquals("FK_Y_Book", importedKeys.getString("FK_NAME"));
assertEquals("BookAuthors", importedKeys.getString("FKTABLE_NAME"));
assertEquals("BookId", importedKeys.getString("FKCOLUMN_NAME"));
assertFalse(importedKeys.next());
importedKeys.close();
ResultSet exportedKeys;
exportedKeys = meta.getExportedKeys(null, null, "Authors");
assertTrue(exportedKeys.next());
assertEquals("Authors", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("Id", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_Authors", exportedKeys.getString("PK_NAME"));
assertEquals("FK_Z_Author", exportedKeys.getString("FK_NAME"));
assertEquals("BookAuthors", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("AuthorId", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
exportedKeys = meta.getExportedKeys(null, null, "Books");
assertTrue(exportedKeys.next());
assertEquals("Books", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("Id", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_Books", exportedKeys.getString("PK_NAME"));
assertEquals("FK_Y_Book", exportedKeys.getString("FK_NAME"));
assertEquals("BookAuthors", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("BookId", exportedKeys.getString("FKCOLUMN_NAME"));
assertTrue(exportedKeys.next());
assertEquals("Books", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("Id", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_Books", exportedKeys.getString("PK_NAME"));
assertEquals("FK_PreviousEdition", exportedKeys.getString("FK_NAME")); // ???
assertEquals("Books", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("PreviousEditionId", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
}
@Test
public void getExportedKeysColsForMultipleImports() throws SQLException {
ResultSet exportedKeys;
stat.executeUpdate("CREATE TABLE PARENT1 (ID1 INTEGER, ID2 INTEGER, CONSTRAINT PK_PARENT1 PRIMARY KEY (ID1))");
stat.executeUpdate("CREATE TABLE CHILD1 (ID1 INTEGER, CONSTRAINT FK_PARENT1 FOREIGN KEY(ID1) REFERENCES PARENT1(ID1))");
stat.executeUpdate("CREATE TABLE CHILD2 (ID2 INTEGER, CONSTRAINT FK_PARENT2 FOREIGN KEY(ID2) REFERENCES PARENT1(ID2))");
exportedKeys = meta.getExportedKeys(null, null, "PARENT1");
assertTrue(exportedKeys.next());
assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("ID1", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("PK_PARENT1", exportedKeys.getString("PK_NAME"));
assertEquals("FK_PARENT1", exportedKeys.getString("FK_NAME"));
assertEquals("CHILD1", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("ID1", exportedKeys.getString("FKCOLUMN_NAME"));
assertTrue(exportedKeys.next());
assertEquals("PARENT1", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("ID2", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("", exportedKeys.getString("PK_NAME"));
assertEquals("FK_PARENT2", exportedKeys.getString("FK_NAME"));
assertEquals("CHILD2", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("ID2", exportedKeys.getString("FKCOLUMN_NAME"));
assertFalse(exportedKeys.next());
exportedKeys.close();
}
@Test
public void columnOrderOfgetTables() throws SQLException {
stat.executeUpdate("CREATE TABLE TABLE1 (ID1 INTEGER PRIMARY KEY AUTOINCREMENT, ID2 INTEGER)");
stat.executeUpdate("CREATE TABLE TABLE2 (ID2 INTEGER, DATA2 VARCHAR(20))");
stat.executeUpdate("CREATE TEMP TABLE TABLE3 (ID3 INTEGER, DATA3 VARCHAR(20))");
stat.executeUpdate("CREATE VIEW VIEW1 (V1, V2) AS SELECT ID1, ID2 FROM TABLE1");
ResultSet rsTables = meta.getTables(null, null, null, new String[] {"TABLE", "VIEW", "GLOBAL TEMPORARY", "SYSTEM TABLE"});
assertTrue(rsTables.next());
// Check order of columns
ResultSetMetaData rsmeta = rsTables.getMetaData();
assertEquals(rsmeta.getColumnCount(), 10);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TABLE_NAME");
assertEquals(rsmeta.getColumnName(4), "TABLE_TYPE");
assertEquals(rsmeta.getColumnName(5), "REMARKS");
assertEquals(rsmeta.getColumnName(6), "TYPE_CAT");
assertEquals(rsmeta.getColumnName(7), "TYPE_SCHEM");
assertEquals(rsmeta.getColumnName(8), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(9), "SELF_REFERENCING_COL_NAME");
assertEquals(rsmeta.getColumnName(10), "REF_GENERATION");
assertEquals("TABLE3", rsTables.getString("TABLE_NAME"));
assertEquals("GLOBAL TEMPORARY", rsTables.getString("TABLE_TYPE"));
assertTrue(rsTables.next());
assertEquals("sqlite_sequence", rsTables.getString("TABLE_NAME"));
assertEquals("SYSTEM TABLE", rsTables.getString("TABLE_TYPE"));
assertTrue(rsTables.next());
assertEquals("TABLE1", rsTables.getString("TABLE_NAME"));
assertEquals("TABLE", rsTables.getString("TABLE_TYPE"));
assertTrue(rsTables.next());
assertEquals("TABLE2", rsTables.getString("TABLE_NAME"));
assertEquals("TABLE", rsTables.getString("TABLE_TYPE"));
assertTrue(rsTables.next());
assertTrue(rsTables.next());
assertEquals("VIEW1", rsTables.getString("TABLE_NAME"));
assertEquals("VIEW", rsTables.getString("TABLE_TYPE"));
rsTables.close();
}
@Test
public void columnOrderOfgetTableTypes() throws SQLException {
ResultSet rs = meta.getTableTypes();
assertTrue(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 1);
assertEquals(rsmeta.getColumnName(1), "TABLE_TYPE");
}
@Test
public void columnOrderOfgetTypeInfo() throws SQLException {
ResultSet rs = meta.getTypeInfo();
assertTrue(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 18);
assertEquals(rsmeta.getColumnName(1), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(2), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(3), "PRECISION");
assertEquals(rsmeta.getColumnName(4), "LITERAL_PREFIX");
assertEquals(rsmeta.getColumnName(5), "LITERAL_SUFFIX");
assertEquals(rsmeta.getColumnName(6), "CREATE_PARAMS");
assertEquals(rsmeta.getColumnName(7), "NULLABLE");
assertEquals(rsmeta.getColumnName(8), "CASE_SENSITIVE");
assertEquals(rsmeta.getColumnName(9), "SEARCHABLE");
assertEquals(rsmeta.getColumnName(10), "UNSIGNED_ATTRIBUTE");
assertEquals(rsmeta.getColumnName(11), "FIXED_PREC_SCALE");
assertEquals(rsmeta.getColumnName(12), "AUTO_INCREMENT");
assertEquals(rsmeta.getColumnName(13), "LOCAL_TYPE_NAME");
assertEquals(rsmeta.getColumnName(14), "MINIMUM_SCALE");
assertEquals(rsmeta.getColumnName(15), "MAXIMUM_SCALE");
assertEquals(rsmeta.getColumnName(16), "SQL_DATA_TYPE");
assertEquals(rsmeta.getColumnName(17), "SQL_DATETIME_SUB");
assertEquals(rsmeta.getColumnName(18), "NUM_PREC_RADIX");
}
@Test
public void columnOrderOfgetColumns() throws SQLException {
ResultSet rs = meta.getColumns(null, null, "test", null);
assertTrue(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 24);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TABLE_NAME");
assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(5), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(6), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(7), "COLUMN_SIZE");
assertEquals(rsmeta.getColumnName(8), "BUFFER_LENGTH");
assertEquals(rsmeta.getColumnName(9), "DECIMAL_DIGITS");
assertEquals(rsmeta.getColumnName(10), "NUM_PREC_RADIX");
assertEquals(rsmeta.getColumnName(11), "NULLABLE");
assertEquals(rsmeta.getColumnName(12), "REMARKS");
assertEquals(rsmeta.getColumnName(13), "COLUMN_DEF");
assertEquals(rsmeta.getColumnName(14), "SQL_DATA_TYPE");
assertEquals(rsmeta.getColumnName(15), "SQL_DATETIME_SUB");
assertEquals(rsmeta.getColumnName(16), "CHAR_OCTET_LENGTH");
assertEquals(rsmeta.getColumnName(17), "ORDINAL_POSITION");
assertEquals(rsmeta.getColumnName(18), "IS_NULLABLE");
// should be SCOPE_CATALOG, but misspelt in the standard
assertEquals(rsmeta.getColumnName(19), "SCOPE_CATLOG");
assertEquals(rsmeta.getColumnName(20), "SCOPE_SCHEMA");
assertEquals(rsmeta.getColumnName(21), "SCOPE_TABLE");
assertEquals(rsmeta.getColumnName(22), "SOURCE_DATA_TYPE");
assertEquals(rsmeta.getColumnName(23), "IS_AUTOINCREMENT");
assertEquals(rsmeta.getColumnName(24), "IS_GENERATEDCOLUMN");
assertEquals(rs.getString("COLUMN_NAME").toUpperCase(), "ID");
assertEquals(rs.getInt("ORDINAL_POSITION"), 1);
}
// the following functions always return an empty resultset, so
// do not bother testing their parameters, only the column types
@Test
public void columnOrderOfgetProcedures() throws SQLException {
ResultSet rs = meta.getProcedures(null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 8);
assertEquals(rsmeta.getColumnName(1), "PROCEDURE_CAT");
assertEquals(rsmeta.getColumnName(2), "PROCEDURE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "PROCEDURE_NAME");
// currently (Java 1.5), cols 4,5,6 are undefined
assertEquals(rsmeta.getColumnName(7), "REMARKS");
assertEquals(rsmeta.getColumnName(8), "PROCEDURE_TYPE");
}
@Test
public void columnOrderOfgetProcedurColumns() throws SQLException {
ResultSet rs = meta.getProcedureColumns(null, null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 13);
assertEquals(rsmeta.getColumnName(1), "PROCEDURE_CAT");
assertEquals(rsmeta.getColumnName(2), "PROCEDURE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "PROCEDURE_NAME");
assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(5), "COLUMN_TYPE");
assertEquals(rsmeta.getColumnName(6), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(7), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(8), "PRECISION");
assertEquals(rsmeta.getColumnName(9), "LENGTH");
assertEquals(rsmeta.getColumnName(10), "SCALE");
assertEquals(rsmeta.getColumnName(11), "RADIX");
assertEquals(rsmeta.getColumnName(12), "NULLABLE");
assertEquals(rsmeta.getColumnName(13), "REMARKS");
}
@Test
public void columnOrderOfgetSchemas() throws SQLException {
ResultSet rs = meta.getSchemas();
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 2);
assertEquals(rsmeta.getColumnName(1), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(2), "TABLE_CATALOG");
}
@Test
public void columnOrderOfgetCatalogs() throws SQLException {
ResultSet rs = meta.getCatalogs();
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 1);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
}
@Test
public void columnOrderOfgetColumnPrivileges() throws SQLException {
ResultSet rs = meta.getColumnPrivileges(null, null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 8);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TABLE_NAME");
assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(5), "GRANTOR");
assertEquals(rsmeta.getColumnName(6), "GRANTEE");
assertEquals(rsmeta.getColumnName(7), "PRIVILEGE");
assertEquals(rsmeta.getColumnName(8), "IS_GRANTABLE");
}
@Test
public void columnOrderOfgetTablePrivileges() throws SQLException {
ResultSet rs = meta.getTablePrivileges(null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 7);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TABLE_NAME");
assertEquals(rsmeta.getColumnName(4), "GRANTOR");
assertEquals(rsmeta.getColumnName(5), "GRANTEE");
assertEquals(rsmeta.getColumnName(6), "PRIVILEGE");
assertEquals(rsmeta.getColumnName(7), "IS_GRANTABLE");
}
@Test
public void columnOrderOfgetBestRowIdentifier() throws SQLException {
ResultSet rs = meta.getBestRowIdentifier(null, null, null, 0, false);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 8);
assertEquals(rsmeta.getColumnName(1), "SCOPE");
assertEquals(rsmeta.getColumnName(2), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(3), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(4), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(5), "COLUMN_SIZE");
assertEquals(rsmeta.getColumnName(6), "BUFFER_LENGTH");
assertEquals(rsmeta.getColumnName(7), "DECIMAL_DIGITS");
assertEquals(rsmeta.getColumnName(8), "PSEUDO_COLUMN");
}
@Test
public void columnOrderOfgetVersionColumns() throws SQLException {
ResultSet rs = meta.getVersionColumns(null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 8);
assertEquals(rsmeta.getColumnName(1), "SCOPE");
assertEquals(rsmeta.getColumnName(2), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(3), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(4), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(5), "COLUMN_SIZE");
assertEquals(rsmeta.getColumnName(6), "BUFFER_LENGTH");
assertEquals(rsmeta.getColumnName(7), "DECIMAL_DIGITS");
assertEquals(rsmeta.getColumnName(8), "PSEUDO_COLUMN");
}
@Test
public void viewIngetPrimaryKeys() throws SQLException {
ResultSet rs;
stat.executeUpdate("create table t1 (c1, c2, c3);");
stat.executeUpdate("create view view_nopk (v1, v2) as select c1, c3 from t1;");
rs = meta.getPrimaryKeys(null, null, "view_nopk");
assertFalse(rs.next());
}
@Test
public void moreOfgetColumns() throws SQLException {
ResultSet rs;
stat.executeUpdate("create table tabcols1 (col1, col2);");
// mixed-case table, column and primary key names
stat.executeUpdate("CREATE TABLE TabCols2 (Col1, Col2);");
// quoted table, column and primary key names
stat.executeUpdate("CREATE TABLE `TabCols3` (`Col1`, `Col2`);");
rs = meta.getColumns(null, null, "tabcols1", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "tabcols1");
assertEquals(rs.getString("COLUMN_NAME"), "col1");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertEquals(rs.getString("IS_NULLABLE"), "YES");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "tabcols1");
assertEquals(rs.getString("COLUMN_NAME"), "col2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
rs = meta.getColumns(null, null, "TabCols2", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TabCols2");
assertEquals(rs.getString("COLUMN_NAME"), "Col1");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertEquals(rs.getString("IS_NULLABLE"), "YES");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TabCols2");
assertEquals(rs.getString("COLUMN_NAME"), "Col2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
rs = meta.getColumns(null, null, "TabCols3", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TabCols3");
assertEquals(rs.getString("COLUMN_NAME"), "Col1");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertEquals(rs.getString("IS_NULLABLE"), "YES");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TabCols3");
assertEquals(rs.getString("COLUMN_NAME"), "Col2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
}
@Test
public void autoincrement() throws SQLException {
ResultSet rs;
// no autoincrement no rowid
stat.executeUpdate("CREATE TABLE TAB1 (COL1 INTEGER NOT NULL PRIMARY KEY, COL2) WITHOUT ROWID;");
// no autoincrement
stat.executeUpdate("CREATE TABLE TAB2 (COL1 INTEGER NOT NULL PRIMARY KEY, COL2);");
// autoincrement
stat.executeUpdate("CREATE TABLE TAB3 (COL1 INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, COL2);");
rs = meta.getColumns(null, null, "TAB1", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB1");
assertEquals(rs.getString("COLUMN_NAME"), "COL1");
assertEquals(rs.getInt("DATA_TYPE"), Types.INTEGER);
assertEquals(rs.getString("IS_NULLABLE"), "NO");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB1");
assertEquals(rs.getString("COLUMN_NAME"), "COL2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
rs = meta.getColumns(null, null, "TAB2", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB2");
assertEquals(rs.getString("COLUMN_NAME"), "COL1");
assertEquals(rs.getInt("DATA_TYPE"), Types.INTEGER);
assertEquals(rs.getString("IS_NULLABLE"), "NO");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "NO");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB2");
assertEquals(rs.getString("COLUMN_NAME"), "COL2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
rs = meta.getColumns(null, null, "TAB3", "%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB3");
assertEquals(rs.getString("COLUMN_NAME"), "COL1");
assertEquals(rs.getInt("DATA_TYPE"), Types.INTEGER);
assertEquals(rs.getString("IS_NULLABLE"), "NO");
assertEquals(rs.getString("COLUMN_DEF"), null);
assertEquals(rs.getString("IS_AUTOINCREMENT"), "YES");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), "TAB3");
assertEquals(rs.getString("COLUMN_NAME"), "COL2");
assertEquals(rs.getInt("DATA_TYPE"), Types.VARCHAR);
assertFalse(rs.next());
}
@Test
public void columnOrderOfgetPrimaryKeys() throws Exception {
ResultSet rs;
ResultSetMetaData rsmeta;
stat.executeUpdate("create table nopk (c1, c2, c3, c4);");
stat.executeUpdate("create table pk1 (col1 primary key, col2, col3);");
stat.executeUpdate("create table pk2 (col1, col2 primary key, col3);");
stat.executeUpdate("create table pk3 (col1, col2, col3, col4, primary key (col3, col2 ));");
// extra spaces and mixed case are intentional, do not remove!
stat.executeUpdate("create table pk4 (col1, col2, col3, col4, " +
"\r\nCONSTraint\r\nnamed primary\r\n\t\t key (col3, col2 ));");
// mixed-case table, column and primary key names - GitHub issue #219
stat.executeUpdate("CREATE TABLE Pk5 (Col1, Col2, Col3, Col4, CONSTRAINT NamedPk PRIMARY KEY (Col3, Col2));");
// quoted table, column and primary key names - GitHub issue #219
stat.executeUpdate("CREATE TABLE `Pk6` (`Col1`, `Col2`, `Col3`, `Col4`, CONSTRAINT `NamedPk` PRIMARY KEY (`Col3`, `Col2`));");
// spaces before and after "primary key" - GitHub issue #236
stat.executeUpdate("CREATE TABLE pk7 (col1, col2, col3, col4 VARCHAR(10),PRIMARY KEY (col1, col2, col3));");
stat.executeUpdate("CREATE TABLE pk8 (col1, col2, col3, col4 VARCHAR(10), PRIMARY KEY(col1, col2, col3));");
stat.executeUpdate("CREATE TABLE pk9 (col1, col2, col3, col4 VARCHAR(10),PRIMARY KEY(col1, col2, col3));");
stat.executeUpdate("CREATE TABLE `Pk10` (`Col1`, `Col2`, `Col3`, `Col4`, CONSTRAINT `NamedPk`PRIMARY KEY (`Col3`, `Col2`));");
stat.executeUpdate("CREATE TABLE `Pk11` (`Col1`, `Col2`, `Col3`, `Col4`, CONSTRAINT `NamedPk` PRIMARY KEY(`Col3`, `Col2`));");
stat.executeUpdate("CREATE TABLE `Pk12` (`Col1`, `Col2`, `Col3`, `Col4`, CONSTRAINT`NamedPk`PRIMARY KEY(`Col3`,`Col2`));");
stat.executeUpdate("CREATE TABLE \"Pk13\" (\"Col1\", \"Col2\", \"Col3\", \"Col4\", CONSTRAINT \"NamedPk\" PRIMARY KEY(\"Col3\",\"Col2\"));");
stat.executeUpdate("CREATE TABLE \"Pk14\" (\"Col1\", \"Col2\", \"Col3\", \"Col4\", PRIMARY KEY(\"Col3\"), FOREIGN KEY (\"Col1\") REFERENCES \"pk1\" (\"col1\"))");
stat.executeUpdate("CREATE TABLE \"Pk15\" (\"Col1\", \"Col2\", \"Col3\", \"Col4\", PRIMARY KEY(\"Col3\", \"Col2\"), FOREIGN KEY (\"Col1\") REFERENCES \"pk1\" (\"col1\"))");
rs = meta.getPrimaryKeys(null, null, "nopk");
assertFalse(rs.next());
rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 6);
assertEquals(rsmeta.getColumnName(1), "TABLE_CAT");
assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TABLE_NAME");
assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME");
assertEquals(rsmeta.getColumnName(5), "KEY_SEQ");
assertEquals(rsmeta.getColumnName(6), "PK_NAME");
rs.close();
assertPrimaryKey(meta, "pk1", null, "col1");
assertPrimaryKey(meta, "pk2", null, "col2");
assertPrimaryKey(meta, "pk3", null, "col3", "col2");
assertPrimaryKey(meta, "pk4", "named", "col3", "col2");
assertPrimaryKey(meta, "Pk5", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "Pk6", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "pk7", null, "col1", "col2", "col3");
assertPrimaryKey(meta, "pk8", null, "col1", "col2", "col3");
assertPrimaryKey(meta, "pk9", null, "col1", "col2", "col3");
assertPrimaryKey(meta, "Pk10", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "Pk11", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "Pk12", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "Pk13", "NamedPk", "Col3", "Col2");
assertPrimaryKey(meta, "Pk14", null, "Col3");
assertPrimaryKey(meta, "Pk15", null, "Col3", "Col2");
}
private void assertPrimaryKey(DatabaseMetaData meta, String tableName, String pkName, String... pkColumns) throws Exception {
final Map<String, Integer> colSeq = new HashMap<String, Integer>();
for (int i = 0; i < pkColumns.length; i++) {
colSeq.put(pkColumns[i], i+1);
}
Arrays.sort(pkColumns);
final ResultSet rs = meta.getPrimaryKeys(null, null, tableName);
assertTrue(rs.next());
for (int i = 0; i < pkColumns.length; i++) {
assertEquals("DatabaseMetaData.getPrimaryKeys: TABLE_CAT", null, rs.getString("TABLE_CAT"));
assertEquals("DatabaseMetaData.getPrimaryKeys: TABLE_SCHEM", null, rs.getString("TABLE_SCHEM"));
assertEquals("DatabaseMetaData.getPrimaryKeys: TABLE_NAME", tableName, rs.getString("TABLE_NAME"));
assertEquals("DatabaseMetaData.getPrimaryKeys: COLUMN_NAME", pkColumns[i], rs.getString("COLUMN_NAME"));
assertEquals("DatabaseMetaData.getPrimaryKeys: PK_NAME", pkName, rs.getString("PK_NAME"));
assertEquals("DatabaseMetaData.getPrimaryKeys: KEY_SEQ", colSeq.get(pkColumns[i]).intValue(), rs.getInt("KEY_SEQ"));
if (i < pkColumns.length - 1) assertTrue(rs.next());
}
assertFalse(rs.next());
rs.close();
}
@Test
public void columnOrderOfgetImportedKeys() throws SQLException {
stat.executeUpdate("create table person (id integer)");
stat.executeUpdate("create table address (pid integer, name, foreign key(pid) references person(id))");
ResultSet importedKeys = meta.getImportedKeys("default", "global", "address");
assertTrue(importedKeys.next());
assertEquals("default", importedKeys.getString("PKTABLE_CAT"));
assertEquals("global", importedKeys.getString("PKTABLE_SCHEM"));
assertEquals("default", importedKeys.getString("FKTABLE_CAT"));
assertEquals("person", importedKeys.getString("PKTABLE_NAME"));
assertEquals("id", importedKeys.getString("PKCOLUMN_NAME"));
assertNotNull(importedKeys.getString("PK_NAME"));
assertNotNull(importedKeys.getString("FK_NAME"));
assertEquals("address", importedKeys.getString("FKTABLE_NAME"));
assertEquals("pid", importedKeys.getString("FKCOLUMN_NAME"));
importedKeys.close();
importedKeys = meta.getImportedKeys(null, null, "person");
assertTrue(!importedKeys.next());
importedKeys.close();
}
@Test
public void columnOrderOfgetExportedKeys() throws SQLException {
stat.executeUpdate("create table person (id integer primary key)");
stat.executeUpdate("create table address (pid integer, name, foreign key(pid) references person(id))");
ResultSet exportedKeys = meta.getExportedKeys("default", "global", "person");
assertTrue(exportedKeys.next());
assertEquals("default", exportedKeys.getString("PKTABLE_CAT"));
assertEquals("global", exportedKeys.getString("PKTABLE_SCHEM"));
assertEquals("default", exportedKeys.getString("FKTABLE_CAT"));
assertEquals("global", exportedKeys.getString("FKTABLE_SCHEM"));
assertNotNull(exportedKeys.getString("PK_NAME"));
assertNotNull(exportedKeys.getString("FK_NAME"));
assertEquals("person", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("id", exportedKeys.getString("PKCOLUMN_NAME"));
assertEquals("address", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("pid", exportedKeys.getString("FKCOLUMN_NAME"));
exportedKeys.close();
exportedKeys = meta.getExportedKeys(null, null, "address");
assertFalse(exportedKeys.next());
exportedKeys.close();
// With explicit primary column defined.
stat.executeUpdate("create table REFERRED (ID integer primary key not null)");
stat.executeUpdate("create table REFERRING (ID integer, RID integer, constraint fk\r\n foreign\tkey\r\n(RID) references REFERRED(id))");
exportedKeys = meta.getExportedKeys(null, null, "referred");
assertEquals("REFERRED", exportedKeys.getString("PKTABLE_NAME"));
assertEquals("REFERRING", exportedKeys.getString("FKTABLE_NAME"));
assertEquals("fk", exportedKeys.getString("FK_NAME"));
exportedKeys.close();
}
@Test
public void columnOrderOfgetCrossReference() throws SQLException {
stat.executeUpdate("create table person (id integer)");
stat.executeUpdate("create table address (pid integer, name, foreign key(pid) references person(id))");
ResultSet cr = meta.getCrossReference(null, null, "person", null, null, "address");
//assertTrue(cr.next());
}
/* TODO
@Test public void columnOrderOfgetTypeInfo() throws SQLException {
@Test public void columnOrderOfgetIndexInfo() throws SQLException {
@Test public void columnOrderOfgetSuperTypes() throws SQLException {
@Test public void columnOrderOfgetSuperTables() throws SQLException {
@Test public void columnOrderOfgetAttributes() throws SQLException {*/
@Test
public void columnOrderOfgetUDTs() throws SQLException {
ResultSet rs = meta.getUDTs(null, null, null, null);
assertFalse(rs.next());
ResultSetMetaData rsmeta = rs.getMetaData();
assertEquals(rsmeta.getColumnCount(), 7);
assertEquals(rsmeta.getColumnName(1), "TYPE_CAT");
assertEquals(rsmeta.getColumnName(2), "TYPE_SCHEM");
assertEquals(rsmeta.getColumnName(3), "TYPE_NAME");
assertEquals(rsmeta.getColumnName(4), "CLASS_NAME");
assertEquals(rsmeta.getColumnName(5), "DATA_TYPE");
assertEquals(rsmeta.getColumnName(6), "REMARKS");
assertEquals(rsmeta.getColumnName(7), "BASE_TYPE");
}
@Test
public void getIndexInfoOnTest() throws SQLException {
ResultSet rs = meta.getIndexInfo(null,null,"test",false,false);
assertNotNull(rs);
}
@Test
public void getIndexInfoIndexedSingle() throws SQLException {
stat.executeUpdate("create table testindex (id integer primary key, fn float default 0.0, sn not null);");
stat.executeUpdate("create index testindex_idx on testindex (sn);");
ResultSet rs = meta.getIndexInfo(null,null,"testindex",false,false);
ResultSetMetaData rsmd = rs.getMetaData();
assertNotNull(rs);
assertNotNull(rsmd);
}
@Test
public void getIndexInfoIndexedSingleExpr() throws SQLException {
stat.executeUpdate("create table testindex (id integer primary key, fn float default 0.0, sn not null);");
stat.executeUpdate("create index testindex_idx on testindex (sn, fn/2);");
ResultSet rs = meta.getIndexInfo(null,null,"testindex",false,false);
ResultSetMetaData rsmd = rs.getMetaData();
assertNotNull(rs);
assertNotNull(rsmd);
}
@Test
public void getIndexInfoIndexedMulti() throws SQLException {
stat.executeUpdate("create table testindex (id integer primary key, fn float default 0.0, sn not null);");
stat.executeUpdate("create index testindex_idx on testindex (sn);");
stat.executeUpdate("create index testindex_pk_idx on testindex (id);");
ResultSet rs = meta.getIndexInfo(null,null,"testindex",false,false);
ResultSetMetaData rsmd = rs.getMetaData();
assertNotNull(rs);
assertNotNull(rsmd);
}
@Test
public void version() throws Exception {
File versionFile = new File("./VERSION");
Properties version = new Properties();
version.load(new FileReader(versionFile));
String versionString = version.getProperty("version");
int majorVersion = Integer.valueOf(versionString.split("\\.")[0]);
int minorVersion = Integer.valueOf(versionString.split("\\.")[1]);
assertTrue("major version check", majorVersion > 0);
assertEquals("driver name","SQLite JDBC", meta.getDriverName());
assertTrue("driver version", meta.getDriverVersion().startsWith(String.format("%d.%d", majorVersion, minorVersion)));
assertEquals("driver major version", majorVersion, meta.getDriverMajorVersion());
assertEquals("driver minor version", minorVersion, meta.getDriverMinorVersion());
assertEquals("db name","SQLite", meta.getDatabaseProductName());
assertEquals("db version", versionString, meta.getDatabaseProductVersion());
assertEquals("db major version", majorVersion, meta.getDatabaseMajorVersion());
assertEquals("db minor version", minorVersion, meta.getDatabaseMinorVersion());
assertEquals("user name", null, meta.getUserName());
}
}
|
package com.zblog.core.tag;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import com.zblog.core.plugin.PageModel;
/**
* 灵活的分页标签,使用方法:
*
* <pre>
* <page:page model="${requestPageAttr}" pageUrl="." showPage="8">
* <page:first>
* somehtml,${pageUrl}-${pageNumber}
* </page:first>
* <page:prev>
* somehtml,${pageUrl}-${pageNumber}
* </page:prev>
* <page:pager>
* <c:choose>
* <c:when test='${dot}'>
* ...
* </c:when>
* <c:when test='${pageNumber==page.pageIndex}'>
* currentIndex,${pageUrl}-${pageNumber}
* </c:when>
* <c:otherwise>
* somehtml,${pageUrl}-${pageNumber}
* </c:otherwise>
* </c:choose>
* </page:pager>
* <page:next>
* somehtml,${pageUrl}-${pageNumber}
* </page:next>
* <page:last>
* somehtml,${pageUrl}-${pageNumber}
* </page:last>
* </page:page>
* </pre>
*
* @author zhou
*
*/
public class Pagination<T> extends TagSupport{
private static final long serialVersionUID = 1L;
private static final int SHOW_PAGE = 10;
// 页面访问参数如/user/product
private String pageUrl;
private PageModel<T> model;
// 显示几个页脚
private int showPage = SHOW_PAGE;
// 最左最右保留几个页脚
private int boundary = 0;
public void setPageUrl(String pageUrl){
this.pageUrl = pageUrl;
}
String getPageUrl(){
return pageUrl;
}
public void setModel(PageModel<T> model){
this.model = model;
}
PageModel<T> getModel(){
return model;
}
public void setShowPage(int showPage){
this.showPage = showPage < 2 ? SHOW_PAGE : showPage;
}
int getShowPage(){
return showPage;
}
public void setBoundary(int boundary){
this.boundary = boundary < 0 ? 0 : boundary;
}
int getBoundary(){
return boundary;
}
@Override
public int doStartTag() throws JspException{
if(model.getTotalPage() < 2)
return TagSupport.SKIP_BODY;
this.pageUrl = genPageUrl();
return TagSupport.EVAL_BODY_INCLUDE;
}
private String genPageUrl(){
String result = pageUrl;
Map<String, Object> query = model.getQuery();
if(query != null && !query.isEmpty()){
result += "?";
for(Map.Entry<String, Object> entry : query.entrySet()){
result += entry.getKey() + "=" + entry.getValue() + "&";
}
result += "page=";
}else{
result += "?page=";
}
return result;
}
}
|
/*
* Copyright (c) 2019, 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 io.cellery.observability.api.exception;
/**
* Internal generic error in the OIDC Manager.
*/
public class OIDCProviderException extends Exception {
public OIDCProviderException(String message, Throwable e) {
super(message, e);
}
public OIDCProviderException(String message) {
super(message);
}
}
|
package org.hl7.davinci.endpoint;
import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.hl7.davinci.endpoint.config.CdsConnect;
import org.hl7.davinci.endpoint.config.GitHubConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class YamlConfig {
// Any property can be read from the .yml resource file
// in this class. Ignoring dashes, variables will map to
// properties of the same name automatically.
@Autowired
Environment env;
private boolean checkJwt;
private URI launchUrl;
private boolean includeFilepathInAppContext;
private boolean checkPractitionerLocation;
private boolean appendParamsToSmartLaunchUrl;
private String hostOrg;
private CdsConnect cdsConnect;
private GitHubConfig gitHubConfig;
private String localDbRules;
private String localDbFhirArtifacts;
public String getLocalDbFhirArtifacts() {
return localDbFhirArtifacts;
}
public void setLocalDbFhirArtifacts(String localDbFhirArtifacts) {
this.localDbFhirArtifacts = localDbFhirArtifacts;
}
public boolean getCheckJwt() {
return checkJwt;
}
public URI getLaunchUrl() { return launchUrl; }
public boolean getIncludeFilepathInAppContext() { return includeFilepathInAppContext; }
public void setCheckJwt(boolean check) { checkJwt = check; }
public void setLaunchUrl(URI launch) { launchUrl = launch; }
public YamlConfig setIncludeFilepathInAppContext(boolean includeFilepathInAppContext) {
this.includeFilepathInAppContext = includeFilepathInAppContext;
return this;
}
public void setCheckPractitionerLocation(boolean checkPractitionerLocation) {
this.checkPractitionerLocation = checkPractitionerLocation;
}
public boolean isCheckPractitionerLocation() {
return checkPractitionerLocation;
}
public String getLocalDbRules() { return localDbRules; }
public void setLocalDbRules(String localDbRules) { this.localDbRules = localDbRules; }
public boolean isAppendParamsToSmartLaunchUrl() {
return appendParamsToSmartLaunchUrl;
}
public YamlConfig setAppendParamsToSmartLaunchUrl(boolean appendParamsToSmartLaunchUrl) {
this.appendParamsToSmartLaunchUrl = appendParamsToSmartLaunchUrl;
return this;
}
public String getContextPath(){
return env.getProperty("server.servlet.contextPath");
}
public String getHostOrg() {return hostOrg;}
public void setHostOrg(String org) {this.hostOrg = org;}
public CdsConnect getCdsConnect() { return cdsConnect; }
public void setCdsConnect(CdsConnect cdsConnect) { this.cdsConnect = cdsConnect; }
public GitHubConfig getGitHubConfig() { return gitHubConfig; }
public void setGitHubConfig(GitHubConfig gitHubConfig) { this.gitHubConfig = gitHubConfig; }
}
|
import java.util.ArrayList;
public class main {
public static void main(String[] args) {
//print all solutions
for (int[] l : losungen()
) {
System.out.println("a: " + l[0] + "b: " + l[1] + "c: " + l[2] + "\n");
}
}
private static ArrayList<int[]> losungen() {
//create a list we want to save the solutions in
ArrayList<int[]> out = new ArrayList<>();
//loop through all possible inputs
for (int a = 0; a < 10; a++) {
for (int b = 0; b < 10; b++) {
for (int c = 0; c < 10; c++) {
//check if the formula is satisfied by the input
if (((a * 100 + b * 10 + c) * 3 == c * 100 + b * 10 + a) && a != b && b != c && c != a) {
//if yes, add the values to the solution
int[] add = {a, b, c};
out.add(add);
}
}
}
}
System.out.println("\nThere are " + out.size() + " Solutions.");
return out;
}
}
|
package io.github.syst3ms.skriptparser.parsing;
import io.github.syst3ms.skriptparser.event.TriggerContext;
import io.github.syst3ms.skriptparser.lang.Expression;
import io.github.syst3ms.skriptparser.log.SkriptLogger;
import io.github.syst3ms.skriptparser.pattern.PatternElement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
/**
* A parser instance used for matching a pattern to a syntax
*/
public class MatchContext {
private String originalPattern;
public PatternElement originalElement;
// Provided to the syntax's class
private final Class<? extends TriggerContext>[] currentContext;
private final SkriptLogger logger;
private List<Expression<?>> parsedExpressions = new ArrayList<>();
private List<MatchResult> regexMatches = new ArrayList<>();
private int patternIndex = 0;
private int parseMark = 0;
public MatchContext(PatternElement e, Class<? extends TriggerContext>[] currentContext, SkriptLogger logger) {
this.originalPattern = e.toString();
this.originalElement = e;
this.currentContext = currentContext;
this.logger = logger;
}
public PatternElement getOriginalElement() {
return originalElement;
}
public String getOriginalPattern() {
return originalPattern;
}
public int getPatternIndex() {
return patternIndex;
}
public void advanceInPattern() {
patternIndex++;
}
public List<Expression<?>> getParsedExpressions() {
return parsedExpressions;
}
public void addExpression(Expression<?> expression) {
parsedExpressions.add(expression);
}
public void addRegexMatch(MatchResult match) {
regexMatches.add(match);
}
public int getParseMark() {
return parseMark;
}
public void addMark(int mark) {
parseMark ^= mark;
}
/**
* Turns this {@link MatchContext} into a {@link ParseContext} used in {@linkplain io.github.syst3ms.skriptparser.lang.SyntaxElement}s
* @return a {@link ParseContext} based on this {@link MatchContext}
*/
public ParseContext toParseResult() {
return new ParseContext(currentContext, originalElement, regexMatches, parseMark, originalPattern, logger);
}
public SkriptLogger getLogger() {
return logger;
}
}
|
package it.polito.ai.lab4.web.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
private static final long serialVersionUID = 1237345251251466177L;
}
|
/**
* 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.ambari.log4j.hadoop.mapreduce.jobhistory;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.ambari.log4j.common.LogParser;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.tools.rumen.Hadoop20JHParser;
import org.apache.hadoop.tools.rumen.JobHistoryParser;
import org.apache.hadoop.util.LineReader;
import org.apache.log4j.spi.LoggingEvent;
public class MapReduceJobHistoryParser implements LogParser {
private JobHistoryParser parser;
private LogLineReader reader = new LogLineReader("Meta VERSION=\"1\" .");
public MapReduceJobHistoryParser() {
try {
parser = new Hadoop20JHParser(reader);
} catch (IOException ioe) {
// SHOULD NEVER HAPPEN!
throw new RuntimeException(ioe);
}
}
@Override
public void addEventToParse(LoggingEvent event) {
reader.addLine(event.getMessage().toString());
}
@Override
public Object getParseResult() throws IOException {
return parser.nextEvent();
}
static class LogLineReader extends LineReader {
private Queue<String> lines = new LinkedBlockingQueue<String>();
public LogLineReader(String line) {
super(null);
addLine(line);
}
private void addLine(String line) {
lines.add(line);
}
public int readLine(Text str) throws IOException {
String line = lines.poll();
if (line != null) {
str.set(line);
return line.length();
}
return 0;
}
public void close() throws IOException {
}
}
}
|
package io.datajuice.nifi.processors;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.processor.*;
import org.apache.nifi.processor.exception.ProcessException;
import java.util.*;
import static io.datajuice.nifi.processors.Relationships.*;
import static io.datajuice.nifi.processors.utils.ProfileManager.profileManager;
import static org.apache.nifi.flowfile.attributes.CoreAttributes.MIME_TYPE;
public class DataProfiler extends AbstractProcessor {
// TODO analysis to understand what properties would be useful Initial thoughts
// 1) A config that tells exactly what type each column is. Could work off of something like filename,
// to allow for multiple mappings to live in single file OR make a user route on that attribute before hand
// 2) Config that tells each profiler what columns to profile
private List<PropertyDescriptor> properties;
private Set<Relationship> relationships;
@Override
public void init(final ProcessorInitializationContext context){
List<PropertyDescriptor> properties = new ArrayList<>();
this.properties = Collections.unmodifiableList(properties);
Set<Relationship> relationships = new HashSet<>();
relationships.add(SUCCESS);
relationships.add(FAILURE);
this.relationships = Collections.unmodifiableSet(relationships);
}
@Override
public Set<Relationship> getRelationships() {
return this.relationships;
}
@Override
public void onTrigger(ProcessContext context, final ProcessSession session)
throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
// TODO add ability to write bad records to a separate file
try{
FlowFile newFlowFile = profileManager(session, flowFile);
session.putAttribute(newFlowFile, CoreAttributes.MIME_TYPE.key(), "application/avro+binary");
session.transfer(newFlowFile, SUCCESS);
session.remove(flowFile);
} catch (Exception e){
session.transfer(flowFile, FAILURE);
}
}
}
|
package exnihilocreatio.handlers;
import exnihilocreatio.config.ModConfig;
import exnihilocreatio.registries.manager.ExNihiloRegistryManager;
import exnihilocreatio.registries.types.CrookReward;
import exnihilocreatio.util.ItemUtil;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLeaves;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.List;
public class HandlerCrook {
@SubscribeEvent(priority = EventPriority.LOWEST)
public void crook(BlockEvent.HarvestDropsEvent event) {
if (event.getWorld().isRemote)
return;
if (event.getHarvester() == null)
return;
if (event.isSilkTouching())
return;
ItemStack held = event.getHarvester().getHeldItemMainhand();
if (!ItemUtil.isCrook(held))
return;
List<CrookReward> rewards = ExNihiloRegistryManager.CROOK_REGISTRY.getRewards(event.getState());
if (rewards.size() > 0) {
event.getDrops().clear();
event.setDropChance(1f);
int fortune = event.getFortuneLevel();
for (CrookReward reward : rewards) {
if (event.getWorld().rand.nextFloat() <= reward.getChance() + (reward.getFortuneChance() * fortune)) {
event.getDrops().add(reward.getStack().copy());
}
}
}
if (event.getState().getBlock() instanceof BlockLeaves) //Simulate vanilla drops without firing event
{
for (int i = 0; i < ModConfig.crooking.numberOfTimesToTestVanillaDrops + 1; i++) {
Block block = event.getState().getBlock();
int fortune = event.getFortuneLevel();
@SuppressWarnings("deprecation")
java.util.List<ItemStack> items = block.getDrops(event.getWorld(), event.getPos(), event.getState(), fortune);
for (ItemStack item : items) {
if (event.getWorld().rand.nextFloat() <= event.getDropChance()) {
Block.spawnAsEntity(event.getWorld(), event.getPos(), item);
}
}
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.query.internal.parse;
import antlr.Token;
import org.apache.geode.cache.query.internal.QCompiler;
public class ASTLimit extends GemFireAST {
public ASTLimit() {}
/** Creates a new instance of ASTSortCriterion */
public ASTLimit(Token t) {
super(t);
}
@Override
public void compile(QCompiler compiler) {
super.compile(compiler);
compiler.compileLimit(getText());
}
}
|
package artifacts.common.item;
import artifacts.client.render.model.curio.DrinkingHatModel;
import artifacts.common.config.Config;
import artifacts.common.init.ModItems;
import net.minecraft.client.renderer.entity.model.BipedModel;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.UseAction;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent;
import top.theillusivec4.curios.api.SlotContext;
import top.theillusivec4.curios.api.type.capability.ICurio;
import java.util.List;
public class DrinkingHatItem extends CurioItem {
private final ResourceLocation texture;
public DrinkingHatItem(ResourceLocation texture) {
this.texture = texture;
addListener(LivingEntityUseItemEvent.Start.class, this::onItemUseStart);
}
@Override
@OnlyIn(Dist.CLIENT)
public void addInformation(ItemStack stack, World world, List<ITextComponent> tooltip, ITooltipFlag flags) {
if (Config.showTooltips) {
if (this != ModItems.PLASTIC_DRINKING_HAT.get()) {
tooltip.add(new TranslationTextComponent(ModItems.PLASTIC_DRINKING_HAT.get().getTranslationKey() + ".tooltip").mergeStyle(TextFormatting.GRAY));
}
}
super.addInformation(stack, world, tooltip, flags);
}
public void onItemUseStart(LivingEntityUseItemEvent.Start event) {
if (event.getItem().getUseAction() == UseAction.DRINK) {
event.setDuration(event.getDuration() / 4);
}
}
@Override
public ICurio.SoundInfo getEquipSound(SlotContext slotContext, ItemStack stack) {
return new ICurio.SoundInfo(SoundEvents.ITEM_ARMOR_EQUIP_LEATHER, 1, 1);
}
protected SoundEvent getEquipSound() {
return SoundEvents.ITEM_BOTTLE_FILL;
}
@Override
@OnlyIn(Dist.CLIENT)
protected BipedModel<LivingEntity> createModel() {
return new DrinkingHatModel();
}
@Override
protected ResourceLocation getTexture() {
return texture;
}
}
|
/*
* Copyright (c) 2009-2018, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT 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.
*/
/*
Copyright (c) 2010, NHIN Direct Project
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the The NHIN Direct Project (nhindirect.org) nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.directconfig.service.jaxws;
import gov.hhs.fha.nhinc.directconfig.service.helpers.CertificateGetOptions;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "getIncomingAnchors", namespace = "http://nhind.org/config")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getIncomingAnchors", namespace = "http://nhind.org/config", propOrder = {
"owner",
"options"
})
public class GetIncomingAnchors {
@XmlElement(name = "owner", namespace = "")
private String owner;
@XmlElement(name = "options", namespace = "")
private CertificateGetOptions options;
/**
*
* @return
* returns String
*/
public String getOwner() {
return this.owner;
}
/**
*
* @param owner
* the value for the owner property
*/
public void setOwner(String owner) {
this.owner = owner;
}
/**
*
* @return
* returns CertificateGetOptions
*/
public CertificateGetOptions getOptions() {
return this.options;
}
/**
*
* @param options
* the value for the options property
*/
public void setOptions(CertificateGetOptions options) {
this.options = options;
}
}
|
package com.zuba.dao;
public class FileUrlDao {
StringBuffer stringBuffer = new StringBuffer();
private static final FileUrlDao single = new FileUrlDao();
// 静态工厂方法
public static FileUrlDao getInstance() {
return single;
}
public void getFileUrl(String string) {
stringBuffer.append(string + "|");
System.out.println(stringBuffer.toString());
}
}
|
package textgen;
import java.util.*;
/**
* An implementation of the MTG interface that uses a list of lists.
* @author UC San Diego Intermediate Programming MOOC team
*/
public class MarkovTextGeneratorLoL implements MarkovTextGenerator {
// The list of words with their next words
private List<ListNode> wordList;
// The starting "word"
private String starter;
// The random number generator
private Random rnGenerator;
// Mapping of word to ListNode representing it
Map<String, ListNode> wordListNodeMap;
public MarkovTextGeneratorLoL(Random generator)
{
wordList = new LinkedList<ListNode>();
starter = "";
rnGenerator = generator;
wordListNodeMap = new HashMap<String, ListNode>();
}
/** Train the generator by adding the sourceText */
@Override
public void train(String sourceText)
{
// TODO: Implement this method
String[] sourceWords = sourceText.split("[\\s]+");
if((wordListNodeMap.isEmpty() && wordList.size() == 0)) //if not trained only then set starter
starter = sourceWords[0];
int i = 0;
for(i = 0; i < sourceWords.length - 1 ; i++) {
updateTrainDS(sourceWords[i], sourceWords[i+1]);
}
updateTrainDS(sourceWords[i], starter);
}
/**
* Generate the number of words requested.
*/
@Override
public String generateText(int numWords) {
// TODO: Implement this method
if((wordListNodeMap.isEmpty() && wordList.size() == 0) || numWords == 0) //if not trained or num words requested is 0
return "";
int count = 0;
StringBuilder generatedText = new StringBuilder();
String currentWord = starter;
String nextWord = null;
generatedText.append(currentWord + ' ');
count += 1;
while(count < numWords) {
nextWord = wordListNodeMap.get(currentWord).getRandomNextWord(rnGenerator);
generatedText.append(nextWord + ' ');
count += 1;
currentWord = nextWord;
}
return generatedText.toString();
}
// Can be helpful for debugging
@Override
public String toString()
{
StringBuilder toReturn = new StringBuilder();
for (ListNode n : wordList)
{
toReturn.append(n.toString());
}
return toReturn.toString();
}
/** Retrain the generator from scratch on the source text */
@Override
public void retrain(String sourceText)
{
// TODO: Implement this method.
wordList = new LinkedList<ListNode>();
wordListNodeMap = new HashMap<String, ListNode>();
train(sourceText);
}
// TODO: Add any private helper methods you need here.
private void updateTrainDS(String currentWord, String nextWord) {
ListNode listNode = null;
if(wordListNodeMap.containsKey(currentWord)) {
listNode = wordListNodeMap.get(currentWord);
} else {
listNode = new ListNode(currentWord);
wordListNodeMap.put(currentWord, listNode);
wordList.add(listNode);
}
listNode.addNextWord(nextWord);
}
/**
* This is a minimal set of tests. Note that it can be difficult
* to test methods/classes with randomized behavior.
* @param args
*/
public static void main(String[] args)
{
// feed the generator a fixed random value for repeatable behavior
MarkovTextGeneratorLoL gen = new MarkovTextGeneratorLoL(new Random(42));
String textString = "Hello. Hello there. This is a test. Hello there. Hello Bob. Test again.";
System.out.println(textString);
gen.train(textString);
System.out.println(gen);
System.out.println(gen.generateText(20));
String textString2 = "You say yes, I say no, "+
"You say stop, and I say go, go, go, "+
"Oh no. You say goodbye and I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello. "+
"I say high, you say low, "+
"You say why, and I say I don't know. "+
"Oh no. "+
"You say goodbye and I say hello, hello, hello. "+
"I don't know why you say goodbye, I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello. "+
"Why, why, why, why, why, why, "+
"Do you say goodbye. "+
"Oh no. "+
"You say goodbye and I say hello, hello, hello. "+
"I don't know why you say goodbye, I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello. "+
"You say yes, I say no, "+
"You say stop and I say go, go, go. "+
"Oh, oh no. "+
"You say goodbye and I say hello, hello, hello. "+
"I don't know why you say goodbye, I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello, hello, hello, "+
"I don't know why you say goodbye, I say hello, hello, hello,";
System.out.println(textString2);
gen.retrain(textString2);
System.out.println(gen);
System.out.println(gen.generateText(20));
}
}
/** Links a word to the next words in the list
* You should use this class in your implementation. */
class ListNode
{
// The word that is linking to the next words
private String word;
// The next words that could follow it
private List<String> nextWords;
ListNode(String word)
{
this.word = word;
nextWords = new LinkedList<String>();
}
public String getWord()
{
return word;
}
public void addNextWord(String nextWord)
{
nextWords.add(nextWord);
}
public String getRandomNextWord(Random generator)
{
// TODO: Implement this method
// The random number generator should be passed from
// the MarkovTextGeneratorLoL class
return nextWords.get(generator.nextInt(nextWords.size()));
}
public String toString()
{
StringBuilder toReturn = new StringBuilder().append(word + ": ");
for (String s : nextWords) {
toReturn.append(s + "->");
}
toReturn.append("\n");
return toReturn.toString();
}
}
|
package wjy.morelove.bean;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 相册
* @author wjy
*/
public class Album implements Serializable{
private Integer id;
private String albumName;
private Date createDatetime;
private List<Photos> photosList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAlbumName() {
return albumName;
}
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public List<Photos> getPhotosList() {
return photosList;
}
public void setPhotosList(List<Photos> photosList) {
this.photosList = photosList;
}
}
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.dax.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dax-2017-04-19/DescribeSubnetGroups" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeSubnetGroupsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Provides an identifier to allow retrieval of paginated results.
* </p>
*/
private String nextToken;
/**
* <p>
* An array of subnet groups. Each element in the array represents a single subnet group.
* </p>
*/
private java.util.List<SubnetGroup> subnetGroups;
/**
* <p>
* Provides an identifier to allow retrieval of paginated results.
* </p>
*
* @param nextToken
* Provides an identifier to allow retrieval of paginated results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* Provides an identifier to allow retrieval of paginated results.
* </p>
*
* @return Provides an identifier to allow retrieval of paginated results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* Provides an identifier to allow retrieval of paginated results.
* </p>
*
* @param nextToken
* Provides an identifier to allow retrieval of paginated results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSubnetGroupsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* An array of subnet groups. Each element in the array represents a single subnet group.
* </p>
*
* @return An array of subnet groups. Each element in the array represents a single subnet group.
*/
public java.util.List<SubnetGroup> getSubnetGroups() {
return subnetGroups;
}
/**
* <p>
* An array of subnet groups. Each element in the array represents a single subnet group.
* </p>
*
* @param subnetGroups
* An array of subnet groups. Each element in the array represents a single subnet group.
*/
public void setSubnetGroups(java.util.Collection<SubnetGroup> subnetGroups) {
if (subnetGroups == null) {
this.subnetGroups = null;
return;
}
this.subnetGroups = new java.util.ArrayList<SubnetGroup>(subnetGroups);
}
/**
* <p>
* An array of subnet groups. Each element in the array represents a single subnet group.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSubnetGroups(java.util.Collection)} or {@link #withSubnetGroups(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param subnetGroups
* An array of subnet groups. Each element in the array represents a single subnet group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSubnetGroupsResult withSubnetGroups(SubnetGroup... subnetGroups) {
if (this.subnetGroups == null) {
setSubnetGroups(new java.util.ArrayList<SubnetGroup>(subnetGroups.length));
}
for (SubnetGroup ele : subnetGroups) {
this.subnetGroups.add(ele);
}
return this;
}
/**
* <p>
* An array of subnet groups. Each element in the array represents a single subnet group.
* </p>
*
* @param subnetGroups
* An array of subnet groups. Each element in the array represents a single subnet group.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeSubnetGroupsResult withSubnetGroups(java.util.Collection<SubnetGroup> subnetGroups) {
setSubnetGroups(subnetGroups);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getSubnetGroups() != null)
sb.append("SubnetGroups: ").append(getSubnetGroups());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeSubnetGroupsResult == false)
return false;
DescribeSubnetGroupsResult other = (DescribeSubnetGroupsResult) obj;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getSubnetGroups() == null ^ this.getSubnetGroups() == null)
return false;
if (other.getSubnetGroups() != null && other.getSubnetGroups().equals(this.getSubnetGroups()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getSubnetGroups() == null) ? 0 : getSubnetGroups().hashCode());
return hashCode;
}
@Override
public DescribeSubnetGroupsResult clone() {
try {
return (DescribeSubnetGroupsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
package com.volmit.react.util;
import org.bukkit.entity.LivingEntity;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Map;
/**
* Fast potion effects like this
* <br/>
* <br/>
* PE.HEAL.d(40).a(2).c(); >> PotionEffect (a = amp; d = dur; c = create)
* <br/>
* PE.HEAL.d(40).a(2).c(Player p) >> Apply potion effect;
*
* @author cyberpwn
*/
public class PE extends PotionEffect {
public static PE ABSORPTION;
public static PE BLINDNESS;
public static PE CONFUSION;
public static PE DAMAGE_RESISTANCE;
public static PE FAST_DIGGING;
public static PE FIRE_RESISTANCE;
public static PE GLOWING;
public static PE HARM;
public static PE HEAL;
public static PE HEALTH_BOOST;
public static PE HUNGER;
public static PE INCREASE_DAMAGE;
public static PE INVISIBILITY;
public static PE JUMP;
public static PE LEVITATION;
public static PE LUCK;
public static PE NIGHT_VISION;
public static PE POISON;
public static PE REGENERATION;
public static PE SATURATION;
public static PE SLOW;
public static PE SLOW_DIGGING;
public static PE SPEED;
public static PE UNLUCK;
public static PE WATER_BREATHING;
public static PE WEAKNESS;
public static PE WITHER;
static {
ABSORPTION = defaulted(PotionEffectType.ABSORPTION);
BLINDNESS = defaulted(PotionEffectType.BLINDNESS);
CONFUSION = defaulted(PotionEffectType.CONFUSION);
DAMAGE_RESISTANCE = defaulted(PotionEffectType.DAMAGE_RESISTANCE);
FAST_DIGGING = defaulted(PotionEffectType.FAST_DIGGING);
FIRE_RESISTANCE = defaulted(PotionEffectType.FIRE_RESISTANCE);
HARM = defaulted(PotionEffectType.HARM);
HEAL = defaulted(PotionEffectType.HEAL);
HEALTH_BOOST = defaulted(PotionEffectType.HEALTH_BOOST);
HUNGER = defaulted(PotionEffectType.HUNGER);
INCREASE_DAMAGE = defaulted(PotionEffectType.INCREASE_DAMAGE);
INVISIBILITY = defaulted(PotionEffectType.INVISIBILITY);
JUMP = defaulted(PotionEffectType.JUMP);
NIGHT_VISION = defaulted(PotionEffectType.NIGHT_VISION);
POISON = defaulted(PotionEffectType.POISON);
REGENERATION = defaulted(PotionEffectType.REGENERATION);
SATURATION = defaulted(PotionEffectType.SATURATION);
SLOW = defaulted(PotionEffectType.SLOW);
SLOW_DIGGING = defaulted(PotionEffectType.SLOW_DIGGING);
SPEED = defaulted(PotionEffectType.SPEED);
WATER_BREATHING = defaulted(PotionEffectType.WATER_BREATHING);
WEAKNESS = defaulted(PotionEffectType.WEAKNESS);
WITHER = defaulted(PotionEffectType.WITHER);
}
public PE(Map<String, Object> map) {
super(map);
}
public PE(PotionEffectType type, int duration, int amplifier, boolean ambient, boolean particles) {
super(type, duration, amplifier, ambient, particles);
}
public PE(PotionEffectType type, int duration, int amplifier, boolean ambient) {
super(type, duration, amplifier, ambient);
}
public PE(PotionEffectType type, int duration, int amplifier) {
super(type, duration, amplifier);
}
public static PE defaulted(PotionEffectType type) {
return new PE(type, 1, 0, false, false);
}
@Override
public Map<String, Object> serialize() {
return super.serialize();
}
@Override
public boolean apply(LivingEntity entity) {
entity.removePotionEffect(getType());
return super.apply(entity);
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int getAmplifier() {
return super.getAmplifier();
}
@Override
public int getDuration() {
return super.getDuration();
}
@Override
public PotionEffectType getType() {
return super.getType();
}
@Override
public boolean isAmbient() {
return super.isAmbient();
}
@Override
public boolean hasParticles() {
return super.hasParticles();
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
/**
* Set the potion duration
*
* @param duration the duration
* @return the new potion wrapper
*/
public PE d(int duration) {
return new PE(getType(), duration, getAmplifier(), false, false);
}
/**
* Set the potion amp
*
* @param amp the amp
* @return the new potion wrapper
*/
public PE a(int amp) {
return new PE(getType(), getDuration(), amp, false, false);
}
/**
* Create the effect
*
* @return the potion effect
*/
public PotionEffect c() {
return new PE(getType(), getDuration(), getAmplifier(), false, false);
}
/**
* Apply an effect to a player/entity
*
* @param l the living entity
*/
public void c(LivingEntity l) {
l.addPotionEffect(new PE(getType(), getDuration(), getAmplifier(), false, false).c());
}
public void crm(LivingEntity l) {
l.addPotionEffect(new PE(getType(), getDuration(), getAmplifier(), false, false).c(), true);
}
public void rm(LivingEntity l) {
l.removePotionEffect(getType());
}
}
|
/*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.pcap;
import io.netty.buffer.ByteBuf;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
final class PcapWriter implements Closeable {
/**
* Logger
*/
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PcapWriter.class);
/**
* {@link OutputStream} where we'll write Pcap data.
*/
private final OutputStream outputStream;
/**
* Set to {@code true} if {@link #outputStream} is closed.
*/
private boolean isClosed;
/**
* This uses {@link OutputStream} for writing Pcap.
* Pcap Global Header is not written on construction.
*/
PcapWriter(OutputStream outputStream) {
this.outputStream = outputStream;
}
/**
* This uses {@link OutputStream} for writing Pcap.
* Pcap Global Header is also written on construction.
*
* @throws IOException If {@link OutputStream#write(byte[])} throws an exception
*/
PcapWriter(OutputStream outputStream, ByteBuf byteBuf) throws IOException {
this.outputStream = outputStream;
PcapHeaders.writeGlobalHeader(byteBuf);
byteBuf.readBytes(outputStream, byteBuf.readableBytes());
}
/**
* Write Packet in Pcap OutputStream.
*
* @param packetHeaderBuf Packer Header {@link ByteBuf}
* @param packet Packet
* @throws IOException If {@link OutputStream#write(byte[])} throws an exception
*/
void writePacket(ByteBuf packetHeaderBuf, ByteBuf packet) throws IOException {
if (isClosed) {
logger.debug("Pcap Write attempted on closed PcapWriter");
}
long timestamp = System.currentTimeMillis();
PcapHeaders.writePacketHeader(
packetHeaderBuf,
(int) (timestamp / 1000L),
(int) (timestamp % 1000L * 1000L),
packet.readableBytes(),
packet.readableBytes()
);
packetHeaderBuf.readBytes(outputStream, packetHeaderBuf.readableBytes());
packet.readBytes(outputStream, packet.readableBytes());
}
@Override
public void close() throws IOException {
if (isClosed) {
logger.debug("PcapWriter is already closed");
} else {
isClosed = true;
outputStream.flush();
outputStream.close();
logger.debug("PcapWriter is now closed");
}
}
}
|
package com.alipay.api.response;
import java.util.List;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
import com.alipay.api.domain.FulfillmentResult;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: zhima.credit.ep.scene.fulfillmentlist.sync response.
*
* @author auto create
* @since 1.0, 2021-03-30 16:59:48
*/
public class ZhimaCreditEpSceneFulfillmentlistSyncResponse extends AlipayResponse {
private static final long serialVersionUID = 7499932921914862421L;
/**
* 履约同步结果列表
*/
@ApiListField("fulfillment_result_list")
@ApiField("fulfillment_result")
private List<FulfillmentResult> fulfillmentResultList;
public void setFulfillmentResultList(List<FulfillmentResult> fulfillmentResultList) {
this.fulfillmentResultList = fulfillmentResultList;
}
public List<FulfillmentResult> getFulfillmentResultList( ) {
return this.fulfillmentResultList;
}
}
|
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xmlobject.detailed;
import junit.framework.TestCase;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.PrintWriter;
import tools.util.ResourceUtil;
import tools.util.JarUtil;
import org.apache.xmlbeans.XmlBeans;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlCursor.TokenType;
import xmlcursor.common.Common;
import xmlobject.common.StringXmlReader;
/**
*
*
*/
public class TestXmlReader extends TestCase {
public TestXmlReader(String name) {
super(name);
}
/**
* Tests read-only concurrency support in XML Beans
* See Radar Bug: 33254
*/
public void testConcurrency() throws Exception {
// Get the file contents
String xmlFile = JarUtil.getResourceFromJar("xbean/xmlcursor/po.xml");
StringXmlReader rdr1 = new StringXmlReader(xmlFile);
StringXmlReader rdr2 = new StringXmlReader(xmlFile);
StringXmlReader rdr3 = new StringXmlReader(xmlFile);
Thread t1 = new Thread(rdr1, "Reader1");
Thread t2 = new Thread(rdr2, "Reader2");
Thread t3 = new Thread(rdr3, "Reader3");
t1.start();
t2.start();
t3.start();
// Wait for threads to finish
t1.join();
t2.join();
t3.join();
// Check the status of the XmlReaders
boolean status = rdr1.getStatus() & rdr2.getStatus() & rdr3.getStatus();
assertTrue("Concurrency Test Failed.", status);
}
public static void main(String args[]) throws Exception {
new TestXmlReader("Test").testConcurrency();
}
}
|
/*
* Copyright 2015 MovingBlocks
*
* 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.terasology.tasks.systems;
import org.terasology.utilities.Assets;
import org.terasology.entitySystem.entity.EntityManager;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterMode;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.logic.inventory.InventoryComponent;
import org.terasology.logic.inventory.InventoryManager;
import org.terasology.logic.inventory.ItemComponent;
import org.terasology.physics.events.CollideEvent;
import org.terasology.registry.In;
import org.terasology.tasks.components.QuestComponent;
import org.terasology.tasks.components.QuestListComponent;
/**
* TODO Type description
*/
@RegisterSystem(RegisterMode.AUTHORITY)
public class QuestPointSystem extends BaseComponentSystem {
@In
private InventoryManager inventoryManager;
@In
private EntityManager entityManager;
@ReceiveEvent(components = QuestListComponent.class)
public void onCollision(CollideEvent event, EntityRef questPoint) {
EntityRef charEnt = event.getOtherEntity();
InventoryComponent inventory = charEnt.getComponent(InventoryComponent.class);
if (inventory != null) {
for (EntityRef itemRef : inventory.itemSlots) {
QuestComponent quest = itemRef.getComponent(QuestComponent.class);
if (quest != null) {
return;
}
}
}
QuestListComponent comp = questPoint.getComponent(QuestListComponent.class);
for (String questItem : comp.questItems) {
Prefab prefab = Assets.getPrefab(questItem).get();
if (prefab.getComponent(ItemComponent.class) != null) {
EntityRef item = entityManager.create(prefab);
inventoryManager.giveItem(charEnt, questPoint, item);
}
}
}
}
|
/*
* Licensed to GraphHopper and Peter Karich under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.coll;
import java.util.BitSet;
/**
* @author Peter Karich
*/
public class GHBitSetImpl extends BitSet implements GHBitSet
{
public GHBitSetImpl()
{
}
public GHBitSetImpl( int nbits )
{
super(nbits);
}
@Override
public boolean contains( int index )
{
return super.get(index);
}
@Override
public void add( int index )
{
super.set(index);
}
@Override
public int getCardinality()
{
return super.cardinality();
}
@Override
public void ensureCapacity( int size )
{
}
@Override
public int next( int index )
{
return super.nextSetBit(index);
}
public int nextClear( int index )
{
return super.nextClearBit(index);
}
@Override
public GHBitSet copyTo( GHBitSet bs )
{
bs.clear();
if (bs instanceof GHBitSetImpl)
{
((GHBitSetImpl) bs).or(this);
} else
{
int len = size();
bs.ensureCapacity(len);
for (int index = super.nextSetBit(0); index >= 0;
index = super.nextSetBit(index + 1))
{
bs.add(index);
}
}
return bs;
}
}
|
package org.doraemon.component.security.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
/**
* @description: 描述
* @author: fengwenping
* @date: 2019/1/11 11:53
*/
@JsonIgnoreProperties(value = {"authorityResources"})
public class AuthorityOperationVO implements Serializable {
private String code;
private String desc;
private AuthorityResourceVO authorityResources;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public AuthorityResourceVO getAuthorityResources() {
return authorityResources;
}
public void setAuthorityResources(AuthorityResourceVO authorityResources) {
this.authorityResources = authorityResources;
}
}
|
package nl.homesensors.sensortag;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class SensorCodeTest {
@Test
void equals() {
EqualsVerifier.forClass(SensorCode.class).verify();
}
}
|
package uca.ruiz.antonio.tfgapp.data.api.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class Proceso implements Serializable {
private long id;
private String anamnesis;
private Diagnostico diagnostico;
private Procedimiento procedimiento;
private Paciente paciente;
private List<Cura> curas;
private String observaciones;
private Date creacion;
public Proceso() {
}
public Proceso(String anamnesis, Diagnostico diagnostico, Procedimiento procedimiento,
String observaciones, Paciente paciente) {
this.anamnesis = anamnesis;
this.diagnostico = diagnostico;
this.procedimiento = procedimiento;
this.observaciones = observaciones;
this.paciente = paciente;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAnamnesis() {
return anamnesis;
}
public void setAnamnesis(String anamnesis) {
this.anamnesis = anamnesis;
}
public Diagnostico getDiagnostico() {
return diagnostico;
}
public void setDiagnostico(Diagnostico diagnostico) {
this.diagnostico = diagnostico;
}
public List<Cura> getCuras() {
return curas;
}
public void setCuras(List<Cura> curas) {
this.curas = curas;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public Date getCreacion() {
return creacion;
}
public void setCreacion(Date creacion) {
this.creacion = creacion;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public Procedimiento getProcedimiento() {
return procedimiento;
}
public void setProcedimiento(Procedimiento procedimiento) {
this.procedimiento = procedimiento;
}
@Override
public String toString() {
return "Proceso{" +
"paciente=" + paciente +
", creacion=" + creacion +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Proceso proceso = (Proceso) o;
if (id != proceso.id) return false;
if (anamnesis != null ? !anamnesis.equals(proceso.anamnesis) : proceso.anamnesis != null)
return false;
if (diagnostico != null ? !diagnostico.equals(proceso.diagnostico) : proceso.diagnostico != null)
return false;
if (procedimiento != null ? !procedimiento.equals(proceso.procedimiento) : proceso.procedimiento != null)
return false;
if (paciente != null ? !paciente.equals(proceso.paciente) : proceso.paciente != null)
return false;
if (curas != null ? !curas.equals(proceso.curas) : proceso.curas != null) return false;
if (observaciones != null ? !observaciones.equals(proceso.observaciones) : proceso.observaciones != null)
return false;
return creacion != null ? creacion.equals(proceso.creacion) : proceso.creacion == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (anamnesis != null ? anamnesis.hashCode() : 0);
result = 31 * result + (diagnostico != null ? diagnostico.hashCode() : 0);
result = 31 * result + (procedimiento != null ? procedimiento.hashCode() : 0);
result = 31 * result + (paciente != null ? paciente.hashCode() : 0);
result = 31 * result + (curas != null ? curas.hashCode() : 0);
result = 31 * result + (observaciones != null ? observaciones.hashCode() : 0);
result = 31 * result + (creacion != null ? creacion.hashCode() : 0);
return result;
}
}
|
package com.joojet.plugins.mobs.equipment.chest;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.EquipmentSlot;
import com.joojet.plugins.mobs.enums.EquipmentType;
import com.joojet.plugins.mobs.equipment.Equipment;
public class DarkNetheriteChestplate extends Equipment
{
public DarkNetheriteChestplate (ChatColor color)
{
super (EquipmentType.DARK_NETHERITE_CHEST, Material.NETHERITE_CHESTPLATE, EquipmentSlot.CHEST, color);
this.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 4);
this.addUnsafeEnchantment(Enchantment.THORNS, 2);
this.addUnsafeEnchantment(Enchantment.DURABILITY, 3);
this.setDisplayName("Dark Netherite Chestpate");
}
}
|
package com.developerchen.blog.module.comment.web;
import com.developerchen.blog.module.comment.domain.entity.Comment;
import com.developerchen.blog.module.comment.service.ICommentService;
import com.developerchen.core.domain.RestResponse;
import com.developerchen.core.util.UserUtils;
import com.developerchen.core.web.BaseController;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 评论 前端控制器
* </p>
*
* @author syc
*/
@RestController
public class CommentController extends BaseController {
private final ICommentService commentService;
public CommentController(ICommentService commentService) {
this.commentService = commentService;
}
/**
* 回复评论
*
* @param comment 评论内容
*/
@PostMapping("/comments")
public RestResponse<?> reply(@Validated Comment comment,
BindingResult result) {
if (result.hasErrors()) {
return RestResponse.fail("回复失败!");
}
Long userId = getUserId();
Long authorId = comment.getAuthorId();
if (authorId == null && userId != null) {
comment.setAuthorId(userId);
}
comment.setIp(UserUtils.getRemoteIp(request));
comment.setAgent(UserUtils.getUserAgent(request));
commentService.replyComment(comment);
return RestResponse.ok();
}
}
|
package crc64a5a37c43dff01024;
public class ProgressRing
extends crc6485314a2a4d7fccfc.BindableProgressBar
implements
mono.android.IGCUserPeer
{
/** @hide */
public static final String __md_methods;
static {
__md_methods =
"n_dispatchTouchEvent:(Landroid/view/MotionEvent;)Z:GetDispatchTouchEvent_Landroid_view_MotionEvent_Handler\n" +
"n_onLayout:(ZIIII)V:GetOnLayout_ZIIIIHandler\n" +
"n_onInitializeAccessibilityNodeInfo:(Landroid/view/accessibility/AccessibilityNodeInfo;)V:GetOnInitializeAccessibilityNodeInfo_Landroid_view_accessibility_AccessibilityNodeInfo_Handler\n" +
"n_sendAccessibilityEvent:(I)V:GetSendAccessibilityEvent_IHandler\n" +
"";
mono.android.Runtime.register ("Windows.UI.Xaml.Controls.ProgressRing, Uno.UI", ProgressRing.class, __md_methods);
}
public ProgressRing (android.content.Context p0)
{
super (p0);
if (getClass () == ProgressRing.class)
mono.android.TypeManager.Activate ("Windows.UI.Xaml.Controls.ProgressRing, Uno.UI", "Android.Content.Context, Mono.Android", this, new java.lang.Object[] { p0 });
}
public ProgressRing (android.content.Context p0, android.util.AttributeSet p1)
{
super (p0, p1);
if (getClass () == ProgressRing.class)
mono.android.TypeManager.Activate ("Windows.UI.Xaml.Controls.ProgressRing, Uno.UI", "Android.Content.Context, Mono.Android:Android.Util.IAttributeSet, Mono.Android", this, new java.lang.Object[] { p0, p1 });
}
public ProgressRing (android.content.Context p0, android.util.AttributeSet p1, int p2)
{
super (p0, p1, p2);
if (getClass () == ProgressRing.class)
mono.android.TypeManager.Activate ("Windows.UI.Xaml.Controls.ProgressRing, Uno.UI", "Android.Content.Context, Mono.Android:Android.Util.IAttributeSet, Mono.Android:System.Int32, mscorlib", this, new java.lang.Object[] { p0, p1, p2 });
}
public ProgressRing (android.content.Context p0, android.util.AttributeSet p1, int p2, int p3)
{
super (p0, p1, p2, p3);
if (getClass () == ProgressRing.class)
mono.android.TypeManager.Activate ("Windows.UI.Xaml.Controls.ProgressRing, Uno.UI", "Android.Content.Context, Mono.Android:Android.Util.IAttributeSet, Mono.Android:System.Int32, mscorlib:System.Int32, mscorlib", this, new java.lang.Object[] { p0, p1, p2, p3 });
}
public boolean dispatchTouchEvent (android.view.MotionEvent p0)
{
return n_dispatchTouchEvent (p0);
}
private native boolean n_dispatchTouchEvent (android.view.MotionEvent p0);
public void onLayout (boolean p0, int p1, int p2, int p3, int p4)
{
n_onLayout (p0, p1, p2, p3, p4);
}
private native void n_onLayout (boolean p0, int p1, int p2, int p3, int p4);
public void onInitializeAccessibilityNodeInfo (android.view.accessibility.AccessibilityNodeInfo p0)
{
n_onInitializeAccessibilityNodeInfo (p0);
}
private native void n_onInitializeAccessibilityNodeInfo (android.view.accessibility.AccessibilityNodeInfo p0);
public void sendAccessibilityEvent (int p0)
{
n_sendAccessibilityEvent (p0);
}
private native void n_sendAccessibilityEvent (int p0);
private java.util.ArrayList refList;
public void monodroidAddReference (java.lang.Object obj)
{
if (refList == null)
refList = new java.util.ArrayList ();
refList.add (obj);
}
public void monodroidClearReferences ()
{
if (refList != null)
refList.clear ();
}
}
|
package com.bergerkiller.bukkit.common.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import org.objenesis.ObjenesisHelper;
import org.objenesis.instantiator.ObjectInstantiator;
import com.bergerkiller.bukkit.common.conversion.Converter;
import com.bergerkiller.bukkit.common.internal.CommonPlugin;
import com.bergerkiller.bukkit.common.reflection.SafeField;
import com.bergerkiller.bukkit.common.utils.CommonUtil;
/**
* Uses reflection to transfer/copy all the fields of a class
*/
public class ClassTemplate<T> {
private Class<T> type;
private List<SafeField<?>> fields;
private ObjectInstantiator instantiator;
/**
* Initializes a new ClassTemplate not pointing to any Class<br>
* Call setClass to define the Class to use
*/
public ClassTemplate() {
}
/**
* Initializes a new ClassTemplate pointing to the Class specified
*
* @param type of Class
*/
public ClassTemplate(Class<T> type) {
setClass(type);
}
/**
* Initializes this Class Template to represent the Class and fields of the type specified
*
* @param type to set the Class to
*/
protected void setClass(Class<T> type) {
this.type = type;
this.fields = null;
if (this.type == null) {
this.instantiator = null;
} else {
this.instantiator = ObjenesisHelper.getInstantiatorOf(type);
}
}
/**
* Gets the Class type represented by this Template
*
* @return Class type
*/
public Class<T> getType() {
return this.type;
}
/**
* Gets all the fields declared in this Class
*
* @return Declared fields
*/
public List<SafeField<?>> getFields() {
if (fields == null) {
if (type == null) {
fields = Collections.emptyList();
} else {
fields = Collections.unmodifiableList(fillFields(new ArrayList<SafeField<?>>(), type));
}
}
return fields;
}
/**
* Gets the field set at a specific index
*
* @param index to get the field at
* @return field at the index
* @throws IllegalArgumentException - If no field is at the index
*/
public SafeField<?> getFieldAt(int index) {
List<SafeField<?>> fields = getFields();
if (index < 0 || index >= fields.size()) {
throw new IllegalArgumentException("No field exists at index " + index);
}
return fields.get(index);
}
private static List<SafeField<?>> fillFields(List<SafeField<?>> fields, Class<?> clazz) {
if (clazz == null) {
return fields;
}
Field[] declared = clazz.getDeclaredFields();
ArrayList<SafeField<?>> newFields = new ArrayList<SafeField<?>>(declared.length);
for (Field field : declared) {
if (!Modifier.isStatic(field.getModifiers())) {
newFields.add(new SafeField<Object>(field));
}
}
fields.addAll(0, newFields);
return fillFields(fields, clazz.getSuperclass());
}
/**
* Gets a new instance of this Class, using the empty constructor
*
* @return A new instance, or null if an error occurred/empty constructor is not available
* @throws IllegalStateException if this ClassTemplate has no (valid) Class set
*/
public T newInstance() {
if (this.type == null) {
throw new IllegalStateException("Class was not found or is not set");
}
try {
return this.type.newInstance();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Gets a new instance of this Class without calling the Class Constructors.
* Calling this method will result in a new instance with all fields set to the default.
* That is, all fields will have 'NULL' values, or for primitives, 0/false/etc.
*
* @return a new Class Instance, or null upon failure
* @throws IllegalStateException if this ClassTemplate has no (valid) Class set
*/
@SuppressWarnings("unchecked")
public T newInstanceNull() {
if (this.instantiator == null) {
throw new IllegalStateException("Class was not found or is not set");
}
try {
return (T) this.instantiator.newInstance();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
/**
* Checks whether a given object is an instance of the class represented by this Template
*
* @param object to check
* @return True if the object is an instance, False if not
*/
public boolean isInstance(Object object) {
return this.type.isInstance(object);
}
/**
* Checks whether the specified clazz object can be assigned to the type represented
* by this ClassTemplate. This template taken as A, and clazz as B, this is equivalent to:<br>
* <b>B instanceof A</b>
*
* @param clazz to check
* @return True if the clazz can be assigned to this template type, False if not
*/
public boolean isAssignableFrom(Class<?> clazz) {
return this.type.isAssignableFrom(clazz);
}
/**
* Checks whether the object class equals the class represented by this Template
*
* @param object to check
* @return True if the object is a direct instance, False if not
*/
public boolean isType(Object object) {
return object != null && isType(object.getClass());
}
/**
* Checks whether a given class instance equals the class represented by this Template
*
* @param clazz to check
* @return True if the clazz is not null and equals the class of this template
*/
public boolean isType(Class<?> clazz) {
return clazz != null && this.type.equals(clazz);
}
/**
* Transfers all the fields from one class instance to the other
*
* @param from instance
* @param to instance
*/
public void transfer(Object from, Object to) {
for (FieldAccessor<?> field : this.getFields()) {
field.transfer(from, to);
}
}
/**
* Checks whether this Class Template is properly initialized and can be used
*
* @return True if this template is valid for use, False if not
*/
public boolean isValid() {
return this.type != null;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(500);
builder.append("Class path: ").append(this.getType().getName()).append('\n');
builder.append("Fields (").append(this.getFields().size()).append("):");
for (FieldAccessor<?> field : this.getFields()) {
builder.append("\n ").append(field.toString());
}
return builder.toString();
}
/**
* Attempts to find the constructor for this Class using the parameter types
*
* @param parameterTypes of the constructor
* @return Constructor
*/
public SafeConstructor<T> getConstructor(Class<?>... parameterTypes) {
return new SafeConstructor<T>(this.getType(), parameterTypes);
}
/**
* Attempts to find the field by name
*
* @param name of the field
* @return field
*/
public <K> SafeField<K> getField(String name) {
return new SafeField<K>(this.getType(), name);
}
/**
* Attempts to find the method by name
*
* @param name of the method
* @param parameterTypes of the method
* @return method
*/
public <K> SafeMethod<K> getMethod(String name, Class<?>... parameterTypes) {
return new SafeMethod<K>(this.getType(), name, parameterTypes);
}
/**
* Gets a statically declared field value
*
* @param name of the static field
* @return Static field value
*/
public <K> K getStaticFieldValue(String name) {
return SafeField.get(getType(), name);
}
/**
* Gets a statically declared field value and uses the
* converter to get the value.
*
* @param name of the static field
* @param converter to use
* @return Converted static field value
*/
public <K> K getStaticFieldValue(String name, Converter<K> converter) {
return converter.convert(getStaticFieldValue(name));
}
/**
* Sets a statically declared field value
*
* @param name of the static field
* @param value to set the static field to
*/
public <K> void setStaticFieldValue(String name, K value) {
SafeField.setStatic(getType(), name, value);
}
/**
* Attempts to create a new template for the class at the path specified.
* If the class is not found, a proper warning is printed.
*
* @param path to the class
* @return a new template, or null if the template could not be made
*/
public static ClassTemplate<?> create(String path) {
Class<?> type = CommonUtil.getClass(path);
if (type == null) {
CommonPlugin.LOGGER.log(Level.WARNING, "Class not found: '" + path + "'");
}
return create(type);
}
/**
* Attempts to create a new template for the class of the class instance specified<br>
* If something fails, an empty instance is returned
*
* @param value of the class to create the template for
* @return a new template
*/
@SuppressWarnings("unchecked")
public static <T> ClassTemplate<T> create(T value) {
return create((Class<T>) value.getClass());
}
/**
* Attempts to create a new template for the class specified<br>
* If something fails, an empty instance is returned
*
* @param clazz to create
* @return a new template
*/
public static <T> ClassTemplate<T> create(Class<T> clazz) {
return new ClassTemplate<T>(clazz);
}
}
|
/**
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.bpmn.core.mgt.services;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.bpmn.core.BPMNServerHolder;
import org.wso2.carbon.bpmn.core.BPSFault;
import org.wso2.carbon.bpmn.core.mgt.model.BPMNInstance;
import org.wso2.carbon.bpmn.core.mgt.model.BPMNVariable;
import org.wso2.carbon.context.CarbonContext;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class BPMNInstanceService {
private static Log log = LogFactory.getLog(BPMNInstanceService.class);
private int processInstanceCount = -1;
private int historyInstanceCount = -1;
/**
* Start process by process ID
*
* @param processID
* @throws BPSFault
*/
public void startProcess(String processID) throws BPSFault {
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
runtimeService.startProcessInstanceById(processID);
}
/**
* Get All process instances
*
* @return list of BPMNInstances
* @throws BPSFault
*/
public BPMNInstance[] getProcessInstances() throws BPSFault {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
List<ProcessInstance> instances = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).list();
BPMNInstance[] bpmnInstances = getTenantBPMNInstances(instances);
return bpmnInstances;
}
/**
* Returns Paginated Instances by passing filter parameters
*
* @param finished
* @param instanceId
* @param startAfter
* @param startBefore
* @param processId
* @param isActive
* @param variables
* @param start
* @param size
* @return list of BPMNInstances for given filter parameters
*/
public BPMNInstance[] getPaginatedInstanceByFilter(boolean finished, String instanceId, Date startAfter,
Date startBefore, String processId, boolean isActive, String variables,
int start, int size) {
List<BPMNInstance> bpmnInstanceList = new ArrayList<>();
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
HistoricProcessInstanceQuery historicQuery = BPMNServerHolder.getInstance().getEngine().getHistoryService()
.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).includeProcessVariables();
query = query.includeProcessVariables();
if (finished) {
historicQuery = historicQuery.finished();
if (instanceId != null && !instanceId.equals("")) {
return getInstanceById(instanceId , finished);
}
if (processId != null && !processId.equals("")) {
historicQuery = historicQuery.processDefinitionId(processId);
}
if (variables != null && !variables.trim().equals("")) {
String variablePairs[] = variables.split(",");
BPMNVariable[] bpmnVariables = new BPMNVariable[variablePairs.length];
for (int i = 0; i < variablePairs.length; i++) {
String pair[] = variablePairs[i].split(":");
if (pair.length == 1) {
bpmnVariables[i] = new BPMNVariable(pair[0], "");
} else {
bpmnVariables[i] = new BPMNVariable(pair[0], pair[1]);
}
}
if(variablePairs != null && variablePairs.length > 0){
for(BPMNVariable variable: bpmnVariables){
if (variable.getName() != null && !variable.getName().equals("")) {
historicQuery = historicQuery
.variableValueLike(variable.getName(), "%" + variable.getValue().toString() + "%");
}
}
}
}
if (startAfter != null) {
historicQuery = historicQuery.startedAfter(startAfter);
}
if (startBefore != null) {
historicQuery = historicQuery.startedBefore(startBefore);
}
processInstanceCount = (int) historicQuery.count();
List<HistoricProcessInstance> instances = historicQuery.listPage(start, size);
for (HistoricProcessInstance instance: instances) {
BPMNInstance bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
List<ProcessDefinition> processes = BPMNServerHolder.getInstance().getEngine().getRepositoryService()
.createProcessDefinitionQuery().processDefinitionTenantId(tenantId.toString())
.processDefinitionId(instance.getProcessDefinitionId()).list();
String processName = instance.getProcessDefinitionId();
if (!processes.isEmpty()) {
processName = processes.get(0).getName();
}
bpmnInstance.setProcessName(processName);
bpmnInstance.setStartTime(instance.getStartTime());
bpmnInstance.setEndTime(instance.getEndTime());
bpmnInstance.setVariables(formatVariables(instance.getProcessVariables()));
bpmnInstanceList.add(bpmnInstance);
}
} else {
historicQuery = historicQuery.unfinished();
if (instanceId != null && !instanceId.equals("")) {
return getInstanceById(instanceId, finished);
}
if (processId != null && !processId.equals("")) {
historicQuery = historicQuery.processDefinitionId(processId);
}
if (variables != null && !variables.trim().equals("")) {
String variablePairs[] = variables.split(",");
BPMNVariable[] bpmnVariables = new BPMNVariable[variablePairs.length];
for (int i = 0; i < variablePairs.length; i++) {
String pair[] = variablePairs[i].split(":");
if (pair.length == 1) {
bpmnVariables[i] = new BPMNVariable(pair[0], "");
} else {
bpmnVariables[i] = new BPMNVariable(pair[0], pair[1]);
}
}
if(variablePairs != null && variablePairs.length > 0){
for(BPMNVariable variable: bpmnVariables){
if (variable.getName() != null && !variable.getName().equals("")) {
historicQuery = historicQuery
.variableValueLike(variable.getName(), "%" + variable.getValue().toString() + "%");
}
}
}
}
if (startAfter != null) {
historicQuery = historicQuery.startedAfter(startAfter);
}
if (startBefore != null) {
historicQuery = historicQuery.startedBefore(startBefore);
}
processInstanceCount = (int) historicQuery.count();
List<HistoricProcessInstance> instances = historicQuery.listPage(start, size);
for (HistoricProcessInstance instance: instances) {
boolean isSuspended = query.processInstanceId(instance.getId()).list().get(0).isSuspended();
if( isSuspended == !isActive) {
BPMNInstance bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
List<ProcessDefinition> processes = BPMNServerHolder.getInstance().getEngine().getRepositoryService()
.createProcessDefinitionQuery().processDefinitionTenantId(tenantId.toString())
.processDefinitionId(instance.getProcessDefinitionId()).list();
String processName = instance.getProcessDefinitionId();
if (!processes.isEmpty()) {
processName = processes.get(0).getName();
}
bpmnInstance.setProcessName(processName);
if (!query.processInstanceId(instance.getId()).list().isEmpty()) {
bpmnInstance.setSuspended(isSuspended);
}
bpmnInstance.setStartTime(instance.getStartTime());
bpmnInstance.setEndTime(instance.getEndTime());
bpmnInstance.setVariables(formatVariables(instance.getProcessVariables()));
bpmnInstanceList.add(bpmnInstance);
}
}
}
return bpmnInstanceList.toArray(new BPMNInstance[bpmnInstanceList.size()]);
}
/**
* Get instances by instance Id and state
*
* @param instanceId
* @param finished
* @return list of BPMNInstances
*/
private BPMNInstance[] getInstanceById(String instanceId, boolean finished) {
List<BPMNInstance> bpmnInstanceList = new ArrayList<>();
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
HistoricProcessInstanceQuery historicQuery = BPMNServerHolder.getInstance().getEngine().getHistoryService()
.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).includeProcessVariables();
query = query.includeProcessVariables();
if (finished) {
historicQuery.finished();
} else {
historicQuery.unfinished();
}
historicQuery = historicQuery.processInstanceId(instanceId);
HistoricProcessInstance instance = historicQuery.singleResult();
if (instance != null) {
processInstanceCount = 1;
BPMNInstance bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
List<ProcessDefinition> processes = BPMNServerHolder.getInstance().getEngine().getRepositoryService()
.createProcessDefinitionQuery().processDefinitionTenantId(tenantId.toString())
.processDefinitionId(instance.getProcessDefinitionId()).list();
String processName = instance.getProcessDefinitionId();
if (!processes.isEmpty()) {
processName = processes.get(0).getName();
}
bpmnInstance.setProcessName(processName);
if (!query.processInstanceId(instance.getId()).list().isEmpty()) {
bpmnInstance.setSuspended(query.processInstanceId(instance.getId()).list().get(0).isSuspended());
}
bpmnInstance.setStartTime(instance.getStartTime());
bpmnInstance.setEndTime(instance.getEndTime());
bpmnInstance.setVariables(formatVariables(instance.getProcessVariables()));
bpmnInstanceList.add(bpmnInstance);
} else {
processInstanceCount = 0;
}
return bpmnInstanceList.toArray(new BPMNInstance[bpmnInstanceList.size()]);
}
/**
* Get paginated instances
*
* @param start
* @param size
* @return list of BPMNInstances
* @throws BPSFault
*/
public BPMNInstance[] getPaginatedInstances(int start, int size) throws BPSFault {
List<BPMNInstance> bpmnInstanceList = new ArrayList<>();
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
HistoricProcessInstanceQuery historicQuery = BPMNServerHolder.getInstance().getEngine().getHistoryService()
.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
processInstanceCount = (int) query.count();
List<ProcessInstance> instances = query.includeProcessVariables().listPage(start, size);
for (ProcessInstance instance: instances) {
BPMNInstance bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
bpmnInstance.setSuspended(instance.isSuspended());
bpmnInstance.setStartTime(historicQuery.processInstanceId(instance.getId()).singleResult().getStartTime());
bpmnInstance.setVariables(formatVariables(instance.getProcessVariables()));
bpmnInstanceList.add(bpmnInstance);
}
return bpmnInstanceList.toArray(new BPMNInstance[bpmnInstanceList.size()]);
}
/**
* Get total instance count
*
* @return count int
* @throws BPSFault
*/
public int getInstanceCount() throws BPSFault {
if(processInstanceCount == -1) {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ProcessEngine engine = BPMNServerHolder.getInstance().getEngine();
RuntimeService runtimeService = engine.getRuntimeService();
ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
processInstanceCount = (int) query.includeProcessVariables().count();
}
return processInstanceCount;
}
/**
* Get paginated history instances
*
* @param start
* @param size
* @return list of BPMNInstances
*/
public BPMNInstance[] getPaginatedHistoryInstances(int start, int size){
BPMNInstance bpmnInstance;
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<BPMNInstance> bpmnInstances = new ArrayList<>();
HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
HistoricProcessInstanceQuery query =
historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString())
.finished().includeProcessVariables();
historyInstanceCount = (int) query.count();
List<HistoricProcessInstance> historicProcessInstances = query.listPage(start, size);
for(HistoricProcessInstance instance: historicProcessInstances){
bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
bpmnInstance.setStartTime(instance.getStartTime());
bpmnInstance.setEndTime(instance.getEndTime());
bpmnInstance.setVariables(formatVariables(instance.getProcessVariables()));
bpmnInstances.add(bpmnInstance);
}
return bpmnInstances.toArray(new BPMNInstance[bpmnInstances.size()]);
}
/**
* Get total history instance count
*
* @return count int
* @throws BPSFault
*/
public int getHistoryInstanceCount() throws BPSFault {
if(historyInstanceCount == -1){
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
HistoricProcessInstanceQuery query =
historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).finished();
historyInstanceCount = (int) query.count();
}
return historyInstanceCount;
}
/**
* Delete history instance by instance ID
* @param instanceId
*/
public void deleteHistoryInstance(String instanceId){
HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
historyService.deleteHistoricProcessInstance(instanceId);
}
/**
* Delete all completed instances
*/
public void deleteAllCompletedInstances(){
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
HistoricProcessInstanceQuery query =
historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).finished();
for(HistoricProcessInstance instance: query.list()){
historyService.deleteHistoricProcessInstance(instance.getId());
}
}
/**
* Get tenant history instances from a passed list
*
* @param instances
* @return list of BPMNInstances
*/
private BPMNInstance[] getTenantBPMNHistoryInstances(List<ProcessInstance> instances) {
BPMNInstance bpmnInstance;
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<BPMNInstance> bpmnInstances = new ArrayList<BPMNInstance>();
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
HistoricProcessInstanceQuery query = BPMNServerHolder.getInstance().getEngine().getHistoryService()
.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
for (ProcessInstance instance : instances) {
bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
bpmnInstance.setSuspended(instance.isSuspended());
bpmnInstance.setStartTime(query.processInstanceId(instance.getId()).singleResult().getStartTime());
bpmnInstance.setVariables(formatVariables(runtimeService.getVariables(instance.getId())));
bpmnInstances.add(bpmnInstance);
}
return bpmnInstances.toArray(new BPMNInstance[bpmnInstances.size()]);
}
/**
* Suspend process instance by instance ID
*
* @param instanceId
* @throws BPSFault
*/
public void suspendProcessInstance(String instanceId) throws BPSFault {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processInstanceTenantId(tenantId.toString()).processInstanceId(instanceId).list();
if (processInstances.isEmpty()) {
String msg = "No process instances with the ID: " + instanceId;
log.error(msg);
throw new BPSFault(msg);
}
runtimeService.suspendProcessInstanceById(instanceId);
}
/**
* Delete process instances by passing a list of IDs
*
* @param instanceIdSet
* @throws BPSFault
*/
public void deleteProcessInstanceSet(String[] instanceIdSet) throws BPSFault {
for (String instanceId : instanceIdSet) {
deleteProcessInstance(instanceId);
}
}
/**
* Delete process instance by passing instance ID
*
* @param instanceId
* @throws BPSFault
*/
public void deleteProcessInstance(String instanceId) throws BPSFault {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery()
.processInstanceTenantId(tenantId.toString()).processInstanceId(instanceId).list();
if (processInstances.isEmpty()) {
HistoryService historyService = BPMNServerHolder.getInstance().getEngine().getHistoryService();
List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery()
.processInstanceTenantId(tenantId.toString()).processInstanceId(instanceId).list();
if (historicProcessInstances.isEmpty()) {
String msg = "No process instances with the ID: " + instanceId;
log.error(msg);
throw new BPSFault(msg);
}
historyService.deleteHistoricProcessInstance(instanceId);
return;
}
runtimeService.deleteProcessInstance(instanceId, "Deleted by user: " + tenantId);
}
/**
* Activate a process instance by passing the instance id
*
* @param instanceId
* @throws BPSFault
*/
public void activateProcessInstance(String instanceId) throws BPSFault {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery()
.processInstanceTenantId(tenantId.toString()).processInstanceId(instanceId).list();
if (processInstances.isEmpty()) {
String msg = "No process instances with the ID: " + instanceId;
log.error(msg);
throw new BPSFault(msg);
}
runtimeService.activateProcessInstanceById(instanceId);
}
/**
* Get process instance diagram as a byte stream by passing the instance ID
*
* @param instanceId
* @return Byte array String
* @throws BPSFault
*/
public String getProcessInstanceDiagram(String instanceId) throws BPSFault {
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
RepositoryService repositoryService = BPMNServerHolder.getInstance().getEngine().getRepositoryService();
List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery()
.processInstanceTenantId(tenantId.toString()).processInstanceId(instanceId).list();
if (processInstances.isEmpty()) {
String msg = "No process instance diagram for ID: " + instanceId;
log.info(msg);
return null;
}
ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
.getDeployedProcessDefinition(processInstances.get(0).getProcessDefinitionId());
if(processDefinition != null && processDefinition.isGraphicalNotationDefined()){
InputStream diagramStream = new DefaultProcessDiagramGenerator().generateDiagram(repositoryService
.getBpmnModel(processDefinition.getId()), "png",
runtimeService.getActiveActivityIds(instanceId));
BufferedImage bufferedImage = ImageIO.read(diagramStream);
return encodeToString(bufferedImage, "png");
}else {
String msg = "Process definition graphical notations doesn't exists: " + instanceId;
log.debug(msg);
}
} catch (IOException e) {
String msg = "Failed to get the process instance.";
log.error(msg, e);
}
return null;
}
/**
* Internally used method to get all tenant BPMN instances from a passed instance list
*
* @param instances
* @return list of BPMNInstances
*/
private BPMNInstance[] getTenantBPMNInstances(List<ProcessInstance> instances) {
BPMNInstance bpmnInstance;
Integer tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
List<BPMNInstance> bpmnInstances = new ArrayList<BPMNInstance>();
RuntimeService runtimeService = BPMNServerHolder.getInstance().getEngine().getRuntimeService();
HistoricProcessInstanceQuery query = BPMNServerHolder.getInstance().getEngine().getHistoryService()
.createHistoricProcessInstanceQuery().processInstanceTenantId(tenantId.toString());
for (ProcessInstance instance : instances) {
bpmnInstance = new BPMNInstance();
bpmnInstance.setInstanceId(instance.getId());
bpmnInstance.setProcessId(instance.getProcessDefinitionId());
bpmnInstance.setSuspended(instance.isSuspended());
bpmnInstance.setStartTime(query.processInstanceId(instance.getId()).singleResult().getStartTime());
bpmnInstance.setVariables(formatVariables(runtimeService.getVariables(instance.getId())));
bpmnInstances.add(bpmnInstance);
}
return bpmnInstances.toArray(new BPMNInstance[bpmnInstances.size()]);
}
/**
* Internally used method to format variables
*
* @param processVariables
* @return list of BPMNInstances
*/
private BPMNVariable[] formatVariables(Map<String, Object> processVariables) {
BPMNVariable[] vars = new BPMNVariable[processVariables.size()];
int currentVar = 0;
for (Map.Entry entry : processVariables.entrySet()) {
Object value = processVariables.get(entry.getKey().toString());
if (value == null) {
value = "null";
} else {
value = String.valueOf(value);
}
vars[currentVar] = new BPMNVariable(entry.getKey().toString(), value.toString());
currentVar++;
}
return vars;
}
/**
* Internally used method to encode a image to String
*
* @param image
* @param type
* @return encoded String
*/
private String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
} catch (IOException e) {
log.error("Could not write image data", e);
} finally {
try {
bos.close();
} catch (IOException e) {
log.error("Could not close the byte stream", e);
}
}
return imageString;
}
}
|
package org.infinispan.test;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.infinispan.transaction.impl.TransactionTable;
import org.infinispan.util.concurrent.locks.LockManager;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
/**
* Base class for tests that operate on a single (most likely local) cache instance. This operates similar to {@link
* org.infinispan.test.MultipleCacheManagersTest}, but on only one CacheManager.
*
* @author Mircea.Markus@jboss.com
* @see org.infinispan.test.MultipleCacheManagersTest
*/
public abstract class SingleCacheManagerTest extends AbstractCacheTest {
protected EmbeddedCacheManager cacheManager;
protected Cache<Object, Object> cache;
protected void setup() throws Exception {
cacheManager = createCacheManager();
if (cache == null) cache = cacheManager.getCache();
}
protected void teardown() {
TestingUtil.killCacheManagers(cacheManager);
cache = null;
cacheManager = null;
}
protected void clearCacheManager() {
TestingUtil.clearContent(cacheManager);
}
@BeforeClass(alwaysRun = true)
protected void createBeforeClass() throws Exception {
try {
if (cleanupAfterTest()) setup();
else assert cleanupAfterMethod() : "you must either cleanup after test or after method";
} catch (Exception e) {
log.error("Unexpected!", e);
throw e;
}
}
@BeforeMethod(alwaysRun = true)
protected void createBeforeMethod() throws Exception {
try {
if (cleanupAfterMethod()) setup();
else assert cleanupAfterTest() : "you must either cleanup after test or after method";
} catch (Exception e) {
log.error("Unexpected!", e);
throw e;
}
}
@AfterClass(alwaysRun=true)
protected void destroyAfterClass() {
try {
if (cleanupAfterTest()) teardown();
} catch (Exception e) {
log.error("Unexpected!", e);
}
}
@AfterMethod(alwaysRun=true)
protected void destroyAfterMethod() {
if (cleanupAfterMethod()) teardown();
}
@AfterMethod(alwaysRun=true)
protected void clearContent() {
if (cleanupAfterTest()) clearCacheManager();
}
protected ConfigurationBuilder getDefaultStandaloneCacheConfig(boolean transactional) {
return TestCacheManagerFactory.getDefaultCacheConfiguration(transactional);
}
protected TransactionManager tm() {
return cache.getAdvancedCache().getTransactionManager();
}
protected Transaction tx() {
try {
return cache.getAdvancedCache().getTransactionManager().getTransaction();
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
protected LockManager lockManager(String cacheName) {
return TestingUtil.extractLockManager(cacheManager.getCache(cacheName));
}
protected LockManager lockManager() {
return TestingUtil.extractLockManager(cache);
}
protected abstract EmbeddedCacheManager createCacheManager() throws Exception;
@SuppressWarnings("unchecked")
protected <K,V> Cache<K, V> cache() {
return (Cache<K, V>)cache;
}
protected <K,V> Cache<K, V> cache(String name) {
return cacheManager.getCache(name);
}
protected void assertNoTransactions() {
assertNoTransactions(cache);
}
protected void assertNoTransactions(final Cache<?, ?> cache) {
eventually(new Condition() {
@Override
public boolean isSatisfied() throws Exception {
int localTxCount = TestingUtil.extractComponent(cache, TransactionTable.class).getLocalTxCount();
if (localTxCount != 0) {
log.tracef("Local tx=%s", localTxCount);
return false;
}
return true;
}
});
}
}
|
/*
* Copyright (C) 2017 Bilibili
*
* 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.bilibili.boxing;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import com.bilibili.boxing.model.BoxingBuilderConfig;
import com.bilibili.boxing.model.BoxingManager;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.config.BoxingCropOption;
import com.bilibili.boxing.model.entity.AlbumEntity;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.presenter.PickerContract;
import com.bilibili.boxing.utils.CameraPickerHelper;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import static android.support.v4.content.PermissionChecker.PERMISSION_GRANTED;
/**
* A abstract class which implements {@link PickerContract.View} for custom media view.
* only one methods need to override {@link #startLoading()}, but there is more function to achieve by
* checking every method can override.
*
* @author ChenSL
*/
public abstract class AbsBoxingViewFragment extends Fragment implements PickerContract.View {
public static final String[] STORAGE_PERMISSIONS =
{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
public static final String[] CAMERA_PERMISSIONS = {Manifest.permission.CAMERA};
private static final int REQUEST_CODE_PERMISSION = 233;
private PickerContract.Presenter mPresenter;
private CameraPickerHelper mCameraPicker;
private Boxing.OnBoxingFinishListener mOnFinishListener;
/**
* start loading when the permission request is completed.
* call {@link #loadMedias()} or {@link #loadMedias(int, String)}, call {@link #loadAlbum()} if albums needed.
*/
public abstract void startLoading();
/**
* called when request {@link Manifest.permission#WRITE_EXTERNAL_STORAGE} and {@link Manifest.permission#CAMERA} permission error.
*
* @param e a IllegalArgumentException, IllegalStateException or SecurityException will be throw
*/
public void onRequestPermissionError(String[] permissions, Exception e) {
}
/**
* called when request {@link Manifest.permission#WRITE_EXTERNAL_STORAGE} and {@link Manifest.permission#CAMERA} permission successfully.
*/
public void onRequestPermissionSuc(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
}
/**
* get the result of using camera to take a photo.
*
* @param media {@link BaseMedia}
*/
public void onCameraFinish(BaseMedia media) {
}
/**
* called when camera start error
*/
public void onCameraError() {
}
/**
* must override when care about the input medias, which means you call {@link #setSelectedBundle(ArrayList)} first.
* this method is called in {@link Fragment#onCreate(Bundle)}, so override this rather than {@link Fragment#onCreate(Bundle)}.
*
* @param bundle If the fragment is being re-created from
* a previous saved state, this is the state.
* @param selectedMedias the input medias, the parameter of {@link #setSelectedBundle(ArrayList)}.
*/
public void onCreateWithSelectedMedias(Bundle bundle, @Nullable List<BaseMedia> selectedMedias) {
}
/**
* override this method to handle the medias.
* make sure {@link #loadMedias()} ()} being called first.
*
* @param medias the results of medias
*/
@Override
public void showMedia(@Nullable List<BaseMedia> medias, int allCount) {
}
/**
* override this method to handle the album.
* make sure {@link #loadAlbum()} being called first.
*
* @param albums the results of albums
*/
@Override
public void showAlbum(@Nullable List<AlbumEntity> albums) {
}
/**
* to clear all medias the first time(the page number is 0). do some clean work.
*/
@Override
public void clearMedia() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
BoxingConfig config;
if (savedInstanceState != null) {
config = savedInstanceState.getParcelable(Boxing.EXTRA_CONFIG);
} else {
config = BoxingManager.getInstance().getBoxingConfig();
}
setPickerConfig(config);
onCreateWithSelectedMedias(savedInstanceState, parseSelectedMedias(savedInstanceState, getArguments()));
super.onCreate(savedInstanceState);
initCameraPhotoPicker(savedInstanceState);
}
@Nullable
private ArrayList<BaseMedia> parseSelectedMedias(Bundle savedInstanceState, Bundle argument) {
ArrayList<BaseMedia> selectedMedias = null;
if (savedInstanceState != null) {
selectedMedias = savedInstanceState.getParcelableArrayList(Boxing.EXTRA_SELECTED_MEDIA);
} else if (argument != null) {
selectedMedias = argument.getParcelableArrayList(Boxing.EXTRA_SELECTED_MEDIA);
}
return selectedMedias;
}
private void initCameraPhotoPicker(Bundle savedInstanceState) {
BoxingConfig config = BoxingManager.getInstance().getBoxingConfig();
if (config == null || !config.isNeedCamera()) {
return;
}
mCameraPicker = new CameraPickerHelper(savedInstanceState);
mCameraPicker.setPickCallback(new CameraListener(this));
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
checkPermissionAndLoad();
}
private void checkPermissionAndLoad() {
try {
if (!BoxingBuilderConfig.TESTING && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(getActivity(), STORAGE_PERMISSIONS[0]) != PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(getActivity(), STORAGE_PERMISSIONS[1]) != PERMISSION_GRANTED) {
requestPermissions(STORAGE_PERMISSIONS, REQUEST_CODE_PERMISSION);
} else {
startLoading();
}
} catch (IllegalArgumentException | IllegalStateException e) {
onRequestPermissionError(STORAGE_PERMISSIONS, e);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (REQUEST_CODE_PERMISSION == requestCode) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onRequestPermissionSuc(requestCode, permissions, grantResults);
} else {
onRequestPermissionError(permissions,
new SecurityException("request android.permission.READ_EXTERNAL_STORAGE error."));
}
}
}
/**
* called when you have input medias, then call {@link #onCreateWithSelectedMedias(Bundle, List)} to get the input medias.
*
* @param selectedMedias input medias
* @return {@link AbsBoxingViewFragment}
*/
public final AbsBoxingViewFragment setSelectedBundle(ArrayList<BaseMedia> selectedMedias) {
Bundle bundle = new Bundle();
if (selectedMedias != null && !selectedMedias.isEmpty()) {
bundle.putParcelableArrayList(Boxing.EXTRA_SELECTED_MEDIA, selectedMedias);
}
setArguments(bundle);
return this;
}
@Override
public final void setPresenter(@NonNull PickerContract.Presenter presenter) {
this.mPresenter = presenter;
}
/**
* get the {@link ContentResolver}
*/
@NonNull
@Override
public final ContentResolver getAppCr() {
return getActivity().getApplicationContext().getContentResolver();
}
/**
* if {@link AbsBoxingViewFragment} is not working with {@link AbsBoxingActivity}, it needs a listener to call
* when the jobs done.
*
* @param onFinishListener {@link Boxing.OnBoxingFinishListener}
*/
final void setOnFinishListener(Boxing.OnBoxingFinishListener onFinishListener) {
mOnFinishListener = onFinishListener;
}
/**
* called the job is done.Click the ok button, take a photo from camera, crop a photo.
* most of the time, you do not have to override.
*
* @param medias the list of selection
*/
@Override
public void onFinish(@NonNull List<BaseMedia> medias) {
Intent intent = new Intent();
intent.putParcelableArrayListExtra(Boxing.EXTRA_RESULT, (ArrayList<BaseMedia>) medias);
if (mOnFinishListener != null) {
mOnFinishListener.onBoxingFinish(intent, medias);
}
}
/**
* need crop or not
*
* @return true, need it.
*/
public final boolean hasCropBehavior() {
BoxingConfig config = BoxingManager.getInstance().getBoxingConfig();
return config != null && config.isSingleImageMode() && config.getCropOption() != null;
}
/**
* to start the crop behavior, call it when {@link #hasCropBehavior()} return true.
*
* @param media the media to be cropped.
* @param requestCode The integer request code originally supplied to
* startActivityForResult(), allowing you to identify who this
* result came from.
*/
@Override
public final void startCrop(@NonNull BaseMedia media, int requestCode) {
BoxingCropOption cropConfig = BoxingManager.getInstance().getBoxingConfig().getCropOption();
BoxingCrop.getInstance().onStartCrop(getActivity(), this, cropConfig, media.getPath(), requestCode);
}
/**
* set or update the config.most of the time, you do not have to call it.
*
* @param config {@link BoxingConfig}
*/
@Override
public final void setPickerConfig(BoxingConfig config) {
if (config == null) {
return;
}
BoxingManager.getInstance().setBoxingConfig(config);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (mCameraPicker != null && requestCode == CameraPickerHelper.REQ_CODE_CAMERA) {
onCameraActivityResult(requestCode, resultCode);
}
if (hasCropBehavior()) {
onCropActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mCameraPicker != null) {
mCameraPicker.onSaveInstanceState(outState);
}
outState.putParcelable(Boxing.EXTRA_CONFIG, BoxingManager.getInstance().getBoxingConfig());
}
/**
* in {@link BoxingConfig.Mode#MULTI_IMG}, call this in {@link Fragment#onSaveInstanceState(Bundle)}.
*
* @param outState Bundle in which to place your saved state.
* @param selected the selected medias.
*/
public final void onSaveMedias(Bundle outState, ArrayList<BaseMedia> selected) {
if (selected != null && !selected.isEmpty()) {
outState.putParcelableArrayList(Boxing.EXTRA_SELECTED_MEDIA, selected);
}
}
/**
* call this to clear resource.
*/
@Override
public void onDestroy() {
super.onDestroy();
if (mPresenter != null) {
mPresenter.destroy();
}
if (mCameraPicker != null) {
mCameraPicker.release();
}
}
/**
* in {@link BoxingConfig.Mode#MULTI_IMG}, call this to pick the selected medias in all medias.
*/
public final void checkSelectedMedia(List<BaseMedia> allMedias, List<BaseMedia> selectedMedias) {
mPresenter.checkSelectedMedia(allMedias, selectedMedias);
}
/**
* load first page of medias.
* use {@link #showMedia(List, int)} to get the result.
*/
public final void loadMedias() {
mPresenter.loadMedias(0, AlbumEntity.DEFAULT_NAME);
}
/**
* load the medias for the specify page and album id.
* use {@link #showMedia(List, int)} to get the result.
*
* @param page page numbers.
* @param albumId the album id is {@link AlbumEntity#mBucketId}.
*/
public final void loadMedias(int page, String albumId) {
mPresenter.loadMedias(page, albumId);
}
/**
* extra call to load albums in database, use {@link #showAlbum(List)} to get result.
* In {@link BoxingConfig.Mode#VIDEO} it is not necessary.
*/
public void loadAlbum() {
if (!BoxingManager.getInstance().getBoxingConfig().isVideoMode()) {
mPresenter.loadAlbums();
}
}
public final boolean hasNextPage() {
return mPresenter.hasNextPage();
}
public final boolean canLoadNextPage() {
return mPresenter.canLoadNextPage();
}
public final void onLoadNextPage() {
mPresenter.onLoadNextPage();
}
/**
* get the max count set before
*/
public final int getMaxCount() {
BoxingConfig config = BoxingManager.getInstance().getBoxingConfig();
if (config == null) {
return BoxingConfig.DEFAULT_SELECTED_COUNT;
}
return config.getMaxCount();
}
/**
* successfully get result from camera in {@link #onActivityResult(int, int, Intent)}.
* call this after other operations.
*/
public void onCameraActivityResult(int requestCode, int resultCode) {
mCameraPicker.onActivityResult(requestCode, resultCode);
}
/**
* successfully get result from crop in {@link #onActivityResult(int, int, Intent)}
*/
public void onCropActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
Uri output = BoxingCrop.getInstance().onCropFinish(resultCode, data);
if (output != null) {
List<BaseMedia> medias = new ArrayList<>(1);
ImageMedia media = new ImageMedia(String.valueOf(System.currentTimeMillis()), output.getPath());
medias.add(media);
onFinish(medias);
}
}
/**
* start camera to take a photo.
*
* @param activity the caller activity.
* @param fragment the caller fragment, may be null.
* @param subFolderPath the folder name in "DCIM/bili/boxing/"
*/
public final void startCamera(Activity activity, Fragment fragment, String subFolderPath) {
try {
if (!BoxingBuilderConfig.TESTING && ContextCompat.checkSelfPermission(getActivity(), CAMERA_PERMISSIONS[0]) != PERMISSION_GRANTED) {
requestPermissions(CAMERA_PERMISSIONS, REQUEST_CODE_PERMISSION);
} else {
if (!BoxingManager.getInstance().getBoxingConfig().isVideoMode()) {
mCameraPicker.startCamera(activity, fragment, subFolderPath);
}
}
} catch (IllegalArgumentException | IllegalStateException e) {
onRequestPermissionError(CAMERA_PERMISSIONS, e);
}
}
private static final class CameraListener implements CameraPickerHelper.Callback {
private WeakReference<AbsBoxingViewFragment> mWr;
CameraListener(AbsBoxingViewFragment fragment) {
mWr = new WeakReference<>(fragment);
}
@Override
public void onFinish(@NonNull CameraPickerHelper helper) {
AbsBoxingViewFragment fragment = mWr.get();
if (fragment == null) {
return;
}
File file = new File(helper.getSourceFilePath());
if (!file.exists()) {
onError(helper);
return;
}
ImageMedia cameraMedia = new ImageMedia(file);
cameraMedia.saveMediaStore(fragment.getAppCr());
fragment.onCameraFinish(cameraMedia);
}
@Override
public void onError(@NonNull CameraPickerHelper helper) {
AbsBoxingViewFragment fragment = mWr.get();
if (fragment == null) {
return;
}
fragment.onCameraError();
}
}
}
|
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8006298
* @summary Using a bool (+/-) prefix on non-bool flag should result in a useful error message
* @library /testlibrary
*/
import com.oracle.java.testlibrary.*;
public class NonBooleanFlagWithInvalidBooleanPrefix {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
"-XX:-MaxRAMFraction=16", "-version");
OutputAnalyzer output = new OutputAnalyzer(pb.start());
output.shouldContain("Unexpected +/- setting in VM option 'MaxRAMFraction=16'");
output.shouldHaveExitValue(1);
pb = ProcessTools.createJavaProcessBuilder(
"-XX:+MaxRAMFraction=16", "-version");
output = new OutputAnalyzer(pb.start());
output.shouldContain("Unexpected +/- setting in VM option 'MaxRAMFraction=16'");
output.shouldHaveExitValue(1);
}
}
|
/*
* Copyright 2010-2014 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.springframework.mobile.device.switcher;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
public class ServerNameSiteUrlFactoryTest {
private StandardSiteUrlFactory factory = new StandardSiteUrlFactory("m.app.com");
private MockHttpServletRequest request = new MockHttpServletRequest();
@Test
public void isRequestForSite() {
request.setServerName("m.app.com");
assertTrue(factory.isRequestForSite(request));
}
@Test
public void notRequestForSite() {
request.setServerName("app.com");
assertFalse(factory.isRequestForSite(request));
}
@Test
public void createSiteUrl() {
request.setServerName("m.app.com");
request.setServerPort(80);
request.setRequestURI("/foo");
assertEquals("http://m.app.com/foo", factory.createSiteUrl(request));
}
}
|
/**
* Copyright (C) 2015 Valkyrie RCP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.valkyriercp.application.config;
import org.valkyriercp.application.ApplicationWindow;
import org.valkyriercp.application.ApplicationWindowConfigurer;
import org.valkyriercp.application.PageDescriptor;
import org.valkyriercp.application.StatusBar;
import org.valkyriercp.application.exceptionhandling.RegisterableExceptionHandler;
import org.valkyriercp.application.session.ApplicationSessionInitializer;
import org.valkyriercp.application.support.ApplicationWindowCommandManager;
import org.valkyriercp.command.support.CommandGroup;
import java.util.function.Consumer;
import java.util.function.Supplier;
public interface ApplicationLifecycleAdvisor {
PageDescriptor getStartingPageDescriptor();
void setStartingPageDescriptor(Supplier<PageDescriptor> descriptor);
void onPreStartup();
void onPostStartup();
void setOnWindowCreated(Consumer<ApplicationWindow> fn);
void setOnWindowOpened(Consumer<ApplicationWindow> fn);
Consumer<ApplicationWindow> getOnWindowCreated();
Consumer<ApplicationWindow> getOnWindowOpened();
boolean onPreWindowClose(ApplicationWindow window);
void onCommandsCreated(ApplicationWindow window);
void onPreWindowOpen(ApplicationWindowConfigurer configurer);
void setOpeningWindow(ApplicationWindow window);
ApplicationWindowCommandManager createWindowCommandManager();
CommandGroup getMenuBarCommandGroup();
CommandGroup getToolBarCommandGroup();
CommandGroup getNavigationCommandGroup();
StatusBar getStatusBar();
void onShutdown();
ApplicationSessionInitializer getApplicationSessionInitializer();
RegisterableExceptionHandler getRegisterableExceptionHandler();
}
|
/*
* blackduck-common
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.blackduck.service.dataservice;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import com.synopsys.integration.blackduck.api.generated.discovery.ApiDiscovery;
import com.synopsys.integration.blackduck.api.generated.view.IssueView;
import com.synopsys.integration.blackduck.api.generated.view.ProjectVersionComponentVersionView;
import com.synopsys.integration.blackduck.api.generated.view.ProjectVersionComponentView;
import com.synopsys.integration.blackduck.api.generated.view.ProjectVersionIssuesView;
import com.synopsys.integration.blackduck.api.generated.view.ProjectVersionView;
import com.synopsys.integration.blackduck.api.manual.temporary.component.IssueRequest;
import com.synopsys.integration.blackduck.service.BlackDuckApiClient;
import com.synopsys.integration.blackduck.service.DataService;
import com.synopsys.integration.exception.IntegrationException;
import com.synopsys.integration.log.IntLogger;
import com.synopsys.integration.rest.HttpUrl;
public class IssueService extends DataService {
public IssueService(BlackDuckApiClient blackDuckApiClient, ApiDiscovery apiDiscovery, IntLogger logger) {
super(blackDuckApiClient, apiDiscovery, logger);
}
public List<ProjectVersionIssuesView> getIssuesForProjectVersion(ProjectVersionView projectVersionView) throws IntegrationException {
return blackDuckApiClient.getAllResponses(projectVersionView.metaIssuesLink());
}
public Optional<IssueView> getIssueByKey(ProjectVersionView projectVersionView, String issueKey) throws IntegrationException {
Predicate<ProjectVersionIssuesView> issueKeyEquals = (issue -> issue.getIssueId().equals(issueKey));
List<ProjectVersionIssuesView> bomComponentIssues = blackDuckApiClient.getSomeMatchingResponses(projectVersionView.metaIssuesLink(), issueKeyEquals, 1);
Optional<ProjectVersionIssuesView> projectVersionIssuesViewOptional = bomComponentIssues.stream().findAny();
if (projectVersionIssuesViewOptional.isPresent()) {
return Optional.ofNullable(getIssueView(projectVersionIssuesViewOptional.get()));
}
return Optional.empty();
}
public IssueView getIssueView(ProjectVersionIssuesView projectVersionIssuesView) throws IntegrationException {
HttpUrl issueUrl = projectVersionIssuesView.getHref();
return blackDuckApiClient.getResponse(issueUrl, IssueView.class);
}
public void createIssueForComponent(ProjectVersionComponentVersionView projectVersionComponentView, IssueRequest issueRequest) throws IntegrationException {
HttpUrl createIssueUrl = projectVersionComponentView.getFirstLink(ProjectVersionComponentView.COMPONENT_ISSUES_LINK);
blackDuckApiClient.post(createIssueUrl, issueRequest);
}
public void updateIssue(IssueView issueView) throws IntegrationException {
blackDuckApiClient.put(issueView);
}
}
|
package m;
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class Snippet104 {
public static void main(String[] args) {
final Display display = new Display();
final int [] count = new int [] {4};
final Image image = new Image(display, 300, 300);
GC gc = new GC(image);
gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
gc.fillRectangle(image.getBounds());
gc.drawText("Splash Screen", 10, 10);
gc.dispose();
final Shell splash = new Shell(SWT.ON_TOP);
final ProgressBar bar = new ProgressBar(splash, SWT.NONE);
bar.setMaximum(count[0]);
Label label = new Label(splash, SWT.NONE);
label.setImage(image);
FormLayout layout = new FormLayout();
splash.setLayout(layout);
FormData labelData = new FormData ();
labelData.right = new FormAttachment (100, 0);
labelData.bottom = new FormAttachment (100, 0);
label.setLayoutData(labelData);
FormData progressData = new FormData ();
progressData.left = new FormAttachment (0, 5);
progressData.right = new FormAttachment (100, -5);
progressData.bottom = new FormAttachment (100, -5);
bar.setLayoutData(progressData);
splash.pack();
Rectangle splashRect = splash.getBounds();
Rectangle displayRect = display.getBounds();
int x = (displayRect.width - splashRect.width) / 2;
int y = (displayRect.height - splashRect.height) / 2;
splash.setLocation(x, y);
splash.open();
display.asyncExec(() -> {
Shell [] shells = new Shell[count[0]];
for (int i1=0; i1<count[0]; i1++) {
shells [i1] = new Shell(display);
shells [i1].setSize (300, 300);
shells [i1].addListener(SWT.Close, e -> --count[0]);
bar.setSelection(i1+1);
try {Thread.sleep(1000);} catch (Throwable e) {}
}
splash.close();
image.dispose();
for (int i2=0; i2<count[0]; i2++) {
shells [i2].setText("SWT Snippet 104 - " + (i2+1));
shells [i2].open();
}
});
while (count [0] != 0) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose();
}
}
|
/**
*
* Copyright 2014 Florian Schmaus
*
* 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.jivesoftware.smack.sasl.provided;
import java.io.UnsupportedEncodingException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.sasl.DigestMd5SaslTest;
import org.junit.Test;
import org.jxmpp.stringprep.XmppStringprepException;
public class SASLDigestMD5Test extends DigestMd5SaslTest {
public SASLDigestMD5Test() {
super(new SASLDigestMD5Mechanism());
}
@Test
public void testDigestMD5() throws SmackException, InterruptedException,
XmppStringprepException, UnsupportedEncodingException {
runTest(false);
}
@Test
public void testDigestMD5Authzid() throws SmackException, InterruptedException,
XmppStringprepException, UnsupportedEncodingException {
runTest(true);
}
}
|
/*
* 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.rocketmq.mqtt.cs.protocol.mqtt.handler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttConnAckMessage;
import io.netty.handler.codec.mqtt.MqttConnAckVariableHeader;
import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttConnectVariableHeader;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.mqtt.common.hook.HookResult;
import org.apache.rocketmq.mqtt.cs.channel.ChannelCloseFrom;
import org.apache.rocketmq.mqtt.cs.channel.ChannelInfo;
import org.apache.rocketmq.mqtt.cs.channel.ChannelManager;
import org.apache.rocketmq.mqtt.cs.config.ConnectConf;
import org.apache.rocketmq.mqtt.cs.protocol.mqtt.MqttPacketHandler;
import org.apache.rocketmq.mqtt.cs.session.loop.SessionLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Component
public class MqttConnectHandler implements MqttPacketHandler<MqttConnectMessage> {
private static Logger logger = LoggerFactory.getLogger(MqttConnectHandler.class);
@Resource
private ChannelManager channelManager;
@Resource
private SessionLoop sessionLoop;
@Resource
private ConnectConf connectConf;
private ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, new ThreadFactoryImpl("check_connect_future"));
@Override
public void doHandler(ChannelHandlerContext ctx, MqttConnectMessage connectMessage, HookResult upstreamHookResult) {
MqttConnectVariableHeader variableHeader = connectMessage.variableHeader();
Channel channel = ctx.channel();
ChannelInfo.setKeepLive(channel, variableHeader.keepAliveTimeSeconds());
ChannelInfo.setClientId(channel, connectMessage.payload().clientIdentifier());
ChannelInfo.setCleanSessionFlag(channel, variableHeader.isCleanSession());
CompletableFuture<Void> future = new CompletableFuture<>();
ChannelInfo.setFuture(channel, ChannelInfo.FUTURE_CONNECT, future);
scheduler.schedule(() -> {
if (!future.isDone()) {
future.complete(null);
}
}, 1, TimeUnit.SECONDS);
String remark = upstreamHookResult.getRemark();
if (!upstreamHookResult.isSuccess()) {
byte connAckCode = (byte) upstreamHookResult.getSubCode();
MqttConnectReturnCode mqttConnectReturnCode = MqttConnectReturnCode.valueOf(connAckCode);
if (mqttConnectReturnCode == null) {
channelManager.closeConnect(channel, ChannelCloseFrom.SERVER, remark);
return;
}
channel.writeAndFlush(getMqttConnAckMessage(mqttConnectReturnCode));
channelManager.closeConnect(channel, ChannelCloseFrom.SERVER, remark);
return;
}
try {
MqttConnAckMessage mqttConnAckMessage = getMqttConnAckMessage(MqttConnectReturnCode.CONNECTION_ACCEPTED);
future.thenAccept(aVoid -> {
if (!channel.isActive()) {
return;
}
ChannelInfo.removeFuture(channel, ChannelInfo.FUTURE_CONNECT);
channel.writeAndFlush(mqttConnAckMessage);
});
sessionLoop.loadSession(ChannelInfo.getClientId(channel), channel);
} catch (Exception e) {
logger.error("Connect:{}", connectMessage.payload().clientIdentifier(), e);
channelManager.closeConnect(channel, ChannelCloseFrom.SERVER, "ConnectException");
}
}
private MqttConnAckMessage getMqttConnAckMessage(MqttConnectReturnCode returnCode) {
MqttConnAckVariableHeader mqttConnAckVariableHeader =
new MqttConnAckVariableHeader(returnCode, false);
MqttFixedHeader mqttFixedHeader =
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
MqttConnAckMessage mqttConnAckMessage =
new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
return mqttConnAckMessage;
}
}
|
// Template Source: Enum.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
/**
* The Enum Label.
*/
public enum Label
{
/**
* title
*/
TITLE,
/**
* url
*/
URL,
/**
* created By
*/
CREATED_BY,
/**
* last Modified By
*/
LAST_MODIFIED_BY,
/**
* authors
*/
AUTHORS,
/**
* created Date Time
*/
CREATED_DATE_TIME,
/**
* last Modified Date Time
*/
LAST_MODIFIED_DATE_TIME,
/**
* file Name
*/
FILE_NAME,
/**
* file Extension
*/
FILE_EXTENSION,
/**
* For Label values that were not expected from the service
*/
UNEXPECTED_VALUE
}
|
package org.raml.simpleemitter.handlers;
import org.raml.simpleemitter.HandlerList;
import org.raml.simpleemitter.NodeHandler;
import org.raml.simpleemitter.YamlEmitter;
import org.raml.yagi.framework.nodes.KeyValueNode;
import org.raml.yagi.framework.nodes.Node;
import org.raml.yagi.framework.nodes.SimpleTypeNode;
import java.io.IOException;
/**
* Created. There, you have it.
*/
public class KeyValueNodeHandler extends NodeHandler<KeyValueNode> {
private final HandlerList handlerList;
public KeyValueNodeHandler(HandlerList handlerList) {
this.handlerList = handlerList;
}
@Override
public boolean handles(Node node) {
return node instanceof KeyValueNode;
}
@Override
public boolean handleSafely(KeyValueNode node, YamlEmitter emitter) throws IOException {
String scalar = isScalar(node.getValue());
if ( scalar != null ) {
emitter.writeTag(node.getKey().toString());
handlerList.handle(node.getValue(), emitter);
} else {
emitter.writeTag(node.getKey().toString());
handlerList.handle(node.getValue(), emitter.indent());
}
return true;
}
private String isScalar(Node node) {
if ( node instanceof SimpleTypeNode) {
return ((SimpleTypeNode<?>)node).getLiteralValue();
} else {
return null;
}
}
}
|
import java.io.FileInputStream;
import java.io.IOException;
public class P01ReadFile {
public static void main(String[] args) {
String inputPath = "C:\\Exercises\\JavaAdvanced\\08.Resources\\input.txt";
try (FileInputStream fis = new FileInputStream(inputPath)) {
int oneByte = fis.read();
while (oneByte >= 0) {
System.out.print(Integer.toBinaryString(oneByte) + " ");
oneByte = fis.read();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* The MIT License
*
* Copyright (c) 2022, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.rules.mvel;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import org.assertj.core.api.Assertions;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.support.composite.UnitRuleGroup;
import org.jeasy.rules.support.reader.JsonRuleDefinitionReader;
import org.jeasy.rules.support.reader.YamlRuleDefinitionReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class MVELRuleFactoryTest {
@Parameterized.Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(
new Object[][] {
{new MVELRuleFactory(new YamlRuleDefinitionReader()), "yml"},
{new MVELRuleFactory(new JsonRuleDefinitionReader()), "json"},
});
}
@Parameterized.Parameter(0)
public MVELRuleFactory factory;
@Parameterized.Parameter(1)
public String fileExtension;
@Test
public void testRulesCreation() throws Exception {
// given
File rulesDescriptor = new File("src/test/resources/rules." + fileExtension);
// when
Rules rules = factory.createRules(new FileReader(rulesDescriptor));
// then
assertThat(rules).hasSize(2);
Iterator<Rule> iterator = rules.iterator();
Rule rule = iterator.next();
assertThat(rule).isNotNull();
assertThat(rule.getName()).isEqualTo("adult rule");
assertThat(rule.getDescription()).isEqualTo("when age is greater than 18, then mark as adult");
assertThat(rule.getPriority()).isEqualTo(1);
rule = iterator.next();
assertThat(rule).isNotNull();
assertThat(rule.getName()).isEqualTo("weather rule");
assertThat(rule.getDescription()).isEqualTo("when it rains, then take an umbrella");
assertThat(rule.getPriority()).isEqualTo(2);
}
@Test
public void testRuleCreationFromFileReader() throws Exception {
// given
Reader adultRuleDescriptorAsReader =
new FileReader("src/test/resources/adult-rule." + fileExtension);
// when
Rule adultRule = factory.createRule(adultRuleDescriptorAsReader);
// then
assertThat(adultRule.getName()).isEqualTo("adult rule");
assertThat(adultRule.getDescription())
.isEqualTo("when age is greater than 18, then mark as adult");
assertThat(adultRule.getPriority()).isEqualTo(1);
}
@Test
public void testRuleCreationFromStringReader() throws Exception {
// given
Path ruleDescriptor = Paths.get("src/test/resources/adult-rule." + fileExtension);
Reader adultRuleDescriptorAsReader =
new StringReader(new String(Files.readAllBytes(ruleDescriptor)));
// when
Rule adultRule = factory.createRule(adultRuleDescriptorAsReader);
// then
assertThat(adultRule.getName()).isEqualTo("adult rule");
assertThat(adultRule.getDescription())
.isEqualTo("when age is greater than 18, then mark as adult");
assertThat(adultRule.getPriority()).isEqualTo(1);
}
@Test
public void testRuleCreationFromFileReader_withCompositeRules() throws Exception {
// given
File rulesDescriptor = new File("src/test/resources/composite-rules." + fileExtension);
// when
Rules rules = factory.createRules(new FileReader(rulesDescriptor));
// then
assertThat(rules).hasSize(2);
Iterator<Rule> iterator = rules.iterator();
Rule rule = iterator.next();
assertThat(rule).isNotNull();
assertThat(rule.getName()).isEqualTo("Movie id rule");
assertThat(rule.getDescription()).isEqualTo("description");
assertThat(rule.getPriority()).isEqualTo(1);
assertThat(rule).isInstanceOf(UnitRuleGroup.class);
rule = iterator.next();
assertThat(rule).isNotNull();
assertThat(rule.getName()).isEqualTo("weather rule");
assertThat(rule.getDescription()).isEqualTo("when it rains, then take an umbrella");
assertThat(rule.getPriority()).isEqualTo(1);
}
@Test
public void testRuleCreationFromFileReader_withInvalidCompositeRuleType() {
// given
File rulesDescriptor =
new File("src/test/resources/composite-rule-invalid-composite-rule-type." + fileExtension);
// when
Assertions.assertThatThrownBy(() -> factory.createRule(new FileReader(rulesDescriptor)))
// then
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(
"Invalid composite rule type, must be one of [UnitRuleGroup, ConditionalRuleGroup, ActivationRuleGroup]");
}
@Test
public void testRuleCreationFromFileReader_withEmptyComposingRules() {
// given
File rulesDescriptor =
new File(
"src/test/resources/composite-rule-invalid-empty-composing-rules." + fileExtension);
// when
Assertions.assertThatThrownBy(() -> factory.createRule(new FileReader(rulesDescriptor)))
// then
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Composite rules must have composing rules specified");
}
@Test
public void testRuleCreationFromFileReader_withNonCompositeRuleDeclaresComposingRules() {
// given
File rulesDescriptor =
new File("src/test/resources/non-composite-rule-with-composing-rules." + fileExtension);
// when
Assertions.assertThatThrownBy(() -> factory.createRule(new FileReader(rulesDescriptor)))
// then
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Non-composite rules cannot have composing rules");
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package shopcar.gui;
/**
*
* @author Vitor Freitas
*/
public interface ITab
{
public static final String RESOURCES = "/resources/";
default void init()
{
setTabValues();
createGraphic();
createContent();
}
public void setTabValues();
public void createGraphic();
public void createContent();
}
|
package org.iplantc.service.tags.utils;
import java.util.Date;
import org.iplantc.service.tags.utils.BindingUtils;
import org.restlet.data.Status;
import org.restlet.resource.ResourceException;
public class QueryParameterUtils {
/**
* Throws an {@link IllegalArgumentException} if no Integer can be parsed
* from the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkInteger(String name, String value) {
toInteger(name, value);
}
/**
* Returns the Integer parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Integer can be parsed.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Integer toInteger(String name, String value) {
try {
return BindingUtils.toInteger(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
/**
* Throws an {@link IllegalArgumentException} if no Long can be parsed from
* the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkLong(String name, String value) {
toLong(name, value);
}
/**
* Returns the Long parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Long can be parsed.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Long toLong(String name, String value) {
try {
return BindingUtils.toLong(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
/**
* Throws an {@link IllegalArgumentException} if no Date can be parsed from
* the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkDate(String name, String value) {
toDate(name, value);
}
/**
* Returns the Date parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Date can be parsed.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Date toDate(String name, String value) {
try {
return BindingUtils.toDate(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
/**
* Throws an {@link IllegalArgumentException} if no Double can be parsed
* from the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkDouble(String name, String value) {
toDouble(name, value);
}
/**
* Returns the Double parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Double can be parsed.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Double toDouble(String name, String value) {
try {
return BindingUtils.toDouble(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
/**
* Throws an {@link IllegalArgumentException} if no Float can be parsed from
* the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkFloat(String name, String value) {
toFloat(name, value);
}
/**
* Returns the Float parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Float can be parsed.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Float toFloat(String name, String value) {
try {
return BindingUtils.toFloat(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
/**
* Throws an {@link IllegalArgumentException} if no Boolean can be parsed
* from the variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static void checkBoolean(String name, String value) {
toBoolean(name, value);
}
/**
* Returns the Boolean parsed from the variable's value. Throws an
* {@link IllegalArgumentException} if no Boolean can be parsed from the
* variable's value.
*
* @param name
* The name of the query parameter.
* @param value
* The variable's value.
*/
public static Boolean toBoolean(String name, String value) {
try {
return BindingUtils.toBoolean(value);
} catch (IllegalArgumentException e) {
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Bad query parameter [" + name + "]: " + e.getMessage());
}
}
}
|
/*
* Copyright 2005-2017 Dozer Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dozer.vo.mapperaware;
/**
* @author Dmitry Spikhalskiy
* @since 03.01.13
*/
public class MapperAwareSimpleSrc {
private MapperAwareSimpleInternal one;
public MapperAwareSimpleInternal getOne() {
return one;
}
public void setOne(MapperAwareSimpleInternal one) {
this.one = one;
}
}
|
/**
* <copyright>
*
* Copyright (c) 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation
*
* </copyright>
*/
package org.eclipse.bpmn2.impl;
import com.google.gwt.user.client.rpc.GwtTransient;
import org.eclipse.bpmn2.Bpmn2Package;
import org.eclipse.bpmn2.ErrorEventDefinition;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Error Event Definition</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.eclipse.bpmn2.impl.ErrorEventDefinitionImpl#getErrorRef <em>Error Ref</em>}</li>
* </ul>
*
* @generated
*/
public class ErrorEventDefinitionImpl extends EventDefinitionImpl implements ErrorEventDefinition {
/**
* The cached value of the '{@link #getErrorRef() <em>Error Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getErrorRef()
* @generated
* @ordered
*/
@GwtTransient
protected org.eclipse.bpmn2.Error errorRef;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ErrorEventDefinitionImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Bpmn2Package.Literals.ERROR_EVENT_DEFINITION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public org.eclipse.bpmn2.Error getErrorRef() {
if (errorRef != null && errorRef.eIsProxy()) {
InternalEObject oldErrorRef = (InternalEObject) errorRef;
errorRef = (org.eclipse.bpmn2.Error) eResolveProxy(oldErrorRef);
if (errorRef != oldErrorRef) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF, oldErrorRef, errorRef));
}
}
return errorRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public org.eclipse.bpmn2.Error basicGetErrorRef() {
return errorRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setErrorRef(org.eclipse.bpmn2.Error newErrorRef) {
org.eclipse.bpmn2.Error oldErrorRef = errorRef;
errorRef = newErrorRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF,
oldErrorRef, errorRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF:
if (resolve)
return getErrorRef();
return basicGetErrorRef();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF:
setErrorRef((org.eclipse.bpmn2.Error) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF:
setErrorRef((org.eclipse.bpmn2.Error) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Bpmn2Package.ERROR_EVENT_DEFINITION__ERROR_REF:
return errorRef != null;
}
return super.eIsSet(featureID);
}
} //ErrorEventDefinitionImpl
|
package org.basex.util;
import static org.basex.util.Token.*;
import org.basex.util.list.ByteList;
/**
* This class provides functions for encoding and decoding Base64 strings.
*
* @author BaseX Team 2005-12, BSD License
* @author Christian Gruen
*/
public final class Base64 {
/** Ending characters. */
private static final byte[] ENDING = token("AQgw");
/** Hidden constructor. */
private Base64() { }
/**
* Encodes the specified string.
* @param token value to be encoded
* @return resulting token
*/
public static String encode(final String token) {
return string(encode(token(token)));
}
/**
* Encodes the specified token.
* @param token value to be encoded
* @return resulting token
*/
public static byte[] encode(final byte[] token) {
final ByteList bl = new ByteList();
final int a = token.length;
final int f = a / 3;
final int p = a - 3 * f;
int c = 0;
for(int i = 0; i < f; ++i) {
final int b0 = token[c++] & 0xff;
final int b1 = token[c++] & 0xff;
final int b2 = token[c++] & 0xff;
bl.add(H2B[b0 >> 2]);
bl.add(H2B[b0 << 4 & 0x3f | b1 >> 4]);
bl.add(H2B[b1 << 2 & 0x3f | b2 >> 6]);
bl.add(H2B[b2 & 0x3f]);
}
if(p != 0) {
final int b0 = token[c++] & 0xff;
bl.add(H2B[b0 >> 2]);
if(p == 1) {
bl.add(H2B[b0 << 4 & 0x3f]);
bl.add('=');
bl.add('=');
} else {
final int b1 = token[c] & 0xff;
bl.add(H2B[b0 << 4 & 0x3f | b1 >> 4]);
bl.add(H2B[b1 << 2 & 0x3f]);
bl.add('=');
}
}
return bl.toArray();
}
/** Hex to byte conversion table. */
private static final byte[] H2B = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/**
* Decodes the specified string.
* @param token value to be decoded
* @return resulting token
*/
public static String decode(final String token) {
return string(decode(token(token)));
}
/**
* Decodes the specified token.
* @param token value to be decoded
* @return resulting token
*/
public static byte[] decode(final byte[] token) {
final ByteList bl = new ByteList();
for(final byte c : token) if(c < 0 || c > ' ') bl.add(c);
final byte[] s = bl.toArray();
if((s.length & 3) != 0) error(s);
final int l = s.length;
final int g = l >>> 2;
int m = 0, n = g;
if(l != 0) {
if(s[l - 1] == '=') {
++m;
--n;
}
if(s[l - 2] == '=') ++m;
if(m == 2 && !contains(ENDING, s[l - 3])) error(substring(s, l - 3));
}
final byte[] val = new byte[3 * g - m];
int c = 0, o = 0;
for(int i = 0; i < n; ++i) {
final int c0 = b2h(s[c++]);
final int c1 = b2h(s[c++]);
final int c2 = b2h(s[c++]);
final int c3 = b2h(s[c++]);
val[o++] = (byte) (c0 << 2 | c1 >> 4);
val[o++] = (byte) (c1 << 4 | c2 >> 2);
val[o++] = (byte) (c2 << 6 | c3);
}
if(m != 0) {
final int c0 = b2h(s[c++]);
final int c1 = b2h(s[c++]);
val[o++] = (byte) (c0 << 2 | c1 >> 4);
if(m == 1) val[o] = (byte) (c1 << 4 | b2h(s[c]) >> 2);
}
return val;
}
/** Byte to hex conversion table. */
private static final byte[] B2H = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1,
-1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51
};
/**
* Converts a single byte to its hex representation.
* @param c character to be encoded
* @return encoded value
*/
private static int b2h(final byte c) {
if(c < 0 || c >= B2H.length) error((char) c);
final int result = B2H[c];
if(result < 0) error((char) c);
return result;
}
/**
* Throws an illegal argument exception for the specified character.
* @param a character
*/
private static void error(final Object a) {
throw new IllegalArgumentException(Util.info("Invalid Base64 cast: %.", a));
}
}
|
package com.appettea.appetteaPOS;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
//import org.greenrobot.eventbus.Subscri
import androidx.annotation.NonNull;
import org.greenrobot.eventbus.EventBus;
import java.util.HashMap;
public class ReceiveSms extends BroadcastReceiver {
private ReceiveSms.GetSms listener;
/**
* Detects left and right swipes across a view.
*/
/*
public ReceiveSms(Context context){
try {
listener=(ReceiveSms.GetSms) context;
}
catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
/*
public ReceiveSms(){
//get
}
*/
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "SMS RECEIVED", Toast.LENGTH_SHORT).show();
// listener=(ReceiveSms.GetSms) context;
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras();
SmsMessage [] msgs;
String msg_from;
if(bundle != null){
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i< msgs.length;i++){
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
if(isCorrect(msg_from,msgBody)){
HashMap<String,String> map = parseMessage(msgBody);
String build = "Code : "+ map.get("code")+'\n'+"phone : "+map.get("phone")+'\n'+"Received :"+map.get("ksh")+'\n'+"Name : "+ map.get("name")+"\n"+"Date :" + map.get("date")+"\n"+"Time :"+map.get("time");
//map.put("code",code); map.put("date",date); map.put("time",time); map.put("ksh",ksh); map.put("phone",phone);map.put("name",person_name);
Toast.makeText(context, "From : "+msg_from+" \n"+build, Toast.LENGTH_SHORT).show();
//listener.passSms(map);
EventBus.getDefault().post(new OnReceiverEvent(new MessageParser(msgBody)));
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
private HashMap<String,String> parseMessage(String message){
HashMap<String,String> map = new HashMap<>();
String msgList = message.replace(".","");
String[] items = msgList.split(" ");
String person_name="";
String date = "";
String time = "";
String ksh = "";
String phone = "";
int i = 0;
for (String item : items) {
Log.e("TAG >", items[i]);
if(i == 3) date = items[i];
if(i == 5) time = items[i]+items[i+1];
if(i == 7) ksh = items[i];
if (i>10 && isNumeric(items[i])){phone = items[i]; break;}
if (i>9 && !isNumeric(items[i])) person_name += items[i]+" ";
i++;
}
String code = items[0];
map.put("code",code); map.put("date",date); map.put("time",time); map.put("ksh",ksh); map.put("phone",phone);map.put("name",person_name);
return map;
}
public static boolean isNumeric(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
public interface GetSms{
public void passSms(HashMap<String,String> map);
}
public void setListener(Context context){
this.listener=(GetSms) context;
}
private boolean isCorrect(String msgFrom,String message){
if (message.contains("Utility") && msgFrom.equals("MPESA")) return true;
return false;
}
}
|
/**
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.rxjava3.internal.operators.mixed;
import java.util.Objects;
import java.util.concurrent.atomic.*;
import org.reactivestreams.*;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
import io.reactivex.rxjava3.internal.util.*;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
/**
* Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones
* while disposing the older ones and emits the latest success value if available, optionally delaying
* errors from the main source or the inner sources.
* <p>History: 2.1.11 - experimental
* @param <T> the upstream value type
* @param <R> the downstream value type
* @since 2.2
*/
public final class FlowableSwitchMapMaybe<T, R> extends Flowable<R> {
final Flowable<T> source;
final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
final boolean delayErrors;
public FlowableSwitchMapMaybe(Flowable<T> source,
Function<? super T, ? extends MaybeSource<? extends R>> mapper,
boolean delayErrors) {
this.source = source;
this.mapper = mapper;
this.delayErrors = delayErrors;
}
@Override
protected void subscribeActual(Subscriber<? super R> s) {
source.subscribe(new SwitchMapMaybeSubscriber<>(s, mapper, delayErrors));
}
static final class SwitchMapMaybeSubscriber<T, R> extends AtomicInteger
implements FlowableSubscriber<T>, Subscription {
private static final long serialVersionUID = -5402190102429853762L;
final Subscriber<? super R> downstream;
final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
final boolean delayErrors;
final AtomicThrowable errors;
final AtomicLong requested;
final AtomicReference<SwitchMapMaybeObserver<R>> inner;
static final SwitchMapMaybeObserver<Object> INNER_DISPOSED =
new SwitchMapMaybeObserver<>(null);
Subscription upstream;
volatile boolean done;
volatile boolean cancelled;
long emitted;
SwitchMapMaybeSubscriber(Subscriber<? super R> downstream,
Function<? super T, ? extends MaybeSource<? extends R>> mapper,
boolean delayErrors) {
this.downstream = downstream;
this.mapper = mapper;
this.delayErrors = delayErrors;
this.errors = new AtomicThrowable();
this.requested = new AtomicLong();
this.inner = new AtomicReference<>();
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(upstream, s)) {
upstream = s;
downstream.onSubscribe(this);
s.request(Long.MAX_VALUE);
}
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onNext(T t) {
SwitchMapMaybeObserver<R> current = inner.get();
if (current != null) {
current.dispose();
}
MaybeSource<? extends R> ms;
try {
ms = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
upstream.cancel();
inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED);
onError(ex);
return;
}
SwitchMapMaybeObserver<R> observer = new SwitchMapMaybeObserver<>(this);
for (;;) {
current = inner.get();
if (current == INNER_DISPOSED) {
break;
}
if (inner.compareAndSet(current, observer)) {
ms.subscribe(observer);
break;
}
}
}
@Override
public void onError(Throwable t) {
if (errors.tryAddThrowableOrReport(t)) {
if (!delayErrors) {
disposeInner();
}
done = true;
drain();
}
}
@Override
public void onComplete() {
done = true;
drain();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
void disposeInner() {
SwitchMapMaybeObserver<R> current = inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED);
if (current != null && current != INNER_DISPOSED) {
current.dispose();
}
}
@Override
public void request(long n) {
BackpressureHelper.add(requested, n);
drain();
}
@Override
public void cancel() {
cancelled = true;
upstream.cancel();
disposeInner();
errors.tryTerminateAndReport();
}
void innerError(SwitchMapMaybeObserver<R> sender, Throwable ex) {
if (inner.compareAndSet(sender, null)) {
if (errors.tryAddThrowableOrReport(ex)) {
if (!delayErrors) {
upstream.cancel();
disposeInner();
}
drain();
}
} else {
RxJavaPlugins.onError(ex);
}
}
void innerComplete(SwitchMapMaybeObserver<R> sender) {
if (inner.compareAndSet(sender, null)) {
drain();
}
}
void drain() {
if (getAndIncrement() != 0) {
return;
}
int missed = 1;
Subscriber<? super R> downstream = this.downstream;
AtomicThrowable errors = this.errors;
AtomicReference<SwitchMapMaybeObserver<R>> inner = this.inner;
AtomicLong requested = this.requested;
long emitted = this.emitted;
for (;;) {
for (;;) {
if (cancelled) {
return;
}
if (errors.get() != null) {
if (!delayErrors) {
errors.tryTerminateConsumer(downstream);
return;
}
}
boolean d = done;
SwitchMapMaybeObserver<R> current = inner.get();
boolean empty = current == null;
if (d && empty) {
errors.tryTerminateConsumer(downstream);
return;
}
if (empty || current.item == null || emitted == requested.get()) {
break;
}
inner.compareAndSet(current, null);
downstream.onNext(current.item);
emitted++;
}
this.emitted = emitted;
missed = addAndGet(-missed);
if (missed == 0) {
break;
}
}
}
static final class SwitchMapMaybeObserver<R>
extends AtomicReference<Disposable> implements MaybeObserver<R> {
private static final long serialVersionUID = 8042919737683345351L;
final SwitchMapMaybeSubscriber<?, R> parent;
volatile R item;
SwitchMapMaybeObserver(SwitchMapMaybeSubscriber<?, R> parent) {
this.parent = parent;
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this, d);
}
@Override
public void onSuccess(R t) {
item = t;
parent.drain();
}
@Override
public void onError(Throwable e) {
parent.innerError(this, e);
}
@Override
public void onComplete() {
parent.innerComplete(this);
}
void dispose() {
DisposableHelper.dispose(this);
}
}
}
}
|
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cloud.contract.stubrunner.spring.cloud.ribbon;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.contract.stubrunner.RunningStubs;
import org.springframework.cloud.contract.stubrunner.StubConfiguration;
import org.springframework.cloud.contract.stubrunner.StubFinder;
import org.springframework.cloud.contract.stubrunner.spring.cloud.StubMapperProperties;
import org.springframework.util.StringUtils;
/**
* Stub Runner representation of a server list
*
* @author Marcin Grzejszczak
* @since 1.0.0
*/
class StubRunnerRibbonServerList implements ServerList<Server> {
private static final Log log = LogFactory
.getLog(MethodHandles.lookup().lookupClass());
private final ServerList<Server> serverList;
StubRunnerRibbonServerList(final StubFinder stubFinder,
final StubMapperProperties stubMapperProperties,
final IClientConfig clientConfig) {
String serviceName = clientConfig.getClientName();
String mappedServiceName = StringUtils
.hasText(stubMapperProperties.fromServiceIdToIvyNotation(serviceName))
? stubMapperProperties.fromServiceIdToIvyNotation(serviceName)
: serviceName;
RunningStubs runningStubs = stubFinder.findAllRunningStubs();
final Map.Entry<StubConfiguration, Integer> entry = runningStubs
.getEntry(mappedServiceName);
final List<Server> servers = new ArrayList<>();
if (entry != null) {
servers.add(new Server("localhost", entry.getValue()) {
@Override
public MetaInfo getMetaInfo() {
return new MetaInfo() {
@Override
public String getAppName() {
return stubMapperProperties.fromIvyNotationToId(
entry.getKey().toColonSeparatedDependencyNotation());
}
@Override
public String getServerGroup() {
return null;
}
@Override
public String getServiceIdForDiscovery() {
return stubMapperProperties
.fromIvyNotationToId(entry.getKey().getArtifactId());
}
@Override
public String getInstanceId() {
return stubMapperProperties
.fromIvyNotationToId(entry.getKey().getArtifactId());
}
};
}
});
}
this.serverList = new ServerList<Server>() {
@Override
public List<Server> getInitialListOfServers() {
return servers;
}
@Override
public List<Server> getUpdatedListOfServers() {
return servers;
}
};
}
@Override
public List<Server> getInitialListOfServers() {
return this.serverList.getInitialListOfServers();
}
@Override
public List<Server> getUpdatedListOfServers() {
return this.serverList.getUpdatedListOfServers();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.