text
stringlengths 7
1.01M
|
|---|
/*
* Copyright 2019-2020 Zheng Jie
*
* 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.treasury.modules.system.rest;
import com.treasury.modules.system.service.DictDetailService;
import com.treasury.modules.system.service.dto.DictDetailQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import com.treasury.annotation.Log;
import com.treasury.exception.BadRequestException;
import com.treasury.modules.system.domain.DictDetail;
import com.treasury.modules.system.service.dto.DictDetailDto;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@RestController
@RequiredArgsConstructor
@Api(tags = "系统:字典详情管理")
@RequestMapping("/api/dictDetail")
public class DictDetailController {
private final DictDetailService dictDetailService;
private static final String ENTITY_NAME = "dictDetail";
@ApiOperation("查询字典详情")
@GetMapping
public ResponseEntity<Object> queryDictDetail(DictDetailQueryCriteria criteria,
@PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable){
return new ResponseEntity<>(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation("查询多个字典详情")
@GetMapping(value = "/map")
public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){
String[] names = dictName.split("[,,]");
Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16);
for (String name : names) {
dictMap.put(name, dictDetailService.getDictByName(name));
}
return new ResponseEntity<>(dictMap, HttpStatus.OK);
}
@Log("新增字典详情")
@ApiOperation("新增字典详情")
@PostMapping
@PreAuthorize("@el.check('dict:add')")
public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
dictDetailService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改字典详情")
@ApiOperation("修改字典详情")
@PutMapping
@PreAuthorize("@el.check('dict:edit')")
public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
dictDetailService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除字典详情")
@ApiOperation("删除字典详情")
@DeleteMapping(value = "/{id}")
@PreAuthorize("@el.check('dict:del')")
public ResponseEntity<Object> deleteDictDetail(@PathVariable Long id){
dictDetailService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
/*
* 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.aliyuncs.v5.rds.model.v20140815;
import com.aliyuncs.v5.RpcAcsRequest;
import com.aliyuncs.v5.http.MethodType;
import com.aliyuncs.v5.rds.Endpoint;
/**
* @author auto create
* @version
*/
public class DescribeDasInstanceConfigRequest extends RpcAcsRequest<DescribeDasInstanceConfigResponse> {
private Long resourceOwnerId;
private String resourceOwnerAccount;
private String clientToken;
private Long ownerId;
private String dBInstanceId;
public DescribeDasInstanceConfigRequest() {
super("Rds", "2014-08-15", "DescribeDasInstanceConfig", "rds");
setMethod(MethodType.POST);
try {
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public Long getResourceOwnerId() {
return this.resourceOwnerId;
}
public void setResourceOwnerId(Long resourceOwnerId) {
this.resourceOwnerId = resourceOwnerId;
if(resourceOwnerId != null){
putQueryParameter("ResourceOwnerId", resourceOwnerId.toString());
}
}
public String getResourceOwnerAccount() {
return this.resourceOwnerAccount;
}
public void setResourceOwnerAccount(String resourceOwnerAccount) {
this.resourceOwnerAccount = resourceOwnerAccount;
if(resourceOwnerAccount != null){
putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
}
public String getClientToken() {
return this.clientToken;
}
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
if(clientToken != null){
putQueryParameter("ClientToken", clientToken);
}
}
public Long getOwnerId() {
return this.ownerId;
}
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
if(ownerId != null){
putQueryParameter("OwnerId", ownerId.toString());
}
}
public String getDBInstanceId() {
return this.dBInstanceId;
}
public void setDBInstanceId(String dBInstanceId) {
this.dBInstanceId = dBInstanceId;
if(dBInstanceId != null){
putQueryParameter("DBInstanceId", dBInstanceId);
}
}
@Override
public Class<DescribeDasInstanceConfigResponse> getResponseClass() {
return DescribeDasInstanceConfigResponse.class;
}
}
|
/*
* 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.jena.sparql.modify;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.jena.graph.Node;
import org.apache.jena.graph.NodeFactory;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.core.DatasetGraphFactory;
import org.apache.jena.sparql.graph.GraphFactory;
import org.apache.jena.sparql.modify.request.Target;
import org.apache.jena.sparql.modify.request.UpdateAdd;
import org.apache.jena.sparql.modify.request.UpdateCreate;
import org.apache.jena.sparql.modify.request.UpdateDrop;
import org.apache.jena.sparql.sse.SSE;
import org.apache.jena.update.Update;
import org.apache.jena.update.UpdateAction;
import org.apache.jena.update.UpdateException;
import org.junit.Test;
public abstract class AbstractTestUpdateGraphMgt extends AbstractTestUpdateBase
{
static final Node graphIRI = NodeFactory.createURI("http://example/graph");
@Test
public void testCreateDrop1() {
DatasetGraph gStore = getEmptyDatasetGraph();
Update u = new UpdateCreate(graphIRI);
UpdateAction.execute(u, gStore);
assertTrue(graphEmpty(gStore.getGraph(graphIRI)));
// With "auto SILENT" then these aren't errors.
boolean silentMode = true;
if ( !silentMode ) {
// try again - should fail (already exists)
try {
UpdateAction.execute(u, gStore);
fail();
} catch (UpdateException ex) {}
}
// Drop it.
u = new UpdateDrop(graphIRI);
UpdateAction.execute(u, gStore);
assertFalse(gStore.containsGraph(graphIRI));
if ( !silentMode ) {
// Drop it again. - should fail
try {
UpdateAction.execute(u, gStore);
fail();
} catch (UpdateException ex) {}
}
}
@Test
public void testCreateDrop2() {
DatasetGraph gStore = getEmptyDatasetGraph();
Update u = new UpdateCreate(graphIRI);
UpdateAction.execute(u, gStore);
u = new UpdateCreate(graphIRI, true);
UpdateAction.execute(u, gStore);
assertTrue(graphEmpty(gStore.getGraph(graphIRI)));
u = new UpdateDrop(graphIRI);
UpdateAction.execute(u, gStore);
assertFalse(gStore.containsGraph(graphIRI));
u = new UpdateDrop(graphIRI, true);
UpdateAction.execute(u, gStore);
}
@Test
public void testCreateDrop3() {
DatasetGraph gStore = getEmptyDatasetGraph();
script(gStore, "create-1.ru");
// JENA-1068
// assertTrue(gStore.containsGraph(graphIRI)) ;
assertTrue(graphEmpty(gStore.getGraph(graphIRI)));
}
@Test
public void testCreateDrop4() {
DatasetGraph gStore = getEmptyDatasetGraph();
gStore.addGraph(graphIRI, GraphFactory.createDefaultGraph());
script(gStore, "drop-1.ru");
assertFalse(gStore.containsGraph(graphIRI));
}
@Test
public void testAdd() {
DatasetGraph gStore = DatasetGraphFactory.create();
Node g1 = SSE.parseNode(":g1");
Node g2 = SSE.parseNode(":g2");
gStore.add(SSE.parseQuad("( :g1 :s :p :o )"));
// ADD GRAPH :g1 TO GRAPH :g2, not SILENT
Update add = new UpdateAdd(Target.create(g1), Target.create(g2), false);
assertFalse(gStore.containsGraph(g2));
UpdateAction.execute(add, gStore);
assertTrue(gStore.containsGraph(g2));
}
}
|
package de.unistuttgart.isw.sfsc.commonjava.util.scheduling;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class SchedulerService implements Scheduler, AutoCloseable {
private final ScheduledExecutorService scheduledExecutorService;
public SchedulerService(int numberOfThreads) {
scheduledExecutorService = Executors.newScheduledThreadPool(numberOfThreads);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
return scheduledExecutorService.schedule(command, delay, unit);
}
@Override
public void execute(Runnable command) {
scheduledExecutorService.execute(command);
}
@Override
public void close() {
scheduledExecutorService.shutdownNow();
}
}
|
/*
* MIT License
*
* Copyright (c) 2019 Udo Borkowski, (ub@abego.org)
*
* 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.abego.guitesting.swing;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Event Dispatch Thread (EDT) Support
*/
public interface EDTSupport {
/**
* Runs the {@code runnable} in the Event Dispatch Thread (EDT) and
* waits until the runnable is finished.
* <p>
* The method may also be called from within the Event Dispatch Thread.
* In that case the runnable runs immediately.
*
* @param runnable the {@link Runnable} to run in the Event Dispatch Thread.
*/
void runInEDT(Runnable runnable);
/**
* Runs the {@code actionListener} with the given {@code event} in the
* Event Dispatch Thread (EDT) (using action.actionPerformed) and
* waits until the actionListener is finished.
* <p>
* The method may also be called from within the Event Dispatch Thread.
* In that case the runnable runs immediately.
*
* @param actionListener the {@link ActionListener} to run in the Event
* Dispatch Thread.
* @param event the {@link ActionEvent} passed to the actionListener
*/
default void runInEDT(ActionListener actionListener, ActionEvent event) {
runInEDT(() -> actionListener.actionPerformed(event));
}
/**
* Runs the {@code actionListener} with an
* {@link ActionEvent#ACTION_PERFORMED} event and
* waits until the actionListener is finished.
* <p>
* The method may also be called from within the Event Dispatch Thread.
* In that case the runnable runs immediately.
*
* @param actionListener the {@link ActionListener} to run in the Event
* Dispatch Thread.
*/
default void runInEDT(ActionListener actionListener) {
runInEDT(actionListener,
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
/**
* Returns {@code true} when the current thread is the Event Dispatch
* Thread, {@code false} otherwise.
*
* @return {@code true} when the current thread is the Event Dispatch
* Thread, {@code false} otherwise
*/
default boolean isEDT() {
return SwingUtilities.isEventDispatchThread();
}
}
|
package test;
import com.google.auto.value.AutoValue;
@AutoValue abstract class NoAutoMoshi {
abstract int a();
}
|
package hw;
public class Test {
public static void main(String[] args) {
System.out.println("hello world.");
}
}
|
package cn.iocoder.mall.pay.biz.dataobject;
import cn.iocoder.common.framework.dataobject.DeletableDO;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 支付通知 App 的日志 DO
*
* 通过该表,记录通知 App 时,产生的日志
*/
@Data
@Accessors(chain = true)
public class PayNotifyLogDO extends DeletableDO {
/**
* 日志编号,自增
*/
private Integer id;
/**
* 通知编号
*/
private Integer notifyId;
/**
* 请求参数
*/
private String request;
/**
* 响应结果
*/
private String response;
/**
* 状态
*
* @see cn.iocoder.mall.pay.api.constant.PayTransactionNotifyStatusEnum
*/
private Integer status;
}
|
/***********************************************************************************
* *
* Copyright (C) 2017 Erasmus MC, Rotterdam, The Netherlands *
* *
* This file is part of Jerboa. *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
* *
***********************************************************************************/
/******************************************************************************************
* Jerboa software version 3.0 - Copyright Erasmus University Medical Center, Rotterdam *
* *
* Author: Mees Mosseveld (MM) - department of Medical Informatics *
* *
* $Rev:: 3961 $: Revision of last commit *
* $Author:: root $: Author of last commit *
* $Date:: 2013-05# $: Date and time (CET) of last commit *
******************************************************************************************/
package org.erasmusmc.jerboa.modifiers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.text.StrBuilder;
import org.erasmusmc.jerboa.Jerboa;
import org.erasmusmc.jerboa.config.DataDefinition;
import org.erasmusmc.jerboa.dataClasses.Patient;
import org.erasmusmc.jerboa.dataClasses.Prescription;
import org.erasmusmc.jerboa.engine.Modifier;
import org.erasmusmc.jerboa.utilities.DateUtilities;
import org.erasmusmc.jerboa.utilities.Logging;
/**
* This modifier defines combinations of drugs prescribed.
* @author bmosseveld
*
*/
public class PrescriptionCombinations extends Modifier {
/**
* The drug group definitions it will look for.
* The drug groups should be distinct.
* Format:
*
* Group Name;ATC, ... ,ATC
*
* where
*
* Group Name = The name of the group that is also used in the combination definitions.
* ATC = An ATC code of a drug that is a member of the group.
*/
public List<String> drugGroups = new ArrayList<String>();
/**
* The combination definitions it will look for.
* Format:
*
* Combination Name;Drug Group, ... ,Drug Group
*
* where
*
* Combination Name = The name of the combination.
* IMPORTANT: In subsequent modifiers and the surrounding module the name of the combination
* has to be preceded by an underscore.
* Drug Group = A drug group, as specified in the drugGroups parameter, that are part of the combination.
*/
public List<String> combinations = new ArrayList<String>();
/**
* When true all duplicates of combinations (same ATC, start date, and duration) are removed, otherwise only
* duplicates where either in both combinations all components of the combination start at the start of the
* combination or in both combinations they do not all start at the start of the combination.
*/
public boolean removeDifferentCompStarts;
/**
* If true, prescriptions of combinations of the same drugs that connect or overlap are merged.
* Merging is never applied to combinations of the original prescriptions (no exposure definition applied).
*/
public boolean mergeCombinations;
private TimeLine timeLine = null;
private TimeLine exposureTimeLine = null;
private TimeLine originalTimeLine = null;
private DrugGroups drugGroupDefinitions = null;
private Combinations combinationDefinitions = null;
private String error = "";
@Override
public boolean init() {
boolean initOK = (drugGroupDefinitions = new DrugGroups(drugGroups)).isOk();
initOK = initOK && (combinationDefinitions = new Combinations(combinations)).isOk();
if (initOK && intermediateFiles){
initOK = initOK && Jerboa.getOutputManager().addFile(this.intermediateFileName,100);
if (initOK) {
String header = "Source";
header += "," + "SubsetID";
header += "," + "PatientID";
header += "," + "Date";
header += "," + "Duration";
header += "," + "Combination";
header += "," + "Dose";
header += "," + "CombinationStartDate";
Jerboa.getOutputManager().writeln(this.intermediateFileName, header, true);
}
else {
error = "Could not create intermediate file " + this.intermediateFileName;
}
}
if (!initOK) {
Logging.add("Modifier " + this.title + ": " + error, Logging.ERROR);
}
return initOK;
}
@Override
public Patient process(Patient patient) {
if ((patient != null) && patient.isInPopulation() && patient.isInCohort()) {
addCombinations(patient.ID, patient.prescriptions,"Prescriptions", mergeCombinations);
if (Jerboa.unitTest) {
exposureTimeLine = timeLine;
}
addCombinations(patient.ID, patient.originalPrescriptions,"Original Prescriptions", false);
if (Jerboa.unitTest) {
originalTimeLine = timeLine;
}
}
return patient;
}
@Override
public void outputResults() {
Jerboa.getOutputManager().closeFile(this.intermediateFileName);
}
@Override
public void setNeededFiles() {
setRequiredFile(DataDefinition.PATIENTS_FILE);
setRequiredFile(DataDefinition.PRESCRIPTIONS_FILE);
}
@Override
public void setNeededExtendedColumns() {
}
@Override
public void setNeededNumericColumns() { }
/**
* Adds all the prescriptions to the timeline as drug groups
*
* @param patientID
* @param prescriptions
* @param intermediateLabel
* @param mergePrescriptions
*/
private void addCombinations(String patientID, List<Prescription> prescriptions, String intermediateLabel, boolean mergePrescriptions) {
// Add prescriptions to timeline as drug group
timeLine = new TimeLine();
for (Prescription prescription : prescriptions) {
String prescriptionATC = prescription.getATC();
Set<String> drugGroups = drugGroupDefinitions.getDrugGroups(prescriptionATC);
for (String drugGroup : drugGroups) {
Prescription drugGroupPrescription = new Prescription(prescription);
drugGroupPrescription.setATC(drugGroup);
timeLine.addPrescription(drugGroupPrescription);
}
}
if (debugPatientIDs.contains(patientID)){
Logging.add(patientID+":"+intermediateLabel);
Logging.add(timeLine.toString());
Logging.addNewLine();
}
// scan each interval in the time for combinations of interest
List<Prescription> addedPrescriptions = new ArrayList<Prescription>();
Set<String> combinationATC = new HashSet<String>();
Map<String, List<Prescription> > combinationPrescriptions = new HashMap<String, List<Prescription> >();
for (Interval interval : timeLine.getTimeLine()) {
Map<String, List<Prescription> > intervalATCMap = interval.getATCMap();
for (Combination combination : combinationDefinitions.getCombinations()) {
/* combinationsList contains for the combination of interest a list of prescriptions
* that are in the combination.
*/
List< List<Prescription> > combinationsList = new ArrayList< List<Prescription> >();
List<Integer> combinationStartDates = new ArrayList<Integer>();
/* create all possible subsets of prescriptions that could form the combination
* if foundAll = false the combination could not be formed from a subset
*/
boolean foundAll = true;
for (String drugGroup : combination.getDrugGroupSet()) {
if (!intervalATCMap.containsKey(drugGroup)) {
foundAll = false;
break;
}
else {
if (combinationsList.size() == 0) {
for (Prescription prescription : intervalATCMap.get(drugGroup)) {
List<Prescription> prescriptionList = new ArrayList<Prescription>();
prescriptionList.add(prescription);
combinationsList.add(prescriptionList);
combinationStartDates.add(prescription.getDate());
}
}
else {
List< List<Prescription> > newCombinationsList = new ArrayList< List<Prescription> >();
List<Integer> newCombinationStartDates = new ArrayList<Integer>();
for (Prescription newPrescription : intervalATCMap.get(drugGroup)) {
int startDate = -1;
for (int combinationNr = 0; combinationNr < combinationsList.size(); combinationNr++) {
List<Prescription> combinations = combinationsList.get(combinationNr);
List<Prescription> newCombination = new ArrayList<Prescription>();
for (Prescription prescription : combinations) {
newCombination.add(prescription);
}
startDate = combinationStartDates.get(combinationNr);
newCombination.add(newPrescription);
if (newPrescription.getDate() != startDate) {
startDate = -1;
}
newCombinationsList.add(newCombination);
newCombinationStartDates.add(startDate);
}
}
combinationsList = newCombinationsList;
combinationStartDates = newCombinationStartDates;
newCombinationsList = null;
}
}
}
if (foundAll) {
for (Integer startDate : combinationStartDates) {
// create a new prescription based on the found subsets that could form the combination
Prescription combinationPrescription = new Prescription();
combinationPrescription.setPatientID(patientID);
combinationPrescription.setATC(combination.getName());
combinationPrescription.setDate(interval.startDate);
combinationPrescription.setDuration(interval.endDate - interval.startDate);
combinationPrescription.setCombinationStartDate(startDate);
combinationPrescription.setDose("MIXED");
combinationPrescription.setPrescriberId(interval.getPrescriberId());
combinationPrescription.setPrescriberType(interval.getPrescriberType());
// Set boolean to check if all components start on this startDate and collect the doses
for (Prescription prescription : combinationsList.get(combinationStartDates.indexOf(startDate))) {
if (prescription.getStartDate() != startDate || prescription.getAllComponentsStart()==false) {
combinationPrescription.setAllComponentsStart(false);
break;
}
}
// Workaround to avoid duplicate entries
boolean exists = false;
for (Prescription prescription : addedPrescriptions){
if (prescription.getATC() == combinationPrescription.getATC() &&
prescription.getDate() == combinationPrescription.getDate() &&
prescription.getDuration() == combinationPrescription.getDuration() &&
(removeDifferentCompStarts || (prescription.getAllComponentsStart() == combinationPrescription.getAllComponentsStart()))) {
exists = true;
break;
}
}
if (!exists) {
addedPrescriptions.add(combinationPrescription);
combinationATC.add(combinationPrescription.getATC());
}
// save all the found combinations to allow merge
List<Prescription> combinations = combinationPrescriptions.get(combination.getName());
if (combinations == null) {
combinations = new ArrayList<Prescription>();
combinationPrescriptions.put(combination.getName(), combinations);
}
combinations.add(combinationPrescription);
}
}
}
}
// Added to avoid duplicates
prescriptions.addAll(addedPrescriptions);
if (mergePrescriptions) {
Collections.sort(prescriptions);
if (intermediateFiles) {
for (Prescription prescription : prescriptions) {
if (combinationATC.contains(prescription.getATC())) {
Jerboa.getOutputManager().write(
this.intermediateFileName,
"BEFORE MERGE " + intermediateLabel
+ "," + prescription.getSubset()
+ "," + prescription.getPatientID()
+ "," + DateUtilities.daysToDate(prescription.getDate())
+ "," + prescription.getDuration()
+ "," + prescription.getATC()
+ "," + (prescription.hasDose() ? prescription.getDose() : "")
+ "," + (prescription.getCombinationStartDate() == -1 ? "" : DateUtilities.daysToDate(prescription.getCombinationStartDate()))
+ System.lineSeparator(),
true);
}
}
}
// Merge consecutive prescriptions of the same combination
for (String combinationName : combinationPrescriptions.keySet()) {
List<Prescription> combinations = combinationPrescriptions.get(combinationName);
Collections.sort(combinations);
Prescription lastCombination = null;
for (Prescription combination : combinations) {
if (lastCombination != null) {
//only consider if the enddate > the lastCombination
// <------- drug ------->
// <----- drug----->
// would otherwise stop the combination
if (combination.getEndDate()>lastCombination.getEndDate()) {
if (lastCombination.getEndDate() == combination.getDate()) {
lastCombination.setDuration(lastCombination.getDuration() + combination.getDuration());
prescriptions.remove(combination);
}
else {
// if (lastCombination.getDuration() < combinationDefinitions.getCombination(combinationName).getMinimumDuration()) {
// prescriptions.remove(lastCombination);
// }
lastCombination = combination;
}
}
}
else {
lastCombination = combination;
}
}
//if ((lastCombination != null) && (lastCombination.getDuration() < combinationDefinitions.getCombination(combinationName).getMinimumDuration())) {
// prescriptions.remove(lastCombination);
//}
}
}
Collections.sort(prescriptions);
if (intermediateFiles) {
for (Prescription prescription : prescriptions) {
if (combinationATC.contains(prescription.getATC())) {
Jerboa.getOutputManager().write(
this.intermediateFileName,
intermediateLabel
+ "," + prescription.getSubset()
+ "," + prescription.getPatientID()
+ "," + DateUtilities.daysToDate(prescription.getDate())
+ "," + prescription.getDuration()
+ "," + prescription.getATC()
+ "," + (prescription.hasDose() ? prescription.getDose() : "")
+ "," + (prescription.getCombinationStartDate() == -1 ? "" : DateUtilities.daysToDate(prescription.getCombinationStartDate()))
+ System.lineSeparator(),
true);
}
}
}
}
public class TimeLine {
private List<Interval> timeLine = new ArrayList<Interval>();
public void addPrescription(Prescription prescription) {
int exposureStart = prescription.getDate();
int exposureEnd = prescription.getEndDate();
int intervalNr = 0;
while (intervalNr < timeLine.size()) {
Interval interval = timeLine.get(intervalNr);
if (((exposureEnd - exposureStart) > 0) && (exposureStart < interval.endDate)) {
Interval newInterval = null;
Interval newInterval2 = null;
if (exposureStart > interval.startDate) {
newInterval = interval.split(exposureStart);
timeLine.add(intervalNr + 1, newInterval);
newInterval2 = null;
if (exposureEnd < newInterval.endDate) {
newInterval2 = newInterval.split(exposureEnd);
timeLine.add(intervalNr + 2, newInterval2);
exposureStart = exposureEnd;
intervalNr++;
}
else {
exposureStart = newInterval.endDate;
intervalNr++;
}
newInterval.addPrescription(prescription);
}
else {
if (exposureEnd < interval.endDate) {
newInterval = interval.split(exposureEnd);
timeLine.add(intervalNr + 1, newInterval);
exposureStart = exposureEnd;
}
else {
exposureStart = interval.endDate;
}
interval.addPrescription(prescription);
}
//if (logDebugInfo > 3) {
// Logging.add(" -> " + interval.toString());
// if (newInterval != null) Logging.add(" " + newInterval.toString());
// if (newInterval2 != null) Logging.add(" " + newInterval2.toString());
//}
}
intervalNr++;
}
if (exposureStart != exposureEnd) {
//TODO Wijziging ongedaan gemaakt
//Interval newInterval;
//if (prescription.getStartDate() != exposureStart) {
// Prescription restPrescription = new Prescription(prescription);
// restPrescription.setAllComponentsStart(false);
// newInterval = new Interval(restPrescription);
//}
//else {
// newInterval = new Interval(prescription);
//}
//TODO
Interval newInterval = new Interval(prescription);
//TODO Wijziging ongedaan gemaakt
newInterval.startDate = exposureStart;
newInterval.endDate = exposureEnd;
timeLine.add(newInterval);
}
}
public List<Interval> getTimeLine() {
return timeLine;
}
public String toString() {
StrBuilder result = new StrBuilder();
result.appendln("TimeLine");
for (Interval interval : timeLine)
result.appendln(" " + interval);
return result.toString();
}
}
public class Interval {
private int startDate = -1;
private int endDate = -1;
private Set<String> atcSet = new HashSet<String>();
private Map<String, List<Prescription> > atcMap = new HashMap<String, List<Prescription> >();
private String prescriberId = "";
private String prescriberType = "";
public Interval(int start, int end) {
startDate = start;
endDate = end;
}
public Interval(Prescription prescription) {
startDate = prescription.getDate();
endDate = prescription.getEndDate();
atcSet.add(prescription.getATC());
List<Prescription> prescriptionList = atcMap.get(prescription.getATC());
if (prescriptionList == null) {
prescriptionList = new ArrayList<Prescription>();
atcMap.put(prescription.getATC(), prescriptionList);
}
prescriptionList.add(prescription);
if (prescriberId.equals("") && prescription.hasPrescriberId() && prescription.hasPrescriberType()) {
prescriberId = prescription.getPrescriberId();
prescriberType = prescription.getPrescriberType();
}
}
public int getDuration() {
return (endDate - startDate);
}
public Set<String> getATCSet() {
return atcSet;
}
public Map<String, List<Prescription> > getATCMap() {
return atcMap;
}
public void setPrescriberId(String id) {
prescriberId = id;
}
public String getPrescriberId() {
return prescriberId;
}
public void setPrescriberType(String type) {
prescriberType = type;
}
public String getPrescriberType() {
return prescriberType;
}
public Interval split(int date) {
Interval newInterval = new Interval(date, endDate);
endDate = date;
for (String atc : atcSet) {
newInterval.atcSet.add(atc);
newInterval.setPrescriberId(prescriberId);
newInterval.setPrescriberType(prescriberType);
}
for (String atc : atcMap.keySet()) {
List<Prescription> prescriptionList = new ArrayList<Prescription>();
for (Prescription prescription : atcMap.get(atc)) {
//TODO Wijziging ongedaan gemaakt
//Prescription newPrescription = new Prescription(prescription);
//newPrescription.setAllComponentsStart(false);
//prescriptionList.add(newPrescription);
//TODO
prescriptionList.add(prescription);
//TODO Wijziging ongedaan gemaakt
}
newInterval.atcMap.put(atc, prescriptionList);
}
return newInterval;
}
public void addPrescription(Prescription prescription) {
atcSet.add(prescription.getATC());
List<Prescription> prescriptionList = atcMap.get(prescription.getATC());
if (prescriptionList == null) {
prescriptionList = new ArrayList<Prescription>();
atcMap.put(prescription.getATC(), prescriptionList);
}
prescriptionList.add(prescription);
if (prescriberId.equals("") && prescription.hasPrescriberId() && prescription.hasPrescriberType()) {
prescriberId = prescription.getPrescriberId();
prescriberType = prescription.getPrescriberType();
}
}
public String toString() {
String result = "";
result += DateUtilities.daysToDate(startDate);
result += "-";
result += DateUtilities.daysToDate(endDate);
result += " (";
result += Integer.toString(getDuration());
result += " days)";
result += ": ";
String resultATCs = "";
for (String atc : atcSet) {
if (!resultATCs.equals("")) {
resultATCs += ", ";
}
resultATCs += atc;
}
result += resultATCs;
return result;
}
}
private class DrugGroups {
private Map<String, Set<String> > drugGroupMap = new HashMap<String, Set<String> >();
private boolean initOK = true;
public DrugGroups(List<String> drugGroupDefinitions) {
if (drugGroupDefinitions.size() > 0) {
for (String drugGroupDefinition : drugGroupDefinitions) {
String[] drugGroupDefinitionSplit = drugGroupDefinition.split(";");
if ((drugGroupDefinitionSplit.length == 2) && (!drugGroupDefinitionSplit[0].equals(""))) {
if (!drugGroupMap.containsKey("_"+drugGroupDefinitionSplit[0])) {
Set<String> drugGroupATCs = new HashSet<String>();
drugGroupMap.put("_"+drugGroupDefinitionSplit[0], drugGroupATCs);
for (String atc : drugGroupDefinitionSplit[1].split(",")) {
if (!atc.equals("")) {
drugGroupATCs.add(atc);
}
}
}
else {
error = "Duplicate drug group name: " + drugGroupDefinitionSplit[0];
initOK = false;
break;
}
}
else {
error = "Incorrect drug group definition: " + drugGroupDefinition;
initOK = false;
break;
}
}
}
else {
error = "No drug groups defined";
initOK = false;
}
}
public boolean isOk() {
return initOK;
}
public Set<String> getDrugGroups(String atc) {
Set<String> matchingDrugGroups = new HashSet<String>();
for (String drugGroup : drugGroupMap.keySet()) {
for (String drugGroupAtc : drugGroupMap.get(drugGroup)) {
if (atc.startsWith(drugGroupAtc)) {
matchingDrugGroups.add(drugGroup);
//TODO Wijziging ongedaan gemaakt
//break;
//TODO Wijziging ongedaan gemaakt
}
}
//TODO Wijziging ongedaan gemaakt
//if (matchingDrugGroups.size() > 0) {
// break;
//}
//TODO Wijziging ongedaan gemaakt
}
return matchingDrugGroups;
}
public String toString() {
StrBuilder result = new StrBuilder();
result.appendln("DrugGroups:");
for (String drugGroupName : drugGroupMap.keySet()) {
String drugGroupString = "";
for (String atc : drugGroupMap.get(drugGroupName)) {
drugGroupString += (drugGroupString.equals("") ? drugGroupName + " = " : ", ") + atc;
}
result.appendln(" " + drugGroupString);
}
return result.toString();
}
}
private class Combinations {
private List<Combination> combinationList = new ArrayList<Combination>();
private Map<String, Combination> combinationIndex = new HashMap<String, Combination>();
private boolean initOK = true;
public Combinations(List<String> combinationDefinitions) {
if (combinationDefinitions.size() > 0) {
for (String combinationDefinition : combinationDefinitions) {
String[] combinationDefinitionSplit = combinationDefinition.split(";");
if ((combinationDefinitionSplit.length >= 2) && (!combinationDefinitionSplit[0].equals(""))) {
//if (combinationNames.add(combinationDefinitionSplit[0])) {
int minimumDuration = 0;
if ((combinationDefinitionSplit.length >= 3) && (!combinationDefinitionSplit[2].equals(""))) {
try {
minimumDuration = Integer.parseInt(combinationDefinitionSplit[2]);
}
catch (NumberFormatException e) {
minimumDuration = 0;
Logging.add("Illegal minimum duration in combination definition: " + combinationDefinition);
}
}
Combination combination = new Combination(combinationDefinitionSplit[0], combinationDefinitionSplit[1], minimumDuration);
if (combination.isOk()) {
combinationList.add(combination);
combinationIndex.put(combination.getName(), combination);
}
else {
initOK = false;
break;
}
//}
//else {
// error = "Duplicate combination name: " + combinationDefinitionSplit[0];
// initOK = false;
// break;
//}
}
else {
error = "Incorrect combination definition: " + combinationDefinition;
initOK = false;
break;
}
}
}
else {
error = "No combinations defined";
initOK = false;
}
}
public boolean isOk() {
Collections.sort(combinationList);
return initOK;
}
public List<Combination> getCombinations() {
return combinationList;
}
@SuppressWarnings("unused")
public Combination getCombination(String combinationName) {
return combinationIndex.get(combinationName);
}
public String toString() {
StrBuilder result = new StrBuilder();
result.appendln("Combinations:");
for (Combination combination : combinationList) {
result.appendln(" " + combination);
}
return result.toString();
}
}
private class Combination implements Comparable<Combination> {
private String name = "";
private Set<String> drugGroupSet = new HashSet<String>();
private int minimumDuration = 0;
private boolean initOK = false;
public Combination(String name, String drugGroups, int minimumDuration) {
this.name = "_"+name;
for (String drugGroup : drugGroups.split(",")) {
if (!drugGroup.equals("")) {
initOK = true;
drugGroupSet.add("_"+drugGroup);
}
}
this.minimumDuration = minimumDuration;
}
@SuppressWarnings("unused")
public int getMinimumDuration() {
return minimumDuration;
}
public boolean isOk() {
return initOK;
}
public String getName() {
return name;
}
public Set<String> getDrugGroupSet() {
return drugGroupSet;
}
public int compareTo(Combination c) {
return (c.drugGroupSet.size() - this.drugGroupSet.size());
}
public String toString() {
String result = "";
for (String drugGroup : drugGroupSet) {
result += (result.equals("") ? name + " = " : ", ") + drugGroup;
}
if (minimumDuration > 0) {
result += " at least " + minimumDuration + " days";
}
return result;
}
}
// GETTERS FOR UNIT TEST
public TimeLine getExposureTimeLine() {
return exposureTimeLine;
}
public TimeLine getOriginalTimeLine() {
return originalTimeLine;
}
//MAIN FOR DEBUGGING
public static void main(String[] args) {
PrescriptionCombinations pc = new PrescriptionCombinations();
pc.drugGroups.add("A;A1,A2,A3");
pc.drugGroups.add("B;B1,B2");
pc.drugGroups.add("C;C1,C2,C3,C4");
pc.combinations = new ArrayList<String>();
pc.combinations.add("A+B;A,B;20");
//pc.combinations.add("A+B+C;A,B,C");
pc.intermediateFiles = false;
pc.intermediateStats = false;
pc.init();
List<Prescription> pList = new ArrayList<Prescription>();
Prescription p;
p = new Prescription(); p.setPatientID("1"); p.setATC("A1"); p.setDate(DateUtilities.dateToDays(new int[] { 2012, 1, 1 })); p.setDuration(55); p.setDose("1"); pList.add(p);
p = new Prescription(); p.setPatientID("1"); p.setATC("B1"); p.setDate(DateUtilities.dateToDays(new int[] { 2012, 2, 1 })); p.setDuration(43); p.setDose("1"); pList.add(p);
p = new Prescription(); p.setPatientID("1"); p.setATC("C1"); p.setDate(DateUtilities.dateToDays(new int[] { 2012, 2, 15 })); p.setDuration(90); p.setDose("1"); pList.add(p);
pc.addCombinations("1", pList, "plist", true);
System.out.println(pList.toString());
}
}
|
/*
* Copyright 2012-2017 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.inspector.model;
import javax.annotation.Generated;
/**
* <p>
* The request was rejected because it attempted to create resources beyond the current AWS account limits. The error
* code describes the limit exceeded.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LimitExceededException extends com.amazonaws.services.inspector.model.AmazonInspectorException {
private static final long serialVersionUID = 1L;
/**
* <p>
* You can immediately retry your request.
* </p>
*/
private Boolean canRetry;
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*/
private String inspectorErrorCode;
/**
* Constructs a new LimitExceededException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public LimitExceededException(String message) {
super(message);
}
/**
* <p>
* You can immediately retry your request.
* </p>
*
* @param canRetry
* You can immediately retry your request.
*/
@com.fasterxml.jackson.annotation.JsonProperty("canRetry")
public void setCanRetry(Boolean canRetry) {
this.canRetry = canRetry;
}
/**
* <p>
* You can immediately retry your request.
* </p>
*
* @return You can immediately retry your request.
*/
@com.fasterxml.jackson.annotation.JsonProperty("canRetry")
public Boolean getCanRetry() {
return this.canRetry;
}
/**
* <p>
* You can immediately retry your request.
* </p>
*
* @param canRetry
* You can immediately retry your request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public LimitExceededException withCanRetry(Boolean canRetry) {
setCanRetry(canRetry);
return this;
}
/**
* <p>
* You can immediately retry your request.
* </p>
*
* @return You can immediately retry your request.
*/
public Boolean isCanRetry() {
return this.canRetry;
}
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*
* @param inspectorErrorCode
* Code that indicates the type of error that is generated.
* @see LimitExceededErrorCode
*/
@com.fasterxml.jackson.annotation.JsonProperty("errorCode")
public void setInspectorErrorCode(String inspectorErrorCode) {
this.inspectorErrorCode = inspectorErrorCode;
}
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*
* @return Code that indicates the type of error that is generated.
* @see LimitExceededErrorCode
*/
@com.fasterxml.jackson.annotation.JsonProperty("errorCode")
public String getInspectorErrorCode() {
return this.inspectorErrorCode;
}
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*
* @param inspectorErrorCode
* Code that indicates the type of error that is generated.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LimitExceededErrorCode
*/
public LimitExceededException withInspectorErrorCode(String inspectorErrorCode) {
setInspectorErrorCode(inspectorErrorCode);
return this;
}
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*
* @param inspectorErrorCode
* Code that indicates the type of error that is generated.
* @see LimitExceededErrorCode
*/
public void setInspectorErrorCode(LimitExceededErrorCode inspectorErrorCode) {
this.inspectorErrorCode = inspectorErrorCode.toString();
}
/**
* <p>
* Code that indicates the type of error that is generated.
* </p>
*
* @param inspectorErrorCode
* Code that indicates the type of error that is generated.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LimitExceededErrorCode
*/
public LimitExceededException withInspectorErrorCode(LimitExceededErrorCode inspectorErrorCode) {
setInspectorErrorCode(inspectorErrorCode);
return this;
}
}
|
package top.hdonghong.dhmall.coupon.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.hdonghong.common.utils.PageUtils;
import top.hdonghong.common.utils.Query;
import top.hdonghong.dhmall.coupon.dao.SkuLadderDao;
import top.hdonghong.dhmall.coupon.entity.SkuLadderEntity;
import top.hdonghong.dhmall.coupon.service.SkuLadderService;
@Service("skuLadderService")
public class SkuLadderServiceImpl extends ServiceImpl<SkuLadderDao, SkuLadderEntity> implements SkuLadderService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SkuLadderEntity> page = this.page(
new Query<SkuLadderEntity>().getPage(params),
new QueryWrapper<SkuLadderEntity>()
);
return new PageUtils(page);
}
}
|
/**
* generated by Xtext 2.19.0
*/
package org.afplib.afpText;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>GCMRK</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.afplib.afpText.GCMRK#getRg <em>Rg</em>}</li>
* </ul>
*
* @see org.afplib.afpText.AfpTextPackage#getGCMRK()
* @model
* @generated
*/
public interface GCMRK extends triplet
{
/**
* Returns the value of the '<em><b>Rg</b></em>' containment reference list.
* The list contents are of type {@link org.afplib.afpText.GCMRKRG}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Rg</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Rg</em>' containment reference list.
* @see org.afplib.afpText.AfpTextPackage#getGCMRK_Rg()
* @model containment="true"
* @generated
*/
EList<GCMRKRG> getRg();
} // GCMRK
|
package com.commerzinfo.input.html.parse.state;
import com.commerzinfo.input.html.parse.ParseStateContext;
import com.commerzinfo.util.DecimalFormatUtil;
import com.commerzinfo.util.RegexUtil;
public class StateBetrag extends ParseState {
public StateBetrag() {
super(StateBetrag.class.getSimpleName());
}
@Override
public boolean checkCondition(String input) {
return RegexUtil.matchesAmount(input);
}
@Override
public void doSomething(ParseStateContext stateContext, String input) throws Exception {
stateContext.getBuchungszeile().setValue((java.math.BigDecimal) DecimalFormatUtil.parse(input, DecimalFormatUtil.Mode.HTML));
stateContext.setState(ParseStateContext.INITIAL_STATE);
}
}
|
package contest.acm;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class CCPC_2017_D {
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
//br = new BufferedReader(new FileReader("in.txt"));
//out = new PrintWriter(new FileWriter("out.txt"));
int A = readInt();
int B = readInt();
if (B >= A) {
out.printf("Dr. Chaz will have %d piece%s of chicken left over!%n", B - A, (B - A) == 1 ? "" : "s");
} else {
out.printf("Dr. Chaz needs %d more piece%s of chicken!%n", A - B, (A - B) == 1 ? "" : "s");
}
out.close();
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}
|
/*
* Copyright (c) 2021 Freya Arbjerg and contributors
*
* 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 lavalink.server.player;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import lavalink.server.io.SocketServer;
import lavalink.server.util.Util;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class EventEmitter extends AudioEventAdapter {
private static final Logger log = LoggerFactory.getLogger(EventEmitter.class);
private final AudioPlayerManager audioPlayerManager;
private final Player linkPlayer;
EventEmitter(AudioPlayerManager audioPlayerManager, Player linkPlayer) {
this.audioPlayerManager = audioPlayerManager;
this.linkPlayer = linkPlayer;
}
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
JSONObject out = new JSONObject();
out.put("op", "event");
out.put("type", "TrackStartEvent");
out.put("guildId", linkPlayer.getGuildId());
try {
out.put("track", Util.toMessage(audioPlayerManager, track));
} catch (IOException e) {
out.put("track", JSONObject.NULL);
}
linkPlayer.getSocket().send(out);
}
@Override
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
JSONObject out = new JSONObject();
out.put("op", "event");
out.put("type", "TrackEndEvent");
out.put("guildId", linkPlayer.getGuildId());
try {
out.put("track", Util.toMessage(audioPlayerManager, track));
} catch (IOException e) {
out.put("track", JSONObject.NULL);
}
out.put("reason", endReason.toString());
linkPlayer.getSocket().send(out);
}
// These exceptions are already logged by Lavaplayer
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
JSONObject out = new JSONObject();
out.put("op", "event");
out.put("type", "TrackExceptionEvent");
out.put("guildId", linkPlayer.getGuildId());
try {
out.put("track", Util.toMessage(audioPlayerManager, track));
} catch (IOException e) {
out.put("track", JSONObject.NULL);
}
out.put("error", exception.getMessage());
linkPlayer.getSocket().send(out);
}
@Override
public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) {
log.warn(track.getInfo().title + " got stuck! Threshold surpassed: " + thresholdMs);
JSONObject out = new JSONObject();
out.put("op", "event");
out.put("type", "TrackStuckEvent");
out.put("guildId", linkPlayer.getGuildId());
try {
out.put("track", Util.toMessage(audioPlayerManager, track));
} catch (IOException e) {
out.put("track", JSONObject.NULL);
}
out.put("thresholdMs", thresholdMs);
linkPlayer.getSocket().send(out);
SocketServer.Companion.sendPlayerUpdate(linkPlayer.getSocket(), linkPlayer);
}
}
|
package com.lwj.netty._3_heartbeat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
/**
* create by lwj on 2020/3/3
*/
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
String eventType = null;
switch (event.state()) {
case READER_IDLE:
eventType = "读空闲";
break;
case WRITER_IDLE:
eventType = "写空闲";
break;
case ALL_IDLE:
eventType = "读写空闲";
break;
}
System.out.println(ctx.channel().remoteAddress() + " : " + eventType);
System.out.println("服务器做相应处理");
}
}
}
|
/*******************************************************************************
* Cloud Foundry
* Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved.
*
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
* You may not use this product except in compliance with the License.
*
* This product includes a number of subcomponents with
* separate copyright notices and license terms. Your use of these
* subcomponents is subject to the terms and conditions of the
* subcomponent's license, as noted in the LICENSE file.
*******************************************************************************/
package org.cloudfoundry.identity.uaa.user;
import org.cloudfoundry.identity.uaa.constants.OriginKeys;
import org.cloudfoundry.identity.uaa.test.JdbcTestBase;
import org.cloudfoundry.identity.uaa.test.TestUtils;
import org.cloudfoundry.identity.uaa.util.TimeService;
import org.cloudfoundry.identity.uaa.zone.IdentityZone;
import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.util.LinkedMultiValueMap;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_INSENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY;
import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY;
import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_SENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY;
import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_SENSITIVE_USER_BY_USERNAME_QUERY;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JdbcUaaUserDatabaseTests extends JdbcTestBase {
private JdbcUaaUserDatabase db;
private static final String JOE_ID = "550e8400-e29b-41d4-a716-446655440000";
private static final String addUserSql = "insert into users (id, username, password, email, givenName, familyName, phoneNumber, origin, identity_zone_id, created, lastmodified, passwd_lastmodified, passwd_change_required) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
private static final String getAuthoritiesSql = "select authorities from users where id=?";
private static final String addAuthoritySql = "update users set authorities=? where id=?";
private static final String addSaltSql = "update users set salt=? where id=?";
private static final String MABEL_ID = UUID.randomUUID().toString();
private static final String ALICE_ID = UUID.randomUUID().toString();
private IdentityZone otherIdentityZone;
private JdbcTemplate template;
public static final String ADD_GROUP_SQL = "insert into groups (id, displayName, identity_zone_id) values (?,?,?)";
public static final String ADD_MEMBER_SQL = "insert into group_membership (group_id, member_id, member_type, authorities) values (?,?,?,?)";
private TimeService timeService;
private void addUser(String id, String name, String password, boolean requiresPasswordChange) {
TestUtils.assertNoSuchUser(template, "id", id);
Timestamp t = new Timestamp(System.currentTimeMillis());
template.update(addUserSql, id, name, password, name.toLowerCase() + "@test.org", name, name, "", OriginKeys.UAA, IdentityZoneHolder.get().getId(),t,t,t,requiresPasswordChange);
}
private void addAuthority(String authority, String userId) {
String id = new RandomValueStringGenerator().generate();
jdbcTemplate.update(ADD_GROUP_SQL, id, authority, IdentityZoneHolder.get().getId());
jdbcTemplate.update(ADD_MEMBER_SQL, id, userId, "USER", "MEMBER");
}
@Before
public void initializeDb() throws Exception {
timeService = mock(TimeService.class);
IdentityZoneHolder.clear();
otherIdentityZone = new IdentityZone();
otherIdentityZone.setId("some-other-zone-id");
template = new JdbcTemplate(dataSource);
db = new JdbcUaaUserDatabase(template, timeService);
db.setDefaultAuthorities(Collections.singleton("uaa.user"));
TestUtils.assertNoSuchUser(template, "id", JOE_ID);
TestUtils.assertNoSuchUser(template, "id", MABEL_ID);
TestUtils.assertNoSuchUser(template, "id", ALICE_ID);
TestUtils.assertNoSuchUser(template, "userName", "jo@foo.com");
addUser(JOE_ID, "Joe", "joespassword", true);
addUser(MABEL_ID, "mabel", "mabelspassword", false);
IdentityZoneHolder.set(otherIdentityZone);
addUser(ALICE_ID, "alice", "alicespassword", false);
IdentityZoneHolder.clear();
}
@After
public void clearDb() throws Exception {
IdentityZoneHolder.clear();
TestUtils.deleteFrom(dataSource, "users");
}
@Test(expected = NullPointerException.class)
public void testStoreUserInfoWithoutId() {
db.storeUserInfo(null, new UserInfo());
}
@Test
public void testStoreNullUserInfo() {
String id = "id";
db.storeUserInfo(id, null);
UserInfo info2 = db.getUserInfo(id);
assertNull(info2.getRoles());
assertNull(info2.getUserAttributes());
}
@Test
public void testStoreUserInfo() {
UserInfo info = new UserInfo();
String id = "id";
LinkedMultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>();
userAttributes.add("single", "1");
userAttributes.add("multi", "2");
userAttributes.add("multi", "3");
info.setUserAttributes(userAttributes);
List<String> roles = new LinkedList(Arrays.asList("role1", "role2", "role3"));
info.setRoles(roles);
db.storeUserInfo(id, info);
UserInfo info2 = db.getUserInfo(id);
assertEquals(info, info2);
assertEquals(userAttributes, info2.getUserAttributes());
assertEquals(roles, info2.getRoles());
roles.add("role4");
userAttributes.add("multi", "4");
db.storeUserInfo(id, info);
UserInfo info3 = db.getUserInfo(id);
assertEquals(info, info3);
assertEquals(userAttributes, info3.getUserAttributes());
assertEquals(roles, info3.getRoles());
}
@Test
public void addedUserHasNoLegacyVerificationBehavior() {
assertFalse(db.retrieveUserById(JOE_ID).isLegacyVerificationBehavior());
assertFalse(db.retrieveUserById(MABEL_ID).isLegacyVerificationBehavior());
IdentityZoneHolder.set(otherIdentityZone);
assertFalse(db.retrieveUserById(ALICE_ID).isLegacyVerificationBehavior());
}
@Test
public void getValidUserSucceeds() {
UaaUser joe = db.retrieveUserByName("joe", OriginKeys.UAA);
validateJoe(joe);
assertNull(joe.getSalt());
assertNotNull(joe.getPasswordLastModified());
assertEquals(joe.getCreated(), joe.getPasswordLastModified());
}
@Test
public void getSaltValueWorks() {
UaaUser joe = db.retrieveUserByName("joe", OriginKeys.UAA);
assertNotNull(joe);
assertNull(joe.getSalt());
template.update(addSaltSql, "salt", JOE_ID);
joe = db.retrieveUserByName("joe", OriginKeys.UAA);
assertNotNull(joe);
assertEquals("salt", joe.getSalt());
}
public boolean isMySQL() {
for (String s : environment.getActiveProfiles()) {
if (s.contains("mysql")) {
return true;
}
}
return false;
}
@Test
public void is_the_right_query_used() throws Exception {
JdbcTemplate template = mock(JdbcTemplate.class);
db.setJdbcTemplate(template);
String username = new RandomValueStringGenerator().generate()+"@test.org";
db.retrieveUserByName(username, OriginKeys.UAA);
verify(template).queryForObject(eq(DEFAULT_CASE_SENSITIVE_USER_BY_USERNAME_QUERY), eq(db.getMapper()), eq(username.toLowerCase()), eq(true), eq(OriginKeys.UAA), eq(OriginKeys.UAA));
db.retrieveUserByEmail(username, OriginKeys.UAA);
verify(template).query(eq(DEFAULT_CASE_SENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY), eq(db.getMapper()), eq(username.toLowerCase()), eq(true), eq(OriginKeys.UAA), eq(OriginKeys.UAA));
db.setCaseInsensitive(true);
db.retrieveUserByName(username, OriginKeys.UAA);
verify(template).queryForObject(eq(DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY), eq(db.getMapper()), eq(username.toLowerCase()), eq(true), eq(OriginKeys.UAA), eq(OriginKeys.UAA));
db.retrieveUserByEmail(username, OriginKeys.UAA);
verify(template).query(eq(DEFAULT_CASE_INSENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY), eq(db.getMapper()), eq(username.toLowerCase()), eq(true), eq(OriginKeys.UAA), eq(OriginKeys.UAA));
}
@Test
public void getValidUserCaseInsensitive() {
for (boolean caseInsensitive : Arrays.asList(true,false)) {
try {
db.setCaseInsensitive(caseInsensitive);
UaaUser joe = db.retrieveUserByName("JOE", OriginKeys.UAA);
validateJoe(joe);
joe = db.retrieveUserByName("joe", OriginKeys.UAA);
validateJoe(joe);
joe = db.retrieveUserByName("Joe", OriginKeys.UAA);
validateJoe(joe);
joe = db.retrieveUserByEmail("joe@test.org", OriginKeys.UAA);
validateJoe(joe);
joe = db.retrieveUserByEmail("JOE@TEST.ORG", OriginKeys.UAA);
validateJoe(joe);
joe = db.retrieveUserByEmail("Joe@Test.Org", OriginKeys.UAA);
validateJoe(joe);
} catch (UsernameNotFoundException x) {
if (!caseInsensitive) {
throw x;
}
if (isMySQL()) {
throw x;
}
}
}
}
protected void validateJoe(UaaUser joe) {
assertNotNull(joe);
assertEquals(JOE_ID, joe.getId());
assertEquals("Joe", joe.getUsername());
assertEquals("joe@test.org", joe.getEmail());
assertEquals("joespassword", joe.getPassword());
assertEquals(true, joe.isPasswordChangeRequired());
assertTrue("authorities does not contain uaa.user",
joe.getAuthorities().contains(new SimpleGrantedAuthority("uaa.user")));
}
@Test(expected = UsernameNotFoundException.class)
public void getNonExistentUserRaisedNotFoundException() {
db.retrieveUserByName("jo", OriginKeys.UAA);
}
@Test
public void getUserWithExtraAuthorities() {
addAuthority("dash.admin", JOE_ID);
UaaUser joe = db.retrieveUserByName("joe", OriginKeys.UAA);
assertTrue("authorities does not contain uaa.user",
joe.getAuthorities().contains(new SimpleGrantedAuthority("uaa.user")));
assertTrue("authorities does not contain dash.admin",
joe.getAuthorities().contains(new SimpleGrantedAuthority("dash.admin")));
}
@Test
public void getUserWithNestedAuthoritiesWorks() {
UaaUser joe = db.retrieveUserByName("joe", OriginKeys.UAA);
assertThat(joe.getAuthorities(),
containsInAnyOrder(
new SimpleGrantedAuthority("uaa.user")
)
);
String directId = new RandomValueStringGenerator().generate();
String indirectId = new RandomValueStringGenerator().generate();
jdbcTemplate.update(ADD_GROUP_SQL, directId, "direct", IdentityZoneHolder.get().getId());
jdbcTemplate.update(ADD_GROUP_SQL, indirectId, "indirect", IdentityZoneHolder.get().getId());
jdbcTemplate.update(ADD_MEMBER_SQL, indirectId, directId, "GROUP", "MEMBER");
jdbcTemplate.update(ADD_MEMBER_SQL, directId, joe.getId(), "USER", "MEMBER");
evaluateNestedJoe();
//add a circular group
jdbcTemplate.update(ADD_MEMBER_SQL, directId, indirectId, "GROUP", "MEMBER");
evaluateNestedJoe();
}
protected void evaluateNestedJoe() {
UaaUser joe;
joe = db.retrieveUserByName("joe", OriginKeys.UAA);
assertThat(joe.getAuthorities(),
containsInAnyOrder(
new SimpleGrantedAuthority("direct"),
new SimpleGrantedAuthority("uaa.user"),
new SimpleGrantedAuthority("indirect")
)
);
}
@Test
public void testUpdatePreviousAndLastLogonTime() {
when(timeService.getCurrentTimeMillis()).thenReturn(1000L);
db.updateLastLogonTime(JOE_ID);
UaaUser joe = db.retrieveUserById(JOE_ID);
assertEquals((long) joe.getLastLogonTime(), 1000L);
assertNull(joe.getPreviousLogonTime());
when(timeService.getCurrentTimeMillis()).thenReturn(2000L);
db.updateLastLogonTime(JOE_ID);
joe = db.retrieveUserById(JOE_ID);
assertEquals((long) joe.getPreviousLogonTime(), 1000L);
assertEquals((long) joe.getLastLogonTime(), 2000L);
}
@Test(expected = UsernameNotFoundException.class)
public void getValidUserInDefaultZoneFromOtherZoneFails() {
IdentityZoneHolder.set(otherIdentityZone);
getValidUserSucceeds();
fail("Should have thrown an exception.");
}
@Test
public void getValidUserInOtherZoneFromOtherZone() {
IdentityZoneHolder.set(otherIdentityZone);
getValidUserInOtherZoneFromDefaultZoneFails();
}
@Test(expected = UsernameNotFoundException.class)
public void getValidUserInOtherZoneFromDefaultZoneFails() {
db.retrieveUserByName("alice", OriginKeys.UAA);
}
@Test
public void retrieveUserByEmail_also_isCaseInsensitive() {
UaaUser joe = db.retrieveUserByEmail("JOE@test.org", OriginKeys.UAA);
validateJoe(joe);
assertNull(joe.getSalt());
assertNotNull(joe.getPasswordLastModified());
assertEquals(joe.getCreated(), joe.getPasswordLastModified());
}
@Test
public void null_if_noUserWithEmail() {
assertNull(db.retrieveUserByEmail("email@doesnot.exist", OriginKeys.UAA));
}
@Test
public void null_if_userWithEmail_in_differentZone(){
assertNull(db.retrieveUserByEmail("alice@test.org", OriginKeys.UAA));
}
}
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pixeldust.launcher;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.animation.TimeInterpolator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import com.pixeldust.launcher.pageindicators.PageIndicator;
import com.pixeldust.launcher.util.LauncherEdgeEffect;
import com.pixeldust.launcher.util.Thunk;
/**
* An abstraction of the original Workspace which supports browsing through a
* sequential list of "pages"
*/
public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
protected static final int INVALID_PAGE = -1;
// the min drag distance for a fling to register, to prevent random page shifts
private static final int MIN_LENGTH_FOR_FLING = 25;
public static final int PAGE_SNAP_ANIMATION_DURATION = 750;
protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
// The page is moved more than halfway, automatically move to the next page on touch up.
private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
private static final float MAX_SCROLL_PROGRESS = 1.0f;
// The following constants need to be scaled based on density. The scaled versions will be
// assigned to the corresponding member variables below.
private static final int FLING_THRESHOLD_VELOCITY = 500;
private static final int MIN_SNAP_VELOCITY = 1500;
private static final int MIN_FLING_VELOCITY = 250;
public static final int INVALID_RESTORE_PAGE = -1001;
private boolean mFreeScroll = false;
private int mFreeScrollMinScrollX = -1;
private int mFreeScrollMaxScrollX = -1;
protected int mFlingThresholdVelocity;
protected int mMinFlingVelocity;
protected int mMinSnapVelocity;
protected boolean mFirstLayout = true;
private int mNormalChildHeight;
@ViewDebug.ExportedProperty(category = "launcher")
protected int mCurrentPage;
protected int mRestorePage = INVALID_RESTORE_PAGE;
private int mChildCountOnLastLayout;
@ViewDebug.ExportedProperty(category = "launcher")
protected int mNextPage = INVALID_PAGE;
protected int mMaxScrollX;
protected LauncherScroller mScroller;
private Interpolator mDefaultInterpolator;
private VelocityTracker mVelocityTracker;
@Thunk
int mPageSpacing = 0;
private float mParentDownMotionX;
private float mParentDownMotionY;
private float mDownMotionX;
private float mDownMotionY;
private float mDownScrollX;
private float mDragViewBaselineLeft;
private float mLastMotionX;
private float mLastMotionXRemainder;
private float mLastMotionY;
private float mTotalMotionX;
private int mLastScreenCenter = -1;
private boolean mCancelTap;
private int[] mPageScrolls;
protected final static int TOUCH_STATE_REST = 0;
protected final static int TOUCH_STATE_SCROLLING = 1;
protected final static int TOUCH_STATE_PREV_PAGE = 2;
protected final static int TOUCH_STATE_NEXT_PAGE = 3;
protected final static int TOUCH_STATE_REORDERING = 4;
protected int mTouchState = TOUCH_STATE_REST;
private boolean mForceScreenScrolled = false;
protected OnLongClickListener mLongClickListener;
protected int mTouchSlop;
private int mMaximumVelocity;
protected boolean mAllowOverScroll = true;
protected int[] mTempVisiblePagesRange = new int[2];
protected static final int INVALID_POINTER = -1;
protected int mActivePointerId = INVALID_POINTER;
protected boolean mIsPageMoving = false;
protected boolean mWasInOverscroll = false;
// Page Indicator
@Thunk
int mPageIndicatorViewId;
protected PageIndicator mPageIndicator;
// The viewport whether the pages are to be contained (the actual view may be larger than the
// viewport)
@ViewDebug.ExportedProperty(category = "launcher")
private Rect mViewport = new Rect();
// Reordering
// We use the min scale to determine how much to expand the actually PagedView measured
// dimensions such that when we are zoomed out, the view is not clipped
private static int REORDERING_DROP_REPOSITION_DURATION = 200;
@Thunk
static int REORDERING_REORDER_REPOSITION_DURATION = 300;
private static int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
private float mMinScale = 1f;
private boolean mUseMinScale = false;
@Thunk
View mDragView;
private Runnable mSidePageHoverRunnable;
@Thunk
int mSidePageHoverIndex = -1;
// This variable's scope is only for the duration of startReordering() and endReordering()
private boolean mReorderingStarted = false;
// This variable's scope is for the duration of startReordering() and after the zoomIn()
// animation after endReordering()
private boolean mIsReordering;
// The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
private static final int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
private int mPostReorderingPreZoomInRemainingAnimationCount;
private Runnable mPostReorderingPreZoomInRunnable;
// Convenience/caching
private static final Matrix sTmpInvMatrix = new Matrix();
private static final float[] sTmpPoint = new float[2];
private static final int[] sTmpIntPoint = new int[2];
private static final Rect sTmpRect = new Rect();
private static final RectF sTmpRectF = new RectF();
protected final Rect mInsets = new Rect();
protected final boolean mIsRtl;
// Edge effect
private final LauncherEdgeEffect mEdgeGlowLeft = new LauncherEdgeEffect();
private final LauncherEdgeEffect mEdgeGlowRight = new LauncherEdgeEffect();
public PagedView(Context context) {
this(context, null);
}
public PagedView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagedView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.PagedView, defStyle, 0);
mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
a.recycle();
setHapticFeedbackEnabled(false);
mIsRtl = Utilities.isRtl(getResources());
init();
}
/**
* Initializes various states for this workspace.
*/
protected void init() {
mScroller = new LauncherScroller(getContext());
setDefaultInterpolator(new ScrollInterpolator());
mCurrentPage = 0;
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledPagingTouchSlop();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
float density = getResources().getDisplayMetrics().density;
mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * density);
mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * density);
mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * density);
setOnHierarchyChangeListener(this);
setWillNotDraw(false);
}
protected void setEdgeGlowColor(int color) {
mEdgeGlowLeft.setColor(color);
mEdgeGlowRight.setColor(color);
}
protected void setDefaultInterpolator(Interpolator interpolator) {
mDefaultInterpolator = interpolator;
mScroller.setInterpolator(mDefaultInterpolator);
}
public void initParentViews(View parent) {
if (mPageIndicatorViewId > -1) {
mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
mPageIndicator.setMarkersCount(getChildCount());
mPageIndicator.setContentDescription(getPageIndicatorDescription());
}
}
// Convenience methods to map points from self to parent and vice versa
private float[] mapPointFromViewToParent(View v, float x, float y) {
sTmpPoint[0] = x;
sTmpPoint[1] = y;
v.getMatrix().mapPoints(sTmpPoint);
sTmpPoint[0] += v.getLeft();
sTmpPoint[1] += v.getTop();
return sTmpPoint;
}
private float[] mapPointFromParentToView(View v, float x, float y) {
sTmpPoint[0] = x - v.getLeft();
sTmpPoint[1] = y - v.getTop();
v.getMatrix().invert(sTmpInvMatrix);
sTmpInvMatrix.mapPoints(sTmpPoint);
return sTmpPoint;
}
private void updateDragViewTranslationDuringDrag() {
if (mDragView != null) {
float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
(mDragViewBaselineLeft - mDragView.getLeft());
float y = mLastMotionY - mDownMotionY;
mDragView.setTranslationX(x);
mDragView.setTranslationY(y);
}
}
public void setMinScale(float f) {
mMinScale = f;
mUseMinScale = true;
requestLayout();
}
@Override
public void setScaleX(float scaleX) {
super.setScaleX(scaleX);
if (isReordering(true)) {
float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
mLastMotionX = p[0];
mLastMotionY = p[1];
updateDragViewTranslationDuringDrag();
}
}
// Convenience methods to get the actual width/height of the PagedView (since it is measured
// to be larger to account for the minimum possible scale)
int getViewportWidth() {
return mViewport.width();
}
public int getViewportHeight() {
return mViewport.height();
}
// Convenience methods to get the offset ASSUMING that we are centering the pages in the
// PagedView both horizontally and vertically
int getViewportOffsetX() {
return (getMeasuredWidth() - getViewportWidth()) / 2;
}
int getViewportOffsetY() {
return (getMeasuredHeight() - getViewportHeight()) / 2;
}
public PageIndicator getPageIndicator() {
return mPageIndicator;
}
/**
* Returns the index of the currently displayed page. When in free scroll mode, this is the page
* that the user was on before entering free scroll mode (e.g. the home screen page they
* long-pressed on to enter the overview). Try using {@link #getPageNearestToCenterOfScreen()}
* to get the page the user is currently scrolling over.
*/
public int getCurrentPage() {
return mCurrentPage;
}
/**
* Returns the index of page to be shown immediately afterwards.
*/
public int getNextPage() {
return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
}
public int getPageCount() {
return getChildCount();
}
public View getPageAt(int index) {
return getChildAt(index);
}
protected int indexToPage(int index) {
return index;
}
/**
* Updates the scroll of the current page immediately to its final scroll position. We use this
* in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
* the previous tab page.
*/
protected void updateCurrentPageScroll() {
// If the current page is invalid, just reset the scroll position to zero
int newX = 0;
if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
newX = getScrollForPage(mCurrentPage);
}
scrollTo(newX, 0);
mScroller.setFinalX(newX);
forceFinishScroller(true);
}
private void abortScrollerAnimation(boolean resetNextPage) {
mScroller.abortAnimation();
// We need to clean up the next page here to avoid computeScrollHelper from
// updating current page on the pass.
if (resetNextPage) {
mNextPage = INVALID_PAGE;
}
}
private void forceFinishScroller(boolean resetNextPage) {
mScroller.forceFinished(true);
// We need to clean up the next page here to avoid computeScrollHelper from
// updating current page on the pass.
if (resetNextPage) {
mNextPage = INVALID_PAGE;
}
}
private int validateNewPage(int newPage) {
int validatedPage = newPage;
// When in free scroll mode, we need to clamp to the free scroll page range.
if (mFreeScroll) {
getFreeScrollPageRange(mTempVisiblePagesRange);
validatedPage = Math.max(mTempVisiblePagesRange[0],
Math.min(newPage, mTempVisiblePagesRange[1]));
}
// Ensure that it is clamped by the actual set of children in all cases
validatedPage = Utilities.boundToRange(validatedPage, 0, getPageCount() - 1);
return validatedPage;
}
/**
* Sets the current page.
*/
public void setCurrentPage(int currentPage) {
if (!mScroller.isFinished()) {
abortScrollerAnimation(true);
}
// don't introduce any checks like mCurrentPage == currentPage here-- if we change the
// the default
if (getChildCount() == 0) {
return;
}
mForceScreenScrolled = true;
mCurrentPage = validateNewPage(currentPage);
updateCurrentPageScroll();
notifyPageSwitchListener();
invalidate();
}
/**
* The restore page will be set in place of the current page at the next (likely first)
* layout.
*/
void setRestorePage(int restorePage) {
mRestorePage = restorePage;
}
int getRestorePage() {
return mRestorePage;
}
/**
* Should be called whenever the page changes. In the case of a scroll, we wait until the page
* has settled.
*/
protected void notifyPageSwitchListener() {
updatePageIndicator();
}
private void updatePageIndicator() {
// Update the page indicator (when we aren't reordering)
if (mPageIndicator != null) {
mPageIndicator.setContentDescription(getPageIndicatorDescription());
if (!isReordering(false)) {
mPageIndicator.setActiveMarker(getNextPage());
}
}
}
protected void pageBeginMoving() {
if (!mIsPageMoving) {
mIsPageMoving = true;
onPageBeginMoving();
}
}
protected void pageEndMoving() {
if (mIsPageMoving) {
mIsPageMoving = false;
onPageEndMoving();
}
}
protected boolean isPageMoving() {
return mIsPageMoving;
}
// a method that subclasses can override to add behavior
protected void onPageBeginMoving() {
}
// a method that subclasses can override to add behavior
protected void onPageEndMoving() {
mWasInOverscroll = false;
}
/**
* Registers the specified listener on each page contained in this workspace.
*
* @param l The listener used to respond to long clicks.
*/
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLongClickListener = l;
final int count = getPageCount();
for (int i = 0; i < count; i++) {
getPageAt(i).setOnLongClickListener(l);
}
super.setOnLongClickListener(l);
}
protected int getUnboundedScrollX() {
return getScrollX();
}
@Override
public void scrollBy(int x, int y) {
scrollTo(getUnboundedScrollX() + x, getScrollY() + y);
}
@Override
public void scrollTo(int x, int y) {
// In free scroll mode, we clamp the scrollX
if (mFreeScroll) {
// If the scroller is trying to move to a location beyond the maximum allowed
// in the free scroll mode, we make sure to end the scroll operation.
if (!mScroller.isFinished() &&
(x > mFreeScrollMaxScrollX || x < mFreeScrollMinScrollX)) {
forceFinishScroller(false);
}
x = Math.min(x, mFreeScrollMaxScrollX);
x = Math.max(x, mFreeScrollMinScrollX);
}
boolean isXBeforeFirstPage = mIsRtl ? (x > mMaxScrollX) : (x < 0);
boolean isXAfterLastPage = mIsRtl ? (x < 0) : (x > mMaxScrollX);
if (isXBeforeFirstPage) {
super.scrollTo(mIsRtl ? mMaxScrollX : 0, y);
if (mAllowOverScroll) {
mWasInOverscroll = true;
if (mIsRtl) {
overScroll(x - mMaxScrollX);
} else {
overScroll(x);
}
}
} else if (isXAfterLastPage) {
super.scrollTo(mIsRtl ? 0 : mMaxScrollX, y);
if (mAllowOverScroll) {
mWasInOverscroll = true;
if (mIsRtl) {
overScroll(x);
} else {
overScroll(x - mMaxScrollX);
}
}
} else {
if (mWasInOverscroll) {
overScroll(0);
mWasInOverscroll = false;
}
super.scrollTo(x, y);
}
// Update the last motion events when scrolling
if (isReordering(true)) {
float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
mLastMotionX = p[0];
mLastMotionY = p[1];
updateDragViewTranslationDuringDrag();
}
}
private void sendScrollAccessibilityEvent() {
AccessibilityManager am =
(AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (am.isEnabled()) {
if (mCurrentPage != getNextPage()) {
AccessibilityEvent ev =
AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
ev.setScrollable(true);
ev.setScrollX(getScrollX());
ev.setScrollY(getScrollY());
ev.setMaxScrollX(mMaxScrollX);
ev.setMaxScrollY(0);
sendAccessibilityEventUnchecked(ev);
}
}
}
// we moved this functionality to a helper function so SmoothPagedView can reuse it
protected boolean computeScrollHelper() {
return computeScrollHelper(true);
}
protected boolean computeScrollHelper(boolean shouldInvalidate) {
if (mScroller.computeScrollOffset()) {
// Don't bother scrolling if the page does not need to be moved
if (getScrollX() != mScroller.getCurrX()
|| getScrollY() != mScroller.getCurrY()) {
float scaleX = mFreeScroll ? getScaleX() : 1f;
int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
scrollTo(scrollX, mScroller.getCurrY());
}
if (shouldInvalidate) {
invalidate();
}
return true;
} else if (mNextPage != INVALID_PAGE && shouldInvalidate) {
sendScrollAccessibilityEvent();
mCurrentPage = validateNewPage(mNextPage);
mNextPage = INVALID_PAGE;
notifyPageSwitchListener();
// We don't want to trigger a page end moving unless the page has settled
// and the user has stopped scrolling
if (mTouchState == TOUCH_STATE_REST) {
pageEndMoving();
}
onPostReorderingAnimationCompleted();
AccessibilityManager am = (AccessibilityManager)
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (am.isEnabled()) {
// Notify the user when the page changes
announceForAccessibility(getCurrentPageDescription());
}
return true;
}
return false;
}
@Override
public void computeScroll() {
computeScrollHelper();
}
public static class LayoutParams extends ViewGroup.LayoutParams {
public boolean isFullScreenPage = false;
/**
* {@inheritDoc}
*/
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams;
}
public int getNormalChildHeight() {
return mNormalChildHeight;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getChildCount() == 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// We measure the dimensions of the PagedView to be larger than the pages so that when we
// zoom out (and scale down), the view is still contained in the parent
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// NOTE: We multiply by 2f to account for the fact that depending on the offset of the
// viewport, we can be at most one and a half screens offset once we scale down
DisplayMetrics dm = getResources().getDisplayMetrics();
int maxSize = Math.max(dm.widthPixels + mInsets.left + mInsets.right,
dm.heightPixels + mInsets.top + mInsets.bottom);
int parentWidthSize = (int) (2f * maxSize);
int parentHeightSize = (int) (2f * maxSize);
int scaledWidthSize, scaledHeightSize;
if (mUseMinScale) {
scaledWidthSize = (int) (parentWidthSize / mMinScale);
scaledHeightSize = (int) (parentHeightSize / mMinScale);
} else {
scaledWidthSize = widthSize;
scaledHeightSize = heightSize;
}
mViewport.set(0, 0, widthSize, heightSize);
if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
// Return early if we aren't given a proper dimension
if (widthSize <= 0 || heightSize <= 0) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
/* Allow the height to be set as WRAP_CONTENT. This allows the particular case
* of the All apps view on XLarge displays to not take up more space then it needs. Width
* is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
* each page to have the same width.
*/
final int verticalPadding = getPaddingTop() + getPaddingBottom();
final int horizontalPadding = getPaddingLeft() + getPaddingRight();
int referenceChildWidth = 0;
// The children are given the same width and height as the workspace
// unless they were set to WRAP_CONTENT
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
// disallowing padding in paged view (just pass 0)
final View child = getPageAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int childWidthMode;
int childHeightMode;
int childWidth;
int childHeight;
if (!lp.isFullScreenPage) {
if (lp.width == LayoutParams.WRAP_CONTENT) {
childWidthMode = MeasureSpec.AT_MOST;
} else {
childWidthMode = MeasureSpec.EXACTLY;
}
if (lp.height == LayoutParams.WRAP_CONTENT) {
childHeightMode = MeasureSpec.AT_MOST;
} else {
childHeightMode = MeasureSpec.EXACTLY;
}
childWidth = getViewportWidth() - horizontalPadding
- mInsets.left - mInsets.right;
childHeight = getViewportHeight() - verticalPadding
- mInsets.top - mInsets.bottom;
mNormalChildHeight = childHeight;
} else {
childWidthMode = MeasureSpec.EXACTLY;
childHeightMode = MeasureSpec.EXACTLY;
childWidth = getViewportWidth();
childHeight = getViewportHeight();
}
if (referenceChildWidth == 0) {
referenceChildWidth = childWidth;
}
final int childWidthMeasureSpec =
MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
final int childHeightMeasureSpec =
MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
setMeasuredDimension(scaledWidthSize, scaledHeightSize);
}
@SuppressLint("DrawAllocation")
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (getChildCount() == 0) {
return;
}
final int childCount = getChildCount();
int offsetX = getViewportOffsetX();
int offsetY = getViewportOffsetY();
// Update the viewport offsets
mViewport.offset(offsetX, offsetY);
final int startIndex = mIsRtl ? childCount - 1 : 0;
final int endIndex = mIsRtl ? -1 : childCount;
final int delta = mIsRtl ? -1 : 1;
int verticalPadding = getPaddingTop() + getPaddingBottom();
LayoutParams lp = (LayoutParams) getChildAt(startIndex).getLayoutParams();
LayoutParams nextLp;
int childLeft = offsetX + (lp.isFullScreenPage ? 0 : getPaddingLeft());
if (mPageScrolls == null || childCount != mChildCountOnLastLayout) {
mPageScrolls = new int[childCount];
}
for (int i = startIndex; i != endIndex; i += delta) {
final View child = getPageAt(i);
if (child.getVisibility() != View.GONE) {
lp = (LayoutParams) child.getLayoutParams();
int childTop;
if (lp.isFullScreenPage) {
childTop = offsetY;
} else {
childTop = offsetY + getPaddingTop() + mInsets.top;
childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
}
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(), childTop + childHeight);
int scrollOffsetLeft = lp.isFullScreenPage ? 0 : getPaddingLeft();
mPageScrolls[i] = childLeft - scrollOffsetLeft - offsetX;
int pageGap = mPageSpacing;
int next = i + delta;
if (next != endIndex) {
nextLp = (LayoutParams) getPageAt(next).getLayoutParams();
} else {
nextLp = null;
}
// Prevent full screen pages from showing in the viewport
// when they are not the current page.
if (lp.isFullScreenPage) {
pageGap = getPaddingLeft();
} else if (nextLp != null && nextLp.isFullScreenPage) {
pageGap = getPaddingRight();
}
childLeft += childWidth + pageGap + getChildGap();
}
}
final LayoutTransition transition = getLayoutTransition();
// If the transition is running defer updating max scroll, as some empty pages could
// still be present, and a max scroll change could cause sudden jumps in scroll.
if (transition != null && transition.isRunning()) {
transition.addTransitionListener(new LayoutTransition.TransitionListener() {
@Override
public void startTransition(LayoutTransition transition, ViewGroup container,
View view, int transitionType) {
}
@Override
public void endTransition(LayoutTransition transition, ViewGroup container,
View view, int transitionType) {
// Wait until all transitions are complete.
if (!transition.isRunning()) {
transition.removeTransitionListener(this);
updateMaxScrollX();
}
}
});
} else {
updateMaxScrollX();
}
if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < childCount) {
updateCurrentPageScroll();
mFirstLayout = false;
}
if (mScroller.isFinished() && mChildCountOnLastLayout != childCount) {
if (mRestorePage != INVALID_RESTORE_PAGE) {
setCurrentPage(mRestorePage);
mRestorePage = INVALID_RESTORE_PAGE;
} else {
setCurrentPage(getNextPage());
}
}
mChildCountOnLastLayout = childCount;
if (isReordering(true)) {
updateDragViewTranslationDuringDrag();
}
}
protected int getChildGap() {
return 0;
}
@Thunk
void updateMaxScrollX() {
mMaxScrollX = computeMaxScrollX();
}
protected int computeMaxScrollX() {
int childCount = getChildCount();
if (childCount > 0) {
final int index = mIsRtl ? 0 : childCount - 1;
return getScrollForPage(index);
} else {
return 0;
}
}
public void setPageSpacing(int pageSpacing) {
mPageSpacing = pageSpacing;
requestLayout();
}
/**
* Called when the center screen changes during scrolling.
*/
protected void screenScrolled(int screenCenter) {
}
@Override
public void onChildViewAdded(View parent, View child) {
// Update the page indicator, we don't update the page indicator as we
// add/remove pages
if (mPageIndicator != null && !isReordering(false)) {
mPageIndicator.addMarker();
}
// This ensures that when children are added, they get the correct transforms / alphas
// in accordance with any scroll effects.
mForceScreenScrolled = true;
updateFreescrollBounds();
invalidate();
}
@Override
public void onChildViewRemoved(View parent, View child) {
mForceScreenScrolled = true;
updateFreescrollBounds();
invalidate();
}
private void removeMarkerForView() {
// Update the page indicator, we don't update the page indicator as we
// add/remove pages
if (mPageIndicator != null && !isReordering(false)) {
mPageIndicator.removeMarker();
}
}
@Override
public void removeView(View v) {
// XXX: We should find a better way to hook into this before the view
// gets removed form its parent...
removeMarkerForView();
super.removeView(v);
}
@Override
public void removeViewInLayout(View v) {
// XXX: We should find a better way to hook into this before the view
// gets removed form its parent...
removeMarkerForView();
super.removeViewInLayout(v);
}
@Override
public void removeViewAt(int index) {
// XXX: We should find a better way to hook into this before the view
// gets removed form its parent...
removeMarkerForView();
super.removeViewAt(index);
}
@Override
public void removeAllViewsInLayout() {
// Update the page indicator, we don't update the page indicator as we
// add/remove pages
if (mPageIndicator != null) {
mPageIndicator.setMarkersCount(0);
}
super.removeAllViewsInLayout();
}
protected int getChildOffset(int index) {
if (index < 0 || index > getChildCount() - 1) return 0;
int offset = getPageAt(index).getLeft() - getViewportOffsetX();
return offset;
}
protected void getFreeScrollPageRange(int[] range) {
range[0] = 0;
range[1] = Math.max(0, getChildCount() - 1);
}
protected void getVisiblePages(int[] range) {
final int count = getChildCount();
range[0] = -1;
range[1] = -1;
if (count > 0) {
final int visibleLeft = -getLeft();
final int visibleRight = visibleLeft + getViewportWidth();
final Matrix pageShiftMatrix = getPageShiftMatrix();
int curScreen = 0;
for (int i = 0; i < count; i++) {
View currPage = getPageAt(i);
// Verify if the page bounds are within the visible range.
sTmpRectF.left = 0;
sTmpRectF.right = currPage.getMeasuredWidth();
currPage.getMatrix().mapRect(sTmpRectF);
sTmpRectF.offset(currPage.getLeft() - getScrollX(), 0);
pageShiftMatrix.mapRect(sTmpRectF);
if (sTmpRectF.left > visibleRight || sTmpRectF.right < visibleLeft) {
if (range[0] == -1) {
continue;
} else {
break;
}
}
curScreen = i;
if (range[0] < 0) {
range[0] = curScreen;
}
}
range[1] = curScreen;
} else {
range[0] = -1;
range[1] = -1;
}
}
protected Matrix getPageShiftMatrix() {
return getMatrix();
}
protected boolean shouldDrawChild(View child) {
return child.getVisibility() == VISIBLE;
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Find out which screens are visible; as an optimization we only call draw on them
final int pageCount = getChildCount();
if (pageCount > 0) {
int halfScreenSize = getViewportWidth() / 2;
int screenCenter = getScrollX() + halfScreenSize;
if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
// set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
// set it for the next frame
mForceScreenScrolled = false;
screenScrolled(screenCenter);
mLastScreenCenter = screenCenter;
}
getVisiblePages(mTempVisiblePagesRange);
final int leftScreen = mTempVisiblePagesRange[0];
final int rightScreen = mTempVisiblePagesRange[1];
if (leftScreen != -1 && rightScreen != -1) {
final long drawingTime = getDrawingTime();
// Clip to the bounds
canvas.save();
canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
getScrollY() + getBottom() - getTop());
// Draw all the children, leaving the drag view for last
for (int i = pageCount - 1; i >= 0; i--) {
final View v = getPageAt(i);
if (v == mDragView) continue;
if (leftScreen <= i && i <= rightScreen && shouldDrawChild(v)) {
drawChild(canvas, v, drawingTime);
}
}
// Draw the drag view on top (if there is one)
if (mDragView != null) {
drawChild(canvas, mDragView, drawingTime);
}
canvas.restore();
}
}
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (getPageCount() > 0) {
if (!mEdgeGlowLeft.isFinished()) {
final int restoreCount = canvas.save();
Rect display = mViewport;
canvas.translate(display.left, display.top);
canvas.rotate(270);
getEdgeVerticalPostion(sTmpIntPoint);
canvas.translate(display.top - sTmpIntPoint[1], 0);
mEdgeGlowLeft.setSize(sTmpIntPoint[1] - sTmpIntPoint[0], display.width());
if (mEdgeGlowLeft.draw(canvas)) {
postInvalidateOnAnimation();
}
canvas.restoreToCount(restoreCount);
}
if (!mEdgeGlowRight.isFinished()) {
final int restoreCount = canvas.save();
Rect display = mViewport;
canvas.translate(display.left + mPageScrolls[mIsRtl ? 0 : (getPageCount() - 1)], display.top);
canvas.rotate(90);
getEdgeVerticalPostion(sTmpIntPoint);
canvas.translate(sTmpIntPoint[0] - display.top, -display.width());
mEdgeGlowRight.setSize(sTmpIntPoint[1] - sTmpIntPoint[0], display.width());
if (mEdgeGlowRight.draw(canvas)) {
postInvalidateOnAnimation();
}
canvas.restoreToCount(restoreCount);
}
}
}
/**
* Returns the top and bottom position for the edge effect.
*/
protected abstract void getEdgeVerticalPostion(int[] pos);
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
int page = indexToPage(indexOfChild(child));
if (page != mCurrentPage || !mScroller.isFinished()) {
snapToPage(page);
return true;
}
return false;
}
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
int focusablePage;
if (mNextPage != INVALID_PAGE) {
focusablePage = mNextPage;
} else {
focusablePage = mCurrentPage;
}
View v = getPageAt(focusablePage);
return v != null && v.requestFocus(direction, previouslyFocusedRect);
}
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
if (super.dispatchUnhandledMove(focused, direction)) {
return true;
}
if (mIsRtl) {
if (direction == View.FOCUS_LEFT) {
direction = View.FOCUS_RIGHT;
} else if (direction == View.FOCUS_RIGHT) {
direction = View.FOCUS_LEFT;
}
}
if (direction == View.FOCUS_LEFT) {
if (getCurrentPage() > 0) {
snapToPage(getCurrentPage() - 1);
return true;
}
} else if (direction == View.FOCUS_RIGHT) {
if (getCurrentPage() < getPageCount() - 1) {
snapToPage(getCurrentPage() + 1);
return true;
}
}
return false;
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
// XXX-RTL: This will be fixed in a future CL
if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
}
if (direction == View.FOCUS_LEFT) {
if (mCurrentPage > 0) {
getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
}
} else if (direction == View.FOCUS_RIGHT) {
if (mCurrentPage < getPageCount() - 1) {
getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
}
}
}
/**
* If one of our descendant views decides that it could be focused now, only
* pass that along if it's on the current page.
* <p>
* This happens when live folders requery, and if they're off page, they
* end up calling requestFocus, which pulls it on page.
*/
@Override
public void focusableViewAvailable(View focused) {
View current = getPageAt(mCurrentPage);
View v = focused;
while (true) {
if (v == current) {
super.focusableViewAvailable(focused);
return;
}
if (v == this) {
return;
}
ViewParent parent = v.getParent();
if (parent instanceof View) {
v = (View) v.getParent();
} else {
return;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept) {
// We need to make sure to cancel our long press if
// a scrollable widget takes over touch events
final View currentPage = getPageAt(mCurrentPage);
if (currentPage != null) {
currentPage.cancelLongPress();
}
}
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
/**
* Returns whether x and y originated within the buffered viewport
*/
private boolean isTouchPointInViewportWithBuffer(int x, int y) {
sTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
mViewport.right + mViewport.width() / 2, mViewport.bottom);
return sTmpRect.contains(x, y);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* This method JUST determines whether we want to intercept the motion.
* If we return true, onTouchEvent will be called and we do the actual
* scrolling there.
*/
acquireVelocityTrackerAndAddMovement(ev);
// Skip touch handling if there are no pages to swipe
if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
/*
* Shortcut the most recurring case: the user is in the dragging
* state and he is moving his finger. We want to intercept this
* motion.
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) &&
(mTouchState == TOUCH_STATE_SCROLLING)) {
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
/*
* mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
* whether the user has moved far enough from his original down touch.
*/
if (mActivePointerId != INVALID_POINTER) {
determineScrollingStart(ev);
}
// if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
// event. in that case, treat the first occurence of a move event as a ACTION_DOWN
// i.e. fall through to the next case (don't break)
// (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
// while it's small- this was causing a crash before we checked for INVALID_POINTER)
break;
}
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
// Remember location of down touch
mDownMotionX = x;
mDownMotionY = y;
mDownScrollX = getScrollX();
mLastMotionX = x;
mLastMotionY = y;
float[] p = mapPointFromViewToParent(this, x, y);
mParentDownMotionX = p[0];
mParentDownMotionY = p[1];
mLastMotionXRemainder = 0;
mTotalMotionX = 0;
mActivePointerId = ev.getPointerId(0);
/*
* If being flinged and user touches the screen, initiate drag;
* otherwise don't. mScroller.isFinished should be false when
* being flinged.
*/
final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop / 3);
if (finishedScrolling) {
mTouchState = TOUCH_STATE_REST;
if (!mScroller.isFinished() && !mFreeScroll) {
setCurrentPage(getNextPage());
pageEndMoving();
}
} else {
if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
mTouchState = TOUCH_STATE_SCROLLING;
} else {
mTouchState = TOUCH_STATE_REST;
}
}
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
resetTouchState();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
releaseVelocityTracker();
break;
}
/*
* The only time we want to intercept motion events is if we are in the
* drag mode.
*/
return mTouchState != TOUCH_STATE_REST;
}
protected void determineScrollingStart(MotionEvent ev) {
determineScrollingStart(ev, 1.0f);
}
/*
* Determines if we should change the touch state to start scrolling after the
* user moves their touch point too far.
*/
protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
// Disallow scrolling if we don't have a valid pointer index
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return;
// Disallow scrolling if we started the gesture from outside the viewport
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
boolean xMoved = xDiff > touchSlop;
if (xMoved) {
// Scroll if the user moved far enough along the X axis
mTouchState = TOUCH_STATE_SCROLLING;
mTotalMotionX += Math.abs(mLastMotionX - x);
mLastMotionX = x;
mLastMotionXRemainder = 0;
onScrollInteractionBegin();
pageBeginMoving();
// Stop listening for things like pinches.
requestDisallowInterceptTouchEvent(true);
}
}
protected void cancelCurrentPageLongPress() {
// Try canceling the long press. It could also have been scheduled
// by a distant descendant, so use the mAllowLongPress flag to block
// everything
final View currentPage = getPageAt(mCurrentPage);
if (currentPage != null) {
currentPage.cancelLongPress();
}
}
protected float getScrollProgress(int screenCenter, View v, int page) {
final int halfScreenSize = getViewportWidth() / 2;
int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
int count = getChildCount();
final int totalDistance;
int adjacentPage = page + 1;
if ((delta < 0 && !mIsRtl) || (delta > 0 && mIsRtl)) {
adjacentPage = page - 1;
}
if (adjacentPage < 0 || adjacentPage > count - 1) {
totalDistance = v.getMeasuredWidth() + mPageSpacing;
} else {
totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
}
float scrollProgress = delta / (totalDistance * 1.0f);
scrollProgress = Math.min(scrollProgress, MAX_SCROLL_PROGRESS);
scrollProgress = Math.max(scrollProgress, -MAX_SCROLL_PROGRESS);
return scrollProgress;
}
public int getScrollForPage(int index) {
if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
return 0;
} else {
return mPageScrolls[index];
}
}
// While layout transitions are occurring, a child's position may stray from its baseline
// position. This method returns the magnitude of this stray at any given time.
public int getLayoutTransitionOffsetForPage(int index) {
if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
return 0;
} else {
View child = getChildAt(index);
int scrollOffset = 0;
LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.isFullScreenPage) {
scrollOffset = mIsRtl ? getPaddingRight() : getPaddingLeft();
}
int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
return (int) (child.getX() - baselineX);
}
}
protected void dampedOverScroll(float amount) {
int screenSize = getViewportWidth();
float f = (amount / screenSize);
if (f < 0) {
mEdgeGlowLeft.onPull(-f);
} else if (f > 0) {
mEdgeGlowRight.onPull(f);
} else {
return;
}
invalidate();
}
protected void overScroll(float amount) {
dampedOverScroll(amount);
}
public void enableFreeScroll() {
setEnableFreeScroll(true);
}
public void disableFreeScroll() {
setEnableFreeScroll(false);
}
void updateFreescrollBounds() {
getFreeScrollPageRange(mTempVisiblePagesRange);
if (mIsRtl) {
mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
} else {
mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
}
}
private void setEnableFreeScroll(boolean freeScroll) {
boolean wasFreeScroll = mFreeScroll;
mFreeScroll = freeScroll;
if (mFreeScroll) {
updateFreescrollBounds();
getFreeScrollPageRange(mTempVisiblePagesRange);
if (getCurrentPage() < mTempVisiblePagesRange[0]) {
setCurrentPage(mTempVisiblePagesRange[0]);
} else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
setCurrentPage(mTempVisiblePagesRange[1]);
}
} else if (wasFreeScroll) {
snapToPage(getNextPage());
}
setEnableOverscroll(!freeScroll);
}
protected void setEnableOverscroll(boolean enable) {
mAllowOverScroll = enable;
}
private int getNearestHoverOverPageIndex() {
if (mDragView != null) {
int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
+ mDragView.getTranslationX());
getFreeScrollPageRange(mTempVisiblePagesRange);
int minDistance = Integer.MAX_VALUE;
int minIndex = indexOfChild(mDragView);
for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
View page = getPageAt(i);
int pageX = page.getLeft() + page.getMeasuredWidth() / 2;
int d = Math.abs(dragX - pageX);
if (d < minDistance) {
minIndex = i;
minDistance = d;
}
}
return minIndex;
}
return -1;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
// Skip touch handling if there are no pages to swipe
if (getChildCount() <= 0) return super.onTouchEvent(ev);
acquireVelocityTrackerAndAddMovement(ev);
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
/*
* If being flinged and user touches, stop the fling. isFinished
* will be false if being flinged.
*/
if (!mScroller.isFinished()) {
abortScrollerAnimation(false);
}
// Remember where the motion event started
mDownMotionX = mLastMotionX = ev.getX();
mDownMotionY = mLastMotionY = ev.getY();
mDownScrollX = getScrollX();
float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
mParentDownMotionX = p[0];
mParentDownMotionY = p[1];
mLastMotionXRemainder = 0;
mTotalMotionX = 0;
mActivePointerId = ev.getPointerId(0);
if (mTouchState == TOUCH_STATE_SCROLLING) {
onScrollInteractionBegin();
pageBeginMoving();
}
break;
case MotionEvent.ACTION_MOVE:
if (mTouchState == TOUCH_STATE_SCROLLING) {
// Scroll to follow the motion event
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return true;
final float x = ev.getX(pointerIndex);
final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
mTotalMotionX += Math.abs(deltaX);
// Only scroll and update mLastMotionX if we have moved some discrete amount. We
// keep the remainder because we are actually testing if we've moved from the last
// scrolled position (which is discrete).
if (Math.abs(deltaX) >= 1.0f) {
scrollBy((int) deltaX, 0);
mLastMotionX = x;
mLastMotionXRemainder = deltaX - (int) deltaX;
} else {
awakenScrollBars();
}
} else if (mTouchState == TOUCH_STATE_REORDERING) {
// Update the last motion position
mLastMotionX = ev.getX();
mLastMotionY = ev.getY();
// Update the parent down so that our zoom animations take this new movement into
// account
float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
mParentDownMotionX = pt[0];
mParentDownMotionY = pt[1];
updateDragViewTranslationDuringDrag();
// Find the closest page to the touch point
final int dragViewIndex = indexOfChild(mDragView);
final int pageUnderPointIndex = getNearestHoverOverPageIndex();
// Do not allow any page to be moved to 0th position.
if (pageUnderPointIndex > 0 && pageUnderPointIndex != indexOfChild(mDragView)) {
mTempVisiblePagesRange[0] = 0;
mTempVisiblePagesRange[1] = getPageCount() - 1;
getFreeScrollPageRange(mTempVisiblePagesRange);
if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
mSidePageHoverIndex = pageUnderPointIndex;
mSidePageHoverRunnable = new Runnable() {
@Override
public void run() {
// Setup the scroll to the correct page before we swap the views
snapToPage(pageUnderPointIndex);
// For each of the pages between the paged view and the drag view,
// animate them from the previous position to the new position in
// the layout (as a result of the drag view moving in the layout)
int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
dragViewIndex + 1 : pageUnderPointIndex;
int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
dragViewIndex - 1 : pageUnderPointIndex;
for (int i = lowerIndex; i <= upperIndex; ++i) {
View v = getChildAt(i);
// dragViewIndex < pageUnderPointIndex, so after we remove the
// drag view all subsequent views to pageUnderPointIndex will
// shift down.
int oldX = getViewportOffsetX() + getChildOffset(i);
int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
// Animate the view translation from its old position to its new
// position
ObjectAnimator anim = (ObjectAnimator) v.getTag();
if (anim != null) {
anim.cancel();
}
v.setTranslationX(oldX - newX);
anim = LauncherAnimUtils.ofFloat(v, View.TRANSLATION_X, 0);
anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
anim.start();
v.setTag(anim);
}
removeView(mDragView);
addView(mDragView, pageUnderPointIndex);
mSidePageHoverIndex = -1;
if (mPageIndicator != null) {
mPageIndicator.setActiveMarker(getNextPage());
}
}
};
postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
}
} else {
removeCallbacks(mSidePageHoverRunnable);
mSidePageHoverIndex = -1;
}
} else {
determineScrollingStart(ev);
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_SCROLLING) {
final int activePointerId = mActivePointerId;
final int pointerIndex = ev.findPointerIndex(activePointerId);
final float x = ev.getX(pointerIndex);
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
final int deltaX = (int) (x - mDownMotionX);
final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
SIGNIFICANT_MOVE_THRESHOLD;
mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Math.abs(velocityX) > mFlingThresholdVelocity;
if (!mFreeScroll) {
// In the case that the page is moved far to one direction and then is flung
// in the opposite direction, we use a threshold to determine whether we should
// just return to the starting page, or if we should skip one further.
boolean returnToOriginalPage = false;
if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
returnToOriginalPage = true;
}
int finalPage;
// We give flings precedence over large moves, which is why we short-circuit our
// test for a large move if a fling has been registered. That is, a large
// move to the left and fling to the right will register as a fling to the right.
boolean isDeltaXLeft = mIsRtl ? deltaX > 0 : deltaX < 0;
boolean isVelocityXLeft = mIsRtl ? velocityX > 0 : velocityX < 0;
if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
(isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
snapToPageWithVelocity(finalPage, velocityX);
} else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
(isFling && isVelocityXLeft)) &&
mCurrentPage < getChildCount() - 1) {
finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
snapToPageWithVelocity(finalPage, velocityX);
} else {
snapToDestination();
}
} else {
if (!mScroller.isFinished()) {
abortScrollerAnimation(true);
}
float scaleX = getScaleX();
int vX = (int) (-velocityX * scaleX);
int initialScrollX = (int) (getScrollX() * scaleX);
mScroller.setInterpolator(mDefaultInterpolator);
mScroller.fling(initialScrollX,
getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
mNextPage = getPageNearestToCenterOfScreen((int) (mScroller.getFinalX() / scaleX));
invalidate();
}
onScrollInteractionEnd();
} else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
// at this point we have not moved beyond the touch slop
// (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
// we can just page
int nextPage = Math.max(0, mCurrentPage - 1);
if (nextPage != mCurrentPage) {
snapToPage(nextPage);
} else {
snapToDestination();
}
} else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
// at this point we have not moved beyond the touch slop
// (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
// we can just page
int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
if (nextPage != mCurrentPage) {
snapToPage(nextPage);
} else {
snapToDestination();
}
} else if (mTouchState == TOUCH_STATE_REORDERING) {
// Update the last motion position
mLastMotionX = ev.getX();
mLastMotionY = ev.getY();
// Update the parent down so that our zoom animations take this new movement into
// account
float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
mParentDownMotionX = pt[0];
mParentDownMotionY = pt[1];
updateDragViewTranslationDuringDrag();
} else {
if (!mCancelTap) {
onUnhandledTap();
}
}
// Remove the callback to wait for the side page hover timeout
removeCallbacks(mSidePageHoverRunnable);
// End any intermediate reordering states
resetTouchState();
break;
case MotionEvent.ACTION_CANCEL:
if (mTouchState == TOUCH_STATE_SCROLLING) {
snapToDestination();
onScrollInteractionEnd();
}
resetTouchState();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
releaseVelocityTracker();
break;
}
return true;
}
private void resetTouchState() {
releaseVelocityTracker();
endReordering();
mCancelTap = false;
mTouchState = TOUCH_STATE_REST;
mActivePointerId = INVALID_POINTER;
mEdgeGlowLeft.onRelease();
mEdgeGlowRight.onRelease();
}
/**
* Triggered by scrolling via touch
*/
protected void onScrollInteractionBegin() {
}
protected void onScrollInteractionEnd() {
}
protected void onUnhandledTap() {
Launcher.getLauncher(getContext()).onClick(this);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL: {
// Handle mouse (or ext. device) by shifting the page depending on the scroll
final float vscroll;
final float hscroll;
if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
vscroll = 0;
hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
} else {
vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
}
if (hscroll != 0 || vscroll != 0) {
boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0)
: (hscroll > 0 || vscroll > 0);
if (isForwardScroll) {
scrollRight();
} else {
scrollLeft();
}
return true;
}
}
}
}
return super.onGenericMotionEvent(event);
}
private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
}
private void releaseVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.clear();
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
// TODO: Make this decision more intelligent.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
mLastMotionY = ev.getY(newPointerIndex);
mLastMotionXRemainder = 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
@Override
public void requestChildFocus(View child, View focused) {
super.requestChildFocus(child, focused);
int page = indexToPage(indexOfChild(child));
if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
snapToPage(page);
}
}
int getPageNearestToCenterOfScreen() {
return getPageNearestToCenterOfScreen(getScrollX());
}
private int getPageNearestToCenterOfScreen(int scaledScrollX) {
int screenCenter = getViewportOffsetX() + scaledScrollX + (getViewportWidth() / 2);
int minDistanceFromScreenCenter = Integer.MAX_VALUE;
int minDistanceFromScreenCenterIndex = -1;
final int childCount = getChildCount();
for (int i = 0; i < childCount; ++i) {
View layout = getPageAt(i);
int childWidth = layout.getMeasuredWidth();
int halfChildWidth = (childWidth / 2);
int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
minDistanceFromScreenCenter = distanceFromScreenCenter;
minDistanceFromScreenCenterIndex = i;
}
}
return minDistanceFromScreenCenterIndex;
}
protected void snapToDestination() {
snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
}
public static class ScrollInterpolator implements Interpolator {
public ScrollInterpolator() {
}
@Override
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1;
}
}
// We want the duration of the page snap animation to be influenced by the distance that
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
protected void snapToPageWithVelocity(int whichPage, int velocity) {
whichPage = validateNewPage(whichPage);
int halfScreenSize = getViewportWidth() / 2;
final int newX = getScrollForPage(whichPage);
int delta = newX - getUnboundedScrollX();
int duration;
if (Math.abs(velocity) < mMinFlingVelocity) {
// If the velocity is low enough, then treat this more as an automatic page advance
// as opposed to an apparent physical response to flinging
snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
return;
}
// Here we compute a "distance" that will be used in the computation of the overall
// snap duration. This is a function of the actual distance that needs to be traveled;
// we keep this value close to half screen size in order to reduce the variance in snap
// duration as a function of the distance the page needs to travel.
float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
float distance = halfScreenSize + halfScreenSize *
distanceInfluenceForSnapDuration(distanceRatio);
velocity = Math.abs(velocity);
velocity = Math.max(mMinSnapVelocity, velocity);
// we want the page's snap velocity to approximately match the velocity at which the
// user flings, so we scale the duration by a value near to the derivative of the scroll
// interpolator at zero, ie. 5. We use 4 to make it a little slower.
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
snapToPage(whichPage, delta, duration);
}
public void snapToPage(int whichPage) {
snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
}
public void snapToPageImmediately(int whichPage) {
snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true, null);
}
protected void snapToPage(int whichPage, int duration) {
snapToPage(whichPage, duration, false, null);
}
protected void snapToPage(int whichPage, int duration, TimeInterpolator interpolator) {
snapToPage(whichPage, duration, false, interpolator);
}
protected void snapToPage(int whichPage, int duration, boolean immediate,
TimeInterpolator interpolator) {
whichPage = validateNewPage(whichPage);
int newX = getScrollForPage(whichPage);
final int delta = newX - getUnboundedScrollX();
snapToPage(whichPage, delta, duration, immediate, interpolator);
}
protected void snapToPage(int whichPage, int delta, int duration) {
snapToPage(whichPage, delta, duration, false, null);
}
protected void snapToPage(int whichPage, int delta, int duration, boolean immediate,
TimeInterpolator interpolator) {
whichPage = validateNewPage(whichPage);
mNextPage = whichPage;
pageBeginMoving();
awakenScrollBars(duration);
if (immediate) {
duration = 0;
} else if (duration == 0) {
duration = Math.abs(delta);
}
if (!mScroller.isFinished()) {
abortScrollerAnimation(false);
}
if (interpolator != null) {
mScroller.setInterpolator(interpolator);
} else {
mScroller.setInterpolator(mDefaultInterpolator);
}
mScroller.startScroll(getUnboundedScrollX(), 0, delta, 0, duration);
updatePageIndicator();
// Trigger a compute() to finish switching pages if necessary
if (immediate) {
computeScroll();
}
mForceScreenScrolled = true;
invalidate();
}
public void scrollLeft() {
if (getNextPage() > 0) snapToPage(getNextPage() - 1);
}
public void scrollRight() {
if (getNextPage() < getChildCount() - 1) snapToPage(getNextPage() + 1);
}
@Override
public boolean performLongClick() {
mCancelTap = true;
return super.performLongClick();
}
// Animate the drag view back to the original position
private void animateDragViewToOriginalPosition() {
if (mDragView != null) {
Animator anim = new LauncherViewPropertyAnimator(mDragView)
.translationX(0)
.translationY(0)
.scaleX(1)
.scaleY(1)
.setDuration(REORDERING_DROP_REPOSITION_DURATION);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
onPostReorderingAnimationCompleted();
}
});
anim.start();
}
}
public void onStartReordering() {
// Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
mTouchState = TOUCH_STATE_REORDERING;
mIsReordering = true;
// We must invalidate to trigger a redraw to update the layers such that the drag view
// is always drawn on top
invalidate();
}
@Thunk
void onPostReorderingAnimationCompleted() {
// Trigger the callback when reordering has settled
--mPostReorderingPreZoomInRemainingAnimationCount;
if (mPostReorderingPreZoomInRunnable != null &&
mPostReorderingPreZoomInRemainingAnimationCount == 0) {
mPostReorderingPreZoomInRunnable.run();
mPostReorderingPreZoomInRunnable = null;
}
}
public void onEndReordering() {
mIsReordering = false;
}
public boolean startReordering(View v) {
int dragViewIndex = indexOfChild(v);
// Do not allow the first page to be moved around
if (mTouchState != TOUCH_STATE_REST || dragViewIndex <= 0) return false;
mTempVisiblePagesRange[0] = 0;
mTempVisiblePagesRange[1] = getPageCount() - 1;
getFreeScrollPageRange(mTempVisiblePagesRange);
mReorderingStarted = true;
// Check if we are within the reordering range
if (mTempVisiblePagesRange[0] <= dragViewIndex &&
dragViewIndex <= mTempVisiblePagesRange[1]) {
// Find the drag view under the pointer
mDragView = getChildAt(dragViewIndex);
mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
mDragViewBaselineLeft = mDragView.getLeft();
snapToPage(getPageNearestToCenterOfScreen());
disableFreeScroll();
onStartReordering();
return true;
}
return false;
}
boolean isReordering(boolean testTouchState) {
boolean state = mIsReordering;
if (testTouchState) {
state &= (mTouchState == TOUCH_STATE_REORDERING);
}
return state;
}
void endReordering() {
// For simplicity, we call endReordering sometimes even if reordering was never started.
// In that case, we don't want to do anything.
if (!mReorderingStarted) return;
mReorderingStarted = false;
// If we haven't flung-to-delete the current child, then we just animate the drag view
// back into position
final Runnable onCompleteRunnable = new Runnable() {
@Override
public void run() {
onEndReordering();
}
};
mPostReorderingPreZoomInRunnable = new Runnable() {
@Override
public void run() {
onCompleteRunnable.run();
enableFreeScroll();
}
};
mPostReorderingPreZoomInRemainingAnimationCount =
NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
// Snap to the current page
snapToPage(indexOfChild(mDragView), 0);
// Animate the drag view back to the front position
animateDragViewToOriginalPosition();
}
/* Accessibility */
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setScrollable(getPageCount() > 1);
if (getCurrentPage() < getPageCount() - 1) {
info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
}
if (getCurrentPage() > 0) {
info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
}
info.setClassName(getClass().getName());
// Accessibility-wise, PagedView doesn't support long click, so disabling it.
// Besides disabling the accessibility long-click, this also prevents this view from getting
// accessibility focus.
info.setLongClickable(false);
info.removeAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_LONG_CLICK);
}
@Override
public void sendAccessibilityEvent(int eventType) {
// Don't let the view send real scroll events.
if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
super.sendAccessibilityEvent(eventType);
}
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setScrollable(getPageCount() > 1);
}
@Override
public boolean performAccessibilityAction(int action, Bundle arguments) {
if (super.performAccessibilityAction(action, arguments)) {
return true;
}
switch (action) {
case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
if (getCurrentPage() < getPageCount() - 1) {
scrollRight();
return true;
}
}
break;
case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
if (getCurrentPage() > 0) {
scrollLeft();
return true;
}
}
break;
}
return false;
}
protected String getPageIndicatorDescription() {
return getCurrentPageDescription();
}
protected String getCurrentPageDescription() {
return getContext().getString(R.string.default_scroll_format,
getNextPage() + 1, getChildCount());
}
@Override
public boolean onHoverEvent(android.view.MotionEvent event) {
return true;
}
}
|
package org.wikiup.modules.jsp.tag;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.wikiup.core.Wikiup;
import org.wikiup.core.impl.Null;
import org.wikiup.core.inf.Dictionary;
import org.wikiup.core.inf.ExpressionLanguage;
import org.wikiup.core.util.StringUtil;
import org.wikiup.modules.jsp.JspServletContainer;
import org.wikiup.modules.jsp.JspServletContext;
import org.wikiup.servlet.ServletProcessorContext;
import org.wikiup.servlet.util.ProcessorContexts;
public class ForeachTag extends BodyTagSupport {
private String in;
private ServletProcessorContext context;
private Iterator<?> iterator;
private String body;
private ExpressionLanguage<Dictionary<?>, String> el = Wikiup.getModel(JspServletContainer.class).getEl();
public void setIn(String in) {
this.in = in;
}
@Override
public int doEndTag() throws JspException {
context.getBeanStack().pop();
return EVAL_PAGE;
}
@Override
public int doStartTag() throws JspException {
int result = SKIP_BODY;
Object ctx;
context = JspServletContext.get().context;
ServletProcessorContext.BeanStack beanStack = context.getBeanStack();
if(in != null) {
ctx = ProcessorContexts.get(context, StringUtil.evaluateEL(in, context), Null.getInstance());
beanStack.push(ctx);
}
Iterable<?> iterable = beanStack.peek(Iterable.class);
iterator = iterable != null ? iterable.iterator() : Null.getInstance();
if(iterator.hasNext() && (ctx = iterator.next()) != null) {
beanStack.push(ctx);
body = null;
result = EVAL_BODY_BUFFERED;
}
if(in != null)
beanStack.pop();
return result;
}
@Override
public int doAfterBody() throws JspException {
ServletProcessorContext.BeanStack beanStack = context.getBeanStack();
beanStack.pop();
Object ctx;
if(body == null)
body = bodyContent.getString();
try {
bodyContent.getEnclosingWriter().print(el.evaluate(context, body));
} catch(IOException e) {
}
if(iterator.hasNext() && (ctx = iterator.next()) != null) {
beanStack.push(ctx);
return EVAL_BODY_AGAIN;
}
return 0;
}
}
|
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.notedb;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.gerrit.server.CommentsUtil.COMMENT_ORDER;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ListMultimap;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Comment;
import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.UsedAt;
import com.google.gerrit.server.config.GerritServerId;
import com.google.inject.Inject;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.util.QuotedString;
public class LegacyChangeNoteWrite {
private final PersonIdent serverIdent;
private final String serverId;
@Inject
public LegacyChangeNoteWrite(
@GerritPersonIdent PersonIdent serverIdent, @GerritServerId String serverId) {
this.serverIdent = serverIdent;
this.serverId = serverId;
}
public PersonIdent newIdent(Account.Id authorId, Date when, PersonIdent serverIdent) {
return new PersonIdent(
authorId.toString(), authorId.get() + "@" + serverId, when, serverIdent.getTimeZone());
}
@VisibleForTesting
public PersonIdent newIdent(Account author, Date when, PersonIdent serverIdent) {
return new PersonIdent(
author.toString(), author.getId().get() + "@" + serverId, when, serverIdent.getTimeZone());
}
public String getServerId() {
return serverId;
}
private void appendHeaderField(PrintWriter writer, String field, String value) {
writer.print(field);
writer.print(": ");
writer.print(value);
writer.print('\n');
}
/**
* Build a note that contains the metadata for and the contents of all of the comments in the
* given comments.
*
* @param comments Comments to be written to the output stream, keyed by patch set ID; multiple
* patch sets are allowed since base revisions may be shared across patch sets. All of the
* comments must share the same RevId, and all the comments for a given patch set must have
* the same side.
* @param out output stream to write to.
*/
@UsedAt(UsedAt.Project.GOOGLE)
public void buildNote(ListMultimap<Integer, Comment> comments, OutputStream out) {
if (comments.isEmpty()) {
return;
}
List<Integer> psIds = new ArrayList<>(comments.keySet());
Collections.sort(psIds);
OutputStreamWriter streamWriter = new OutputStreamWriter(out, UTF_8);
try (PrintWriter writer = new PrintWriter(streamWriter)) {
String revId = comments.values().iterator().next().revId;
appendHeaderField(writer, ChangeNoteUtil.REVISION, revId);
for (int psId : psIds) {
List<Comment> psComments = COMMENT_ORDER.sortedCopy(comments.get(psId));
Comment first = psComments.get(0);
short side = first.side;
appendHeaderField(
writer,
side <= 0 ? ChangeNoteUtil.BASE_PATCH_SET : ChangeNoteUtil.PATCH_SET,
Integer.toString(psId));
if (side < 0) {
appendHeaderField(writer, ChangeNoteUtil.PARENT_NUMBER, Integer.toString(-side));
}
String currentFilename = null;
for (Comment c : psComments) {
checkArgument(
revId.equals(c.revId),
"All comments being added must have all the same RevId. The "
+ "comment below does not have the same RevId as the others "
+ "(%s).\n%s",
revId,
c);
checkArgument(
side == c.side,
"All comments being added must all have the same side. The "
+ "comment below does not have the same side as the others "
+ "(%s).\n%s",
side,
c);
String commentFilename = QuotedString.GIT_PATH.quote(c.key.filename);
if (!commentFilename.equals(currentFilename)) {
currentFilename = commentFilename;
writer.print("File: ");
writer.print(commentFilename);
writer.print("\n\n");
}
appendOneComment(writer, c);
}
}
}
}
private void appendOneComment(PrintWriter writer, Comment c) {
// The CommentRange field for a comment is allowed to be null. If it is
// null, then in the first line, we simply use the line number field for a
// comment instead. If it isn't null, we write the comment range itself.
Comment.Range range = c.range;
if (range != null) {
writer.print(range.startLine);
writer.print(':');
writer.print(range.startChar);
writer.print('-');
writer.print(range.endLine);
writer.print(':');
writer.print(range.endChar);
} else {
writer.print(c.lineNbr);
}
writer.print("\n");
writer.print(NoteDbUtil.formatTime(serverIdent, c.writtenOn));
writer.print("\n");
appendIdent(writer, ChangeNoteUtil.AUTHOR, c.author.getId(), c.writtenOn);
if (!c.getRealAuthor().equals(c.author)) {
appendIdent(writer, ChangeNoteUtil.REAL_AUTHOR, c.getRealAuthor().getId(), c.writtenOn);
}
String parent = c.parentUuid;
if (parent != null) {
appendHeaderField(writer, ChangeNoteUtil.PARENT, parent);
}
appendHeaderField(writer, ChangeNoteUtil.UNRESOLVED, Boolean.toString(c.unresolved));
appendHeaderField(writer, ChangeNoteUtil.UUID, c.key.uuid);
if (c.tag != null) {
appendHeaderField(writer, ChangeNoteUtil.TAG, c.tag);
}
byte[] messageBytes = c.message.getBytes(UTF_8);
appendHeaderField(writer, ChangeNoteUtil.LENGTH, Integer.toString(messageBytes.length));
writer.print(c.message);
writer.print("\n\n");
}
private void appendIdent(PrintWriter writer, String header, Account.Id id, Timestamp ts) {
PersonIdent ident = newIdent(id, ts, serverIdent);
StringBuilder name = new StringBuilder();
PersonIdent.appendSanitized(name, ident.getName());
name.append(" <");
PersonIdent.appendSanitized(name, ident.getEmailAddress());
name.append('>');
appendHeaderField(writer, header, name.toString());
}
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.gaap.v20180529.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class ModifyProxiesAttributeResponse extends AbstractModel{
/**
* The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
@SerializedName("RequestId")
@Expose
private String RequestId;
/**
* Get The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public String getRequestId() {
return this.RequestId;
}
/**
* Set The unique request ID, which is returned for each request. RequestId is required for locating a problem.
* @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem.
*/
public void setRequestId(String RequestId) {
this.RequestId = RequestId;
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
|
import javax.swing.*;
import java.awt.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();//creating JFrame
JPanel panel = new JPanel();
frame.setSize(600, 800);//set size
frame.add(panel);
frame.setLayout(null);
frame.setVisible(true);
}
}
|
package common;
import java.time.LocalTime;
import java.util.Map;
public class Drone extends Model implements Runnable {
private static final long serialVersionUID = 6613147626169007647L;
private Boolean restocking = false; //boolean to check if drone is currently restocking
private Boolean delivering = false; //boolean to check if drone is currently delivering
private Boolean active = false; //boolean to check if drone is currently active
private Boolean enabled = true; //boolean to check if drone is enabled
private Integer speed; //speed of drone
private Thread thread;
public Drone (String name, Integer speed) {
this.name = name;
this.speed = speed;
}
@Override
public String getName() {
return name;
}
@Override
public void run() {
while(!active && enabled) {
droneRestock(Stock.checkIngredientStock());
}
}
/**
* method to monitor delivery activities of drone
* @param order
*/
public void delivery(Order order) {
LocalTime time = LocalTime.now().withNano(0);
if (!restocking) {
if(order!=null) {
delivering = true;
order.deliverOrder();
Postcode postcode = order.getUser().getPostcode();
Integer approxTime = (int) (postcode.getDistance()/speed);
LocalTime deliveryTime = time.plusMinutes(approxTime);
Integer i = time.compareTo(deliveryTime);
while(i==-1) {
delivering = true;
active = true;
}
System.out.println("Estimated delivery time to " + postcode.getName() + ": " + approxTime);
for (Map.Entry<Dish, Number> entry : order.getUser().getBasket().entrySet()) {
for (Dish dish : StaffItemsManager.getDishes()) {
if (dish != null && (int) entry.getValue() >= dish.getDishManager().getQuantity()) {
dish.getDishManager().usage((int) entry.getValue());
} else {
System.err.println(dish.getName() +" stock is low");
}
}
}
System.out.println("Delivery to " + postcode.getName() + " completed at: " + deliveryTime);
Stock.checkDishStock();
}
} else
System.out.println("Drone is currently busy restocking.");
order.completedOrder();
active = false;
delivering = false;
}
/**
* method to monitor restocking of ingredients using drone
* @param ingredient
*/
public void droneRestock(Ingredient ingredient) {
LocalTime time = LocalTime.now().withNano(0);
if (!delivering) {
restocking = true;
Double d = ingredient.getSupplier().getDistance();
Integer approxTime = (int) (d/speed);
LocalTime restockTime = time.plusMinutes(approxTime);
Integer i = time.compareTo(restockTime);
while(i==-1) {
restocking = true;
active = true;
}
System.out.println("Estimated restocking time: " + approxTime );
Stock.checkIngredientStock();
System.out.println(ingredient.getName() + " has been restocked.");
} else
System.out.println("Drone is currently busy delivering.");
active = false;
restocking = false;
}
/**
* method to start thread
*/
public void start() {
System.out.println(name + " is currently working.");
if (thread.equals(null)) {
thread = new Thread (this, name);
thread.start();
}
}
/**
* method that returns current status of drone
* @return String
*/
public String getDroneStatus() {
if(restocking)
return name + " is currently restocking.";
else if(delivering)
return name + " is currently delivering.";
return name + " is idle.";
}
public Integer getSpeed() {
return speed;
}
public Boolean getRestocking() {
return restocking;
}
public Boolean getDelivering() {
return delivering;
}
public Boolean isActive() {
return active;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
|
package com.myfreax.www.arp_scanner.subnet;
import java.net.InetAddress;
public class Device {
public String ip;
public String hostname;
public String mac;
public String vendor;
public float time = 0;
public Device(InetAddress ip) {
this.ip = ip.getHostAddress();
this.hostname = ip.getCanonicalHostName();
}
@Override
public String toString() {
return "Device{" +
"ip='" + ip + '\'' +
"vendor='" + vendor + '\'' +
", hostname='" + hostname + '\'' +
", mac='" + mac + '\'' +
", time=" + time +
'}';
}
}
|
package org.tek.code.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.tek.code.model.TestUser;
import org.tek.code.service.impl.TestUserServiceImpl;
import javax.servlet.http.HttpServletRequest;
/**
* @author Nick
* @date 2020/11/14
*/
@RestController
public class TestUserComtroller {
@Autowired
private TestUserServiceImpl testUserService;
@GetMapping(value = "/getUserInfoById")
@ResponseBody
public TestUser getUserInfo(String id) {
return testUserService.getUserById(id);
}
}
|
package de.ropemc.api.wrapper.net.minecraft.world.biome;
import de.ropemc.api.wrapper.net.minecraft.world.World;
import java.util.Random;
import de.ropemc.api.wrapper.net.minecraft.util.BlockPos;
import de.ropemc.api.wrapper.net.minecraft.world.gen.feature.WorldGenAbstractTree;
import de.ropemc.api.wrapper.net.minecraft.world.chunk.ChunkPrimer;
import de.ropemc.api.wrapper.WrappedClass;
@WrappedClass("net.minecraft.world.biome.BiomeGenHills")
public interface BiomeGenHills {
BiomeGenBase createMutatedBiome(int var0);
void decorate(World var0, Random var1, BlockPos var2);
WorldGenAbstractTree genBigTreeChance(Random var0);
void genTerrainBlocks(World var0, Random var1, ChunkPrimer var2, int var3, int var4, double var5);
BiomeGenHills mutateHills(BiomeGenBase var0);
}
|
/*
* Copyright 2015 Hippo B.V. (http://www.onehippo.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.hippoecm.repository.standardworkflow;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Value;
import org.hippoecm.repository.util.JcrUtils;
import org.junit.Test;
import org.onehippo.repository.testutils.RepositoryTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ExpandingCopyHandlerTest extends RepositoryTestCase {
private Node source;
private Node target;
@Override
public void setUp() throws Exception {
super.setUp();
final Node test = session.getRootNode().addNode("test");
source = test.addNode("source");
source.setProperty("prop", "value");
source.setProperty("multiprop", new String[] { "value1", "value2" });
source.addNode("child").setProperty("prop", "value");
target = test.addNode("target");
}
@Test
public void testCopyWithNodeNameSubstitutes() throws Exception {
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./_name", new String[] { "substitute" });
put("./child/_name", new String[] { "substitute" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(source, handler);
assertTrue(session.nodeExists("/test/target/substitute"));
assertTrue(session.nodeExists("/test/target/substitute/substitute"));
}
@Test
public void testCopyWithPropertyValueSubstitutes() throws Exception {
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./prop", new String[] { "substitute" });
put("./child/prop", new String[] { "substitute" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(source, handler);
assertEquals("substitute", session.getProperty("/test/target/source/prop").getString());
assertEquals("substitute", session.getProperty("/test/target/source/child/prop").getString());
}
@Test
public void testCopyNodeNameAndPropertyValueSubstitutesAlsoMatchesWildcard() throws Exception {
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./_node/_name", new String[] { "substitute" });
put("./_node/prop", new String[] { "substitute" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(source, handler);
assertTrue(session.nodeExists("/test/target/source/substitute"));
assertEquals("substitute", session.getProperty("/test/target/source/substitute/prop").getString());
}
@Test
public void testCopyWithMultiPropertyValueSubstitution() throws Exception {
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./multiprop", new String[] { "substitute1", "substitute2" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(source, handler);
final Value[] values = session.getProperty("/test/target/source/multiprop").getValues();
assertEquals(2, values.length);
assertEquals("substitute1", values[0].getString());
assertEquals("substitute2", values[1].getString());
}
@Test
public void testCopyWithMultiPropertyValueIndexedSubstitution() throws Exception {
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./multiprop[1]", new String[] { "substitute" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(source, handler);
final Value[] values = session.getProperty("/test/target/source/multiprop").getValues();
assertEquals(2, values.length);
assertEquals("substitute", values[1].getString());
}
@Test
public void testNodeIsNotRenamedIfDefinitionDisallowsIt() throws Exception {
Node handle = session.getNode("/test").addNode("handle", "hippo:handle");
handle.addMixin("hippo:translated");
final Node translation = handle.addNode("hippo:translation", "hippo:translation");
translation.setProperty("hippo:language", "test");
translation.setProperty("hippo:message", "test");
handle.addNode("document", "hippo:document");
final Map<String, String[]> substitutes = new HashMap<String, String[]>() {{
put("./_node/_name", new String[] { "substitute" });
}};
ExpandingCopyHandler handler = new ExpandingCopyHandler(target, substitutes, session.getValueFactory());
JcrUtils.copyTo(handle, handler);
// according to the substitution pattern hippo:translation node should have been renamed
// but this doesn't happen because it would violate the constraints on the handle node
assertTrue(session.nodeExists("/test/target/handle/hippo:translation"));
// the document node at the same level does get renamed
assertTrue(session.nodeExists("/test/target/handle/substitute"));
assertEquals("hippo:translation", session.getNode("/test/target/handle/hippo:translation").getPrimaryNodeType().getName());
assertEquals("hippo:document", session.getNode("/test/target/handle/substitute").getPrimaryNodeType().getName());
}
}
|
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.io.File;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* 发送电子邮件
*/
public class SendMailUtil {
// private static final String smtphost = "192.168.1.70";
/*private static final String from = "thinkgem@163.com";
private static final String fromName = "测试公司";
private static final String charSet = "utf-8";
private static final String username = "thinkgem@163.com";
private static final String password = "123456";*/
private static final String from = "mail.hengtiansoft.com";
private static final String fromName = "测试公司";
private static final String charSet = "utf-8";
private static final String username = "yuqiangjia@hengtiansoft.com";
private static final String password = "Spring2016";
private static Map<String, String> hostMap = new HashMap<String, String>();
static {
// 126
hostMap.put("smtp.126", "smtp.126.com");
// qq
hostMap.put("smtp.qq", "smtp.qq.com");
// 163
hostMap.put("smtp.163", "smtp.163.com");
// sina
hostMap.put("smtp.sina", "smtp.sina.com.cn");
// tom
hostMap.put("smtp.tom", "smtp.tom.com");
// 263
hostMap.put("smtp.263", "smtp.263.net");
// yahoo
hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
// hotmail
hostMap.put("smtp.hotmail", "smtp.live.com");
// gmail
hostMap.put("smtp.gmail", "smtp.gmail.com");
hostMap.put("smtp.port.gmail", "465");
}
public static String getHost(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return hostMap.get(key);
} else {
throw new Exception("unSupportEmail");
}
}
public static int getSmtpPort(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp.port." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return Integer.parseInt(hostMap.get(key));
} else {
return 25;
}
}
/**
* 发送模板邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param templatePath
* 模板地址
* @param map
* 模板map
*/
public static void sendFtlMail(String toMailAddr, String subject,
String templatePath, Map<String, Object> map) {
Template template = null;
Configuration freeMarkerConfig = null;
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
freeMarkerConfig = new Configuration();
freeMarkerConfig.setDirectoryForTemplateLoading(new File(
getFilePath()));
// 获取模板
template = freeMarkerConfig.getTemplate(getFileName(templatePath),
new Locale("Zh_cn"), "UTF-8");
// 模板内容转换为string
String htmlText = FreeMarkerTemplateUtils
.processTemplateIntoString(template, map);
System.out.println(htmlText);
hemail.setMsg(htmlText);
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
/**
* 发送普通邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param message
* 发送email信息
*/
public static void sendCommonMail(String toMailAddr, String subject,
String message) {
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
hemail.setMsg(message);
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
public static String getHtmlText(String templatePath,
Map<String, Object> map) {
Template template = null;
String htmlText = "";
try {
Configuration freeMarkerConfig = null;
freeMarkerConfig = new Configuration();
freeMarkerConfig.setDirectoryForTemplateLoading(new File(
getFilePath()));
// 获取模板
template = freeMarkerConfig.getTemplate(getFileName(templatePath),
new Locale("Zh_cn"), "UTF-8");
// 模板内容转换为string
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(
template, map);
System.out.println(htmlText);
} catch (Exception e) {
e.printStackTrace();
}
return htmlText;
}
private static String getFilePath() {
String path = getAppPath(SendMailUtil.class);
path = path + File.separator + "mailtemplate" + File.separator;
path = path.replace("\\", "/");
System.out.println(path);
return path;
}
private static String getFileName(String path) {
path = path.replace("\\", "/");
System.out.println(path);
return path.substring(path.lastIndexOf("/") + 1);
}
// @SuppressWarnings("unchecked")
public static String getAppPath(Class<?> cls) {
// 检查用户传入的参数是否为空
if (cls == null)
throw new java.lang.IllegalArgumentException("参数不能为空!");
ClassLoader loader = cls.getClassLoader();
// 获得类的全名,包括包名
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
// 如果不是匿名包,将包名转化为路径
if (pack != null) {
String packName = pack.getName();
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if (packName.startsWith("java.") || packName.startsWith("javax."))
throw new java.lang.IllegalArgumentException("不要传送系统类!");
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if (packName.indexOf(".") < 0)
path = packName + "/";
else {// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
while (end != -1) {
path = path + packName.substring(start, end) + "/";
start = end + 1;
end = packName.indexOf(".", start);
}
path = path + packName.substring(start) + "/";
}
}
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java.net.URL url = loader.getResource(path + clsName);
// 从URL对象中获取路径信息
String realPath = url.getPath();
// 去掉路径信息中的协议名"file:"
int pos = realPath.indexOf("file:");
if (pos > -1)
realPath = realPath.substring(pos + 5);
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if (realPath.endsWith("!"))
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("realPath----->" + realPath);
return realPath;
}
// private static File getFile(String path){
// File file =
// SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
// return file;
// }
//
public static void main(String[] args) {
// HtmlEmail hemail = new HtmlEmail();
// try {
// hemail.setHostName("smtp.exmail.qq.com");
// hemail.setCharset("utf-8");
// hemail.addTo("fly.1206@qq.com");
// hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
// hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
// hemail.setSubject("sendemail test!");
// hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
// hemail.send();
// System.out.println("email send true!");
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("email send error!");
// }
Map<String, Object> map = new HashMap<String, Object>();
map.put("subject", "测试标题");
map.put("content", "测试 内容");
String templatePath = "mailtemplate/test.ftl";
sendFtlMail("test@163.com", "sendemail test!", templatePath, map);
// System.out.println(getFileName("mailtemplate/test.ftl"));
}
}
|
package io.cattle.platform.core.constants;
public class LoadBalancerConstants {
public static final String FIELD_LB_CERTIFICATE_IDS = "certificateIds";
public static final String FIELD_LB_DEFAULT_CERTIFICATE_ID = "defaultCertificateId";
}
|
package com.llf.springboot.util;
import java.util.List;
public class PagedResult {
private int page; // 当前页数
private int total; // 总页数
private long records; // 总记录数
private List<?> rows; // 每行显示的内容
public PagedResult(){
}
public PagedResult(int page,int total){
this.page=page;
this.total=total;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public long getRecords() {
return records;
}
public void setRecords(long records) {
this.records = records;
}
public List<?> getRows() {
return rows;
}
public void setRows(List<?> rows) {
this.rows = rows;
}
}
|
// Copyright (c) Team 564.
// Open Source Software; you can modify and/or share it under the terms of
// the BSD license file in the root directory of this project.
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
import java.util.List;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.geometry.Pose2d;
import edu.wpi.first.wpilibj.geometry.Rotation2d;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.CommandGroupBase;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.RunCommand;
import io.github.oblarg.oblog.annotations.Log;
import frc.robot.Constants.DriverStation;
import frc.robot.Constants.DrivetrainConstants;
import frc.robot.Constants.IntakeConstants;
import frc.robot.Constants.ShooterConstants;
import frc.robot.commands.AutoInitCommand;
import frc.robot.commands.DisabledInitCommand;
import frc.robot.commands.DriveTrajectoryCommand;
import frc.robot.commands.TeleopInitCommand;
import frc.robot.driverinput.F310Controller;
import frc.robot.subsystems.DrivetrainSubsystem;
import frc.robot.subsystems.IntakeSubsystem;
import frc.robot.subsystems.ShooterSubsystem;
import frc.robot.subsystems.VisionSubsystem;
/** Contains all of the robot's subsystems, commands, and button mappings. */
public class RobotContainer {
// Subsystems
@Log private final DrivetrainSubsystem m_drivetrainSubsystem = new DrivetrainSubsystem();
@Log private final IntakeSubsystem m_intakeSubsystem = new IntakeSubsystem();
@Log private final ShooterSubsystem m_shooterSubsystem = new ShooterSubsystem();
@Log private final VisionSubsystem m_visionSubsystem = new VisionSubsystem();
// Commands
private final DisabledInitCommand m_disabledInitCommand =
new DisabledInitCommand(m_drivetrainSubsystem);
private final AutoInitCommand m_autoInitCommand =
new AutoInitCommand(m_drivetrainSubsystem, m_shooterSubsystem);
private final TeleopInitCommand m_teleopInitCommand =
new TeleopInitCommand(m_drivetrainSubsystem, m_shooterSubsystem);
// Resets the robot position and rotation. Note that running this will interrupt any interruptible
// commands that are using the drivetrain subsystem.
@Log
private final Command m_resetOdometryCommand =
new InstantCommand(m_drivetrainSubsystem::resetOdometry, m_drivetrainSubsystem)
.withName("Reset Odometry");
// Follows the example trajectory from the FRC Docs Trajectory Tutorial.
private final DriveTrajectoryCommand m_exampleAutoCommand =
new DriveTrajectoryCommand(
m_drivetrainSubsystem,
// Start at the origin facing the +X direction
new Pose2d(0, 0, new Rotation2d(0)),
// Pass through these two interior waypoints, making an 's' curve path
List.of(new Translation2d(1, 1), new Translation2d(2, -1)),
// End 3 meters straight ahead of where we started, facing forward
new Pose2d(3, 0, new Rotation2d(0)));
// Driver Input
private final F310Controller m_controllerDrive =
new F310Controller(DriverStation.kPortControllerDrive);
private final F310Controller m_controllerManip =
new F310Controller(DriverStation.kPortControllerManip);
// Autonmous Chooser
@Log(
name = "Autonomous Chooser",
width = 2,
height = 1,
rowIndex = 0,
columnIndex = 10,
tabName = "Driver View")
private final SendableChooser<Command> m_autoChooser = new SendableChooser<>();
// Initializes the default commands and command bindings.
public RobotContainer() {
// Configure the automous chooser.
m_autoChooser.setDefaultOption("Example Autonomous Trajectory", m_exampleAutoCommand);
// Configure default commands.
m_drivetrainSubsystem.setDefaultCommand(
new RunCommand(
() ->
m_drivetrainSubsystem.arcadeDrive(
m_controllerDrive.getY(GenericHID.Hand.kLeft),
m_controllerDrive.getX(GenericHID.Hand.kRight)),
m_drivetrainSubsystem)
.withName("Arcade Drive"));
// Configure button to command bindings.
configureButtonBindings();
}
/** Configures button to command bindings. */
private void configureButtonBindings() {
// Configure drive speed multipliers controls.
Command resetDriveSpeedCommand =
new InstantCommand(
() -> m_drivetrainSubsystem.setDriveSpeed(DrivetrainConstants.kSpeedNormal),
m_drivetrainSubsystem);
m_controllerDrive
.axisLt
.whenPressed(
() -> m_drivetrainSubsystem.setDriveSpeed(DrivetrainConstants.kSpeedSlow),
m_drivetrainSubsystem)
.whenReleased(resetDriveSpeedCommand);
m_controllerDrive
.axisRt
.whenPressed(
() -> m_drivetrainSubsystem.setDriveSpeed(DrivetrainConstants.kSpeedFast),
m_drivetrainSubsystem)
.whenReleased(resetDriveSpeedCommand);
// Configure ball intake controls.
m_controllerManip
.axisLeftY
.whenPressed(
() ->
m_intakeSubsystem.startBelt(
Math.signum(m_controllerManip.getY(GenericHID.Hand.kLeft))
* IntakeConstants.kSpeedBelt),
m_intakeSubsystem)
.whenReleased(m_intakeSubsystem::stopBelt, m_intakeSubsystem);
m_controllerManip
.axisRightY
.whenPressed(
() ->
m_intakeSubsystem.startIntake(
Math.signum(m_controllerManip.getY(GenericHID.Hand.kRight))
* IntakeConstants.kSpeedIntake),
m_intakeSubsystem)
.whenReleased(m_intakeSubsystem::stopIntake, m_intakeSubsystem);
// Configure ball shooting controls.
m_controllerManip.buttonLs.whenPressed(m_shooterSubsystem::toggleSolenoid, m_shooterSubsystem);
m_controllerManip
.axisLt
.whenPressed(
() -> m_shooterSubsystem.startShooting(ShooterConstants.kSpeedSlow), m_shooterSubsystem)
.whenReleased(m_shooterSubsystem::stopShooting, m_shooterSubsystem);
m_controllerManip
.axisRt
.whenPressed(
() -> m_shooterSubsystem.startShooting(ShooterConstants.kSpeedNormal),
m_shooterSubsystem)
.whenReleased(m_shooterSubsystem::stopShooting, m_shooterSubsystem);
}
/**
* Passes the disabled init command to the Robot class.
*
* @return The command to run.
*/
public Command getDisabledInitCommand() {
return m_disabledInitCommand;
}
/**
* Passes the autonomous init command to the Robot class.
*
* @return The command to run.
*/
public Command getAutoInitCommand() {
// Get the current autonomous command. This may be obtained from a SendableChooser.
Command autoCommand = m_autoChooser.getSelected();
// WPILibJ keeps track of every command that gets added to a group, adding them to a blacklist.
// If you try scheduling, or creating another group with a blacklisted command, an exception is
// thrown. Since we know that, in Robot.java, there won't be more than one init method running
// at once, we can safely assume that this won't result in any weirdness with different
// instances of these getting interleaved.
CommandGroupBase.clearGroupedCommand(m_autoInitCommand);
CommandGroupBase.clearGroupedCommand(autoCommand);
return m_autoInitCommand.andThen(autoCommand);
}
/**
* Passes the teleop init command to the Robot class.
*
* @return The command to run.
*/
public Command getTeleopInitCommand() {
return m_teleopInitCommand;
}
}
|
/*
* 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;
/**
* A RuntimeException being thrown whenever an operation on a bucket that
* has been closed is attempted.
*
* @author Simon Baslé
* @since 1.0.1
*/
public class BucketClosedException extends CouchbaseException {
public BucketClosedException() {
super();
}
public BucketClosedException(String message) {
super(message);
}
public BucketClosedException(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.xjm.dao;
import com.xjm.dto.MetaDto;
import com.xjm.dto.cond.MetaCond;
import com.xjm.model.MetaDomain;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* 项目dao
* Created by JianMin-xie on 2019/4/29.
*/
@Mapper
@Component
public interface MetaDao {
/**
* 添加项目
* @param meta
* @return
*/
int addMeta(MetaDomain meta);
/**
* 删除项目
* @param mid
* @return
*/
int deleteMetaById(@Param("mid") Integer mid);
/**
* 更新项目
* @param meta
* @return
*/
int updateMeta(MetaDomain meta);
/**
* 根据编号获取项目
* @param mid
* @return
*/
MetaDomain getMetaById(@Param("mid") Integer mid);
/**
* 根据条件查询
* @param metaCond
* @return
*/
List<MetaDomain> getMetasByCond(MetaCond metaCond);
/**
* 根据类型获取meta数量
* @param type
* @return
*/
Long getMetasCountByType(@Param("type") String type);
/**
* 根据sql查询
* @param paraMap
* @return
*/
List<MetaDto> selectFromSql(Map<String, Object> paraMap);
}
|
package me.ningsk.filterlibrary.glfilter.effect;
import android.content.Context;
import android.opengl.GLES20;
import me.ningsk.filterlibrary.glfilter.base.GLImageFilter;
import me.ningsk.filterlibrary.glfilter.utils.OpenGLUtils;
/**
* 缩放滤镜
*/
public class GLImageEffectScaleFilter extends GLImageFilter {
private static final String FRAGMENT_SHADER = ""
+ "precision mediump float;\n" +
"varying vec2 textureCoordinate;\n" +
"uniform sampler2D inputTexture;\n" +
"\n" +
"uniform float scale;\n" +
"\n" +
"void main() {\n" +
" vec2 uv = textureCoordinate.xy;\n" +
" // 将纹理坐标中心转成(0.0, 0.0)再做缩放\n" +
" vec2 center = vec2(0.5, 0.5);\n" +
" uv -= center;\n" +
" uv = uv / scale;\n" +
" uv += center;\n" +
" \n" +
" gl_FragColor = texture2D(inputTexture, uv);\n" +
"}";
private int mScaleHandle;
private boolean plus = true;
private float mScale = 1.0f;
private float mOffset = 0.0f;
public GLImageEffectScaleFilter(Context context) {
this(context, VERTEX_SHADER, FRAGMENT_SHADER);
}
public GLImageEffectScaleFilter(Context context, String vertexShader, String fragmentShader) {
super(context, vertexShader, fragmentShader);
}
@Override
public void initProgramHandle() {
super.initProgramHandle();
if (mProgramHandle != OpenGLUtils.GL_NOT_INIT) {
mScaleHandle = GLES20.glGetUniformLocation(mProgramHandle, "scale");
}
}
@Override
public void onDrawFrameBegin() {
super.onDrawFrameBegin();
mOffset += plus ? +0.06f : -0.06f;
if (mOffset >= 1.0f) {
plus = false;
} else if (mOffset <= 0.0f) {
plus = true;
}
mScale = 1.0f + 0.5f * getInterpolation(mOffset);
GLES20.glUniform1f(mScaleHandle, mScale);
}
private float getInterpolation(float input) {
return (float)(Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}
}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.security.privateca.v1beta1;
import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/** AUTO-GENERATED DOCUMENTATION AND CLASS */
@javax.annotation.Generated("by GAPIC protoc plugin")
public class LocationName implements ResourceName {
private static final PathTemplate PATH_TEMPLATE =
PathTemplate.createWithoutUrlEncoding("projects/{project}/locations/{location}");
private volatile Map<String, String> fieldValuesMap;
private final String project;
private final String location;
public String getProject() {
return project;
}
public String getLocation() {
return location;
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder(this);
}
private LocationName(Builder builder) {
project = Preconditions.checkNotNull(builder.getProject());
location = Preconditions.checkNotNull(builder.getLocation());
}
public static LocationName of(String project, String location) {
return newBuilder().setProject(project).setLocation(location).build();
}
public static String format(String project, String location) {
return newBuilder().setProject(project).setLocation(location).build().toString();
}
public static LocationName parse(String formattedString) {
if (formattedString.isEmpty()) {
return null;
}
Map<String, String> matchMap =
PATH_TEMPLATE.validatedMatch(
formattedString, "LocationName.parse: formattedString not in valid format");
return of(matchMap.get("project"), matchMap.get("location"));
}
public static List<LocationName> parseList(List<String> formattedStrings) {
List<LocationName> list = new ArrayList<>(formattedStrings.size());
for (String formattedString : formattedStrings) {
list.add(parse(formattedString));
}
return list;
}
public static List<String> toStringList(List<LocationName> values) {
List<String> list = new ArrayList<String>(values.size());
for (LocationName value : values) {
if (value == null) {
list.add("");
} else {
list.add(value.toString());
}
}
return list;
}
public static boolean isParsableFrom(String formattedString) {
return PATH_TEMPLATE.matches(formattedString);
}
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
fieldMapBuilder.put("project", project);
fieldMapBuilder.put("location", location);
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public String getFieldValue(String fieldName) {
return getFieldValuesMap().get(fieldName);
}
@Override
public String toString() {
return PATH_TEMPLATE.instantiate("project", project, "location", location);
}
/** Builder for LocationName. */
public static class Builder {
private String project;
private String location;
public String getProject() {
return project;
}
public String getLocation() {
return location;
}
public Builder setProject(String project) {
this.project = project;
return this;
}
public Builder setLocation(String location) {
this.location = location;
return this;
}
private Builder() {}
private Builder(LocationName locationName) {
project = locationName.project;
location = locationName.location;
}
public LocationName build() {
return new LocationName(this);
}
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof LocationName) {
LocationName that = (LocationName) o;
return (this.project.equals(that.project)) && (this.location.equals(that.location));
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= project.hashCode();
h *= 1000003;
h ^= location.hashCode();
return h;
}
}
|
/*
* MAL/SPP Binding for CCSDS Mission Operations Framework
* Copyright (C) 2015 Deutsches Zentrum für Luft- und Raumfahrt e.V. (DLR).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package de.dlr.gsoc.mo.malspp.transport;
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.ccsds.moims.mo.mal.MALException;
import org.ccsds.moims.mo.testbed.util.spp.SpacePacket;
import org.ccsds.moims.mo.testbed.util.spp.SpacePacketHeader;
public class SPPSegmenter implements Iterator {
private static final String TOO_SMALL = "SPACE_PACKET_SIZE_LIMIT too small to accomodate secondary header and at least one octet of user data.";
private static final int COUNTER_LENGTH = 4; // Number of bytes for the 'Segment Counter'.
// Position of all the flag bits in the secondary header; if present 'Source'
// and 'Destination
// Identifier' follow immediately, then 'Segment Counter':
private static final int FLAG_IDX = 20;
private final Queue<SpacePacket[]> readyMessages = new LinkedList<>();
private final SortedMap<Long, SpacePacket> packetStore = new TreeMap<>();
private final SortedSet<Long> startPacketCounters = new TreeSet<>();
private final SortedSet<Long> endPacketCounters = new TreeSet<>();
private Long unsegmentedPacketCounter;
private final SortedMap<Long, Long> timeouts = new TreeMap<>();
private final long timeout;
public SPPSegmenter(final long timeout) {
this.timeout = timeout;
}
/**
* Gets the value of the 'Segment Counter' field in the Space Packet's secondary
* header.
*
* No error checking is performed. If the Space Packet is malformed due to a
* body that is too short an IndexOutOfBoundsException is thrown. If this method
* is called on a Space Packet not containing a segment counter (because it is
* unsegmented) the behavior is undefined.
*
* @param spacePacket Space Packet that contains a 'Segment Counter' field.
* @return Value of the 'Segment Counter' field.
*/
private static long getSegmentCounter(final SpacePacket spacePacket) {
final byte[] body = spacePacket.getBody();
final byte flags = body[FLAG_IDX];
final int counter_pos = FLAG_IDX + 1 + ((flags & 0b10000000) >>> 7) + ((flags & 0b01000000) >>> 6);
long counter = 0;
for (int i = 0; i < COUNTER_LENGTH; i++) {
counter <<= 8;
counter |= body[counter_pos + i] & 0xFF;
}
return counter;
}
private SpacePacket[] getCompleteSequence() {
// Check if an unsegmented packet has been received or if both start and end
// packet are
// present and the correct number of packets in-between has been received.
// Returns all
// packets belonging to a complete sequence, null otherwise.
if (null != unsegmentedPacketCounter) {
final SpacePacket[] ret = new SpacePacket[] { packetStore.remove(unsegmentedPacketCounter) };
unsegmentedPacketCounter = null;
return ret;
}
if (startPacketCounters.isEmpty() || endPacketCounters.isEmpty()) {
return null;
}
final long startCounter = startPacketCounters.first();
final long endCounter = endPacketCounters.first();
final long counterDiff = endCounter - startCounter;
if (counterDiff < 0) {
return null;
}
final SortedMap<Long, SpacePacket> subMap = packetStore.subMap(startCounter, endCounter + 1);
if (subMap.size() == counterDiff + 1) {
startPacketCounters.remove(startCounter);
endPacketCounters.remove(endCounter);
final SpacePacket[] ret = subMap.values().toArray(new SpacePacket[1]);
subMap.clear(); // writes through to packetStore
return ret;
}
return null;
}
private void storePacket(final SpacePacket spacePacket) {
long counter = -1;
final int seq = spacePacket.getHeader().getSequenceFlags();
if (seq != 0b11) { // packet is segmented and has a counter
counter = getSegmentCounter(spacePacket);
}
packetStore.put(counter, spacePacket);
timeouts.put(System.currentTimeMillis(), counter);
switch (seq) {
case 0b11:
unsegmentedPacketCounter = counter;
break;
case 0b01:
startPacketCounters.add(counter);
break;
case 0b10:
endPacketCounters.add(counter);
break;
}
}
private void deleteTimedOutPackets() {
final long now = System.currentTimeMillis();
final SortedMap<Long, Long> timedOut = timeouts.headMap(now - timeout);
final Collection<Long> timedOutCounters = timedOut.values();
for (final long counter : timedOutCounters) {
packetStore.remove(counter);
startPacketCounters.remove(counter);
endPacketCounters.remove(counter);
}
timedOut.clear(); // writes through to timeouts
}
public void process(final SpacePacket spacePacket) {
// TODO: Timeout can be made nicer. Here checking for timed out packets only
// happens
// when a new packet is processed, which can leave the last packet in memory
// although it
// might have timed out.
if (timeout != 0) {
deleteTimedOutPackets();
}
storePacket(spacePacket);
final SpacePacket[] ready = getCompleteSequence();
if (null != ready) {
readyMessages.add(ready);
}
}
/**
* If necessary, split the data in body across several Space Packets. The Space
* Packets primary header that is passed into the method is used as template,
* necessary fields (sequenceCounter and sequenceFlags) are overwritten, using
* the passed in sequenceCounter as starting number.
*
* @param packetDataFieldSizeLimit
* @param primaryHeader
* @param primaryApidQualifier
* @param secondaryHeaderPart1
* @param secondaryHeaderPart2
* @param body
* @param sequenceCounter
* @param segmentCounter
* @return
* @throws org.ccsds.moims.mo.mal.MALException
*/
public static SpacePacket[] split(final int packetDataFieldSizeLimit, final int primaryApidQualifier,
final SpacePacketHeader primaryHeader, final byte[] secondaryHeaderPart1, final byte[] secondaryHeaderPart2,
final byte[] body, final SPPCounter sequenceCounter, final SPPCounter segmentCounter) throws MALException {
final Queue<SpacePacket> spacePackets = new LinkedList<>();
final int sndHdrLength = secondaryHeaderPart1.length + secondaryHeaderPart2.length;
final int userDataFieldSizeLimit;
if (!(sndHdrLength < packetDataFieldSizeLimit)) {
// Strictly speaking all the other cases are sufficient for determining packet
// splitting
// and error cases. The case that the secondary header fills out the complete
// packet
// without leaving a single byte left for the message body is fine for messages
// without
// body. However, the standard (4.4.10) requires an error to be generated in
// this case.
throw new MALException(TOO_SMALL);
} else if (sndHdrLength + body.length <= packetDataFieldSizeLimit) {
// Message fits in one packet, no segment counter needed.
userDataFieldSizeLimit = packetDataFieldSizeLimit - sndHdrLength;
} else if (sndHdrLength + COUNTER_LENGTH >= packetDataFieldSizeLimit) {
// Message does not fit in one packet, but counter in secondary header (size: 4
// bytes)
// makes secondary header too large, such that no user data can be fit into a
// packet.
throw new MALException(TOO_SMALL);
} else {
// Message does not fit in one packet, but secondary header including the
// segment
// counter is small enough such that user data can be fit into the packets.
userDataFieldSizeLimit = packetDataFieldSizeLimit - sndHdrLength - COUNTER_LENGTH;
}
int remaining = body.length;
final int numberOfPackets = java.lang.Math.max((remaining - 1) / userDataFieldSizeLimit + 1, 1);
final Iterator<Long> sequenceCounterIter = sequenceCounter.increment(numberOfPackets);
final Iterator<Long> segmentCounterIter = (numberOfPackets > 1) ? segmentCounter.increment(numberOfPackets)
: null;
int offset = 0;
final ByteArrayOutputStream os = new ByteArrayOutputStream();
do {
// combine secondary header and MAL message body to space packet body
os.write(secondaryHeaderPart1, 0, secondaryHeaderPart1.length);
// only write segment counter if message does not fit in a single packet
if (numberOfPackets > 1) {
final long c = segmentCounterIter.next(); // segmentCounterIter cannot be null here
for (int i = COUNTER_LENGTH - 1; i >= 0; i--) {
os.write((byte) (c >>> (i * 8)));
}
}
os.write(secondaryHeaderPart2, 0, secondaryHeaderPart2.length);
final int segmentLength = java.lang.Math.min(userDataFieldSizeLimit, remaining);
os.write(body, offset, segmentLength);
remaining -= segmentLength;
// find out correct sequence flags according to offset and remaining bytes
int sequenceFlags = 0b00; // continuation segment
if (offset == 0 && remaining == 0) {
sequenceFlags = 0b11; // unsegmented
} else if (offset == 0) {
sequenceFlags = 0b01; // first segment
} else if (remaining == 0) {
sequenceFlags = 0b10; // last segment
}
offset += segmentLength;
// clone template primary header and change relevant values
final SpacePacketHeader spHeader = new SpacePacketHeader(primaryHeader.getPacketVersionNumber(),
primaryHeader.getPacketType(), primaryHeader.getSecondaryHeaderFlag(), primaryHeader.getApid(),
sequenceFlags, sequenceCounterIter.next().shortValue());
// create space packet
final SpacePacket spacePacket = new SpacePacket(spHeader, primaryApidQualifier, os.toByteArray(), 0, os.size());
spacePackets.add(spacePacket);
os.reset();
} while (remaining > 0);
return spacePackets.toArray(new SpacePacket[1]);
}
@Override
public boolean hasNext() {
return !readyMessages.isEmpty();
}
@Override
public SpacePacket[] next() {
return readyMessages.remove();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
|
/*
* Copyright 2015-2020 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.macie2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Provides information about the total storage size (in bytes) or number of objects that Amazon Macie can't analyze in
* one or more S3 buckets. In a BucketMetadata object, this data is for a specific bucket. In a
* GetBucketStatisticsResponse object, this data is aggregated for all the buckets in the query results.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/macie2-2020-01-01/ObjectLevelStatistics" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ObjectLevelStatistics implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects don't
* have a file name extension for a supported file or storage format.
* </p>
*/
private Long fileType;
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class.
* </p>
*/
private Long storageClass;
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*/
private Long total;
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects don't
* have a file name extension for a supported file or storage format.
* </p>
*
* @param fileType
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* don't have a file name extension for a supported file or storage format.
*/
public void setFileType(Long fileType) {
this.fileType = fileType;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects don't
* have a file name extension for a supported file or storage format.
* </p>
*
* @return The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the
* objects don't have a file name extension for a supported file or storage format.
*/
public Long getFileType() {
return this.fileType;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects don't
* have a file name extension for a supported file or storage format.
* </p>
*
* @param fileType
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* don't have a file name extension for a supported file or storage format.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ObjectLevelStatistics withFileType(Long fileType) {
setFileType(fileType);
return this;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class.
* </p>
*
* @param storageClass
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* use an unsupported storage class.
*/
public void setStorageClass(Long storageClass) {
this.storageClass = storageClass;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class.
* </p>
*
* @return The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the
* objects use an unsupported storage class.
*/
public Long getStorageClass() {
return this.storageClass;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class.
* </p>
*
* @param storageClass
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* use an unsupported storage class.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ObjectLevelStatistics withStorageClass(Long storageClass) {
setStorageClass(storageClass);
return this;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param total
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* use an unsupported storage class or don't have a file name extension for a supported file or storage
* format.
*/
public void setTotal(Long total) {
this.total = total;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @return The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the
* objects use an unsupported storage class or don't have a file name extension for a supported file or
* storage format.
*/
public Long getTotal() {
return this.total;
}
/**
* <p>
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects use an
* unsupported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param total
* The total storage size (in bytes) or number of objects that Amazon Macie can't analyze because the objects
* use an unsupported storage class or don't have a file name extension for a supported file or storage
* format.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ObjectLevelStatistics withTotal(Long total) {
setTotal(total);
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 (getFileType() != null)
sb.append("FileType: ").append(getFileType()).append(",");
if (getStorageClass() != null)
sb.append("StorageClass: ").append(getStorageClass()).append(",");
if (getTotal() != null)
sb.append("Total: ").append(getTotal());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ObjectLevelStatistics == false)
return false;
ObjectLevelStatistics other = (ObjectLevelStatistics) obj;
if (other.getFileType() == null ^ this.getFileType() == null)
return false;
if (other.getFileType() != null && other.getFileType().equals(this.getFileType()) == false)
return false;
if (other.getStorageClass() == null ^ this.getStorageClass() == null)
return false;
if (other.getStorageClass() != null && other.getStorageClass().equals(this.getStorageClass()) == false)
return false;
if (other.getTotal() == null ^ this.getTotal() == null)
return false;
if (other.getTotal() != null && other.getTotal().equals(this.getTotal()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getFileType() == null) ? 0 : getFileType().hashCode());
hashCode = prime * hashCode + ((getStorageClass() == null) ? 0 : getStorageClass().hashCode());
hashCode = prime * hashCode + ((getTotal() == null) ? 0 : getTotal().hashCode());
return hashCode;
}
@Override
public ObjectLevelStatistics clone() {
try {
return (ObjectLevelStatistics) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.macie2.model.transform.ObjectLevelStatisticsMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.bean.builtin;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.spi.InjectionPoint;
import org.jboss.weld.injection.ForwardingInjectionPoint;
/**
* {@link InjectionPoint} that represents an injected {@link Event} or {@link Instance} object.
*
* @see CDI 1.1 5.5.7
*
* @author Jozef Hartinger
*
*/
public class DynamicLookupInjectionPoint extends ForwardingInjectionPoint implements Serializable {
private static final long serialVersionUID = -4102173765226078459L;
private final InjectionPoint injectionPoint;
private final Type type;
private final Set<Annotation> qualifiers;
public DynamicLookupInjectionPoint(InjectionPoint injectionPoint, Type type, Set<Annotation> qualifiers) {
this.injectionPoint = injectionPoint;
this.type = type;
this.qualifiers = qualifiers;
}
@Override
protected InjectionPoint delegate() {
return injectionPoint;
}
@Override
public Type getType() {
return type;
}
@Override
public Set<Annotation> getQualifiers() {
return qualifiers;
}
}
|
package ax.stardust.skvirrel.monitoring;
import android.content.Context;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
import java.util.stream.Collectors;
import ax.stardust.skvirrel.R;
import ax.stardust.skvirrel.stock.parcelable.ParcelableStock;
import ax.stardust.skvirrel.util.SkvirrelUtils;
/**
* Abstract class holding fundamental data/functionality shared by all different monitorings.
*/
public abstract class AbstractMonitoring {
/**
* The different monitoring types and their corresponding string resource id's.
*/
public enum MonitoringType {
PRICE(R.string.price),
RSI(R.string.rsi);
private final int stringResourceId;
MonitoringType(int stringResourceId) {
this.stringResourceId = stringResourceId;
}
/**
* To get the translated name of this monitoring type
*
* @param context context from which text is resolved from
* @return translated name
*/
public String getTranslatedName(Context context) {
return context.getString(stringResourceId);
}
}
// handle to owner of this monitoring
protected transient StockMonitoring stockMonitoring;
// type of monitoring
protected MonitoringType monitoringType;
// comparator of monitoring
protected Criteria.Comparator comparator = Criteria.Comparator.BELOW;
// flag indicating whether or not this monitoring has been notified
protected boolean notified;
/**
* Creates a new instance of monitoring
*
* @param stockMonitoring stock monitoring which holds this monitoring
*/
protected AbstractMonitoring(StockMonitoring stockMonitoring) {
this.stockMonitoring = stockMonitoring;
}
public void setStockMonitoring(StockMonitoring stockMonitoring) {
this.stockMonitoring = stockMonitoring;
}
public StockMonitoring getStockMonitoring() {
return stockMonitoring;
}
public MonitoringType getMonitoringType() {
return monitoringType;
}
public Criteria.Comparator getComparator() {
return comparator;
}
public void setComparator(Criteria.Comparator comparator) {
this.comparator = comparator;
}
public boolean isNotified() {
return notified;
}
/**
* To mark this monitoring as notified
* Note. no spelling mistake :)
*/
public void notifyy() {
notified = true;
}
/**
* To reset notified state of monitoring
*/
public void resetNotified() {
notified = false;
}
/**
* To get a string of translated monitoring names for given monitorings. If for example a
* list of monitorings Price, RSI and SMA are given and the language of context is english than a
* string like this is returned: price, RSI and SMA
*
* @param context context for which texts are retrieved
* @param monitorings monitorings to get their names translated and joined
* @return string of joined and translated monitoring names
*/
public static String getJoinedTranslatedMonitoringNames(Context context, List<AbstractMonitoring> monitorings) {
List<String> translatedMonitoringNames = monitorings.stream()
.map(monitoring -> {
MonitoringType monitoringType = monitoring.getMonitoringType();
String translatedName = monitoringType.getTranslatedName(context);
if (MonitoringType.PRICE.equals(monitoringType)) {
return StringUtils.toRootLowerCase(translatedName);
}
return translatedName;
})
.collect(Collectors.toList());
return SkvirrelUtils.join(context, translatedMonitoringNames);
}
/**
* Indicating whether or not this monitoring should be monitored. Criteria is: this monitoring must
* be valid and not already notified
*
* @return true if this monitoring should be monitored else false
*/
public boolean shouldBeMonitored() {
return isValid() && !isNotified();
}
/**
* To set monitoring value, provided string must be numeric
*
* @param numericString numeric string to be transformed to a real numeric value by the implementor
*/
public abstract void setValue(String numericString);
/**
* To get monitoring value as string
*
* @return monitoring value as string
*/
public abstract String getValue();
/**
* To reset value of monitoring, typical use case is when user give empty input
*/
public abstract void resetValue();
/**
* Indicating whether or not this monitoring actually is valid to be used for monitoring
*
* @return true if this monitoring is ready to be used else false
*/
public abstract boolean isValid();
/**
* To check monitoring criteria against data within given parcelable stock, if true is returned
* it means that we got a hit for this monitoring and it should be handled for notification
*
* @param parcelableStock parcelable stock which data is about to be checked against criteria within the monitoring
* @return true if criteria within monitoring are met else false
*/
public abstract boolean checkMonitoringCriteria(ParcelableStock parcelableStock);
}
|
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* 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.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2004-2005 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.internal.runtime.methods;
import org.jruby.RubyModule;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author jpetersen
*/
public class AliasMethod extends DynamicMethod {
private DynamicMethod oldMethod;
public AliasMethod(RubyModule implementationClass, DynamicMethod oldMethod, String oldName) {
super(implementationClass, oldMethod.getVisibility(), oldName);
this.oldMethod = oldMethod;
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused) {
return oldMethod.call(context, self, klazz, name);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg) {
return oldMethod.call(context, self, klazz, name, arg);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg1, IRubyObject arg2) {
return oldMethod.call(context, self, klazz, name, arg1, arg2);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3) {
return oldMethod.call(context, self, klazz, name, arg1, arg2, arg3);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject[] args) {
return oldMethod.call(context, self, klazz, name, args);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, Block block) {
return oldMethod.call(context, self, klazz, name, block);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg1, Block block) {
return oldMethod.call(context, self, klazz, name, arg1, block);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg1, IRubyObject arg2, Block block) {
return oldMethod.call(context, self, klazz, name, arg1, arg2, block);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block) {
return oldMethod.call(context, self, klazz, name, arg1, arg2, arg3, block);
}
@Override
public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule klazz, String unused, IRubyObject[] args, Block block) {
return oldMethod.call(context, self, klazz, name, args, block);
}
public DynamicMethod dup() {
return new AliasMethod(implementationClass, oldMethod, name);
}
@Override
public Arity getArity(){
return oldMethod.getArity();
}
public String getOldName() {
return name;
}
@Override
public DynamicMethod getRealMethod() {
return oldMethod.getRealMethod();
}
@Override
public long getSerialNumber() {
return oldMethod.getSerialNumber();
}
}
|
package i5.las2peer.services.test;
import java.net.HttpURLConnection;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.MediaType;
import i5.las2peer.api.Context;
import i5.las2peer.api.ManualDeployment;
import i5.las2peer.api.ServiceException;
import i5.las2peer.api.logging.MonitoringEvent;
import i5.las2peer.restMapper.RESTService;
import i5.las2peer.restMapper.annotations.ServicePath;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Contact;
import io.swagger.annotations.Info;
import io.swagger.annotations.License;
import io.swagger.annotations.SwaggerDefinition;
import org.json.simple.*;
import java.util.HashMap;
import java.util.Map;
/**
*
* test-microservice101
*
* This microservice was generated by the CAE (Community Application Editor). If you edit it, please
* make sure to keep the general structure of the file and only add the body of the methods provided
* in this main file. Private methods are also allowed, but any "deeper" functionality should be
* outsourced to (imported) classes.
*
*/
@ServicePath("test")
@ManualDeployment
public class test extends RESTService {
public test() {
super();
// read and set properties values
setFieldValues();
}
@Override
public void initResources() {
getResourceConfig().register(RootResource.class);
}
// //////////////////////////////////////////////////////////////////////////////////////
// REST methods
// //////////////////////////////////////////////////////////////////////////////////////
@Api
@SwaggerDefinition(
info = @Info(title = "test-microservice101", version = "$Metadata_Version$",
description = "$Metadata_Description$",
termsOfService = "$Metadata_Terms$",
contact = @Contact(name = "test", email = "CAEAddress@gmail.com") ,
license = @License(name = "BSD",
url = "https://github.com/CAE-Community-Application-Editor/microservice-test-microservice101/blob/master/LICENSE.txt") ) )
@Path("/")
public static class RootResource {
private final test service = (test) Context.getCurrent().getService();
/**
*
* testMethod
*
*
*
*
* @return Response
*
*/
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "testResponse")
})
@ApiOperation(value = "testMethod", notes = " ")
public Response testMethod() {
// service method invocations
// testResponse
boolean testResponse_condition = true;
if(testResponse_condition) {
JSONObject testResult = new JSONObject();
testResult.put("testKey", "testValue");
return Response.status(HttpURLConnection.HTTP_OK).entity(testResult.toJSONString()).build();
}
return null;
}
}
// //////////////////////////////////////////////////////////////////////////////////////
// Service methods (for inter service calls)
// //////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////
// Custom monitoring message descriptions (can be called via RMI)
// //////////////////////////////////////////////////////////////////////////////////////
public Map<String, String> getCustomMessageDescriptions() {
Map<String, String> descriptions = new HashMap<>();
return descriptions;
}
}
|
package thaumicenergistics.client.gui.buttons;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import thaumicenergistics.client.textures.AEStateIconsEnum;
import thaumicenergistics.common.container.ContainerKnowledgeInscriber.CoreSaveState;
import thaumicenergistics.common.registries.ThEStrings;
/**
* Displays save state icons.
*
* @author Nividica
*
*/
@SideOnly(Side.CLIENT)
public class GuiButtonSaveDelete
extends ThEStateButton
{
private String cachedTooltip;
public GuiButtonSaveDelete( final int ID, final int xPosition, final int yPosition, final CoreSaveState initialState )
{
// Call super
super( ID, xPosition, yPosition, 16, 16, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON );
// Initial state
this.setSaveState( initialState );
}
@Override
public void getTooltip( final List<String> tooltip )
{
tooltip.add( this.cachedTooltip );
}
/**
* Sets the save state of the button.
*
* @param saveState
*/
public void setSaveState( final CoreSaveState saveState )
{
switch ( saveState )
{
case Disabled_InvalidRecipe:
this.enabled = false;
this.stateIcon = null;
this.cachedTooltip = ThEStrings.TooltipButton_InscriberInvalid.getLocalized();
break;
case Disabled_CoreFull:
this.enabled = false;
this.stateIcon = null;
this.cachedTooltip = ThEStrings.TooltipButton_InscriberFull.getLocalized();
break;
case Enabled_Delete:
this.enabled = true;
this.stateIcon = AEStateIconsEnum.DELETE;
this.cachedTooltip = ThEStrings.TooltipButton_InscriberDelete.getLocalized();
break;
case Enabled_Save:
this.enabled = true;
this.stateIcon = AEStateIconsEnum.SAVE;
this.cachedTooltip = ThEStrings.TooltipButton_InscriberSave.getLocalized();
break;
case Disabled_MissingCore:
this.enabled = false;
this.stateIcon = null;
this.cachedTooltip = ThEStrings.TooltipButton_InscriberMissing.getLocalized();
break;
default:
break;
}
}
}
|
/*
* Copyright (c) 2021 Martin Koster
*
* 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 com.github.actionfx.texteditor.controller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Scanner;
import javax.inject.Inject;
import com.github.actionfx.core.ActionFX;
import com.github.actionfx.core.annotation.AFXControlValue;
import com.github.actionfx.core.annotation.AFXController;
import com.github.actionfx.core.annotation.AFXFromFileOpenDialog;
import com.github.actionfx.core.annotation.AFXFromFileSaveDialog;
import com.github.actionfx.core.annotation.AFXFromTextInputDialog;
import com.github.actionfx.core.annotation.AFXOnAction;
import com.github.actionfx.core.annotation.AFXRequiresUserConfirmation;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
/**
* Controller for a simple text editor.
* <p>
* The demo shows how menus and dialogs like open-, save-, information- and
* confirmation dialogs can be integrated with ActionFX.
* <p>
* Please note that the referenced menu items are not injected here via @FXML,
* but these are of course preset in the view's scene graph.
*
* @author koster
*
*/
@AFXController(viewId = "textEditorDemoView", fxml = "/fxml/TextEditor.fxml", maximized = true, title = "Text Editor")
public class TextEditorController {
@FXML
private TextArea editorTextArea;
@Inject
private ActionFX actionFX;
@AFXOnAction(nodeId = "openFileMenuItem", async = true)
public void openFile(@AFXFromFileOpenDialog(title = "Open Text File", extensionFilter = { "Text Files",
"*.txt" }) final Path path) throws IOException {
editorTextArea.clear();
try (final Scanner scanner = new Scanner(path)) {
scanner.useDelimiter(System.lineSeparator());
while (scanner.hasNext()) {
// since we activated "async=true", we are not inside the JavaFX thread.
// So changing the state of UI components requires us using
// Platform.runLater(..)
final String line = scanner.next();
Platform.runLater(() -> editorTextArea.appendText(line + System.lineSeparator()));
}
}
}
@AFXOnAction(nodeId = "saveFileMenuItem", async = true)
public void saveFile(
@AFXFromFileSaveDialog(title = "Save Text File", extensionFilter = { "Text Files",
"*.txt" }) final File file,
@AFXControlValue("editorTextArea") final String text) throws IOException {
try (final BufferedWriter writer = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8))) {
writer.write(text);
}
// show an information dialog that saving was successful
Platform.runLater(() -> actionFX.showInformationDialog("Save successful",
"File '" + file.getAbsolutePath() + "' has been successfully saved.", null));
}
@AFXOnAction(nodeId = "closeMenuItem")
@AFXRequiresUserConfirmation(title = "Exit", header = "Exit Text Editor", content = "Are you sure you want to exit the Text Editor?")
public void close() {
Platform.exit();
}
@AFXOnAction(nodeId = "findMenuItem")
public void find(
@AFXFromTextInputDialog(title = "Find", header = "Search for text", content = "Please enter a text to search for") final String searchText,
@AFXControlValue("editorTextArea") final String text) {
final int beginIndex = text.indexOf(searchText);
if (beginIndex > -1) {
final int endIndex = beginIndex + searchText.length();
editorTextArea.selectRange(beginIndex, endIndex);
} else {
actionFX.showInformationDialog("Find", "Text '" + searchText + "' has not been found!", null);
}
}
@AFXOnAction(nodeId = "aboutMenuItem")
public void about() {
actionFX.showInformationDialog("About", "About Text Editor",
"This is a simple Text Editor realized with ActionFX.");
}
}
|
package com.vikingsen.inject.viewmodel;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
@Target(TYPE)
@Retention(CLASS)
public @interface ViewModelModule {
}
|
package com.geektcp.alpha.algorithm.tree.btree;
/**
* @author tanghaiyang on 2019/1/21.
*/
public class BPlusTree {
}
|
package evolved.genetics.characters;
import evolved.model.compute.Operator;
public abstract class OperatorCharactor implements GeneCharacter {
private final Operator operator;
public OperatorCharactor(Operator operator) {
this.operator = operator;
}
public Operator getOperator() {
return operator;
}
}
|
/**
The MIT License (MIT) * Copyright (c) 2016 铭飞科技(mingsoft.net)
* 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 com.mingsoft.cms.bean;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import com.mingsoft.base.constant.Const;
import com.mingsoft.basic.entity.AppEntity;
import com.mingsoft.basic.entity.ColumnEntity;
import com.mingsoft.parser.IParserRegexConstant;
import com.mingsoft.util.StringUtil;
/**
*
*
* <p>
* <b>铭飞MS平台</b>
* </p>
*
* <p>
* Copyright: Copyright (c) 2014 - 2015
* </p>
*
* <p>
* Company:景德镇铭飞科技有限公司
* </p>
*
* @author 姓名 史爱华
*
* @version
*
* <p>
* 版权所有 铭飞科技
* </p>
*
* <p>
* Comments: ArticleEntity实体的bean用于给外部请求数据使用
* </p>
*
* <p>
* Create Date:2015-06-15
* </p>
*
* <p>
* Modification history:
* </p>
*/
public class ArticleBean {
/**
* 文章内容
*/
private String articleContent;
/**
* 文章作者
*/
private String articleAuthor;
/**
* 文章属性
*/
private String articleType ;
private int articleFreeOrder;
/**
* 文章的来源
*/
private String articleSource;
/**
* 文章跳转链接地址
*/
private String articleUrl;
/**
* 文章关键字
*/
private String articleKeyword;
/**
* 文章标题
*/
private String articleTitle;
/**
* 文章描述
*/
private String articleDescription;
/**
* 文章所属的分类Id
*/
private int articleCategoryId;
/**
* 文章url地址 主要是用户生成html使用
*/
private String articleLinkURL;
/**
* 文章分类url地址,主要是用户生成html使用
*/
private String articleTypeLinkURL;
/**
* 一对一管理栏目
*/
private ColumnEntity column;
/**
* 发布时间
*/
private Timestamp articleDateTime;
/**
* 更新时间
*/
private Date articleUpdateTime;
/**
* 缩略图
*/
private String articleThumbnails;
/**
* 点击次数
*/
private int articleHit;
public int getArticleFreeOrder() {
return articleFreeOrder;
}
public void setArticleFreeOrder(int articleFreeOrder) {
this.articleFreeOrder = articleFreeOrder;
}
public String getArticleTitle() {
return articleTitle;
}
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
}
public String getArticleDescription() {
return articleDescription;
}
public void setArticleDescription(String articleDescription) {
this.articleDescription = articleDescription;
}
public int getArticleCategoryId() {
return articleCategoryId;
}
public void setArticleCategoryId(int articleCategoryId) {
this.articleCategoryId = articleCategoryId;
}
public int getArticleHit() {
return articleHit;
}
public void setArticleHit(int articleHit) {
this.articleHit = articleHit;
}
public Timestamp getArticleDateTime() {
return articleDateTime;
}
public void setArticleDateTime(Timestamp articleDateTime) {
this.articleDateTime = articleDateTime;
}
public Date getArticleUpdateTime() {
return articleUpdateTime;
}
public void setArticleUpdateTime(Date articleUpdateTime) {
this.articleUpdateTime = articleUpdateTime;
}
public String getArticleThumbnails() {
return articleThumbnails;
}
public void setArticleThumbnails(String articleThumbnails) {
this.articleThumbnails = articleThumbnails;
}
/**
* 获取文章实体所属的栏目实体
* @return
*/
public ColumnEntity getColumn() {
return column;
}
/**
* 设置文章所属的栏目实体
* @param column
*/
public void setColumn(ColumnEntity column) {
this.column = column;
}
public String getArticleTypeLinkURL() {
return articleTypeLinkURL;
}
public void setArticleTypeLinkURL(String articleTypeLinkURL) {
this.articleTypeLinkURL = articleTypeLinkURL;
}
public String getArticleLinkURL() {
return articleLinkURL;
}
public void setArticleLinkURL(String articleLinkURL) {
this.articleLinkURL = articleLinkURL;
}
/**
* 获取文章作者
* @return 返回文章作者
*/
public String getArticleAuthor() {
return articleAuthor;
}
/**
* 获取文章内容
* @return 返回文章内容
*/
public String getArticleContent() {
return articleContent;
}
/**
* 获取文章关键字
* @return 返回文章关键字
*/
public String getArticleKeyword() {
return articleKeyword;
}
/**
* 获取文章的来源
* @return 返回文章的来源
*/
public String getArticleSource() {
return articleSource;
}
/**
* 获取文章属性
* @return 返回文章属性
*/
public String getArticleType() {
return articleType;
}
/**
* 获取文章跳转链接
* @return 返回文章跳转链接
*/
public String getArticleUrl() {
return articleUrl;
}
/**
* 设置文章作者
* @param articleAuthor 传入文章作者
*/
public void setArticleAuthor(String articleAuthor) {
this.articleAuthor = articleAuthor;
}
/**
* 设置文章内容
* @param articleContent 传入文章内容
*/
public void setArticleContent(String articleContent) {
this.articleContent = articleContent;
}
/**
* 设置文章关键字
* @param articleKeyword 传入文章关键字列表
*/
public void setArticleKeyword(String articleKeyword) {
this.articleKeyword = articleKeyword;
}
/**
* 设置文章的来源
* @param articleSource 传入文章的来源
*/
public void setArticleSource(String articleSource) {
this.articleSource = articleSource;
}
/**
* 设置文章属性
* @param articleType 传入文章属性
*/
public void setArticleType(String articleType) {
this.articleType = articleType;
}
/**
* 设置文章跳转链接
* @param articleUrl 传入文章跳转链接地址
*/
public void setArticleUrl(String articleUrl) {
this.articleUrl = articleUrl;
}
public String getArticleUrl(AppEntity app) {
if (!StringUtil.isBlank(app.getAppMobileStyle())) {
return app.getAppHostUrl()+IParserRegexConstant.HTML_SAVE_PATH+Const.SEPARATOR+IParserRegexConstant.MOBILE+Const.SEPARATOR+this.getArticleUrl();
}
return app.getAppHostUrl()+Const.SEPARATOR+IParserRegexConstant.HTML_SAVE_PATH+Const.SEPARATOR+this.getArticleUrl();
}
}
|
/*
* Copyright [2012] [ShopWiki]
*
* 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.shopwiki.roger.rpc;
import java.io.IOException;
import java.util.*;
import com.google.common.collect.Lists;
import com.rabbitmq.client.*;
import com.shopwiki.roger.RabbitConnector;
import com.shopwiki.roger.rpc.RpcServer.WorkerFactory;
/**
* Basic implementation of {@link WorkerFactory}.
* The user instantiates one and adds their {@link RequestHandler}s to it.
* Uses the same set of Channels (and Threads) for each {@link RequestHandler}.
*
* @author rstewart
*/
public class BasicWorkerFactory implements WorkerFactory {
private final Map<String, RequestHandler<?,?>> nameToHandler = new LinkedHashMap<String, RequestHandler<?,?>>();
private final RabbitConnector connector;
private final int numThreads;
public BasicWorkerFactory(RabbitConnector connector, int numThreads) {
this.connector = connector;
this.numThreads = numThreads;
}
public void addHandler(String name, RequestHandler<?,?> handler) {
nameToHandler.put(name, handler);
}
public Map<String, RequestHandler<?,?>> getHandlerMap() {
return Collections.unmodifiableMap(nameToHandler);
}
@Override
public Connection createConnection() throws IOException {
return connector.newConnection(numThreads); // non-daemon
}
@Override
public List<RpcWorker> createWorkers(Connection conn, String queuePrefix) throws IOException {
List<Channel> channels = new ArrayList<Channel>();
for (int i = 0; i < numThreads; i++) {
Channel channel = conn.createChannel();
channel.basicQos(1);
channels.add(channel);
}
List<RpcWorker> workers = Lists.newArrayListWithCapacity(nameToHandler.size());
for (String procedureName : nameToHandler.keySet()) {
RequestHandler<?,?> handler = nameToHandler.get(procedureName);
RpcWorker worker = new RpcWorker(handler, channels, queuePrefix, procedureName);
workers.add(worker);
}
return workers;
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.xaml;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
import system.xaml.AttachableMemberIdentifier;
/**
* The base .NET class managing System.Xaml.IAttachedPropertyStore, System.Xaml, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Xaml.IAttachedPropertyStore" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Xaml.IAttachedPropertyStore</a>
*/
public interface IAttachedPropertyStore extends IJCOBridgeReflected {
/**
* Fully assembly qualified name: System.Xaml, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
*/
public static final String assemblyFullName = "System.Xaml, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
/**
* Assembly name: System.Xaml
*/
public static final String assemblyShortName = "System.Xaml";
/**
* Qualified class name: System.Xaml.IAttachedPropertyStore
*/
public static final String className = "System.Xaml.IAttachedPropertyStore";
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link IAttachedPropertyStore}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link IAttachedPropertyStore} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static IAttachedPropertyStore ToIAttachedPropertyStore(IJCOBridgeReflected from) throws Throwable {
JCOBridge bridge = JCOBridgeInstance.getInstance("System.Xaml, Version=6.0.2.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
JCType classType = bridge.GetType(className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName));
NetType.AssertCast(classType, from);
return new IAttachedPropertyStoreImplementation(from.getJCOInstance());
}
/**
* Returns the reflected Assembly name
*
* @return A {@link String} representing the Fullname of reflected Assembly
*/
public String getJCOAssemblyName();
/**
* Returns the reflected Class name
*
* @return A {@link String} representing the Fullname of reflected Class
*/
public String getJCOClassName();
/**
* Returns the reflected Class name used to build the object
*
* @return A {@link String} representing the name used to allocated the object
* in CLR context
*/
public String getJCOObjectName();
/**
* Returns the instantiated class
*
* @return An {@link java.lang.Object} representing the instance of the instantiated Class
*/
public java.lang.Object getJCOInstance();
/**
* Returns the instantiated class Type
*
* @return A {@link JCType} representing the Type of the instantiated Class
*/
public JCType getJCOType();
// Methods section
public boolean RemoveProperty(AttachableMemberIdentifier attachableMemberIdentifier) throws Throwable;
public boolean TryGetProperty(AttachableMemberIdentifier attachableMemberIdentifier, JCORefOut<NetObject> value) throws Throwable;
public void SetProperty(AttachableMemberIdentifier attachableMemberIdentifier, NetObject value) throws Throwable;
// Properties section
public int getPropertyCount() throws Throwable;
// Instance Events section
}
|
package test.module.framework.tests.functional.service;
import org.testng.annotations.Test;
import core.apiCore.helpers.DataHelper;
import core.apiCore.helpers.JsonHelper;
import core.apiCore.interfaces.RestApiInterface;
import core.helpers.Helper;
import core.support.configReader.Config;
import core.support.objects.ServiceObject;
import test.module.framework.TestBase;
/**
* @author ehsan matean
*
*/
public class JsonTemplateTest extends TestBase {
@Test()
public void getRequestBodyFromJsonTemplate_valid() {
Config.putValue("quizItem", "quiz2");
ServiceObject serviceObject = new ServiceObject()
.withTemplateFile("Quiz.json")
.withRequestBody("quiz.sport.q1.options:2:value_<@quizItem>");
String updatedJson = JsonHelper.getRequestBodyFromJsonTemplate(serviceObject);
updatedJson = DataHelper.replaceParameters(updatedJson);
String updatedValue = JsonHelper.getJsonValue(updatedJson, "quiz.sport.q1.options");
Helper.assertEquals("value_quiz2", updatedValue);
}
@Test()
public void getRequestBodyFromJsonTemplate_requestbody_update() {
Config.putValue("quizItem", "quiz2");
ServiceObject serviceObject = new ServiceObject()
.withTemplateFile("Quiz.json")
.withRequestBody("_UPDATE_REQUEST_ quiz.sport.q1.options:2:value_<@quizItem>");
String updatedJson = DataHelper.getRequestBodyIncludingTemplate(serviceObject);
String updatedValue = JsonHelper.getJsonValue(updatedJson, "quiz.sport.q1.options");
Helper.assertEquals("value_quiz2", updatedValue);
}
@Test()
public void getRequestBodyFromJsonTemplate_valid_no_body() {
Config.putValue("quizItem", "quiz2");
ServiceObject serviceObject = new ServiceObject()
.withTemplateFile("Quiz.json")
.withRequestBody("");
String updatedJson = JsonHelper.getRequestBodyFromJsonTemplate(serviceObject);
String updatedValue = JsonHelper.getJsonValue(updatedJson, "quiz.sport.q1.options");
Helper.assertEquals("New York Bulls,Los Angeles Kings,Golden State Warriros,Huston Rocket", updatedValue);
}
@Test()
public void restapi_create_user_template() throws Exception {
// create user
String expected = "_VERIFY.JSON.PART_ .id:isNotEmpty;";
ServiceObject serviceObject = new ServiceObject()
.withUriPath("http://demo.autonomx.io/content-manager/explorer/user/?source=users-permissions")
.withContentType("application/x-www-form-urlencoded")
.withMethod("POST")
.withRequestHeaders("Authorization: Bearer <@accessTokenAdmin>")
.withRequestBody("username:zzz_test<@_RAND16>,\n" +
"email:testuser+<@_TIME_STRING_16>@gmail.com,\n" +
"password:password<@_TIME_STRING_16>,\n" +
"confirmed:true")
.withRespCodeExp("201")
.withOutputParams("id:<$userId>")
.withExpectedResponse(expected);
RestApiInterface.RestfullApiInterface(serviceObject);
// update user with template
serviceObject = new ServiceObject()
.withUriPath("http://demo.autonomx.io/content-manager/explorer/user/<@userId>?source=users-permissions")
.withContentType("application/json")
.withMethod("PUT")
.withRequestHeaders("Authorization: Bearer <@accessTokenAdmin>")
.withTemplateFile("User.json")
.withRequestBody("username:zzz_update<@_RAND16>;email:testUpdate1+<@_TIME_STRING_16>@gmail.com;")
.withRespCodeExp("200")
.withExpectedResponse("_VERIFY.JSON.PART_ email:1:equalTo(testUpdate1+<@_TIME_STRING_16>@gmail.com);");
RestApiInterface.RestfullApiInterface(serviceObject);
}
@Test()
public void getRequestBodyFromJsonTemplate_data_file() {
ServiceObject serviceObject = new ServiceObject()
.withTemplateFile("Car.json")
.withRequestBody("DataFile:Car:ninja");
String updatedJson = DataHelper.getRequestBodyIncludingTemplate(serviceObject);
String updatedValue = JsonHelper.getJsonValue(updatedJson, ".type");
Helper.assertEquals("motorcycle", updatedValue);
updatedValue = JsonHelper.getJsonValue(updatedJson, ".year");
Helper.assertEquals("2018", updatedValue);
updatedValue = JsonHelper.getJsonValue(updatedJson, ".model");
Helper.assertEquals("null", updatedValue);
}
}
|
package ch10;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* A multithreaded example showing how to safely update Swing components
* from a background thread. The ProgressPretender class below slowly
* counts up to 100 and keeps a JLabel updated with the current value.
*/
public class ProgressDemo {
public static void main( String[] args ) {
JFrame frame = new JFrame( "SwingUtilities 'invoke' Demo" );
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.setSize( 300, 180 );
JLabel label = new JLabel("Download Progress Goes Here!", JLabel.CENTER );
Thread pretender = new Thread(new ProgressPretender(label));
JButton simpleButton = new JButton("Start");
simpleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
simpleButton.setEnabled(false);
pretender.start();
}
});
JLabel checkLabel = new JLabel("Can you still type?");
JTextField checkField = new JTextField(10);
frame.add(label);
frame.add(simpleButton);
frame.add(checkLabel);
frame.add(checkField);
frame.setVisible( true );
}
}
/**
* Simulated worker that updates a provided JLabel
* with the work "progress". In this simulation, we just
* count from 0 to 100 with a one-second delay between
* each step.
*/
class ProgressPretender implements Runnable {
JLabel label;
int progress;
public ProgressPretender(JLabel label) {
this.label = label;
progress = 0;
}
public void run() {
while (progress <= 100) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText(progress + "%");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
System.err.println("Someone interrupted us. Skipping download.");
break;
}
progress++;
}
}
}
|
package com.ccb.demo;
import com.alibaba.fastjson.JSONObject;
import com.ccb.util.AESUtil;
import com.ccb.util.HttpUtil;
import com.ccb.util.RSAUtilV2;
import com.ccb.util.SHA256withRSA;
/**
* 用户请求政融支付加密参数Demo
*/
public class EncryDemo {
/**
* 双方用于加解密的密钥 可调用 AESUtil.getAESSecureKey() 获取
*/
private static final String AES_KEY = "bf7f4a47755bfd811b36c7b6dba88c34";
/**
* 签名私钥 使用调用政融原有私钥 否则会导致验签不过。
*/
private static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCDcj2lNGdpEwFY196A/pcT9s9/+XgfI6rYb5GeBoOattnEL7JAe3Zbob0XtZDOnuYP+3yaorqVmDvwFAsACt9ac8jXXpghvLHIW8rdv25jbjlajOcwQy/H42+tBKgZV7oO3r8zj58PvjXjj7wwFEHiacRMI3Y6YCYi60omKQeCk9bY7L5FK7Mym4GrNT4+tv5A/zyBS7NuaCO8reup5BVtg2MjVuizoMDOPNr7sT1oqFj21KqbIrL+TzQe/hiddOrRVY8llAtXmq0lvMcjfnfgCtbs+rhYijIXjfi1VEh+cq9Gl4RY/3Vh5KE58jgVk7ggFuyvDmr57sDtb62V8RgZAgMBAAECggEAKTNfuy6n0zmPzIctSQWD2VAdTiGl0yzc2iZuYDfufEogC+xfVPLd8G7L1Gim0PzhY9USA25KSaWD9AZ0RDkkNTfhlhAiY0DAAOs0tTjRovzjoUxVEr2cdm0FjhfNkNP8j7il+cVkuAyI26Er/W38ELnSO4NKBZYpnfxeK4PkxLqZW8/NKUXJni7FaPni2S7tWhgkt7Zqa/gdLnCQMLaf9xePhLzqrM2gT10kkZjBDQ4WqvfsgLRMUJ8B40e3QezYxTtYlzaZCSibBMI+gMnBKJOzXf01wUybNpBWYmDFMDoMColILB2GeSTzO92V0DceewaOamBpKaXTj/DeMFZuuQKBgQDbiHF+/GOIirzdWe0SiJkKmv4MRvIcTGrwGOepdEimbDvFaq+M4JxS0n5drufxq1E8kmDAcLfatvf7NZ0+FZBMMMfl3giLcpZvgCxKxABefdZdkOsTvTgG0ckKwf9qO2Yq+A6tlk52Hv80tecXsIDGdvQnU/52xryTUBcbdWjfCwKBgQCZR/FaPUFDjkRwU/uHq21azGUNCUjKH6O1ULRBWJdQBv5OLvCxqvwXSJGAYaG1JdwP15jI4jNzJfmmM8IT3Jw65zAlhXe01l2LEf7PohAVN5LDqd5Lq2rwCYhAV5aspk7Wc2gHhTsyRgTZWeLHF7i1Xc0JlmW5mgW4/t7QExCr6wKBgCs+z4zCTyEgo1+/TTIvcmZibdUhTKRCcXZmkYwR+hW+kG+tOnO381NlX7s4rzwuEUyrUR/XlIAjNupnf1gxi0FXAqnHeUtvAS9pwk/gGGqEw2ufFo/G4HiHbuENojDdDp08TDfpuf8O0BskEifafyOZXzM4GpJvR8qFJmgkUspNAoGAaWGl1FWixhBMizGiD59TOoalvrWwXo4sHh8THo4K0ZFNS3FIN84HLPbOWgZFh+Y0iou+VfX2S2dDYPnap48XtgN1/YXqS+DJRTClEBkql3uyomTqGPoMNmVHUH0ncSGRuCx1zB3UGfc7pDcBC8IKUl7f9YR6AYWcA5julP1Wi+sCgYEAyysEFyNAlTaDrtVMqYcRZ2Gufqoi/2qUzFFQnT6HTuhiB+S67p0VYaTPI4/XllrftkfiVYmt/gI2YuGhzrgO3vF6ucsqrNfnFdeA2HUomcO4XkFygt/die1pgAZ+XRL232F1kIWSbmIoerVBubc+vAZpEtVjVVJNgMMPSz29Nrs=";
//请求地址
private static final String REQUEST_URL = "http://govpaytestay.mytunnel.site/online/bmjf/MainPlat";
/**
* 使用政融支付平台公钥对加密密钥进行RSA非对称加密 此处密钥更换为具体公钥
*/
private static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkxJVDKgDhDGS/OCBDmqD1F5j8yzeimmEmaFjz3w+oO6vUDpJ+bGesONsK0Ue1ttOyFBm0x1IRRmJJWTTL9NSNm+f8P1nttZiRSdWIgOjXwxZvasndDN9cUArilIGPNhpLxkHaZkzvym/GKPPbr/p5ys/iFFjZsxGTJ5k84KnK83yC503TGqLweOp24/ghJZO80lPH3ZNTQUqmV4JodTdRvirJbPAZBoc2lUkizYX4NitAqCDnXXFN8JT9C2tJONy6s8JRsuXC7Y6+kffXTxUne2UAvuwkyBJtMsiH3a38yj9V9PLbggOST9gpUG7ISwe2PGWamYsx0/tJJR8avUnwwIDAQAB";
public static void main(String[] args) {
EncryDemo demo = new EncryDemo();
String param = "Vno=2&Sgn_Algr=SHA256withRSA&Usr_ID=12345&Crdt_Nm=张三&Crdt_Tp=1010&Crdt_No=130132199809896781&MblPh_No=19801207665&IsMobile=2&Email=abc@sina.com&Tms=20190809121212";
//demo.oldRequestZrzfDncryptParam(param);
demo.newRequestZrzfDncryptParam(param);
/**
* 执行后续逻辑
*/
}
/**
* 此场景模拟用户请求政融支付 适配未优化Form表单提交的用户
* 获取到加密的Uri后跳转页面-进行缴费
*
* @param oriParam 签名原串 按实际接口原串拼接 这里以安阳为例
* @return
*/
public String oldRequestZrzfDncryptParam(String oriParam) {
AESUtil aesUtil = new AESUtil();
StringBuffer strbuff = new StringBuffer();
//用户签名 -> 私钥签名 -> 用于双方认证
String signInf = SHA256withRSA.sign(PRIVATE_KEY, oriParam);
//拼接签名信息 用于加密
String str = oriParam + "&SIGN_INF=" + signInf;
System.out.println("参数信息用于加密:" + str);
System.out.println("AES加密参数信息--------");
String encryptParam = aesUtil.encrypt(str, AES_KEY);
System.out.println("AES加密后参数:" + encryptParam);
//加密AES密钥 这里使用RSA加密 政融会解密获取AES密钥后再解密请求参数
String rsaEncryKey = RSAUtilV2.encryptByPublic(AES_KEY.getBytes(), RSAUtilV2.getPublicKey(PUBLIC_KEY));
System.out.println("RSA加密AES密钥:" + rsaEncryKey);
/**
* 拼接请求政融最终的uri 例如:
* https://ay.govpay.ccb.com/online/bmjf/MainPlat?Encrypt_Ind=1&Encrypt_key=xxx&Bus_para=XXX
*/
strbuff.append(REQUEST_URL);
//1表示加密 0表示不加密 这里默认拼1
strbuff.append("?Encrypt_Ind=1");
//拼接AES加密后的密钥
strbuff.append("&Encrypt_key=");
strbuff.append(rsaEncryKey);
//拼接AES加密后参数
strbuff.append("&Bus_para=");
strbuff.append(encryptParam);
System.out.println("用户请求政融支付加密后URI:" + strbuff.toString());
return strbuff.toString();
}
/**
* 此场景模拟用户请求政融支付 适配已优化Form表单Post请求的用户 这里使用HTTP模拟
* 获取到加密的参数后请求政融平台
*
* @param oriParam 签名原串 按实际接口原串拼接 这里以安阳为例
* @return
*/
public String newRequestZrzfDncryptParam(String oriParam) {
AESUtil aesUtil = new AESUtil();
//用户签名 -> 私钥签名 -> 用于双方认证
String signInf = SHA256withRSA.sign(PRIVATE_KEY, oriParam);
//拼接签名信息 用于加密
String str = oriParam + "&SIGN_INF=" + signInf;
System.out.println("参数信息用于加密:" + str);
System.out.println("AES加密参数信息--------");
String encryptParam = aesUtil.encrypt(str, AES_KEY);
System.out.println("AES加密后参数:" + encryptParam);
//加密AES密钥 这里使用RSA加密 政融会解密获取AES密钥后再解密请求参数
String rsaEncryKey = RSAUtilV2.encryptByPublic(AES_KEY.getBytes(), RSAUtilV2.getPublicKey(PUBLIC_KEY));
System.out.println("RSA加密AES密钥:" + rsaEncryKey);
/**
* 组装请求政融的参数 实际按照接口文档为准!!!
*/
JSONObject json = new JSONObject();
//1表示加密 0表示不加密 这里默认拼1
json.put("Encrypt_Ind", "1");
//RSA加密后的AES密钥
json.put("Encrypt_key", rsaEncryKey);
//AES加密后参数
json.put("Bus_para", encryptParam);
System.out.println("请求参数:" + json.toJSONString());
/**
* 此处向政融发送请求。这里的url是安阳为例
*/
//用户接收请求地址
String result = "";
try {
result = HttpUtil.doJsonPost(REQUEST_URL, json.toString());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("http返回信息:" + result);
return result;
}
}
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.config.impl.extension;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
/**
* External utility capable of accepting a {@link ArquillianDescriptor},
* replacing any sysprop EL expressions with a proper value or default,
* and returning a new instance of the {@link ArquillianDescriptor}.
* Fulfills ARQ-148.
* <p>
* TODO To eventually become part of a chain-based event mechanism
* as defined by ARQ-284.
*
* @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
*/
class ConfigurationSysPropResolver {
/**
* Internal ctor, not to be called
*/
private ConfigurationSysPropResolver() {
throw new UnsupportedOperationException("No instances permitted");
}
/**
* Returns a new instance of {@link ArquillianDescriptor} by resolving any
* sysprop EL expressions in the provided {@link ArquillianDescriptor} to real
* values or defaults
*
* @param descriptor
* The input to resolve, required
*
* @throws IllegalArgumentException
*/
static ArquillianDescriptor resolveSystemProperties(final ArquillianDescriptor descriptor)
throws IllegalArgumentException {
final String descrStr = descriptor.exportAsString();
final ArquillianDescriptor newArqDescriptor = Descriptors.importAs(ArquillianDescriptor.class).fromString(
StringPropertyReplacer.replaceProperties(descrStr));
return newArqDescriptor;
}
}
|
package com.refactor.bootcamp.incomplete_library_class.example_1;
import java.util.Date;
public class InCompleteLibraryClassExample1 {
public Date getBillAmountDate() {
Date date = new Date(2016, 10, 1);
return nextDate(date);
}
private static Date nextDate(Date date) {
//foreign method ,should be on date
return new Date(date.getYear(), date.getMonth(), date.getDate() + 1);
}
}
|
//
// Copyright (c) 2007 Tridium, Inc.
// Licensed under the Academic Free License version 3.0
//
// History:
// 12 Mar 07 Brian Frank Creation
//
package sedonac.ir;
import sedona.Facets;
import sedonac.ast.*;
import sedonac.namespace.*;
/**
* IrField
*/
public class IrField
extends IrSlot
implements Field
{
//////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////
public IrField(IrType parent, int flags, String name,
Facets facets, Type type)
{
super(parent, flags, name, facets);
this.type = type;
this.storage = new IrAddressable.Impl(qname + " (storage)");
}
//////////////////////////////////////////////////////////////////////////
// Method
//////////////////////////////////////////////////////////////////////////
public boolean isField() { return true; }
public boolean isMethod() { return false; }
public Type type() { return type; }
public Expr.Literal define() { return define; }
public int ctorLengthParam() { return ctorLengthParam; }
//////////////////////////////////////////////////////////////////////////
// Memory
//////////////////////////////////////////////////////////////////////////
public int offsetWidth()
{
if (isConst() && isStatic()) return 2;
if (isDefine()) return 2;
if (offset <= 0xff) return 1;
if (offset <= 0xffff) return 2;
return 4;
}
//////////////////////////////////////////////////////////////////////////
// Fields
//////////////////////////////////////////////////////////////////////////
public Type type;
public int offset = -1; // bytes from start of static or instance mem
public boolean arrayInit; // {...} array initialization
public Expr.Literal define; // if define
public IrAddressable storage; // block index of storage only if const static
public int ctorLengthParam = -1; // see sedonac.ast.FieldDef
public Expr ctorLengthArg; // argument to ctorLengthParam (Literal or define Field)
}
|
package com.pwaquim.professionalcard;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
|
package com.github.onozaty.sql.resultset.core;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import org.junit.Test;
/**
* {@link CsvDestination}のテストです。
* @author onozaty
*
*/
public class CsvDestinationTest {
@Test
public void test() throws IOException {
Column<String> column1 = new Column<>("col1", null); // ValueRetrieverは参照しないのでnullで
Column<Integer> column2 = new Column<>("col2", null);
Column<Object> column3 = new Column<>("col3", null);
try (
StringWriter writer = new StringWriter();
CsvDestination csvDestination = new CsvDestination(writer)) {
csvDestination.prepare(Arrays.asList(column1, column2, column3));
csvDestination.output(column1, "a");
csvDestination.output(column2, 1);
csvDestination.output(column3, null);
csvDestination.endRecord();
csvDestination.output(column1, "\"");
csvDestination.output(column2, 1000);
csvDestination.output(column3, false);
csvDestination.endRecord();
String result = writer.toString();
assertThat(result)
.isEqualTo(
"col1,col2,col3\r\n"
+ "a,1,\r\n"
+ "\"\"\"\",1000,false\r\n");
}
}
}
|
package com.keekan.bean;
import java.io.Serializable;
/**
* @author KEEKAN.10000
* @version 1.0 <br>
* Copyright (C), 2012-, keekan.com <br>
* This program is protected by copyright laws. <br>
* Program Name: KEEKAN<br>
* Class Name: 照片表持久化Bean类 <br>
*/
public class PhotoBean implements Serializable {
private static final long serialVersionUID = 1L;
private Integer photoId; //照片ID
private String rawPhotoName; //原照片名
private String photoName; //照片名
private String photoDescription; //照片描述
private Integer ownAlbumId; //所属相册ID
private String uploadDate; //上传时间
public Integer getPhotoId() {
return photoId;
}
public void setPhotoId(Integer photoId) {
this.photoId = photoId;
}
public String getRawPhotoName() {
return rawPhotoName;
}
public void setRawPhotoName(String rawPhotoName) {
this.rawPhotoName = rawPhotoName;
}
public String getPhotoName() {
return photoName;
}
public void setPhotoName(String photoName) {
this.photoName = photoName;
}
public String getPhotoDescription() {
return photoDescription;
}
public void setPhotoDescription(String photoDescription) {
this.photoDescription = photoDescription;
}
public Integer getOwnAlbumId() {
return ownAlbumId;
}
public void setOwnAlbumId(Integer ownAlbumId) {
this.ownAlbumId = ownAlbumId;
}
public String getUploadDate() {
return uploadDate;
}
public void setUploadDate(String uploadDate) {
this.uploadDate = uploadDate;
}
}
|
package com.dcxiaolou.tinyJD.bean;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class PmsProductImage implements Serializable {
@Id
@Column
private String id;
@Column
private String productId;
@Column
private String imgName;
@Column
private String imgUrl;
public PmsProductImage() {
}
public PmsProductImage(String id, String productId, String imgName, String imgUrl) {
this.id = id;
this.productId = productId;
this.imgName = imgName;
this.imgUrl = imgUrl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
@Override
public String toString() {
return "PmsProductImage{" +
"id='" + id + '\'' +
", productId='" + productId + '\'' +
", imgName='" + imgName + '\'' +
", imgUrl='" + imgUrl + '\'' +
'}';
}
}
|
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.orm.jpa;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.boot.test.autoconfigure.AutoConfigurationImportedCondition.importedAutoConfiguration;
/**
* Integration tests for {@link DataJpaTest}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@RunWith(SpringRunner.class)
@DataJpaTest
@TestPropertySource(properties = "spring.jpa.hibernate.use-new-id-generator-mappings=false")
public class DataJpaTestIntegrationTests {
@Autowired
private TestEntityManager entities;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private ExampleRepository repository;
@Autowired
private DataSource dataSource;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testEntityManager() {
ExampleEntity entity = this.entities.persist(new ExampleEntity("spring", "123"));
this.entities.flush();
Object id = this.entities.getId(entity);
ExampleEntity found = this.entities.find(ExampleEntity.class, id);
assertThat(found.getName()).isEqualTo("spring");
}
@Test
public void testEntityManagerPersistAndGetId() {
Long id = this.entities.persistAndGetId(new ExampleEntity("spring", "123"), Long.class);
assertThat(id).isNotNull();
String reference = this.jdbcTemplate.queryForObject("SELECT REFERENCE FROM EXAMPLE_ENTITY WHERE ID = ?",
new Object[]{id}, String.class);
assertThat(reference).isEqualTo("123");
}
@Test
public void testRepository() {
this.entities.persist(new ExampleEntity("spring", "123"));
this.entities.persist(new ExampleEntity("boot", "124"));
this.entities.flush();
ExampleEntity found = this.repository.findByReference("124");
assertThat(found.getName()).isEqualTo("boot");
}
@Test
public void replacesDefinedDataSourceWithEmbeddedDefault() throws Exception {
String product = this.dataSource.getConnection().getMetaData().getDatabaseProductName();
assertThat(product).isEqualTo("H2");
}
@Test
public void didNotInjectExampleComponent() {
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
.isThrownBy(() -> this.applicationContext.getBean(ExampleComponent.class));
}
@Test
public void flywayAutoConfigurationWasImported() {
assertThat(this.applicationContext).has(importedAutoConfiguration(FlywayAutoConfiguration.class));
}
@Test
public void liquibaseAutoConfigurationWasImported() {
assertThat(this.applicationContext).has(importedAutoConfiguration(LiquibaseAutoConfiguration.class));
}
}
|
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.util;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
public final class HashtableOfType {
// to avoid using Enumerations, walk the individual tables skipping nulls
public char[] keyTable[];
public ReferenceBinding valueTable[];
public int elementSize; // number of elements in the table
int threshold;
public HashtableOfType() {
this(3);
}
public HashtableOfType(int size) {
this.elementSize = 0;
this.threshold = size; // size represents the expected number of elements
int extraRoom = (int) (size * 1.75f);
if (this.threshold == extraRoom)
extraRoom++;
this.keyTable = new char[extraRoom][];
this.valueTable = new ReferenceBinding[extraRoom];
}
public boolean containsKey(char[] key) {
int length = this.keyTable.length,
index = CharOperation.hashCode(key) % length;
int keyLength = key.length;
char[] currentKey;
while ((currentKey = this.keyTable[index]) != null) {
if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
return true;
if (++index == length) {
index = 0;
}
}
return false;
}
public ReferenceBinding get(char[] key) {
int length = this.keyTable.length,
index = CharOperation.hashCode(key) % length;
int keyLength = key.length;
char[] currentKey;
while ((currentKey = this.keyTable[index]) != null) {
if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
return this.valueTable[index];
if (++index == length) {
index = 0;
}
}
return null;
}
public ReferenceBinding put(char[] key, ReferenceBinding value) {
int length = this.keyTable.length,
index = CharOperation.hashCode(key) % length;
int keyLength = key.length;
char[] currentKey;
while ((currentKey = this.keyTable[index]) != null) {
if (currentKey.length == keyLength && CharOperation.equals(currentKey, key))
return this.valueTable[index] = value;
if (++index == length) {
index = 0;
}
}
this.keyTable[index] = key;
this.valueTable[index] = value;
// assumes the threshold is never equal to the size of the table
if (++this.elementSize > this.threshold)
rehash();
return value;
}
private void rehash() {
HashtableOfType newHashtable = new HashtableOfType(this.elementSize < 100 ? 100 : this.elementSize * 2); // double the number of expected elements
char[] currentKey;
for (int i = this.keyTable.length; --i >= 0;)
if ((currentKey = this.keyTable[i]) != null)
newHashtable.put(currentKey, this.valueTable[i]);
this.keyTable = newHashtable.keyTable;
this.valueTable = newHashtable.valueTable;
this.threshold = newHashtable.threshold;
}
public int size() {
return this.elementSize;
}
public String toString() {
String s = ""; //$NON-NLS-1$
ReferenceBinding type;
for (int i = 0, length = this.valueTable.length; i < length; i++)
if ((type = this.valueTable[i]) != null)
s += type.toString() + "\n"; //$NON-NLS-1$
return s;
}
}
|
/*
* 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-2022 the original author or authors.
*/
package org.assertj.core.api;
import java.util.Comparator;
import org.assertj.core.data.Offset;
import org.assertj.core.data.Percentage;
import org.assertj.core.internal.Bytes;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.util.CheckReturnValue;
import org.assertj.core.util.VisibleForTesting;
/**
* Base class for all implementations of assertions for {@link Byte}s.
*
* @param <SELF> the "self" type of this assertion class. Please read "<a href="http://bit.ly/1IZIRcY"
* target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>"
* for more details.
*
* @author Drummond Dawson
* @author Yvonne Wang
* @author David DIDIER
* @author Ansgar Konermann
* @author Alex Ruiz
* @author Mikhail Mazursky
* @author Nicolas François
* @author Cal027
*/
public abstract class AbstractByteAssert<SELF extends AbstractByteAssert<SELF>> extends AbstractComparableAssert<SELF, Byte>
implements NumberAssert<SELF, Byte> {
@VisibleForTesting
Bytes bytes = Bytes.instance();
protected AbstractByteAssert(Byte actual, Class<?> selfType) {
super(actual, selfType);
}
/**
* Verifies that the actual value is equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat((byte) 1).isEqualTo((byte) 1);
* assertThat((byte) 0).isEqualTo(Byte.valueOf("0"));
*
* // assertions will fail
* assertThat((byte) 1).isEqualTo((byte) 0);
* assertThat(Byte.valueOf("1")).isEqualTo((byte) 0);</code></pre>
*
* @param expected the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not equal to the given one.
*/
public SELF isEqualTo(byte expected) {
bytes.assertEqual(info, actual, expected);
return myself;
}
/**
* Verifies that the actual value is not equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat((byte) 0).isNotEqualTo((byte) 1);
* assertThat(Byte.valueOf("1")).isNotEqualTo((byte) 0);
*
* // assertions will fail
* assertThat((byte) 0).isNotEqualTo((byte) 0);
* assertThat(Byte.valueOf("0")).isNotEqualTo((byte) 0);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to the given one.
*/
public SELF isNotEqualTo(byte other) {
bytes.assertNotEqual(info, actual, other);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isZero() {
bytes.assertIsZero(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isNotZero() {
bytes.assertIsNotZero(info, actual);
return myself;
}
/** {@inheritDoc} */
@Override
public SELF isOne() {
bytes.assertIsOne(info, actual);
return myself;
}
/**
* {@inheritDoc}
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 1).isPositive();
*
* // assertion will fail
* assertThat((byte) -1).isPositive();</code></pre>
*
*/
@Override
public SELF isPositive() {
bytes.assertIsPositive(info, actual);
return myself;
}
/**
* {@inheritDoc}
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) -1).isNegative();
*
* // assertion will fail
* assertThat((byte) 1).isNegative();</code></pre>
*
*/
@Override
public SELF isNegative() {
bytes.assertIsNegative(info, actual);
return myself;
}
/**
* {@inheritDoc}
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 1).isNotNegative();
*
* // assertion will fail
* assertThat((byte) -1).isNotNegative();</code></pre>
*
*/
@Override
public SELF isNotNegative() {
bytes.assertIsNotNegative(info, actual);
return myself;
}
/**
* {@inheritDoc}
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) -1).isNotPositive();
*
* // assertion will fail
* assertThat((byte) 1).isNotPositive();</code></pre>
*
*/
@Override
public SELF isNotPositive() {
bytes.assertIsNotPositive(info, actual);
return myself;
}
/**
* Verifies that the actual value is even.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat((byte) 12).isEven();
* assertThat((byte) -46).isEven();
*
* // assertions will fail
* assertThat((byte) 3).isEven();
* assertThat((byte) 15).isEven();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not even.
* @since 3.17.0
*/
public SELF isEven() {
bytes.assertIsEven(info, actual);
return myself;
}
/**
* Verifies that the actual value is odd.
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat((byte) 3).isOdd();
* assertThat((byte) -17).isOdd();
*
* // assertions will fail
* assertThat((byte) 2).isOdd();
* assertThat((byte) -24).isOdd();</code></pre>
*
* @return this assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is not odd.
* @since 3.17.0
*/
public SELF isOdd() {
bytes.assertIsOdd(info, actual);
return myself;
}
/**
* Verifies that the actual value is less than the given one.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 1).isLessThan((byte) 2);
*
* // assertion will fail
* assertThat((byte) 1).isLessThan((byte) 0);
* assertThat((byte) 1).isLessThan((byte) 1);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to or greater than the given one.
*/
public SELF isLessThan(byte other) {
bytes.assertLessThan(info, actual, other);
return myself;
}
/**
* Verifies that the actual value is less than or equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 1).isLessThanOrEqualTo((byte) 2);
* assertThat((byte) 1).isLessThanOrEqualTo((byte) 1);
*
* // assertion will fail
* assertThat((byte) 1).isLessThanOrEqualTo((byte) 0);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is greater than the given one.
*/
public SELF isLessThanOrEqualTo(byte other) {
bytes.assertLessThanOrEqualTo(info, actual, other);
return myself;
}
/**
* Verifies that the actual value is greater than the given one.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 2).isGreaterThan((byte) 1);
*
* // assertion will fail
* assertThat((byte) 2).isGreaterThan((byte) 3);
* assertThat((byte) 2).isGreaterThan((byte) 2);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is equal to or less than the given one.
*/
public SELF isGreaterThan(byte other) {
bytes.assertGreaterThan(info, actual, other);
return myself;
}
/**
* Verifies that the actual value is greater than or equal to the given one.
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 2).isGreaterThanOrEqualTo((byte) 1);
* assertThat((byte) 2).isGreaterThanOrEqualTo((byte) 2);
*
* // assertion will fail
* assertThat((byte) 2).isGreaterThanOrEqualTo((byte) 3);</code></pre>
*
* @param other the given value to compare the actual value to.
* @return {@code this} assertion object.
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value is less than the given one.
*/
public SELF isGreaterThanOrEqualTo(byte other) {
bytes.assertGreaterThanOrEqualTo(info, actual, other);
return myself;
}
/**
* Verifies that the actual value is in [start, end] range (start included, end included).
*
* <p>
* Example:
* <pre><code class='java'> // assertions will pass
* assertThat((byte) 1).isBetween((byte) -1, (byte) 2);
* assertThat((byte) 1).isBetween((byte) 1, (byte) 2);
* assertThat((byte) 1).isBetween((byte) 0, (byte) 1);
*
* // assertion will fail
* assertThat((byte) 1).isBetween((byte) 2, (byte) 3);</code></pre>
*
*/
@Override
public SELF isBetween(Byte start, Byte end) {
bytes.assertIsBetween(info, actual, start, end);
return myself;
}
/**
* Verifies that the actual value is in ]start, end[ range (start excluded, end excluded).
*
* <p>
* Example:
* <pre><code class='java'> // assertion will pass
* assertThat((byte) 1).isStrictlyBetween((byte) -1, (byte) 2);
*
* // assertions will fail
* assertThat((byte) 1).isStrictlyBetween((byte) 1, (byte) 2);
* assertThat((byte) 1).isStrictlyBetween((byte) 0, (byte) 1);
* assertThat((byte) 1).isStrictlyBetween((byte) 2, (byte) 3);</code></pre>
*
*/
@Override
public SELF isStrictlyBetween(Byte start, Byte end) {
bytes.assertIsStrictlyBetween(info, actual, start, end);
return myself;
}
/**
* Verifies that the actual number is close to the given one within the given offset value.
* <p>
* When <i>abs(actual - expected) == offset value</i>, the assertion:
* <ul>
* <li><b>succeeds</b> when using {@link Assertions#within(Byte)}</li>
* <li><b>fails</b> when using {@link Assertions#byLessThan(Byte)} or {@link Offset#strictOffset(Number)}</li>
* </ul>
* <p>
* <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Byte)} implies a <b>strict</b> comparison,
* use {@link Assertions#within(Byte)} to get the old behavior.
* <p>
* Examples:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 3));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 3));
*
* // if difference is exactly equals to the offset, it's ok ...
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 2));
* // ... but not with byLessThan which implies a strict comparison
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 2)); // FAIL
*
* // assertions will fail
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 1));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 1));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 2));</code></pre>
*
* @param expected the given int to compare the actual value to.
* @param offset the given positive offset.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws AssertionError if the actual value is not close enough to the given one.
*/
public SELF isCloseTo(byte expected, Offset<Byte> offset) {
bytes.assertIsCloseTo(info, actual, expected, offset);
return myself;
}
/**
* Verifies that the actual number is not close to the given one by less than the given offset.<br>
* <p>
* When <i>abs(actual - expected) == offset value</i>, the assertion:
* <ul>
* <li><b>succeeds</b> when using {@link Assertions#byLessThan(Byte)} or {@link Offset#strictOffset(Number)}</li>
* <li><b>fails</b> when using {@link Assertions#within(Byte)}</li>
* </ul>
* <p>
* <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Byte)} implies a <b>strict</b> comparison,
* use {@link Assertions#within(Byte)} to get the old behavior.
* <p>
* Examples:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 1));
* assertThat((byte) 5).isNotCloseTo((byte) 7, within((byte) 1));
* // diff == offset but isNotCloseTo succeeds as we use byLessThan
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 2));
*
* // assertions will fail
* assertThat((byte) 5).isNotCloseTo((byte) 7, within((byte) 2));
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 3));</code></pre>
*
* @param expected the given int to compare the actual value to.
* @param offset the given positive offset.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws AssertionError if the actual value is close to the given one.
* @see Assertions#byLessThan(Byte)
* @since 2.6.0 / 3.6.0
*/
public SELF isNotCloseTo(byte expected, Offset<Byte> offset) {
bytes.assertIsNotCloseTo(info, actual, expected, offset);
return myself;
}
/**
* Verifies that the actual number is close to the given one within the given offset value.
* <p>
* When <i>abs(actual - expected) == offset value</i>, the assertion:
* <ul>
* <li><b>succeeds</b> when using {@link Assertions#within(Byte)}</li>
* <li><b>fails</b> when using {@link Assertions#byLessThan(Byte)} or {@link Offset#strictOffset(Number)}</li>
* </ul>
* <p>
* <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Byte)} implies a <b>strict</b> comparison,
* use {@link Assertions#within(Byte)} to get the old behavior.
* <p>
* Examples:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 3));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 3));
*
* // if difference is exactly equals to the offset, it's ok ...
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 2));
* // ... but not with byLessThan which implies a strict comparison
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 2)); // FAIL
*
* // assertions will fail
* assertThat((byte) 5).isCloseTo((byte) 7, within((byte) 1));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 1));
* assertThat((byte) 5).isCloseTo((byte) 7, byLessThan((byte) 2));</code></pre>
*
* @param expected the given int to compare the actual value to.
* @param offset the given positive offset.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws AssertionError if the actual value is not close enough to the given one.
*/
@Override
public SELF isCloseTo(Byte expected, Offset<Byte> offset) {
bytes.assertIsCloseTo(info, actual, expected, offset);
return myself;
}
/**
* Verifies that the actual number is not close to the given one by less than the given offset.<br>
* <p>
* When <i>abs(actual - expected) == offset value</i>, the assertion:
* <ul>
* <li><b>succeeds</b> when using {@link Assertions#byLessThan(Byte)} or {@link Offset#strictOffset(Number)}</li>
* <li><b>fails</b> when using {@link Assertions#within(Byte)}</li>
* </ul>
* <p>
* <b>Breaking change</b> since 2.9.0/3.9.0: using {@link Assertions#byLessThan(Byte)} implies a <b>strict</b> comparison,
* use {@link Assertions#within(Byte)} to get the old behavior.
* <p>
* Examples:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 1));
* assertThat((byte) 5).isNotCloseTo((byte) 7, within((byte) 1));
* // diff == offset but isNotCloseTo succeeds as we use byLessThan
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 2));
*
* // assertions will fail
* assertThat((byte) 5).isNotCloseTo((byte) 7, within((byte) 2));
* assertThat((byte) 5).isNotCloseTo((byte) 7, byLessThan((byte) 3));</code></pre>
*
* @param expected the given int to compare the actual value to.
* @param offset the given positive offset.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws AssertionError if the actual value is close to the given one.
* @see Assertions#byLessThan(Byte)
* @since 2.6.0 / 3.6.0
*/
@Override
public SELF isNotCloseTo(Byte expected, Offset<Byte> offset) {
bytes.assertIsNotCloseTo(info, actual, expected, offset);
return myself;
}
/**
* Verifies that the actual number is close to the given one within the given percentage.<br>
* If difference is equal to the percentage value, assertion is considered valid.
* <p>
* Example with byte:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 11).isCloseTo(Byte.valueOf(10), withinPercentage((byte) 20));
*
* // if difference is exactly equals to the computed offset (1), it's ok
* assertThat((byte) 11).isCloseTo(Byte.valueOf(10), withinPercentage((byte) 10));
*
* // assertion will fail
* assertThat((byte) 11).isCloseTo(Byte.valueOf(10), withinPercentage((byte) 5));</code></pre>
*
* @param expected the given number to compare the actual value to.
* @param percentage the given positive percentage.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws NullPointerException if the expected number is {@code null}.
* @throws AssertionError if the actual value is not close to the given one.
*/
@Override
public SELF isCloseTo(Byte expected, Percentage percentage) {
bytes.assertIsCloseToPercentage(info, actual, expected, percentage);
return myself;
}
/**
* Verifies that the actual number is not close to the given one b the given percentage.<br>
* If difference is equal to the percentage value, the assertion fails.
* <p>
* Example with byte:
* <pre><code class='java'> // assertion will pass:
* assertThat((byte) 11).isNotCloseTo(Byte.valueOf(10), withinPercentage((byte) 5));
*
* // assertions will fail
* assertThat((byte) 11).isNotCloseTo(Byte.valueOf(10), withinPercentage((byte) 10));
* assertThat((byte) 11).isNotCloseTo(Byte.valueOf(10), withinPercentage((byte) 20));</code></pre>
*
* @param expected the given number to compare the actual value to.
* @param percentage the given positive percentage.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws NullPointerException if the expected number is {@code null}.
* @throws AssertionError if the actual value is close to the given one.
* @since 2.6.0 / 3.6.0
*/
@Override
public SELF isNotCloseTo(Byte expected, Percentage percentage) {
bytes.assertIsNotCloseToPercentage(info, actual, expected, percentage);
return myself;
}
/**
* Verifies that the actual number is close to the given one within the given percentage.<br>
* If difference is equal to the percentage value, assertion is considered valid.
* <p>
* Example with byte:
* <pre><code class='java'> // assertions will pass:
* assertThat((byte) 11).isCloseTo((byte) 10, withinPercentage((byte) 20));
*
* // assertions will fail
* assertThat((byte) 11).isCloseTo((byte) 10, withinPercentage((byte) 10));
* assertThat((byte) 11).isCloseTo((byte) 10, withinPercentage((byte) 5));</code></pre>
*
* @param expected the given number to compare the actual value to.
* @param percentage the given positive percentage.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws NullPointerException if the expected number is {@code null}.
* @throws AssertionError if the actual value is close to the given one.
*/
public SELF isCloseTo(byte expected, Percentage percentage) {
bytes.assertIsCloseToPercentage(info, actual, expected, percentage);
return myself;
}
/**
* Verifies that the actual number is not close to the given one by the given percentage.<br>
* If difference is equal to the percentage value, the assertion fails.
* <p>
* Example with byte:
* <pre><code class='java'> // assertion will pass:
* assertThat((byte) 11).isNotCloseTo((byte) 10, withinPercentage((byte) 5));
*
* // assertions will fail
* assertThat((byte) 11).isNotCloseTo((byte) 10, withinPercentage((byte) 10));
* assertThat((byte) 11).isNotCloseTo((byte) 10, withinPercentage((byte) 20));</code></pre>
*
* @param expected the given number to compare the actual value to.
* @param percentage the given positive percentage.
* @return {@code this} assertion object.
* @throws NullPointerException if the given offset is {@code null}.
* @throws NullPointerException if the expected number is {@code null}.
* @throws AssertionError if the actual value is close to the given one.
* @since 2.6.0 / 3.6.0
*/
public SELF isNotCloseTo(byte expected, Percentage percentage) {
bytes.assertIsNotCloseToPercentage(info, actual, expected, percentage);
return myself;
}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super Byte> customComparator) {
return usingComparator(customComparator, null);
}
@Override
@CheckReturnValue
public SELF usingComparator(Comparator<? super Byte> customComparator, String customComparatorDescription) {
this.bytes = new Bytes(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription));
return super.usingComparator(customComparator, customComparatorDescription);
}
@Override
@CheckReturnValue
public SELF usingDefaultComparator() {
this.bytes = Bytes.instance();
return super.usingDefaultComparator();
}
}
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.common.event.tracking.phase.plugin;
import org.spongepowered.common.event.tracking.IPhaseState;
import org.spongepowered.common.event.tracking.TrackingUtil;
import org.spongepowered.common.event.tracking.phase.block.BlockPhaseState;
import org.spongepowered.common.event.tracking.phase.entity.EntityPhaseState;
import org.spongepowered.common.event.tracking.phase.generation.GenerationPhase;
/**
* Used for tasks scheduled with both the Sponge scheduler, and the built-in 'scheduled task' system in MinecraftServer
*/
public class ScheduledTaskPhaseState extends BasicPluginState {
@Override
public BasicPluginContext createPhaseContext() {
return super.createPhaseContext()
.addCaptures();
}
@Override
public boolean canSwitchTo(IPhaseState<?> state) {
return state instanceof BlockPhaseState || state instanceof EntityPhaseState || state == GenerationPhase.State.TERRAIN_GENERATION;
}
@Override
public void unwind(BasicPluginContext phaseContext) {
// TODO - Determine if we need to pass the supplier or perform some parameterized
// process if not empty method on the capture object.
TrackingUtil.processBlockCaptures(this, phaseContext);
}
}
|
public synchronized int executeCommand(Vector<String> pvStatement) throws Exception {
int ret = 0, i = 0;
Statement stmt = null;
String temp = "";
try {
oConexion.setAutoCommit(false);
stmt = oConexion.createStatement();
for (i = 0; i < pvStatement.size(); i++) {
temp = (String) pvStatement.elementAt(i);
ret += stmt.executeUpdate(temp);
}
oConexion.commit();
} catch (SQLException e) {
oConexion.rollback();
throw e;
} finally {
stmt.close();
stmt = null;
}
return ret;
}
|
package rocks.inspectit.ocelot.config.model.instrumentation.rules;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.mockito.Spy;
import rocks.inspectit.ocelot.config.model.InspectitConfig;
import rocks.inspectit.ocelot.config.model.instrumentation.InstrumentationSettings;
import rocks.inspectit.ocelot.config.model.instrumentation.InternalSettings;
import rocks.inspectit.ocelot.config.model.instrumentation.SpecialSensorSettings;
import rocks.inspectit.ocelot.config.model.instrumentation.actions.ActionCallSettings;
import rocks.inspectit.ocelot.config.model.metrics.MetricsSettings;
import rocks.inspectit.ocelot.config.validation.Violation;
import rocks.inspectit.ocelot.config.validation.ViolationBuilder;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
public class InstrumentationRuleSettingsTest {
InspectitConfig root;
InstrumentationSettings instr;
MetricsSettings metrics;
InstrumentationRuleSettings rule;
@Spy
ViolationBuilder vios;
@BeforeEach
void setupDefaultSettings() {
instr = new InstrumentationSettings();
instr.setSpecial(new SpecialSensorSettings());
instr.setInternal(new InternalSettings());
rule = new InstrumentationRuleSettings();
instr.setRules(Maps.newHashMap("my-rule", rule));
metrics = new MetricsSettings();
root = new InspectitConfig();
root.setInstrumentation(instr);
root.setMetrics(metrics);
}
@Nested
class PerformValidation {
@Test
void testNonExistingMetric() {
Map<String, MetricRecordingSettings> metricUsages = new HashMap<>();
metricUsages.put("m123456", MetricRecordingSettings.builder().value("42").build());
rule.setMetrics(metricUsages);
List<Violation> violations = new ArrayList<>();
instr.performValidation(root, new ViolationBuilder(violations));
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getMessage()).containsIgnoringCase("metric");
assertThat(violations.get(0).getParameters().values()).contains("m123456");
}
@Test
void testNonExistingScope() {
rule.setScopes(Collections.singletonMap("my-scope", true));
List<Violation> violations = new ArrayList<>();
instr.performValidation(root, new ViolationBuilder(violations));
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getMessage())
.containsIgnoringCase("scope")
.containsIgnoringCase("exist");
}
@Test
void testNonExistingInclude() {
rule.setInclude(Collections.singletonMap("non-existant-rule", true));
List<Violation> violations = new ArrayList<>();
instr.performValidation(root, new ViolationBuilder(violations));
assertThat(violations).hasSize(1);
assertThat(violations.get(0).getMessage())
.containsIgnoringCase("include")
.containsIgnoringCase("exist");
}
@Test
void ensureAllCallsValidated() {
ActionCallSettings preEntryCall = Mockito.spy(ActionCallSettings.class);
preEntryCall.setAction("someAction");
doNothing().when(preEntryCall).performValidation(any(), any());
ActionCallSettings entryCall = Mockito.spy(ActionCallSettings.class);
entryCall.setAction("someAction");
doNothing().when(entryCall).performValidation(any(), any());
ActionCallSettings postEntryCall = Mockito.spy(ActionCallSettings.class);
postEntryCall.setAction("someAction");
doNothing().when(postEntryCall).performValidation(any(), any());
ActionCallSettings preExitCall = Mockito.spy(ActionCallSettings.class);
preExitCall.setAction("someAction");
doNothing().when(preExitCall).performValidation(any(), any());
ActionCallSettings exitCall = Mockito.spy(ActionCallSettings.class);
exitCall.setAction("someAction");
doNothing().when(exitCall).performValidation(any(), any());
ActionCallSettings postExitCall = Mockito.spy(ActionCallSettings.class);
postExitCall.setAction("someAction");
doNothing().when(postExitCall).performValidation(any(), any());
rule.setPreEntry(Collections.singletonMap("pre_entry_data", preEntryCall));
rule.setEntry(Collections.singletonMap("entry_data", entryCall));
rule.setPostEntry(Collections.singletonMap("post_entry_data", postEntryCall));
rule.setPreExit(Collections.singletonMap("pre_exit_data", preExitCall));
rule.setExit(Collections.singletonMap("exit_data", exitCall));
rule.setPostExit(Collections.singletonMap("exit_data", postExitCall));
List<Violation> violations = new ArrayList<>();
instr.performValidation(root, new ViolationBuilder(violations));
assertThat(violations).hasSize(0);
verify(preEntryCall).performValidation(same(instr), any());
verify(entryCall).performValidation(same(instr), any());
verify(postEntryCall).performValidation(same(instr), any());
verify(preExitCall).performValidation(same(instr), any());
verify(exitCall).performValidation(same(instr), any());
verify(postExitCall).performValidation(same(instr), any());
}
}
}
|
package osmedile.intellij.stringmanip.escaping;
import osmedile.intellij.stringmanip.AbstractStringManipAction;
import java.util.Map;
public class EscapeJsonAction extends AbstractStringManipAction<Object> {
@Override
public String transformByLine(Map<String, Object> actionContext, String s) {
return org.apache.commons.text.StringEscapeUtils.escapeJson(s);
}
}
|
package com.google.codeu.data;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Review {
private final UUID reviewId; //This is the ID of the review
private final long timestamp;
private String author; //The user posting the review
private long rating;
private String comment;
private List<String> pictures;
private final String bookId;
private String bookName;
/**
* Creates a new Review object for every new review for cases when
* the user wants to provide only a rating.
*/
public Review(String author, long rating, String bookId, String bookName) {
this(UUID.randomUUID(), System.currentTimeMillis(), author, rating, "",
new ArrayList<String>(), bookId, bookName);
}
/**
* Creates a new Review object for every new review for cases when
* the user wants to provide a review without any pictures.
*/
public Review(String author, long rating, String comment, String bookId, String bookName) {
this(UUID.randomUUID(), System.currentTimeMillis(), author, rating, comment,
new ArrayList<String>(), bookId, bookName);
}
/**
* Creates a new Review object for every new review for cases when
* the user wants to provide a complete review.
*/
public Review(String author, long rating, String comment,
List<String> pictures, String bookId, String bookName) {
this(UUID.randomUUID(), System.currentTimeMillis(), author, rating, comment,
pictures, bookId, bookName);
}
/**
* Constructor method to retrieve existing data from datastore.
*/
public Review(UUID reviewId, long timestamp, String author, long rating,
String comment, List<String> pictures, String bookId, String bookName) {
this.reviewId = reviewId;
this.author = author;
this.rating = rating;
this.comment = comment;
this.pictures = pictures;
this.timestamp = timestamp;
this.bookId = bookId;
this.bookName = bookName;
}
public UUID getId() {
return reviewId;
}
public long getTimestamp() {
return timestamp;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public long getRating() {
return rating;
}
public void setRating(long rating) {
this.rating = rating;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List<String> getPictures() {
return pictures;
}
public void setPictures(List<String> pictures) {
this.pictures = pictures;
}
public String getBookId() {
return bookId;
}
public String getBookName() {
return bookName;
}
}
|
/**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.kaaproject.kaa.server.common.thrift.gen.cli;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2016-1-19")
public class CommandResult implements org.apache.thrift.TBase<CommandResult, CommandResult._Fields>, java.io.Serializable, Cloneable, Comparable<CommandResult> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CommandResult");
private static final org.apache.thrift.protocol.TField STATUS_FIELD_DESC = new org.apache.thrift.protocol.TField("status", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new CommandResultStandardSchemeFactory());
schemes.put(TupleScheme.class, new CommandResultTupleSchemeFactory());
}
/**
*
* @see CommandStatus
*/
public CommandStatus status; // required
public String message; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
/**
*
* @see CommandStatus
*/
STATUS((short)1, "status"),
MESSAGE((short)2, "message");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // STATUS
return STATUS;
case 2: // MESSAGE
return MESSAGE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.STATUS, new org.apache.thrift.meta_data.FieldMetaData("status", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, CommandStatus.class)));
tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CommandResult.class, metaDataMap);
}
public CommandResult() {
}
public CommandResult(
CommandStatus status,
String message)
{
this();
this.status = status;
this.message = message;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public CommandResult(CommandResult other) {
if (other.isSetStatus()) {
this.status = other.status;
}
if (other.isSetMessage()) {
this.message = other.message;
}
}
public CommandResult deepCopy() {
return new CommandResult(this);
}
@Override
public void clear() {
this.status = null;
this.message = null;
}
/**
*
* @see CommandStatus
*/
public CommandStatus getStatus() {
return this.status;
}
/**
*
* @see CommandStatus
*/
public CommandResult setStatus(CommandStatus status) {
this.status = status;
return this;
}
public void unsetStatus() {
this.status = null;
}
/** Returns true if field status is set (has been assigned a value) and false otherwise */
public boolean isSetStatus() {
return this.status != null;
}
public void setStatusIsSet(boolean value) {
if (!value) {
this.status = null;
}
}
public String getMessage() {
return this.message;
}
public CommandResult setMessage(String message) {
this.message = message;
return this;
}
public void unsetMessage() {
this.message = null;
}
/** Returns true if field message is set (has been assigned a value) and false otherwise */
public boolean isSetMessage() {
return this.message != null;
}
public void setMessageIsSet(boolean value) {
if (!value) {
this.message = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case STATUS:
if (value == null) {
unsetStatus();
} else {
setStatus((CommandStatus)value);
}
break;
case MESSAGE:
if (value == null) {
unsetMessage();
} else {
setMessage((String)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case STATUS:
return getStatus();
case MESSAGE:
return getMessage();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case STATUS:
return isSetStatus();
case MESSAGE:
return isSetMessage();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof CommandResult)
return this.equals((CommandResult)that);
return false;
}
public boolean equals(CommandResult that) {
if (that == null)
return false;
boolean this_present_status = true && this.isSetStatus();
boolean that_present_status = true && that.isSetStatus();
if (this_present_status || that_present_status) {
if (!(this_present_status && that_present_status))
return false;
if (!this.status.equals(that.status))
return false;
}
boolean this_present_message = true && this.isSetMessage();
boolean that_present_message = true && that.isSetMessage();
if (this_present_message || that_present_message) {
if (!(this_present_message && that_present_message))
return false;
if (!this.message.equals(that.message))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_status = true && (isSetStatus());
list.add(present_status);
if (present_status)
list.add(status.getValue());
boolean present_message = true && (isSetMessage());
list.add(present_message);
if (present_message)
list.add(message);
return list.hashCode();
}
@Override
public int compareTo(CommandResult other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetStatus()).compareTo(other.isSetStatus());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetStatus()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.status, other.status);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetMessage()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("CommandResult(");
boolean first = true;
sb.append("status:");
if (this.status == null) {
sb.append("null");
} else {
sb.append(this.status);
}
first = false;
if (!first) sb.append(", ");
sb.append("message:");
if (this.message == null) {
sb.append("null");
} else {
sb.append(this.message);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class CommandResultStandardSchemeFactory implements SchemeFactory {
public CommandResultStandardScheme getScheme() {
return new CommandResultStandardScheme();
}
}
private static class CommandResultStandardScheme extends StandardScheme<CommandResult> {
public void read(org.apache.thrift.protocol.TProtocol iprot, CommandResult struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // STATUS
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.status = org.kaaproject.kaa.server.common.thrift.gen.cli.CommandStatus.findByValue(iprot.readI32());
struct.setStatusIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // MESSAGE
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.message = iprot.readString();
struct.setMessageIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, CommandResult struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.status != null) {
oprot.writeFieldBegin(STATUS_FIELD_DESC);
oprot.writeI32(struct.status.getValue());
oprot.writeFieldEnd();
}
if (struct.message != null) {
oprot.writeFieldBegin(MESSAGE_FIELD_DESC);
oprot.writeString(struct.message);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class CommandResultTupleSchemeFactory implements SchemeFactory {
public CommandResultTupleScheme getScheme() {
return new CommandResultTupleScheme();
}
}
private static class CommandResultTupleScheme extends TupleScheme<CommandResult> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, CommandResult struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetStatus()) {
optionals.set(0);
}
if (struct.isSetMessage()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetStatus()) {
oprot.writeI32(struct.status.getValue());
}
if (struct.isSetMessage()) {
oprot.writeString(struct.message);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, CommandResult struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.status = org.kaaproject.kaa.server.common.thrift.gen.cli.CommandStatus.findByValue(iprot.readI32());
struct.setStatusIsSet(true);
}
if (incoming.get(1)) {
struct.message = iprot.readString();
struct.setMessageIsSet(true);
}
}
}
}
|
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------
* DatasetReader.java
* ------------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 20-Nov-2002 : Version 1 (DG);
*
*/
package org.jfree.data.xml;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.PieDataset;
import org.xml.sax.SAXException;
/**
* A utility class for reading datasets from XML.
*/
public class DatasetReader {
/**
* Reads a {@link PieDataset} from an XML file.
*
* @param file the file.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static PieDataset readPieDatasetFromXML(File file)
throws IOException {
InputStream in = new FileInputStream(file);
return readPieDatasetFromXML(in);
}
/**
* Reads a {@link PieDataset} from a stream.
*
* @param in the input stream.
*
* @return A dataset.
*
* @throws IOException if there is an I/O error.
*/
public static PieDataset readPieDatasetFromXML(InputStream in)
throws IOException {
PieDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
PieDatasetHandler handler = new PieDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
/**
* Reads a {@link CategoryDataset} from a file.
*
* @param file the file.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(File file)
throws IOException {
InputStream in = new FileInputStream(file);
return readCategoryDatasetFromXML(in);
}
/**
* Reads a {@link CategoryDataset} from a stream.
*
* @param in the stream.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(InputStream in)
throws IOException {
CategoryDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
}
|
package odms.bridge;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javafx.application.Platform;
import odms.commons.model.Disease;
import odms.commons.model.MedicalProcedure;
import odms.commons.model.User;
import odms.commons.model._enum.Organs;
import odms.commons.model.datamodel.ComboBoxClinician;
import odms.commons.model.datamodel.Medication;
import odms.commons.model.datamodel.ReceiverOrganDetailsHolder;
import odms.commons.model.dto.CollectionCountsTransferObject;
import odms.commons.model.dto.UserOverview;
import odms.commons.utils.Log;
import odms.commons.utils.PhotoHelper;
import odms.controller.AppController;
import odms.controller.gui.popup.utils.AlertWindowFactory;
import odms.controller.gui.widget.CountableLoadingWidget;
import okhttp3.*;
import java.io.IOException;
import java.util.*;
public class UserBridge extends RoleBridge {
private static final String USERS = "/users/";
private static final String FAILED_TO_PUT_TO = "Failed to PUT to ";
public static final String COULD_NOT_MAKE_A_CALL_TO = "Could not make a call to ";
private static final String FAILED_TO_POST_TO = "Failed to POST to ";
public UserBridge(OkHttpClient client) {
super(client);
}
public void getUsers(int startIndex, int count, String name, String region, String gender, String token, CountableLoadingWidget tableview) {
String url = ip + "/users?startIndex=" + startIndex + "&count=" + count + "&name=" + name + "®ion=" + region + "&gender=" + gender;
Request request = new Request.Builder().header(tokenHeader, token).url(url).tag("Tag").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Platform.runLater(() -> AlertWindowFactory.generateError("Users:" + e));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
CollectionCountsTransferObject<UserOverview> result = new Gson().fromJson(response.body().string(), new TypeToken<CollectionCountsTransferObject<UserOverview>>() {
}.getType());
Collection<UserOverview> overviews = result.getCollection();
AppController.getInstance().getUserOverviews().clear();
AppController.getInstance().addUserOverviews(overviews);
if (tableview != null) {
Platform.runLater(() -> {
if (overviews.isEmpty()) tableview.setWaiting(false);
tableview.setCount(result.getTotalCount());
});
}
response.close();
}
});
}
public void postUser(User user) {
String url = ip + USERS;
RequestBody requestBody = RequestBody.create(json, new Gson().toJson(user));
Request request = new Request.Builder().post(requestBody).url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not make the call to POST /users");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Failed to make POST call to /users code: " + response.code());
}
response.close();
}
});
}
public void postUserSilently(User user) {
String url = ip + "/usersSilent/";
RequestBody requestBody = RequestBody.create(json, new Gson().toJson(user));
Request request = new Request.Builder().post(requestBody).url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not make the call to POST /users");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Failed to make POST call to /users");
}
response.close();
}
});
}
public User getUser(String nhi) throws IOException {
User toReturn;
String url = ip + USERS + nhi;
Request request = new Request.Builder().url(url).build();
try {
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
toReturn = handler.decodeUser(response);
toReturn.setProfilePhotoFilePath(getProfilePicture(nhi));
} else {
toReturn = null;
}
}
} catch (IOException ex) {
Log.warning("Could not make GET call to /users/" + nhi, ex);
throw ex;
}
return toReturn;
}
public void putUser(User user, String nhi) {
String url = ip + USERS + nhi;
RequestBody body = RequestBody.create(json, new Gson().toJson(user));
Request request = new Request.Builder().url(url).put(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not PUT to " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_PUT_TO + url + " Response code: " + response.code());
}
response.close();
}
});
}
public void deleteUser(User user) {
String url = ip + USERS + user.getNhi();
Request request = new Request.Builder().url(url).delete().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not DELETE " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Failed to DELETE to " + url);
}
response.close();
}
});
}
public void postUserProcedures(MedicalProcedure procedure, String nhi, String token) {
String url = ip + USERS + nhi + "/procedures";
RequestBody body = RequestBody.create(json, new Gson().toJson(procedure));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not POST procedures to " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Failed to POST procedures to " + url);
}
response.close();
}
});
}
public void putUserProcedures(List<MedicalProcedure> procedures, String nhi, String token) {
String url = ip + USERS + nhi + "/procedures";
RequestBody body = RequestBody.create(json, new Gson().toJson(procedures));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).put(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not PUT procedures to " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_PUT_TO + url);
}
response.close();
}
});
}
public void postMedications(Medication medication, String nhi, String token) {
String url = ip + USERS + nhi + "/medications";
RequestBody body = RequestBody.create(json, new Gson().toJson(medication));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not POST procedures to " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_POST_TO + url);
}
response.close();
}
});
}
public void putMedications(List<Medication> medications, String nhi, String token) {
String url = ip + USERS + nhi + "/medications";
RequestBody body = RequestBody.create(json, new Gson().toJson(medications));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).put(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not PUT medications to " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_PUT_TO + url);
}
response.close();
}
});
}
public void postDiseases(Disease disease, String nhi, String token) {
String url = ip + USERS + nhi + "/diseases";
RequestBody body = RequestBody.create(json, new Gson().toJson(disease));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not POST diseases to " + url);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_POST_TO + url);
}
response.close();
}
});
}
public void putDiseases(List<Disease> diseases, String nhi, String token) {
String url = ip + USERS + nhi + "/diseases";
RequestBody body = RequestBody.create(json, new Gson().toJson(diseases));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).put(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not PUT to " + url);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException(FAILED_TO_PUT_TO + url);
}
response.close();
}
});
}
public void postReceivingOrgans(Map<Organs, ArrayList<ReceiverOrganDetailsHolder>> receiving, String nhi, String token) {
String url = ip + USERS + nhi + "/receiving";
RequestBody body = RequestBody.create(json, new Gson().toJson(receiving));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).post(body).build();
client.newCall(request).enqueue(CommonMethods.loggedCallback("POST", url));
}
public void putReceivingOrgans(Map<Organs, ArrayList<ReceiverOrganDetailsHolder>> receiving, String nhi, String token) {
String url = ip + USERS + nhi + "/receiving";
RequestBody body = RequestBody.create(json, new Gson().toJson(receiving));
Request request = new Request.Builder().url(url).addHeader(tokenHeader, token).put(body).build();
client.newCall(request).enqueue(CommonMethods.loggedCallback("PUT", url));
}
public void postDonatingOrgans(Set<Organs> donating, String nhi) {
String url = ip + USERS + nhi + "/donating";
RequestBody body = RequestBody.create(json, new Gson().toJson(donating));
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(CommonMethods.loggedCallback("POST", url));
}
public void putDonatingOrgans(Set<Organs> donating, String nhi) {
String url = ip + USERS + nhi + "/donating";
RequestBody body = RequestBody.create(json, new Gson().toJson(donating));
Request request = new Request.Builder().url(url).put(body).build();
client.newCall(request).enqueue(CommonMethods.loggedCallback("PUT", url));
}
public String getProfilePicture(String nhi) throws IOException {
String url = ip + USERS + nhi + "/photo";
Request request = new Request.Builder().get().url(url).build();
try(Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String contentType = response.header("Content-Type");
String[] bits = contentType.split("/");
String format = bits[bits.length-1];
return handler.decodeProfilePicture(response.body(), nhi, format);
} else if(response.code() == 404){
return null;
} else {
throw new IOException("Failed to get profile picture");
}
}
}
public void putProfilePicture(String nhi, String profilePicturePath) throws IOException {
String url = ip + USERS + nhi + "/photo";
String[] bits = profilePicturePath.split("\\.");
String format = bits[bits.length-1];
byte[] bytesFromImage = PhotoHelper.getBytesFromImage(profilePicturePath);
if(bytesFromImage.length == 0){
return;
}
RequestBody body = RequestBody.create(MediaType.parse("image/"+format), bytesFromImage);
Request request = new Request.Builder().url(url).put(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.warning("Could not PUT " + url, e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()) {
Log.warning("Failed to PUT " + url + " Response code: " + response.code());
throw new IOException("Could not PUT " + url);
}
response.close();
}
});
}
/**
* checks whether a user can be found in the database
* @param nhi nhi of the user to search for
* @return true if the user can be found, false otherwise
*/
public boolean getExists(String nhi) {
Request request = new Request.Builder().get().url(ip + "/users/exists/" + nhi).build();
try (Response res = client.newCall(request).execute()) {
return res.body().string().equalsIgnoreCase("true");
} catch (NullPointerException | IOException ex) {
Log.warning("could not determine if the admin exists", ex);
return false;
}
}
/**
* Asks the server to get the preferred clinician for the specified user
* @param nhi of the user to get the preferred clinician for.
* @return comboBoxClinician representing the preferred clinician
* @throws IOException if the call cannot be made
*/
public ComboBoxClinician getPreferredClinician(String nhi) throws IOException{
ComboBoxClinician clinician = null;
String url = ip + USERS + nhi + "/preferred-clinician";
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body == null) {
Log.warning("The response body was null");
response.close();
return null;
}
if (body.contentLength() == 2) { //if it returns empty array
response.close();
return null;
}
clinician = new Gson().fromJson(body.string(), new TypeToken<ComboBoxClinician>() {
}.getType());
}
response.close();
return clinician;
}
/**
* Updates the preferred clinician of the user
* @param nhi of the user to get the preferred clinician for.
* @param staffId the id of the preferred clinician
*/
public void putPreferredClinician(String nhi, String staffId) {
String url = ip + USERS + nhi + "/preferred-clinician";
RequestBody body = RequestBody.create(json, new Gson().toJson(staffId));
Request request = new Request.Builder().put(body).url(url).build();
client.newCall(request).enqueue(CommonMethods.loggedCallback("PUT", url));
}
}
|
package live.thought.scatterbrain;
import static org.junit.Assert.*;
import org.junit.Test;
public class PrivateKeyTest
{
@Test
public void test()
{
PrivateKey testKey = new PrivateKey(false);
assertNotNull(testKey);
System.out.println(testKey);
}
}
|
/**
* Trust Payments SDK
*
* This library allows to interact with the Trust Payments payment service.
*
* 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.trustpayments.sdk.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.trustpayments.sdk.model.EntityQuery;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
import java.time.OffsetDateTime;
/**
* The entity property export request contains the information required to create an export of a list of entities.
*/
@ApiModel(description = "The entity property export request contains the information required to create an export of a list of entities.")
public class EntityExportRequest {
@JsonProperty("properties")
protected List<String> properties = new ArrayList<>();
@JsonProperty("query")
protected EntityQuery query = null;
public EntityExportRequest properties(List<String> properties) {
this.properties = properties;
return this;
}
public EntityExportRequest addPropertiesItem(String propertiesItem) {
this.properties.add(propertiesItem);
return this;
}
/**
* The properties is a list of property paths which should be exported.
* @return properties
**/
@ApiModelProperty(required = true, value = "The properties is a list of property paths which should be exported.")
public List<String> getProperties() {
return properties;
}
public void setProperties(List<String> properties) {
this.properties = properties;
}
public EntityExportRequest query(EntityQuery query) {
this.query = query;
return this;
}
/**
* The query limits the returned entries. The query allows to restrict the entries to return and it allows to control the order of them.
* @return query
**/
@ApiModelProperty(value = "The query limits the returned entries. The query allows to restrict the entries to return and it allows to control the order of them.")
public EntityQuery getQuery() {
return query;
}
public void setQuery(EntityQuery query) {
this.query = query;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EntityExportRequest entityExportRequest = (EntityExportRequest) o;
return Objects.equals(this.properties, entityExportRequest.properties) &&
Objects.equals(this.query, entityExportRequest.query);
}
@Override
public int hashCode() {
return Objects.hash(properties, query);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EntityExportRequest {\n");
sb.append(" properties: ").append(toIndentedString(properties)).append("\n");
sb.append(" query: ").append(toIndentedString(query)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package payne.framework.pigeon.core;
import payne.framework.pigeon.core.exception.TaskExecuteException;
import payne.framework.pigeon.core.exception.TaskRevokeException;
public interface Task {
void execute() throws TaskExecuteException;
void revoke() throws TaskRevokeException;
}
|
package com.pacoworks.cardframework.api.model.conditions;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.pacoworks.cardframework.api.CFWContext;
import com.pacoworks.cardframework.api.model.values.ICFWValue;
import lombok.ToString;
import javax.annotation.Generated;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"type", "left", "right"
})
@ToString
public class NotEqualsCondition extends CFWCondition {
public static final String CONDITION_NAME = "not_equals";
@JsonProperty("left")
private ICFWValue left;
@JsonProperty("right")
private ICFWValue right;
/**
* @return The left
*/
@JsonProperty("left")
public ICFWValue getLeft() {
return left;
}
/**
* @param left The left
*/
@JsonProperty("left")
public void setLeft(ICFWValue left) {
this.left = left;
}
/**
* @return The right
*/
@JsonProperty("right")
public ICFWValue getRight() {
return right;
}
/**
* @param right The right
*/
@JsonProperty("right")
public void setRight(ICFWValue right) {
this.right = right;
}
@Override
public boolean getResult(CFWContext cfwContext) {
if (left == null || right == null) {
return false;
}
return left.getValue(cfwContext) != right.getValue(cfwContext);
}
}
|
package knokko.rpg.entity.data;
import java.util.ArrayList;
import java.util.List;
import knokko.rpg.data.WorldData;
import knokko.rpg.entity.creature.EntityEye;
import knokko.rpg.entity.creature.EntityMonkey;
import knokko.util.EntityUtils;
import knokko.util.ExtraUtils;
import knokko.util.Position;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
public class EntityMonkeyGroupData extends EntityData{
public EntityMonkeyGroupData(World world) {
super(world);
WorldData.get(worldObj).monkeyTeams.add(this);
}
public EntityMonkey leader;
public String leaderId;
public List targets = new ArrayList();
public List targetIds = new ArrayList();
public void onUpdate(){
if(targetIds.size() > 0){
String id = (String) targetIds.get(targetIds.size() - 1);
Entity entity = EntityUtils.getEntityByUUID(worldObj, id);
if(entity instanceof EntityLivingBase){
targets.add(entity);
targetIds.remove(id);
}
}
if(targets != null && !targets.isEmpty() && ExtraUtils.divineAccurate(ticksExisted, 10) == ticksExisted / 10){
int times = 0;
while(times < targets.size()){
EntityLivingBase target = (EntityLivingBase) targets.get(times);
if(target == null){
targets.remove(target);
}
if(target != null && target.isDead){
targets.remove(target);
}
++times;
}
}
if(leader == null && !worldObj.isRemote){
if(leaderId != null && !leaderId.isEmpty()){
leader = (EntityMonkey) EntityUtils.getEntityByUUID(worldObj, leaderId);
}
else {
leader = (EntityMonkey) worldObj.findNearestEntityWithinAABB(EntityMonkey.class, AxisAlignedBB.getBoundingBox(posX - 64, posY - 64, posZ - 64, posX + 64, posY + 64, posZ + 64), this);
}
if(ticksExisted > 40){
setDead();
}
}
if(leader != null){
setPosition(leader.posX, leader.posY, leader.posZ);
if(leader.isDead){
leader = null;
leaderId = null;
ticksExisted = 0;
}
}
}
@Override
protected void entityInit() {
}
@Override
public void readEntityFromNBT(NBTTagCompound nbt) {
int times = 0;
while(nbt.hasKey("target" + times)){
targetIds.add(nbt.getString("target" + times));
++times;
}
leaderId = nbt.getString("leader");
WorldData.get(worldObj).monkeyTeams.add(this);
}
@Override
public void writeEntityToNBT(NBTTagCompound nbt) {
int times = 0;
while(times < targets.size()){
EntityLivingBase entity = (EntityLivingBase) targets.get(times);
nbt.setString("target" + times, entity.getUniqueID().toString());
++times;
}
if(leader != null){
nbt.setString("leader", leader.getUniqueID().toString());
}
}
}
|
package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.SmaliTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestArithNot extends SmaliTest {
/*
Smali Code equivalent:
public static class TestCls {
public int test1(int a) {
return ~a;
}
public long test2(long b) {
return ~b;
}
}
*/
@Test
public void test() {
ClassNode cls = getClassNodeFromSmaliWithPath("arith", "TestArithNot");
String code = cls.getCode().toString();
assertThat(code, containsString("return ~a;"));
assertThat(code, containsString("return ~b;"));
assertThat(code, not(containsString("^")));
}
}
|
package org.jeecg.modules.shiro.authc.aop;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.jeecg.modules.shiro.authc.JwtToken;
import org.jeecg.modules.shiro.vo.DefContants;
import org.jeecg.modules.system.util.TenantContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import lombok.extern.slf4j.Slf4j;
/**
* @Description: 鉴权登录拦截器
* @Author: Scott
* @Date: 2018/10/7
**/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {
/**
* 执行登录认证
*
* @param request
* @param response
* @param mappedValue
* @return
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
try {
executeLogin(request, response);
return true;
} catch (Exception e) {
throw new AuthenticationException("Token失效,请重新登录", e);
}
}
/**
*
*/
@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader(DefContants.X_ACCESS_TOKEN);
JwtToken jwtToken = new JwtToken(token);
// 提交给realm进行登入,如果错误他会抛出异常并被捕获
getSubject(request, response).login(jwtToken);
// 如果没有抛出异常则代表登入成功,返回true
return true;
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
// 是否允许发送Cookie,默认Cookie不包括在CORS请求之中。设为true时,表示服务器允许Cookie包含在请求中。
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
// 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
//update-begin-author:taoyan date:20200708 for:多租户用到
String tenant_id = httpServletRequest.getHeader(DefContants.TENANT_ID);
TenantContext.setTenant(tenant_id);
//update-end-author:taoyan date:20200708 for:多租户用到
return super.preHandle(request, response);
}
}
|
/**
* Copyright (C) 2009 Aisino Corporation Inc.
*
* No.18A, Xingshikou street, Haidian District,Beijing
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Aisino Corporation Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Aisino.
*/
package org.amote.client;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.gmote.common.packet.AbstractPacket;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import android.widget.Gallery.LayoutParams;
/**
* Game Activity.
* @author aisino
*
*/
public class ImageBrowser extends Activity implements BaseActivity,
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
ActivityUtil mUtil = null;
ProgressDialog mDialog = null;
Gallery mGallery = null;
List<String> mImages = null;
//Map<Integer, Drawable> imageCache = new HashMap<Integer, Drawable>();
@Override
public void onCreate(Bundle icicle) {
System.out.println("ImageBrowser");
super.onCreate(icicle);
mUtil = new ActivityUtil();
mUtil.onCreate(icicle, this);
Intent intent = getIntent();
mImages = intent
.getStringArrayListExtra(getString(R.string.gmote_stream_playlist));
setContentView(R.layout.image_browser);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setSelection(intent.getIntExtra(getString(R.string.file_type), 0), false);
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// super.onCreateOptionsMenu(menu);
// mUtil.onCreateOptionsMenu(menu);
//
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// super.onOptionsItemSelected(item);
// return mUtil.onOptionsItemSelected(item);
// }
@Override
protected Dialog onCreateDialog(int id) {
return mUtil.onCreateDialog(id);
}
@Override
public void onStart() {
super.onStart();
mUtil.onStart(this);
}
@Override
public void onStop() {
super.onStop();
mUtil.onStop();
}
@Override
public void onResume() {
super.onResume();
mUtil.onResume();
}
@Override
public void onPause() {
super.onPause();
mUtil.onPause();
}
public void handleReceivedPacket(AbstractPacket reply) {
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageDrawable(((ImageView)v).getDrawable());
}
public Drawable getDrawable(int position) {
return new BitmapDrawable(getBitmap(position));
}
public Bitmap getBitmap(int position) {
Bitmap bitmap = null;
try {
URL aURL = new URL(mImages.get(position) + "?sessionId=" + getSessionId());
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
bitmap = bm;
} catch (IOException e) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.image_viewer);
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return bitmap;
}
private String getSessionId() {
Remote remote = Remote.getInstance();
return remote.getSessionId();
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
i.setFocusable(false);
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageDrawable(getDrawable(position));
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
return i;
}
private Context mContext;
}
}
|
package org.open.source.factory.mapper.dao;
import org.open.source.factory.mapper.AbstractMapper;
import org.open.source.model.Line;
import org.open.source.model.ViewObject;
import org.open.source.util.FormatHelper;
import java.util.ArrayList;
import java.util.List;
/**
* @author tianbo
* @date 2018-06-26 Tuesday 10:28 根据create table生成空的DAO类
*/
public class SqlToDAOMapper extends AbstractMapper {
@Override
public ViewObject decorate(ViewObject viewObject) {
ViewObject result = new ViewObject();
List<Line> lines = new ArrayList<>();
// TABLE NAME定义
lines.add(new Line().setType("String").setName("TABLE_NAME = \"" + FormatHelper.formatToTableName
(viewObject.getObjectName()) + "\""));
// INSERT COLUMNS
lines.add(new Line().setType("String").setName("INSERT_COLUMNS = \"" + FormatHelper.formatToInsertColumns
(viewObject.getLines()) + "\""));
// SELECT COLUMNS
lines.add(new Line().setType("String").setName("SELECT_COLUMNS = \"" + FormatHelper.formatToSelectColumns
(viewObject.getLines()) + "\""));
// INSERT VALUES
lines.add(new Line().setType("String").setName("INSERT_VALUES = \"" + FormatHelper.formatToInsertValues
(viewObject.getLines()) + "\""));
// UPDATE COLUMNS
lines.add(new Line().setType("String").setName("UPDATE_COLUMNS = \"" + FormatHelper.formatToUpdateColumns
(viewObject.getLines()) + "\""));
result.setObjectName(FormatHelper.convert2UpperCamel(viewObject.getObjectName()) + "DAO");
result.setLines(lines);
return result;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.itest.springboot;
import org.apache.camel.itest.springboot.util.ArquillianPackager;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(ArquillianExtension.class)
public class CamelRssTest extends AbstractSpringBootTestSupport {
@Deployment
public static Archive<?> createSpringBootPackage() throws Exception {
return ArquillianPackager.springBootPackage(createTestConfig());
}
public static ITestConfig createTestConfig() {
return new ITestConfigBuilder()
.module(inferModuleName(CamelRssTest.class))
.build();
}
@Test
public void componentTests() throws Exception {
this.runComponentTest(config);
this.runModuleUnitTestsIfEnabled(config);
}
}
|
package api.longpoll.bots.model.objects.additional;
import com.google.gson.annotations.SerializedName;
/**
* Describes price.
*
* @see <a href="https://vk.com/dev/price">Price</a>
*/
public class Price {
/**
* Integer price value multiplied by 100.
*/
@SerializedName("amount")
private Integer amount;
/**
* Price currency.
*/
@SerializedName("currency")
private Currency currency;
/**
* Localized price and currency.
*/
@SerializedName("text")
private String text;
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "Price{" +
"amount=" + amount +
", currency=" + currency +
", text='" + text + '\'' +
'}';
}
}
|
package com.virtualpairprogrammers.staffmanagement.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.virtualpairprogrammers.staffmanagement.domain.StaffRecord;
import com.virtualpairprogrammers.staffmanagement.services.ExternalDriverMonitoringSystem;
import com.virtualpairprogrammers.staffmanagement.services.StaffService;
@RestController
public class StaffManagementController {
@Autowired
private StaffService staffService;
@Autowired
private ExternalDriverMonitoringSystem externalDriverMonitoringSystem;
@RequestMapping(method=RequestMethod.GET, value="/driver/{vehicleName}", produces="application/json")
public ResponseEntity<StaffRecord> getDriverAssignedTo(@PathVariable String vehicleName)
{
try {
return new ResponseEntity<StaffRecord>(staffService.getDriverDetailsFor(vehicleName), HttpStatus.OK);
}
catch (Exception e)
{
return new ResponseEntity<>(HttpStatus.BAD_GATEWAY);
}
}
// See case #22 for details of this odd design...
@RequestMapping(method=RequestMethod.POST, value="/driver/{vehicleName}/{speed}")
public void updateSpeedLogFor(@PathVariable String vehicleName, @PathVariable String speed)
{
StaffRecord driverDetails = this.getDriverAssignedTo(vehicleName).getBody();
externalDriverMonitoringSystem.updateSpeedLogFor(driverDetails.getName(), speed);
}
}
|
/*
* 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.directory.server.core.api.entry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
/**
* Unit tests class ClonedServerEntry.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
@Execution(ExecutionMode.CONCURRENT)
public class ClonedServerEntryTest
{
private static Entry clonedServerEntryA;
private static Entry clonedServerEntryACopy;
private static Entry clonedServerEntryB;
private static Entry clonedServerEntryA1;
private static Entry clonedServerEntryACopy1;
private static Entry clonedServerEntryB1;
private static Entry clonedServerEntryC1;
/**
* Initialize name instances
*/
@BeforeAll
public static void initNames() throws Exception
{
Entry eA = new DefaultEntry( "dc=example,dc=com" );
Entry eB = new DefaultEntry( "dc=example,dc=com" );
Entry eC = new DefaultEntry( "dc=test,dc=org" );
clonedServerEntryA = new ClonedServerEntry();
clonedServerEntryACopy = new ClonedServerEntry();
clonedServerEntryB = new ClonedServerEntry();
clonedServerEntryA1 = new ClonedServerEntry( eA );
clonedServerEntryACopy1 = new ClonedServerEntry( eA );
clonedServerEntryB1 = new ClonedServerEntry( eB );
clonedServerEntryC1 = new ClonedServerEntry( eC );
}
@Test
public void testEqualsNull() throws Exception
{
assertFalse( clonedServerEntryA.equals( null ) );
assertFalse( clonedServerEntryA1.equals( null ) );
}
@Test
public void testEqualsReflexive() throws Exception
{
assertEquals( clonedServerEntryA, clonedServerEntryA );
assertEquals( clonedServerEntryA1, clonedServerEntryA1 );
}
@Test
public void testHashCodeReflexive() throws Exception
{
assertEquals( clonedServerEntryA.hashCode(), clonedServerEntryA.hashCode() );
assertEquals( clonedServerEntryA1.hashCode(), clonedServerEntryA1.hashCode() );
}
@Test
public void testEqualsSymmetric() throws Exception
{
assertEquals( clonedServerEntryA, clonedServerEntryACopy );
assertEquals( clonedServerEntryACopy, clonedServerEntryA );
assertEquals( clonedServerEntryA1, clonedServerEntryACopy1 );
assertEquals( clonedServerEntryACopy1, clonedServerEntryA1 );
}
@Test
public void testHashCodeSymmetric() throws Exception
{
assertEquals( clonedServerEntryA.hashCode(), clonedServerEntryACopy.hashCode() );
assertEquals( clonedServerEntryACopy.hashCode(), clonedServerEntryA.hashCode() );
assertEquals( clonedServerEntryA1.hashCode(), clonedServerEntryACopy1.hashCode() );
assertEquals( clonedServerEntryACopy1.hashCode(), clonedServerEntryA1.hashCode() );
}
@Test
public void testEqualsTransitive() throws Exception
{
assertEquals( clonedServerEntryA, clonedServerEntryACopy );
assertEquals( clonedServerEntryACopy, clonedServerEntryB );
assertEquals( clonedServerEntryA, clonedServerEntryB );
assertEquals( clonedServerEntryA1, clonedServerEntryACopy1 );
assertEquals( clonedServerEntryACopy1, clonedServerEntryB1 );
assertEquals( clonedServerEntryA1, clonedServerEntryB1 );
}
@Test
public void testHashCodeTransitive() throws Exception
{
assertEquals( clonedServerEntryA.hashCode(), clonedServerEntryACopy.hashCode() );
assertEquals( clonedServerEntryACopy.hashCode(), clonedServerEntryB.hashCode() );
assertEquals( clonedServerEntryA.hashCode(), clonedServerEntryB.hashCode() );
assertEquals( clonedServerEntryA1.hashCode(), clonedServerEntryACopy1.hashCode() );
assertEquals( clonedServerEntryACopy1.hashCode(), clonedServerEntryB1.hashCode() );
assertEquals( clonedServerEntryA1.hashCode(), clonedServerEntryB1.hashCode() );
}
@Test
public void testNotEqualDiffValue() throws Exception
{
assertFalse( clonedServerEntryA1.equals( clonedServerEntryC1 ) );
assertFalse( clonedServerEntryC1.equals( clonedServerEntryA1 ) );
}
}
|
/**
* Copyright (c) 2009-2019, Yegor Bugayenko
* 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 rultor.com 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 com.rultor;
import co.stateful.RtSttc;
import co.stateful.Sttc;
import co.stateful.cached.CdSttc;
import co.stateful.retry.ReSttc;
import com.google.common.collect.EvictingQueue;
import com.jcabi.aspects.Cacheable;
import com.jcabi.aspects.LogExceptions;
import com.jcabi.aspects.Tv;
import com.jcabi.dynamo.Credentials;
import com.jcabi.dynamo.Region;
import com.jcabi.dynamo.retry.ReRegion;
import com.jcabi.github.Github;
import com.jcabi.github.RtGithub;
import com.jcabi.github.mock.MkGithub;
import com.jcabi.github.wire.RetryCarefulWire;
import com.jcabi.log.Logger;
import com.jcabi.manifests.Manifests;
import com.jcabi.urn.URN;
import com.rultor.cached.CdTalks;
import com.rultor.dynamo.DyTalks;
import com.rultor.spi.Pulse;
import com.rultor.spi.Talks;
import com.rultor.spi.Tick;
import com.rultor.web.TkApp;
import io.sentry.Sentry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.takes.http.Exit;
import org.takes.http.FtCli;
/**
* Command line entry.
*
* @author Yegor Bugayenko (yegor256@gmail.com)
* @version $Id: 7931eddbb72858f039085149783887ee1f8f9122 $
* @since 1.50
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
@SuppressWarnings("PMD.ExcessiveImports")
public final class Entry {
/**
* Arguments.
*/
private final transient Iterable<String> arguments;
/**
* Ctor.
* @param args Command line args
*/
public Entry(final String... args) {
this.arguments = Arrays.asList(args);
}
/**
* Main entry point.
* @param args Arguments
* @throws IOException If fails
*/
@LogExceptions
public static void main(final String... args) throws IOException {
Logger.info(Entry.class, "Starting Rultor on the command line...");
new Entry(args).exec();
}
/**
* Run it all.
* @throws IOException If fails
*/
public void exec() throws IOException {
final String dsn = Manifests.read("Rultor-SentryDsn");
if (!dsn.startsWith("test")) {
Sentry.init(dsn);
}
final Talks talks = new CdTalks(
new DyTalks(
this.dynamo(), this.sttc().counters().get("rt-talk")
)
);
Logger.info(this, "Starting the Routine...");
final Routine routine = new Routine(
talks, Entry.pulse(), this.github(), this.sttc()
);
Logger.info(this, "Starting the web front to run forever...");
try {
new FtCli(
new TkApp(talks, Entry.pulse(), new Toggles.InFile()),
this.arguments
).start(Exit.NEVER);
} finally {
routine.close();
}
}
/**
* Make github.
* @return Github
* @throws IOException If fails
*/
@Cacheable(forever = true)
private Github github() throws IOException {
Logger.info(this, "Connecting GitHub...");
final String token = Manifests.read("Rultor-GithubToken");
final Github github;
if (token.startsWith("${")) {
github = new MkGithub();
} else {
github = new RtGithub(
new RtGithub(token).entry().through(
RetryCarefulWire.class,
Tv.HUNDRED
)
);
}
Logger.info(this, "GitHub object instantiated...");
Logger.info(
this, "GitHub connected as @%s",
github.users().self().login()
);
return github;
}
/**
* Sttc.
* @return Sttc
*/
@Cacheable(forever = true)
private Sttc sttc() {
Logger.info(this, "Connecting Sttc...");
final Sttc sttc = new CdSttc(
new ReSttc(
RtSttc.make(
URN.create(Manifests.read("Rultor-SttcUrn")),
Manifests.read("Rultor-SttcToken")
)
)
);
Logger.info(this, "Sttc connected as %s", sttc);
return sttc;
}
/**
* Dynamo DB region.
* @return Region
*/
@Cacheable(forever = true)
private Region dynamo() {
Logger.info(this, "Connecting DynamoDB...");
final String key = Manifests.read("Rultor-DynamoKey");
Credentials creds = new Credentials.Simple(
key,
Manifests.read("Rultor-DynamoSecret")
);
if (key.startsWith("AAAAA")) {
final int port = Integer.parseInt(
System.getProperty("dynamo.port")
);
creds = new Credentials.Direct(creds, port);
Logger.warn(this, "test DynamoDB at port #%d", port);
}
Logger.info(this, "DynamoDB connected as %s", key);
return new Region.Prefixed(
new ReRegion(new Region.Simple(creds)), "rt-"
);
}
/**
* Create pulse.
* @return Pulse
*/
@Cacheable(forever = true)
private static Pulse pulse() {
final Collection<Tick> ticks = Collections.synchronizedCollection(
EvictingQueue.<Tick>create((int) TimeUnit.HOURS.toMinutes(1L))
);
final Collection<Throwable> error = Collections.synchronizedCollection(
new ArrayList<Throwable>(1)
);
// @checkstyle AnonInnerLengthCheck (50 lines)
return new Pulse() {
@Override
public void add(final Tick tick) {
ticks.add(tick);
}
@Override
public Iterable<Tick> ticks() {
return Collections.unmodifiableCollection(ticks);
}
@Override
public Iterable<Throwable> error() {
return Collections.unmodifiableCollection(error);
}
@Override
public void error(final Iterable<Throwable> errors) {
error.clear();
for (final Throwable err : errors) {
error.add(err);
}
}
};
}
}
|
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.go.server.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.GoConfigFileDao;
import com.thoughtworks.go.domain.ArtifactType;
import com.thoughtworks.go.domain.DefaultJobPlan;
import com.thoughtworks.go.domain.DefaultSchedulingContext;
import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.domain.JobInstance;
import com.thoughtworks.go.domain.JobInstances;
import com.thoughtworks.go.domain.JobPlan;
import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.JobState;
import com.thoughtworks.go.domain.JobStateTransition;
import com.thoughtworks.go.domain.JobStateTransitions;
import com.thoughtworks.go.domain.Pipeline;
import com.thoughtworks.go.domain.Stage;
import com.thoughtworks.go.domain.StageIdentifier;
import com.thoughtworks.go.helper.BuildPlanMother;
import com.thoughtworks.go.helper.JobInstanceMother;
import com.thoughtworks.go.helper.PipelineMother;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.service.InstanceFactory;
import com.thoughtworks.go.server.service.JobInstanceService;
import com.thoughtworks.go.server.service.ScheduleService;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.server.ui.SortOrder;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.LogFixture;
import com.thoughtworks.go.util.TimeProvider;
import com.thoughtworks.go.util.command.EnvironmentVariableContext;
import org.apache.log4j.Level;
import org.hamcrest.core.Is;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import static com.thoughtworks.go.helper.JobInstanceMother.building;
import static com.thoughtworks.go.helper.JobInstanceMother.cancelled;
import static com.thoughtworks.go.helper.JobInstanceMother.completed;
import static com.thoughtworks.go.helper.JobInstanceMother.failed;
import static com.thoughtworks.go.helper.JobInstanceMother.rescheduled;
import static com.thoughtworks.go.helper.JobInstanceMother.scheduled;
import static com.thoughtworks.go.helper.ModificationsMother.modifySomeFiles;
import static com.thoughtworks.go.server.dao.PersistentObjectMatchers.hasSameId;
import static com.thoughtworks.go.util.GoConfigFileHelper.env;
import static com.thoughtworks.go.util.GoConstants.DEFAULT_APPROVED_BY;
import static com.thoughtworks.go.util.DataStructureUtils.a;
import static com.thoughtworks.go.util.DataStructureUtils.m;
import static com.thoughtworks.go.util.TestUtils.sizeIs;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:WEB-INF/applicationContext-global.xml",
"classpath:WEB-INF/applicationContext-dataLocalAccess.xml",
"classpath:WEB-INF/applicationContext-acegi-security.xml"
})
public class JobInstanceSqlMapDaoTest {
@Autowired private JobInstanceSqlMapDao jobInstanceDao;
@Autowired private JobInstanceService jobInstanceService;
@Autowired private EnvironmentVariableDao environmentVariableDao;
@Autowired private PipelineDao pipelineDao;
@Autowired private DatabaseAccessHelper dbHelper;
@Autowired private StageDao stageDao;
@Autowired private GoCache goCache;
@Autowired private TransactionTemplate transactionTemplate;
@Autowired private ScheduleService scheduleService;
@Autowired private GoConfigFileDao goConfigFileDao;
@Autowired private InstanceFactory instanceFactory;
private GoConfigFileHelper configHelper = new GoConfigFileHelper();
private long stageId;
private static final String JOB_NAME = "functional";
private static final String JOB_NAME_IN_DIFFERENT_CASE = "FUnctiONAl";
private final String projectOne = "project1";
private static final String STAGE_NAME = "mingle";
private static final String PIPELINE_NAME = "pipeline";
private PipelineConfig pipelineConfig;
private Pipeline savedPipeline;
private Stage savedStage;
private static final Date MOST_RECENT_DATE = new DateTime().plusMinutes(20).toDate();
private int counter;
private static final String OTHER_JOB_NAME = "unit";
private DefaultSchedulingContext schedulingContext;
private SqlMapClientTemplate actualSqlClientTemplate;
@Before
public void setUp() throws Exception {
dbHelper.onSetUp();
goCache.clear();
pipelineConfig = PipelineMother.withSingleStageWithMaterials(PIPELINE_NAME, STAGE_NAME, BuildPlanMother.withBuildPlans(JOB_NAME, OTHER_JOB_NAME));
schedulingContext = new DefaultSchedulingContext(DEFAULT_APPROVED_BY);
savedPipeline = instanceFactory.createPipelineInstance(pipelineConfig, modifySomeFiles(pipelineConfig), schedulingContext, "md5-test", new TimeProvider());
dbHelper.savePipelineWithStagesAndMaterials(savedPipeline);
actualSqlClientTemplate = jobInstanceDao.getSqlMapClientTemplate();
savedStage = savedPipeline.getFirstStage();
stageId = savedStage.getId();
counter = savedPipeline.getFirstStage().getCounter();
JobInstance job = savedPipeline.getStages().first().getJobInstances().first();
job.setIgnored(true);
goCache.clear();
configHelper.usingCruiseConfigDao(goConfigFileDao);
configHelper.onSetUp();
}
@After
public void teardown() throws Exception {
jobInstanceDao.setSqlMapClientTemplate(actualSqlClientTemplate);
dbHelper.onTearDown();
configHelper.onTearDown();
}
@Test
public void shouldSaveAndRetrieveIncompleteBuild() throws Exception {
JobInstance expected = scheduled(JOB_NAME, new Date());
expected = jobInstanceDao.save(stageId, expected);
assertThat(expected.getId(), is(not(0L)));
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual, hasSameId(expected));
}
@Test public void shouldGetBuildIngBuildAsMostRecentBuildByPipelineLabelAndStageCounter() throws Exception {
JobInstance expected = JobInstanceMother.building(JOB_NAME);
expected.setScheduledDate(MOST_RECENT_DATE);
expected = jobInstanceDao.save(stageId, expected);
JobInstance actual = jobInstanceDao.mostRecentJobWithTransitions(
new JobIdentifier(PIPELINE_NAME, savedPipeline.getLabel(), STAGE_NAME,
String.valueOf(counter), JOB_NAME));
assertThat(actual.getId(), is(expected.getId()));
assertThat("JobInstance should match", actual.getId(), is(expected.getId()));
assertThat(actual.getTransitions(), is(expected.getTransitions()));
}
@Test public void shouldGetCompletedBuildAsMostRecentBuildByPipelineLabelAndStageCounter() throws Exception {
JobInstance expected = JobInstanceMother.completed(JOB_NAME, JobResult.Unknown);
expected.setScheduledDate(MOST_RECENT_DATE);
expected = jobInstanceDao.save(stageId, expected);
JobInstance actual = jobInstanceDao.mostRecentJobWithTransitions(
new JobIdentifier(PIPELINE_NAME, savedPipeline.getLabel(), STAGE_NAME,
String.valueOf(counter), JOB_NAME));
assertThat("JobInstance should match", actual.getId(), is(expected.getId()));
}
@Test
public void shouldFindJobByPipelineCounterWhenTwoPipelinesWithSameLabel() {
pipelineConfig.setLabelTemplate("fixed-label");
Pipeline oldPipeline = createNewPipeline(pipelineConfig);
Pipeline newPipeline = createNewPipeline(pipelineConfig);
JobInstance expected = oldPipeline.getFirstStage().getJobInstances().first();
JobInstance actual = jobInstanceDao.mostRecentJobWithTransitions(
new JobIdentifier(oldPipeline, oldPipeline.getFirstStage(), expected));
assertThat(actual.getId(), is(expected.getId()));
}
private Pipeline createNewPipeline(PipelineConfig pipelineConfig) {
Pipeline pipeline = instanceFactory.createPipelineInstance(pipelineConfig, modifySomeFiles(pipelineConfig), new DefaultSchedulingContext(
DEFAULT_APPROVED_BY), "md5-test", new TimeProvider());
dbHelper.savePipelineWithStagesAndMaterials(pipeline);
return pipeline;
}
@Test public void shouldFindJobIdByPipelineCounter() throws Exception {
long actual = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(savedPipeline, savedStage), JOB_NAME).getBuildId();
assertThat(actual, is(savedStage.getJobInstances().getByName(JOB_NAME).getId()));
}
@Test public void shouldInvalidateSessionAndFetchJobIdentifier_WhenNewJobIsInserted() throws Exception {
configHelper.addPipeline(pipelineConfig);
configHelper.turnOffSecurity();
StageIdentifier stageIdentifier = new StageIdentifier(savedPipeline.getName(), savedPipeline.getCounter(), savedPipeline.getLabel(), savedStage.getName(), Integer.toString(savedStage.getCounter()+1));
assertThat(jobInstanceDao.findOriginalJobIdentifier(stageIdentifier, JOB_NAME), is(nullValue()));
dbHelper.passStage(savedStage);
Stage stage = scheduleService.rerunStage(savedPipeline.getName(), savedPipeline.getLabel(), savedStage.getName());
JobIdentifier actual = jobInstanceDao.findOriginalJobIdentifier(stageIdentifier, JOB_NAME);
assertThat(actual, is(notNullValue()));
assertThat(actual, is(new JobIdentifier(stageIdentifier, JOB_NAME, stage.getFirstJob().getId())));
}
@Test public void shouldFindJobIdByPipelineLabel() throws Exception {
long actual = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), JOB_NAME).getBuildId();
assertThat(actual, is(savedStage.getJobInstances().getByName(JOB_NAME).getId()));
}
@Test public void findByJobIdShouldBeJobNameCaseAgnostic() throws Exception {
long actual = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), JOB_NAME_IN_DIFFERENT_CASE).getBuildId();
assertThat(actual, is(savedStage.getJobInstances().getByName(JOB_NAME).getId()));
}
@Test public void shouldCacheJobIdentifierForGivenAttributes() throws Exception {
SqlMapClientTemplate template = mock(SqlMapClientTemplate.class);
jobInstanceDao.setSqlMapClientTemplate(template);
Map attrs = m(
"pipelineName", PIPELINE_NAME,
"pipelineCounter", null,
"pipelineLabel", savedPipeline.getLabel(),
"stageName", STAGE_NAME,
"stageCounter", counter,
"jobName", JOB_NAME_IN_DIFFERENT_CASE);
JobIdentifier jobIdentifier = new JobIdentifier(PIPELINE_NAME, savedPipeline.getCounter(), savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter), JOB_NAME);
when(template.queryForObject("findJobId", attrs)).thenReturn(jobIdentifier);
assertThat(jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), JOB_NAME_IN_DIFFERENT_CASE), is(jobIdentifier));
verify(template).queryForObject("findJobId", attrs);
assertThat(jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), JOB_NAME_IN_DIFFERENT_CASE), not(sameInstance(jobIdentifier)));
assertThat(jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), JOB_NAME), is(jobIdentifier));
verifyNoMoreInteractions(template);
}
@Test public void findByJobIdShouldLoadOriginalJobWhenCopiedForJobRerun() throws Exception {
Stage firstOldStage = savedPipeline.getStages().get(0);
Stage newStage = instanceFactory.createStageForRerunOfJobs(firstOldStage, a(JOB_NAME), new DefaultSchedulingContext("loser", new Agents()), pipelineConfig.get(0), new TimeProvider(), "md5");
stageDao.saveWithJobs(savedPipeline, newStage);
dbHelper.passStage(newStage);
JobIdentifier oldJobIdentifierThroughOldJob = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(counter)), OTHER_JOB_NAME);
JobIdentifier oldJobIdentifierThroughCopiedNewJob = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(newStage.getCounter())), OTHER_JOB_NAME);
JobIdentifier newJobIdentifierThroughRerunJob = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(PIPELINE_NAME, null, savedPipeline.getLabel(), STAGE_NAME, String.valueOf(newStage.getCounter())), JOB_NAME);
assertThat(oldJobIdentifierThroughOldJob, is(firstOldStage.getJobInstances().getByName(OTHER_JOB_NAME).getIdentifier()));
assertThat(oldJobIdentifierThroughCopiedNewJob, is(firstOldStage.getJobInstances().getByName(OTHER_JOB_NAME).getIdentifier()));
assertThat(newJobIdentifierThroughRerunJob, is(newStage.getJobInstances().getByName(JOB_NAME).getIdentifier()));
}
@Test public void findJobIdShouldExcludeIgnoredJob() throws Exception {
JobInstance oldJob = savedStage.getJobInstances().getByName(JOB_NAME);
jobInstanceDao.ignore(oldJob);
JobInstance expected = JobInstanceMother.scheduled(JOB_NAME);
expected = jobInstanceDao.save(stageId, expected);
long actual = jobInstanceDao.findOriginalJobIdentifier(new StageIdentifier(savedPipeline, savedStage), JOB_NAME).getBuildId();
assertThat(actual, is(expected.getId()));
}
@Test public void shouldFindAllInstancesOfJobsThatAreRunOnAllAgents() throws Exception {
List<JobInstance> before = stageDao.mostRecentJobsForStage(PIPELINE_NAME, STAGE_NAME);
String uuid1 = UUID.randomUUID().toString();
String uuid2 = UUID.randomUUID().toString();
JobInstance instance1 = savedJobForAgent(uuid1);
JobInstance instance2 = savedJobForAgent(uuid2);
List<JobInstance> after = stageDao.mostRecentJobsForStage(PIPELINE_NAME, STAGE_NAME);
after.removeAll(before);
assertThat(after.toArray(), hasItemInArray(hasProperty("name", is(instance1.getName()))));
assertThat(after.toArray(), hasItemInArray(hasProperty("name", is(instance2.getName()))));
assertThat("Expected 2 but got " + after, after.size(), is(2));
}
private JobInstance savedJobForAgent(final String uuid) {
return (JobInstance) transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
JobInstance jobInstance = scheduled(JOB_NAME + "-" + uuid, new DateTime().plusMinutes(1).toDate());
jobInstance.setRunOnAllAgents(true);
jobInstanceService.save(savedStage.getIdentifier(), stageId, jobInstance);
jobInstance.changeState(JobState.Building);
jobInstance.setAgentUuid(uuid);
jobInstanceDao.updateStateAndResult(jobInstance);
return jobInstance;
}
});
}
@Test(expected = DataRetrievalFailureException.class)
public void shouldReturnNullObjectWhenNoBuildInstanceFound() throws Exception {
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(999);
assertThat(actual.isNull(), is(true));
}
@Test public void shouldReturnBuildInstanceIfItExists() throws Exception {
JobInstance jobInstance = JobInstanceMother.completed("Baboon", JobResult.Passed);
JobInstance instance = jobInstanceDao.save(stageId, jobInstance);
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(instance.getId());
assertThat(actual.isNull(), is(false));
}
private JobInstance[] createJobs(final String name, int count) {
JobInstance[] before = new JobInstance[count];
for(int i = 0; i < count; i++) {
before[i] = saveJob(name + "-" + i);
}
return before;
}
@Test public void shouldLogStatusUpdatesOfCompletedJobs() throws Exception {
LogFixture logFixture = LogFixture.startListening(Level.WARN);
JobInstance instance = runningJob("1");
completeJobs(instance);
instance.schedule();
jobInstanceDao.updateStateAndResult(instance);
assertThat(logFixture.getLog(), logFixture.contains(Level.WARN, "State change for a completed Job is not allowed."), is(true));
logFixture.stopListening();
}
private JobInstance[] completeJobs(JobInstance ... instances) {
for (JobInstance instance : instances) {
complete(instance);
}
return instances;
}
private long createNewStage() {
PipelineConfig anotherConfig = PipelineMother.withSingleStageWithMaterials("hatred", "hatedChild", BuildPlanMother.withBuildPlans(JOB_NAME, OTHER_JOB_NAME));
Pipeline anotherPipeline = instanceFactory.createPipelineInstance(anotherConfig, modifySomeFiles(anotherConfig), new DefaultSchedulingContext(DEFAULT_APPROVED_BY), "md5-test", new TimeProvider());
dbHelper.savePipelineWithStagesAndMaterials(anotherPipeline);
return anotherPipeline.getFirstStage().getId();
}
private JobInstance saveJob() {
String jobName = "Baboon";
return saveJob(jobName);
}
private JobInstance saveJob(String jobName) {
JobInstance jobInstance = JobInstanceMother.completed(jobName, JobResult.Passed);
jobInstanceDao.save(stageId, jobInstance);
return jobInstance;
}
private JobInstance runningJob(final String name) {
JobInstance jobInstance = JobInstanceMother.buildingInstance("pipeline", "stage", name, "1");
jobInstanceDao.save(stageId, jobInstance);
return jobInstance;
}
private JobInstance runningJob(String pipeline, String stage, String job, long stageId) {
JobInstance jobInstance = JobInstanceMother.buildingInstance(pipeline, stage, job, "1");
jobInstanceDao.save(stageId, jobInstance);
return jobInstance;
}
private void complete(JobInstance jobInstance) {
jobInstance.completing(JobResult.Passed);
jobInstance.completed(new Date());
jobInstanceDao.updateStateAndResult(jobInstance);
}
@Test public void shouldUpdateBuildResult() throws Exception {
JobInstance jobInstance = JobInstanceMother.scheduled("Baboon");
jobInstanceDao.save(stageId, jobInstance);
jobInstance.cancel();
jobInstanceDao.updateStateAndResult(jobInstance);
JobInstance instance = jobInstanceDao.buildByIdWithTransitions(jobInstance.getId());
assertThat(instance.getResult(), is(JobResult.Cancelled));
jobInstance.fail();
jobInstanceDao.updateStateAndResult(jobInstance);
instance = jobInstanceDao.buildByIdWithTransitions(jobInstance.getId());
assertThat(instance.getResult(), is(JobResult.Failed));
}
@Test(expected = DataRetrievalFailureException.class)
public void shouldReturnNullObjectIfItNotExists() throws Exception {
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(1);
assertThat(actual.isNull(), is(true));
}
@Test public void shouldNotGetJobsFromBeforeTheJobNameIsChanged() throws Exception {
String oldName = "oldName";
createSomeJobs(oldName, 15);
String newName = "newName";
createSomeJobs(newName, 10);
JobInstances myinstances = jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, newName, 25);
assertThat(myinstances.size(), is(10));
assertThat(myinstances.get(0).getName(), is(not(oldName)));
assertThat(myinstances.get(0).getName(), is(newName));
}
private long createSomeJobs(String jobName, int count) throws SQLException {
long stageId = 0;
for (int i = 0; i < count; i++) {
Pipeline newPipeline = createNewPipeline(pipelineConfig);
stageId = newPipeline.getFirstStage().getId();
JobInstance job = JobInstanceMother.completed(jobName, JobResult.Passed);
jobInstanceDao.save(stageId, job);
}
return stageId;
}
private void createCopiedJobs(long stageId, String jobName, int count) throws SQLException {
for (int i = 0; i < count; i++) {
JobInstance job = JobInstanceMother.completed(jobName, JobResult.Failed);
job.setOriginalJobId(1L);
jobInstanceDao.save(stageId, job);
}
}
@Test
public void shouldGetMostRecentCompletedBuildsWhenTotalBuildsIsLessThan25() throws Exception {
JobInstance jobInstance = JobInstanceMother.completed("shouldnotload", JobResult.Passed);
jobInstanceDao.save(stageId, jobInstance);
createSomeJobs(JOB_NAME, 3);
JobInstances instances = jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25);
assertThat(instances.size(), is(3));
}
@Test
public void shouldLoadStageCounter() throws Exception {
JobInstance jobInstance = JobInstanceMother.completed("shouldnotload", JobResult.Passed);
jobInstanceDao.save(stageId, jobInstance);
createSomeJobs(JOB_NAME, 3);
JobInstances instances = jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25);
for (JobInstance instance : instances) {
Pipeline pipeline = pipelineDao.pipelineByBuildIdWithMods(instance.getId());
String locator = pipeline.getName() +
"/" + pipeline.getLabel() + "/" + savedStage.getName() + "/1/" + JOB_NAME;
assertThat(instance.getIdentifier().buildLocator(), Is.is(locator));
}
}
@Test public void shouldGet25Builds() throws Exception {
createSomeJobs(JOB_NAME, 30);
JobInstances instances = jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25);
assertThat(instances.size(), is(25));
for (JobInstance instance : instances) {
assertThat(instance.getIdentifier().getBuildName(), is(JOB_NAME));
}
}
@Test
public void shouldGet25Builds_AlthoughFirst5AreCopied() throws Exception {
long stageId = createSomeJobs(JOB_NAME, 30);
createCopiedJobs(stageId, JOB_NAME, 5);
JobInstances instances = jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25);
assertThat(instances.size(), is(25));
for (JobInstance instance : instances) {
assertThat(instance.getIdentifier().getBuildName(), is(JOB_NAME));
assertThat("Should not have retrieved copied-over jobs", instance.isCopy(), is(false));
}
}
@Test public void shouldGetMostRecentCompletedBuildsWhenTwoStagesWithIdenticalStageNamesAndBuildPlanNames()
throws Exception {
Pipeline otherPipeline = PipelineMother.passedPipelineInstance(PIPELINE_NAME + "2", STAGE_NAME, JOB_NAME);
dbHelper.savePipelineWithStagesAndMaterials(otherPipeline);
for (int i = 0; i < 2; i++) {
Pipeline completedPipeline = PipelineMother.passedPipelineInstance(PIPELINE_NAME, STAGE_NAME, JOB_NAME);
dbHelper.savePipelineWithStagesAndMaterials(completedPipeline);
}
assertThat(jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25).size(), is(2));
assertThat(jobInstanceDao.latestCompletedJobs(otherPipeline.getName(), STAGE_NAME, JOB_NAME, 25).size(), is(1));
}
@Test public void shouldIgnoreBuildingBuilds() throws Exception {
JobInstance instance = JobInstanceMother.completed("shouldnotload", JobResult.Passed);
jobInstanceDao.save(stageId, instance);
JobInstance building = JobInstanceMother.building(JOB_NAME);
JobInstance saved = jobInstanceDao.save(stageId, building);
JobInstances instances =
jobInstanceDao.latestCompletedJobs(PIPELINE_NAME, STAGE_NAME, JOB_NAME, 25);
assertThat(instances.size(), is(0));
}
@Test
public void shouldLoadRerunOfCounterValueForScheduledBuilds() {
List<JobPlan> jobPlans = jobInstanceDao.orderedScheduledBuilds();
assertThat(jobPlans.size(), is(2));
assertThat(jobPlans.get(0).getIdentifier().getRerunOfCounter(), is(nullValue()));
assertThat(jobPlans.get(1).getIdentifier().getRerunOfCounter(), is(nullValue()));
dbHelper.passStage(savedStage);
Stage stage = instanceFactory.createStageForRerunOfJobs(savedStage, a(JOB_NAME), schedulingContext, pipelineConfig.getStage(new CaseInsensitiveString(STAGE_NAME)), new TimeProvider(), "md5");
dbHelper.saveStage(savedPipeline, stage, stage.getOrderId() + 1);
jobPlans = jobInstanceDao.orderedScheduledBuilds();
assertThat(jobPlans.size(), is(1));
assertThat(jobPlans.get(0).getIdentifier().getRerunOfCounter(), is(savedStage.getCounter()));
}
@Test
public void shouldGetAllScheduledBuildsInOrder() throws Exception {
// in setup, we created 2 scheduled builds
assertThat(jobInstanceDao.orderedScheduledBuilds().size(), is(2));
JobIdentifier jobIdentifier = new JobIdentifier(PIPELINE_NAME, "LABEL-1", STAGE_NAME, "1", JOB_NAME);
long newestId = schedule(JOB_NAME, stageId, new Date(10001), jobIdentifier);
long olderId = schedule(JOB_NAME, stageId, new Date(10000), jobIdentifier);
long oldestId = schedule(JOB_NAME, stageId, new Date(999), jobIdentifier);
List<JobPlan> jobPlans = jobInstanceDao.orderedScheduledBuilds();
assertThat(jobPlans.size(), is(5));
assertJobInstance(jobPlans.get(0), oldestId, PIPELINE_NAME, STAGE_NAME);
assertJobInstance(jobPlans.get(1), olderId, PIPELINE_NAME, STAGE_NAME);
assertJobInstance(jobPlans.get(2), newestId, PIPELINE_NAME, STAGE_NAME);
}
private long schedule(String jobName, long stageId, Date date, JobIdentifier jobIdentifier) {
JobInstance newest = new JobInstance(jobName);
newest.setScheduledDate(date);
jobInstanceDao.save(stageId, newest);
jobInstanceDao.save(newest.getId(), new DefaultJobPlan(new Resources(), new ArtifactPlans(),
new ArtifactPropertiesGenerators(), -1, jobIdentifier));
return newest.getId();
}
private void assertJobInstance(JobPlan actual, long expect, String pipelineName, String stageName) {
assertThat(actual.getPipelineName(), is(pipelineName));
assertThat(actual.getStageName(), is(stageName));
assertThat("JobInstance should match", actual.getJobId(), is(expect));
}
@Test public void shouldUpdateStateTransitions() throws Exception {
JobInstance expected = scheduled(JOB_NAME, new Date(1000));
jobInstanceDao.save(stageId, expected);
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual.getTransitions(), sizeIs(1));
expected.changeState(JobState.Assigned);
jobInstanceDao.updateStateAndResult(expected);
actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual.getTransitions(), sizeIs(2));
for (JobStateTransition transition : actual.getTransitions()) {
assertThat(transition.getStageId(), is(stageId));
}
}
@Test public void shouldUpdateBuildStatus() throws Exception {
JobInstance expected = scheduled(JOB_NAME);
jobInstanceDao.save(stageId, expected);
expected.changeState(JobState.Building);
jobInstanceDao.updateStateAndResult(expected);
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual.getState(), is(JobState.Building));
assertThat(actual.getTransitions().size(), is(2));
}
@Test public void shouldUpdateAssignedInfo() throws Exception {
JobInstance expected = scheduled(JOB_NAME);
jobInstanceDao.save(stageId, expected);
expected.changeState(JobState.Building);
expected.setAgentUuid("uuid");
jobInstanceDao.updateAssignedInfo(expected);
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual.getState(), is(JobState.Building));
assertThat(actual.getTransitions().size(), is(2));
assertThat(actual.getAgentUuid(), is("uuid"));
}
@Test public void shouldUpdateCompletingInfo() throws Exception {
JobInstance expected = scheduled(JOB_NAME);
jobInstanceDao.save(stageId, expected);
expected.changeState(JobState.Completing);
expected.setResult(JobResult.Failed);
jobInstanceDao.updateStateAndResult(expected);
JobInstance actual = jobInstanceDao.buildByIdWithTransitions(expected.getId());
assertThat(actual.getState(), is(JobState.Completing));
assertThat(actual.getTransitions().size(), is(2));
assertThat(actual.getResult(), is(JobResult.Failed));
}
@Test
public void shouldSaveTransitionsCorrectly() {
JobInstance jobInstance = scheduled(projectOne, new Date(1));
jobInstance.completing(JobResult.Failed, new Date(3));
jobInstanceDao.save(stageId, jobInstance);
JobInstance loaded = jobInstanceDao.buildByIdWithTransitions(jobInstance.getId());
JobStateTransitions actualTransitions = loaded.getTransitions();
assertThat(actualTransitions, sizeIs(2));
assertThat(actualTransitions.first().getCurrentState(), is(JobState.Scheduled));
}
@Test
public void shouldSaveResources() {
JobInstance instance = jobInstanceDao.save(stageId, new JobInstance(JOB_NAME));
instance.setIdentifier(new JobIdentifier(savedPipeline, savedStage, instance));
JobPlan plan = new DefaultJobPlan(new Resources("something"), new ArtifactPlans(),
new ArtifactPropertiesGenerators(), instance.getId(),
instance.getIdentifier());
jobInstanceDao.save(instance.getId(), plan);
JobPlan retrieved = jobInstanceDao.loadPlan(plan.getJobId());
assertThat(retrieved, is(plan));
}
@Test
public void shouldSaveEnvironmentVariables() {
JobInstance instance = jobInstanceDao.save(stageId, new JobInstance(JOB_NAME));
instance.setIdentifier(new JobIdentifier(savedPipeline, savedStage, instance));
EnvironmentVariablesConfig variables = new EnvironmentVariablesConfig();
variables.add("VARIABLE_NAME", "variable value");
variables.add("TRIGGER_VAR", "junk val");
JobPlan plan = new DefaultJobPlan(new Resources(), new ArtifactPlans(),
new ArtifactPropertiesGenerators(), instance.getId(),
instance.getIdentifier(), null, variables, new EnvironmentVariablesConfig());
jobInstanceDao.save(instance.getId(), plan);
environmentVariableDao.save(savedPipeline.getId(), EnvironmentVariableDao.EnvironmentVariableType.Trigger, GoConfigFileHelper.env("TRIGGER_VAR", "trigger val"));
JobPlan retrieved = jobInstanceDao.loadPlan(plan.getJobId());
assertThat(retrieved.getVariables(), is(plan.getVariables()));
EnvironmentVariableContext context = new EnvironmentVariableContext();
retrieved.applyTo(context);
assertThat(context.getProperty("VARIABLE_NAME"), is("variable value"));
assertThat(context.getProperty("TRIGGER_VAR"), is("trigger val"));
}
@Test
public void shouldLoadEnvironmentVariablesForScheduledJobs() {
JobInstance newInstance = new JobInstance(JOB_NAME);
newInstance.schedule();
JobInstance instance = jobInstanceDao.save(stageId, newInstance);
instance.setIdentifier(new JobIdentifier(savedPipeline, savedStage, instance));
EnvironmentVariablesConfig variables = new EnvironmentVariablesConfig();
variables.add("VARIABLE_NAME", "variable value");
variables.add("TRIGGER_VAR", "junk val");
JobPlan plan = new DefaultJobPlan(new Resources(), new ArtifactPlans(),
new ArtifactPropertiesGenerators(), instance.getId(),
instance.getIdentifier(), null, variables, new EnvironmentVariablesConfig());
jobInstanceDao.save(instance.getId(), plan);
environmentVariableDao.save(savedPipeline.getId(), EnvironmentVariableDao.EnvironmentVariableType.Trigger, GoConfigFileHelper.env("TRIGGER_VAR", "trigger val"));
List<JobPlan> retrieved = jobInstanceDao.orderedScheduledBuilds();
JobPlan reloadedPlan = planForJob(retrieved, plan.getJobId());
EnvironmentVariableContext context = new EnvironmentVariableContext();
reloadedPlan.applyTo(context);
assertThat(reloadedPlan.getVariables(), is(plan.getVariables()));
assertThat(context.getProperty("VARIABLE_NAME"), is("variable value"));
assertThat(context.getProperty("TRIGGER_VAR"), is("trigger val"));
}
private JobPlan planForJob(List<JobPlan> retrieved, long expectedJobId) {
for (JobPlan loadedJobPlan : retrieved) {
if (loadedJobPlan.getJobId() == expectedJobId) {
return loadedJobPlan;
}
}
return null;
}
@Test
public void shouldLoadArtifactPropertiesGeneratorsInOrderForAssignment() throws Exception {
ArtifactPropertiesGenerator prop1 = new ArtifactPropertiesGenerator("test1", "src", "//xpath");
ArtifactPropertiesGenerator prop2 = new ArtifactPropertiesGenerator("test2", "src", "//xpath");
ArtifactPropertiesGenerator prop3 = new ArtifactPropertiesGenerator("test3", "src", "//xpath");
ArtifactPropertiesGenerator prop4 = new ArtifactPropertiesGenerator("test4", "src", "//xpath");
ArtifactPropertiesGenerator prop5 = new ArtifactPropertiesGenerator("test5", "src", "//xpath");
JobInstance instance = jobInstanceDao.save(stageId, new JobInstance(projectOne));
instance.setIdentifier(new JobIdentifier(savedPipeline, savedStage, instance));
JobPlan savedPlan = new DefaultJobPlan(new Resources(), artifactPlans(),
new ArtifactPropertiesGenerators(prop1, prop2, prop3, prop4, prop5), instance.getId(),
instance.getIdentifier());
jobInstanceDao.save(instance.getId(), savedPlan);
JobPlan plan = findPlan(jobInstanceDao.orderedScheduledBuilds(), projectOne);
List<ArtifactPropertiesGenerator> generators = plan.getPropertyGenerators();
assertThat(generators.size(), is(5));
assertThat(generators.get(0), is(prop1));
assertThat(generators.get(1), is(prop2));
assertThat(generators.get(2), is(prop3));
assertThat(generators.get(3), is(prop4));
assertThat(generators.get(4), is(prop5));
}
@Test
public void shouldLoadArtifactsAndResourcesForAssignment() throws Exception {
JobInstance instance = jobInstanceDao.save(stageId, new JobInstance(projectOne));
instance.setIdentifier(new JobIdentifier(savedPipeline, savedStage, instance));
Resources resources = new Resources("one, two, three");
JobPlan savedPlan = new DefaultJobPlan(resources, artifactPlans(),
new ArtifactPropertiesGenerators(), instance.getId(),
instance.getIdentifier());
jobInstanceDao.save(instance.getId(), savedPlan);
final List<JobPlan> planList = jobInstanceDao.orderedScheduledBuilds();
final List<JobPlan> plans = findPlans(planList, projectOne);
assertThat(plans.size(), is(1));
assertThat(plans.get(0).getResources(), is((List<Resource>) resources));
}
@Test
public void shouldLoadJobIdentifierForAssignment() throws Exception {
JobInstance jobInstance = scheduled(projectOne);
jobInstanceDao.save(stageId, jobInstance);
JobPlan job = findPlan(jobInstanceDao.orderedScheduledBuilds(), projectOne);
assertThat(job.getIdentifier(), is(jobIdentifier(jobInstance)));
}
@Test
public void shouldLoadAgentUuidForAssignment() throws Exception {
JobInstance jobInstance = scheduled(projectOne);
jobInstance.setAgentUuid("uuid1");
jobInstanceDao.save(stageId, jobInstance);
JobPlan job = findPlan(jobInstanceDao.orderedScheduledBuilds(), projectOne);
assertThat(job.getAgentUuid(), is("uuid1"));
}
@Test
public void shouldLoadRunOnAllAgentsForAssignment() throws Exception {
JobInstance jobInstance = scheduled(projectOne);
jobInstance.setRunOnAllAgents(true);
jobInstanceDao.save(stageId, jobInstance);
JobInstance reloaded = jobInstanceDao.buildByIdWithTransitions(jobInstance.getId());
assertThat(reloaded.isRunOnAllAgents(), is(true));
}
private JobIdentifier jobIdentifier(JobInstance jobInstance) {
return new JobIdentifier(savedPipeline, savedStage, jobInstance);
}
private JobPlan findPlan(List<JobPlan> list, String jobName) {
final List<JobPlan> planList = findPlans(list, jobName);
if (planList.size() > 0) {
return planList.get(0);
}
return null;
}
private List<JobPlan> findPlans(List<JobPlan> list, String jobName) {
List<JobPlan> result = new ArrayList<JobPlan>();
for (JobPlan buildNameBean : list) {
if (jobName.equals(buildNameBean.getName())) {
result.add(buildNameBean);
}
}
return result;
}
@Test
public void shouldGetLatestInProgressBuildByAgentUuid() throws Exception {
JobInstance buildingJob = building(projectOne, new Date(1));
final String uuid = "uuid";
buildingJob.setAgentUuid(uuid);
jobInstanceDao.save(stageId, buildingJob);
JobInstance completedJob = JobInstanceMother.completed("anotherBuild", JobResult.Passed);
completedJob.setAgentUuid(uuid);
jobInstanceDao.save(stageId, completedJob);
JobInstance jobInstance = jobInstanceDao.getLatestInProgressBuildByAgentUuid(uuid);
assertThat(jobInstance, hasSameId(buildingJob));
assertThat(jobInstance.getIdentifier(), is(jobIdentifier(jobInstance)));
}
@Test
public void shouldGetInProgressJobs() throws Exception {
JobInstance buildingJob1 = building(projectOne, new Date(1));
buildingJob1.setAgentUuid("uuid1");
jobInstanceDao.save(stageId, buildingJob1);
JobInstance buildingJob2 = building("project2", new Date(2));
buildingJob2.setAgentUuid("uuid2");
jobInstanceDao.save(stageId, buildingJob2);
JobInstance buildingJob3 = building("project3", new Date(3));
buildingJob3.setAgentUuid("uuid3");
jobInstanceDao.save(stageId, buildingJob3);
List<String> liveAgentIds = new ArrayList<String>() {
{
add("uuid1");
add("uuid2");
}
};
JobInstances list = jobInstanceDao.findHungJobs(liveAgentIds);
assertThat(list.size(), is(1));
JobInstance reloaded = list.get(0);
assertThat(reloaded, hasSameId(buildingJob3));
assertThat(reloaded.getIdentifier(), is(jobIdentifier(buildingJob3)));
}
@Test
public void shouldIgnore() throws Exception {
JobInstance instance = scheduled(projectOne);
jobInstanceDao.save(stageId, instance);
jobInstanceDao.ignore(instance);
JobInstance reloaded = jobInstanceDao.buildByIdWithTransitions(instance.getId());
assertThat(reloaded.isIgnored(), is(true));
}
@Test
public void shouldKnowIfBuildIdentifierIsValid() throws Exception {
assertThat(jobInstanceDao.isValid(PIPELINE_NAME, STAGE_NAME, JOB_NAME), is(true));
assertThat(jobInstanceDao.isValid("unknown", STAGE_NAME, JOB_NAME), is(false));
}
@Test
public void shouldGetCompletedJobsOnAgentForARange(){
String agentUuid = "special_uuid";
JobInstance buildingJob = building("job1", new Date(1));
buildingJob.setAgentUuid(agentUuid);
jobInstanceDao.save(stageId, buildingJob);
JobInstance completedJob = completed("job2", JobResult.Passed, new Date(1));
completedJob.setAgentUuid(agentUuid);
jobInstanceDao.save(stageId, completedJob);
JobInstance cancelledJob = cancelled("job3");
cancelledJob.setAgentUuid("something_different");//Different UUID. Should not be considered
jobInstanceDao.save(stageId, cancelledJob);
JobInstance rescheduledJob = rescheduled("rescheduled", agentUuid);
jobInstanceDao.save(stageId, rescheduledJob);
jobInstanceDao.ignore(rescheduledJob);
List<JobInstance> jobInstances = jobInstanceDao.completedJobsOnAgent(agentUuid, JobInstanceService.JobHistoryColumns.stage, SortOrder.ASC, 0, 10);
assertThat(jobInstances.size(), is(2));
JobInstance actual = jobInstances.get(0);
assertThat(actual.getName(), is(completedJob.getName()));
completedJob.setIdentifier(actual.getIdentifier());
assertThat(actual, is(completedJob));
actual = jobInstances.get(1);
assertThat(actual.getName(), is(rescheduledJob.getName()));
rescheduledJob.setIdentifier(actual.getIdentifier());
assertThat(actual, is(rescheduledJob));
}
@Test
public void shouldGetTotalNumberOfCompletedJobsForAnAgent(){
String agentUuid = "special_uuid";
JobInstance buildingJob = building("job1", new Date(1));
buildingJob.setAgentUuid(agentUuid);
jobInstanceDao.save(stageId, buildingJob);
JobInstance completedJob = completed("job2", JobResult.Passed, new Date(1));
completedJob.setAgentUuid(agentUuid);
jobInstanceDao.save(stageId, completedJob);
JobInstance rescheduledJob = rescheduled("rescheduled", agentUuid);
jobInstanceDao.save(stageId, rescheduledJob);
jobInstanceDao.ignore(rescheduledJob);
JobInstance cancelledJob = cancelled("job3");
cancelledJob.setAgentUuid("something_different");//Different UUID. Should not be counted
jobInstanceDao.save(stageId, cancelledJob);
JobInstance simpleJob = failed("simpleJob");
simpleJob.setAgentUuid(agentUuid);
jobInstanceDao.save(stageId, simpleJob);
assertThat(jobInstanceDao.totalCompletedJobsOnAgent(agentUuid), is(3));
}
private ArtifactPlans artifactPlans() {
ArtifactPlans artifactPlans = new ArtifactPlans();
artifactPlans.add(new ArtifactPlan(ArtifactType.file, "src", "dest"));
artifactPlans.add(new ArtifactPlan(ArtifactType.file, "src1", "dest2"));
return artifactPlans;
}
}
|
package eu.csaware.stix2.test.reference;
import eu.csaware.stix2.common.*;
import eu.csaware.stix2.sdos.Indicator;
import eu.csaware.stix2.sdos.Malware;
import eu.csaware.stix2.sros.Relationship;
import eu.csaware.stix2.test.util.TestConstants;
import eu.csaware.stix2.test.util.TestUtil;
import eu.csaware.stix2.util.Stix2Gson;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
*
*/
class BundleTest {
private static final String PATH = "reference/bundle.json";
private static Bundle bundle;
@BeforeAll
static void setUp() throws Exception {
String jsonString = TestUtil.readResourceFile(PATH);
bundle = Stix2Gson.DEBUG.fromJson(jsonString, Bundle.class);
}
@AfterAll
static void tearDown() throws Exception {
}
@Test
void testType() {
Assertions.assertEquals(Stix2Type.BUNDLE, bundle.getType());
}
@Test
void testId() {
Assertions.assertEquals(TestConstants.BUNDLE_ID, bundle.getId());
}
@Test
void testSpecVersion() {
Assertions.assertEquals("2.0", bundle.getSpecVersion());
}
@Test
void testObjectsSize() {
Assertions.assertNotNull(bundle.getObjects());
Assertions.assertEquals(3, bundle.getObjects().size());
}
@Test
void testIndicatorType() {
TypedStixObject indicator = bundle.getObjects().get(0);
Assertions.assertNotNull(indicator);
Assertions.assertTrue(indicator instanceof Indicator);
}
@Test
void testMalwareType() {
TypedStixObject malware = bundle.getObjects().get(1);
Assertions.assertNotNull(malware);
Assertions.assertTrue(malware instanceof Malware);
}
@Test
void testRelationshipType() {
TypedStixObject indicator = bundle.getObjects().get(2);
Assertions.assertNotNull(indicator);
Assertions.assertTrue(indicator instanceof Relationship);
}
@Test
void testIndicatorId() {
Indicator indicator = (Indicator) bundle.getObjects().get(0);
Assertions.assertEquals(TestConstants.INDICATOR_ID, indicator.getId());
}
@Test
void testMalwareId() {
Malware malware = (Malware) bundle.getObjects().get(1);
Assertions.assertEquals(TestConstants.MALWARE_ID, malware.getId());
}
@Test
void testRelationshipId() {
Relationship relationship = (Relationship) bundle.getObjects().get(2);
Assertions.assertEquals(TestConstants.RELATIONSHIP_ID, relationship.getId());
}
@Test
void testNullSafety() {
Bundle bundle = new Bundle();
Assertions.assertNotNull(bundle.getObjects());
}
@Test
void testCreation() throws IOException {
List<String> labelsIndicator = Collections.singletonList(OpenVocabularyDefaults.INDICATOR_LABEL_MALICIOUS_ACTIVITY);
Indicator indicator = new Indicator(
TestConstants.INDICATOR_UUID,
labelsIndicator,
"[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
TestConstants.DATE_TIME_EXTRA,
TestConstants.DATE_TIME_CREATED,
TestConstants.DATE_TIME_MODIFIED
);
List<String> labelsMalware = Collections.singletonList(OpenVocabularyDefaults.MALWARE_LABEL_RANSOMWARE);
Malware malware = new Malware(
TestConstants.MALWARE_UUID,
labelsMalware,
"Cryptolocker",
TestConstants.DATE_TIME_CREATED,
TestConstants.DATE_TIME_MODIFIED
);
Relationship relationship = new Relationship(
TestConstants.RELATIONSHIP_UUID,
Relationship.TYPE_INDICATES,
TestConstants.INDICATOR_ID,
TestConstants.MALWARE_ID,
TestConstants.DATE_TIME_CREATED,
TestConstants.DATE_TIME_MODIFIED
);
List<TypedStixObject> objects = Arrays.asList(indicator, malware, relationship);
Bundle bundle = new Bundle(
TestConstants.BUNDLE_UUID,
"2.0",
objects
);
Assertions.assertNotNull(bundle);
String created = Stix2Gson.DEBUG.toJson(bundle);
String jsonString = TestUtil.readResourceFile(PATH);
Assertions.assertEquals(TestUtil.sanitizeJson(jsonString), TestUtil.sanitizeJson(created));
TestUtil.writeSerializedOutputFile(PATH, created);
}
@Test
void testAutoType() throws IOException {
String jsonString = TestUtil.readResourceFile(PATH);
TypedStixObject core = Stix2Gson.DEBUG.fromJson(jsonString, TypedStixObject.class);
Assertions.assertTrue(core instanceof Bundle);
}
}
|
/*******************************************************************************
* Copyright 2015 Alexander Casall, Manuel Mauky
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package de.saxsys.mvvmfx.utils.mapping.accessorfunctions;
import java.util.function.BiConsumer;
/**
* A functional interface to define a setter method of a generic type.
*
* @param <M>
* the generic type of the model.
* @param <T>
* the generic type of the field.
*/
@FunctionalInterface
public interface ObjectSetter<M, T> extends BiConsumer<M, T> {
/**
* @param model
* the model instance.
* @param value
* the new value to be set.
*/
@Override
void accept(M model, T value);
}
|
package ca.uhn.fhir.jpa.subscription.module.cache;
import ca.uhn.fhir.jpa.subscription.module.BaseSubscriptionDstu3Test;
import org.hl7.fhir.dstu3.model.Subscription;
import org.junit.After;
public abstract class BaseSubscriptionRegistryTest extends BaseSubscriptionDstu3Test {
public static final String SUBSCRIPTION_ID = "1";
public static final String ORIG_CRITERIA = "Patient?";
public static final String NEW_CRITERIA = "Observation?";
@After
public void clearRegistryAfter() {
super.clearRegistry();
}
protected Subscription createSubscription() {
Subscription subscription = new Subscription();
subscription.setId(SUBSCRIPTION_ID);
subscription.setCriteria(ORIG_CRITERIA);
subscription.setStatus(Subscription.SubscriptionStatus.ACTIVE);
setChannel(subscription, Subscription.SubscriptionChannelType.RESTHOOK);
return subscription;
}
protected void setChannel(Subscription theSubscription, Subscription.SubscriptionChannelType theResthook) {
Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
channel.setType(theResthook);
channel.setPayload("application/json");
channel.setEndpoint("http://unused.test.endpoint/");
theSubscription.setChannel(channel);
}
}
|
package me.devsaki.hentoid.activities.bundles;
import android.os.Bundle;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Helper class to transfer payload data to {@link me.devsaki.hentoid.viewholders.ContentItem}
* through a Bundle
* <p>
* Use Builder class to set data; use Parser class to get data
*/
public class ContentItemBundle {
private static final String KEY_DELETE_PROCESSING = "is_being_deleted";
private static final String KEY_FAV_STATE = "favourite";
private static final String KEY_READS = "reads";
private static final String KEY_COVER_URI = "cover_uri";
private ContentItemBundle() {
throw new UnsupportedOperationException();
}
public static final class Builder {
private final Bundle bundle = new Bundle();
public void setIsBeingDeleted(boolean isBeingDeleted) {
bundle.putBoolean(KEY_DELETE_PROCESSING, isBeingDeleted);
}
public void setIsFavourite(boolean isFavourite) {
bundle.putBoolean(KEY_FAV_STATE, isFavourite);
}
public void setReads(long reads) {
bundle.putLong(KEY_READS, reads);
}
public void setCoverUri(String uri) {
bundle.putString(KEY_COVER_URI, uri);
}
public boolean isEmpty() {
return bundle.isEmpty();
}
public Bundle getBundle() {
return bundle;
}
}
public static final class Parser {
private final Bundle bundle;
public Parser(@Nonnull Bundle bundle) {
this.bundle = bundle;
}
@Nullable
public Boolean isBeingDeleted() {
if (bundle.containsKey(KEY_DELETE_PROCESSING))
return bundle.getBoolean(KEY_DELETE_PROCESSING);
else return null;
}
@Nullable
public Boolean isFavourite() {
if (bundle.containsKey(KEY_FAV_STATE)) return bundle.getBoolean(KEY_FAV_STATE);
else return null;
}
@Nullable
public Long getReads() {
if (bundle.containsKey(KEY_READS)) return bundle.getLong(KEY_READS);
else return null;
}
@Nullable
public String getCoverUri() {
if (bundle.containsKey(KEY_COVER_URI)) return bundle.getString(KEY_COVER_URI);
else return null;
}
}
}
|
package com.atguigu.gmall.pms.controller;
import java.util.Arrays;
import java.util.Map;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.core.bean.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.atguigu.gmall.pms.entity.SpuImagesEntity;
import com.atguigu.gmall.pms.service.SpuImagesService;
/**
* spu图片
*
* @author baixin
* @email 230326401@qq.com
* @date 2020-02-23 00:03:18
*/
@Api(tags = "spu图片 管理")
@RestController
@RequestMapping("pms/spuimages")
public class SpuImagesController {
@Autowired
private SpuImagesService spuImagesService;
/**
* 列表
*/
@ApiOperation("分页查询(排序)")
@GetMapping("/list")
@PreAuthorize("hasAuthority('pms:spuimages:list')")
public Resp<PageVo> list(QueryCondition queryCondition) {
PageVo page = spuImagesService.queryPage(queryCondition);
return Resp.ok(page);
}
/**
* 信息
*/
@ApiOperation("详情查询")
@GetMapping("/info/{id}")
@PreAuthorize("hasAuthority('pms:spuimages:info')")
public Resp<SpuImagesEntity> info(@PathVariable("id") Long id){
SpuImagesEntity spuImages = spuImagesService.getById(id);
return Resp.ok(spuImages);
}
/**
* 保存
*/
@ApiOperation("保存")
@PostMapping("/save")
@PreAuthorize("hasAuthority('pms:spuimages:save')")
public Resp<Object> save(@RequestBody SpuImagesEntity spuImages){
spuImagesService.save(spuImages);
return Resp.ok(null);
}
/**
* 修改
*/
@ApiOperation("修改")
@PostMapping("/update")
@PreAuthorize("hasAuthority('pms:spuimages:update')")
public Resp<Object> update(@RequestBody SpuImagesEntity spuImages){
spuImagesService.updateById(spuImages);
return Resp.ok(null);
}
/**
* 删除
*/
@ApiOperation("删除")
@PostMapping("/delete")
@PreAuthorize("hasAuthority('pms:spuimages:delete')")
public Resp<Object> delete(@RequestBody Long[] ids){
spuImagesService.removeByIds(Arrays.asList(ids));
return Resp.ok(null);
}
}
|
/*
* Copyright 2000-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 com.intellij.ui;
import com.intellij.openapi.ui.Divider;
import com.intellij.openapi.ui.PseudoSplitter;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.vcs.changes.RefreshablePanel;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.JBUI.Panels;
import com.intellij.util.ui.MouseEventHandler;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import static com.intellij.icons.AllIcons.General.*;
public abstract class SplitterWithSecondHideable {
public interface OnOffListener<T> {
void on(T t);
void off(T t);
}
@NotNull private final PseudoSplitter mySplitter;
@NotNull private final AbstractTitledSeparatorWithIcon myTitledSeparator;
@NotNull private final OnOffListener<Integer> myListener;
@NotNull private final JPanel myFictivePanel;
private float myPreviousProportion;
public SplitterWithSecondHideable(boolean vertical,
@NotNull String separatorText,
@NotNull JComponent firstComponent,
@NotNull OnOffListener<Integer> listener) {
myListener = listener;
myFictivePanel = Panels.simplePanel();
myTitledSeparator = new MyTitledSeparator(separatorText, vertical);
mySplitter = new MySplitter(vertical);
mySplitter.setDoubleBuffered(true);
mySplitter.setFirstComponent(firstComponent);
mySplitter.setSecondComponent(myFictivePanel);
mySplitter.setProportion(1.0f);
}
public void setText(String value) {
myTitledSeparator.setText(value);
}
@NotNull
public Splitter getComponent() {
return mySplitter;
}
protected abstract RefreshablePanel createDetails();
protected abstract float getSplitterInitialProportion();
public float getUsedProportion() {
return isOn() ? mySplitter.getProportion() : myPreviousProportion;
}
public void initOn() {
myTitledSeparator.initOn();
}
public void on() {
myTitledSeparator.on();
}
public void off() {
myTitledSeparator.off();
}
public boolean isOn() {
return myTitledSeparator.myOn;
}
private class MyTitledSeparator extends AbstractTitledSeparatorWithIcon {
public MyTitledSeparator(@NotNull String separatorText, boolean vertical) {
super(ComboArrowRight, vertical ? ComboArrowDown : ComboArrowRightPassive, separatorText);
}
@Override
protected RefreshablePanel createPanel() {
return createDetails();
}
@Override
protected void initOnImpl() {
float proportion = myPreviousProportion > 0 ? myPreviousProportion : getSplitterInitialProportion();
mySplitter.setSecondComponent(myDetailsComponent.getPanel());
mySplitter.setResizeEnabled(true);
SwingUtilities.invokeLater(() -> {
mySplitter.fixFirst(proportion);
mySplitter.invalidate();
mySplitter.validate();
mySplitter.repaint();
});
}
@Override
protected void onImpl() {
float proportion = myPreviousProportion > 0 ? myPreviousProportion : getSplitterInitialProportion();
int firstSize = mySplitter.isVertical() ? mySplitter.getFirstComponent().getHeight() : mySplitter.getFirstComponent().getWidth();
// !! order is important! first fix
mySplitter.fixFirst();
myListener.on((int)((1 - proportion) * firstSize / proportion));
mySplitter.setSecondComponent(myDetailsComponent.getPanel());
mySplitter.revalidate();
mySplitter.repaint();
mySplitter.setResizeEnabled(true);
}
@Override
protected void offImpl() {
int previousSize = mySplitter.isVertical() ? mySplitter.getSecondComponent().getHeight() : mySplitter.getSecondComponent().getWidth();
mySplitter.setSecondComponent(myFictivePanel);
myPreviousProportion = mySplitter.getProportion();
mySplitter.freeAll();
mySplitter.setProportion(1.0f);
mySplitter.revalidate();
mySplitter.repaint();
myListener.off(previousSize);
mySplitter.setResizeEnabled(false);
}
}
private class MySplitter extends PseudoSplitter {
@NotNull private final MouseEventHandler myMouseListener = new MouseEventHandler() {
@Override
public void mouseEntered(MouseEvent event) {
myTitledSeparator.mySeparator.setCursor(new Cursor(isOn() ? Cursor.S_RESIZE_CURSOR : Cursor.DEFAULT_CURSOR));
super.mouseEntered(event);
}
@Override
public void mouseExited(MouseEvent event) {
myTitledSeparator.mySeparator.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
super.mouseExited(event);
}
@Override
protected void handle(MouseEvent event) {
if (event.getID() == MouseEvent.MOUSE_DRAGGED || event.getID() == MouseEvent.MOUSE_MOVED) {
((MyDivider)myDivider).processMouseMotionEvent(event);
}
else {
((MyDivider)myDivider).processMouseEvent(event);
}
}
};
public MySplitter(boolean vertical) {
super(vertical);
myTitledSeparator.mySeparator.addMouseListener(myMouseListener);
myTitledSeparator.mySeparator.addMouseMotionListener(myMouseListener);
}
@Override
protected Divider createDivider() {
MyDivider divider = new MyDivider();
divider.add(myTitledSeparator,
new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.emptyInsets(),
0, 0));
return divider;
}
@Override
public int getDividerWidth() {
return isVertical() ? myTitledSeparator.getHeight() : myTitledSeparator.getWidth();
}
private class MyDivider extends DividerImpl {
@Override
public void processMouseMotionEvent(MouseEvent e) {
super.processMouseMotionEvent(e);
}
@Override
public void processMouseEvent(MouseEvent e) {
super.processMouseEvent(e);
}
}
}
}
|
/*
* Druid - a distributed column store.
* Copyright 2012 - 2015 Metamarkets Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.druid.segment.filter;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import io.druid.query.filter.AndDimFilter;
import io.druid.query.filter.DimFilter;
import io.druid.query.filter.ExtractionDimFilter;
import io.druid.query.filter.Filter;
import io.druid.query.filter.InDimFilter;
import io.druid.query.filter.JavaScriptDimFilter;
import io.druid.query.filter.NotDimFilter;
import io.druid.query.filter.OrDimFilter;
import io.druid.query.filter.RegexDimFilter;
import io.druid.query.filter.SearchQueryDimFilter;
import io.druid.query.filter.SelectorDimFilter;
import io.druid.query.filter.SpatialDimFilter;
import javax.annotation.Nullable;
import java.util.List;
/**
*/
public class Filters
{
public static List<Filter> convertDimensionFilters(List<DimFilter> filters){
return Lists.transform(
filters,
new Function<DimFilter, Filter>()
{
@Override
public Filter apply(@Nullable DimFilter input)
{
return convertDimensionFilters(input);
}
}
);
}
public static Filter convertDimensionFilters(DimFilter dimFilter)
{
if (dimFilter == null) {
return null;
}
Filter filter = null;
if (dimFilter instanceof AndDimFilter) {
filter = new AndFilter(convertDimensionFilters(((AndDimFilter) dimFilter).getFields()));
} else if (dimFilter instanceof OrDimFilter) {
filter = new OrFilter(convertDimensionFilters(((OrDimFilter) dimFilter).getFields()));
} else if (dimFilter instanceof NotDimFilter) {
filter = new NotFilter(convertDimensionFilters(((NotDimFilter) dimFilter).getField()));
} else if (dimFilter instanceof SelectorDimFilter) {
final SelectorDimFilter selectorDimFilter = (SelectorDimFilter) dimFilter;
filter = new SelectorFilter(selectorDimFilter.getDimension(), selectorDimFilter.getValue());
} else if (dimFilter instanceof ExtractionDimFilter) {
final ExtractionDimFilter extractionDimFilter = (ExtractionDimFilter) dimFilter;
filter = new ExtractionFilter(
extractionDimFilter.getDimension(),
extractionDimFilter.getValue(),
extractionDimFilter.getExtractionFn()
);
} else if (dimFilter instanceof RegexDimFilter) {
final RegexDimFilter regexDimFilter = (RegexDimFilter) dimFilter;
filter = new RegexFilter(regexDimFilter.getDimension(), regexDimFilter.getPattern());
} else if (dimFilter instanceof SearchQueryDimFilter) {
final SearchQueryDimFilter searchQueryFilter = (SearchQueryDimFilter) dimFilter;
filter = new SearchQueryFilter(searchQueryFilter.getDimension(), searchQueryFilter.getQuery());
} else if (dimFilter instanceof JavaScriptDimFilter) {
final JavaScriptDimFilter javaScriptDimFilter = (JavaScriptDimFilter) dimFilter;
filter = new JavaScriptFilter(javaScriptDimFilter.getDimension(), javaScriptDimFilter.getFunction());
} else if (dimFilter instanceof SpatialDimFilter) {
final SpatialDimFilter spatialDimFilter = (SpatialDimFilter) dimFilter;
filter = new SpatialFilter(spatialDimFilter.getDimension(), spatialDimFilter.getBound());
} else if (dimFilter instanceof InDimFilter) {
final InDimFilter inDimFilter = (InDimFilter) dimFilter;
final List<Filter> listFilters = Lists.transform(
inDimFilter.getValues(), new Function<String, Filter>()
{
@Nullable
@Override
public Filter apply(@Nullable String input)
{
return new SelectorFilter(inDimFilter.getDimension(), input);
}
}
);
filter = new OrFilter(listFilters);
}
return filter;
}
}
|
/*
* 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.kafka.streams.processor.internals;
import org.apache.kafka.common.internals.Topic;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
/**
* InternalTopicConfig captures the properties required for configuring
* the internal topics we create for change-logs and repartitioning etc.
*/
public class InternalTopicConfig {
public enum CleanupPolicy { compact, delete }
private final String name;
private final Map<String, String> logConfig;
private final Set<CleanupPolicy> cleanupPolicies;
private Long retentionMs;
public InternalTopicConfig(final String name, final Set<CleanupPolicy> defaultCleanupPolicies, final Map<String, String> logConfig) {
Objects.requireNonNull(name, "name can't be null");
Topic.validate(name);
if (defaultCleanupPolicies.isEmpty()) {
throw new IllegalArgumentException("Must provide at least one cleanup policy");
}
this.name = name;
this.cleanupPolicies = defaultCleanupPolicies;
this.logConfig = logConfig;
}
/* for test use only */
boolean isCompacted() {
return cleanupPolicies.contains(CleanupPolicy.compact);
}
private boolean isCompactDelete() {
return cleanupPolicies.contains(CleanupPolicy.compact) && cleanupPolicies.contains(CleanupPolicy.delete);
}
/**
* Get the configured properties for this topic. If rententionMs is set then
* we add additionalRetentionMs to work out the desired retention when cleanup.policy=compact,delete
*
* @param additionalRetentionMs - added to retention to allow for clock drift etc
* @return Properties to be used when creating the topic
*/
public Properties toProperties(final long additionalRetentionMs) {
final Properties result = new Properties();
for (Map.Entry<String, String> configEntry : logConfig.entrySet()) {
result.put(configEntry.getKey(), configEntry.getValue());
}
if (retentionMs != null && isCompactDelete()) {
result.put(InternalTopicManager.RETENTION_MS, String.valueOf(retentionMs + additionalRetentionMs));
}
if (!logConfig.containsKey(InternalTopicManager.CLEANUP_POLICY_PROP)) {
final StringBuilder builder = new StringBuilder();
for (CleanupPolicy cleanupPolicy : cleanupPolicies) {
builder.append(cleanupPolicy.name()).append(",");
}
builder.deleteCharAt(builder.length() - 1);
result.put(InternalTopicManager.CLEANUP_POLICY_PROP, builder.toString());
}
return result;
}
public String name() {
return name;
}
public void setRetentionMs(final long retentionMs) {
if (!logConfig.containsKey(InternalTopicManager.RETENTION_MS)) {
this.retentionMs = retentionMs;
}
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final InternalTopicConfig that = (InternalTopicConfig) o;
return Objects.equals(name, that.name) &&
Objects.equals(logConfig, that.logConfig) &&
Objects.equals(retentionMs, that.retentionMs) &&
Objects.equals(cleanupPolicies, that.cleanupPolicies);
}
@Override
public int hashCode() {
return Objects.hash(name, logConfig, retentionMs, cleanupPolicies);
}
@Override
public String toString() {
return "InternalTopicConfig(" +
"name=" + name +
", logConfig=" + logConfig +
", cleanupPolicies=" + cleanupPolicies +
", retentionMs=" + retentionMs +
")";
}
}
|
package io.github.prototypez.appjoint.app;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import io.github.prototypez.appjoint.core.ServiceProvider;
import io.github.prototypez.service.app.AppService;
import io.github.prototypez.service.app.callback.AppCallback;
import io.github.prototypez.service.app.entity.AppEntity;
import io.reactivex.Observable;
/**
* 组件化过程不可能一蹴而就,组件化的过程是 App 模块渐渐 “瘦身”的过程
* 最终 App 模块仅仅作为整个应用的一个 “application 壳”,但是组件化
* 的过程是缓慢的,我们要允许在组件化的过程中,子模块依然可以调用 App
* 模块内的方法
*/
@ServiceProvider
public class AppServiceImpl implements AppService {
@Override public String callMethodSyncOfApp() {
return "syncMethodResultApp";
}
@Override public Observable<AppEntity> observableOfApp() {
return Observable.just(new AppEntity("rxJavaResultApp"));
}
@Override public void callMethodAsyncOfApp(final AppCallback<AppEntity> callback) {
new Thread(() -> callback.onResult(new AppEntity("asyncMethodResultApp"))).start();
}
@Override public void startActivityOfApp(Context context) {
Intent intent = new Intent(context, LegacyActivity.class);
context.startActivity(intent);
}
@Override public Fragment obtainFragmentOfApp() {
return LegacyFragment.Companion.newInstance();
}
}
|
package one.jodi.core.service;
public interface ProjectService {
void deleteProject();
}
|
/*
According to apache license
This is fork of christocracy cordova-plugin-background-geolocation plugin
https://github.com/christocracy/cordova-plugin-background-geolocation
Differences to original version:
1. location is not persisted to db anymore, but broadcasted using intents instead
*/
package com.tenforwardconsulting.bgloc;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.marianhello.bgloc.Config;
import com.marianhello.bgloc.provider.AbstractLocationProvider;
import com.marianhello.utils.Tone;
import java.util.List;
import static java.lang.Math.abs;
import static java.lang.Math.pow;
import static java.lang.Math.round;
public class DistanceFilterLocationProvider extends AbstractLocationProvider implements LocationListener {
private static final String TAG = DistanceFilterLocationProvider.class.getSimpleName();
private static final String P_NAME = "com.tenforwardconsulting.cordova.backgroundgeolocation";
private static final String STATIONARY_REGION_ACTION = P_NAME + ".STATIONARY_REGION_ACTION";
private static final String STATIONARY_ALARM_ACTION = P_NAME + ".STATIONARY_ALARM_ACTION";
private static final String SINGLE_LOCATION_UPDATE_ACTION = P_NAME + ".SINGLE_LOCATION_UPDATE_ACTION";
private static final String STATIONARY_LOCATION_MONITOR_ACTION = P_NAME + ".STATIONARY_LOCATION_MONITOR_ACTION";
private static final long STATIONARY_TIMEOUT = 5 * 1000 * 60; // 5 minutes.
private static final long STATIONARY_LOCATION_POLLING_INTERVAL_LAZY = 3 * 1000 * 60; // 3 minutes.
private static final long STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE = 1 * 1000 * 60; // 1 minute.
private static final int MAX_STATIONARY_ACQUISITION_ATTEMPTS = 5;
private static final int MAX_SPEED_ACQUISITION_ATTEMPTS = 3;
private Boolean isMoving = false;
private Boolean isAcquiringStationaryLocation = false;
private Boolean isAcquiringSpeed = false;
private Integer locationAcquisitionAttempts = 0;
private Location lastLocation;
private Location stationaryLocation;
private float stationaryRadius;
private PendingIntent stationaryAlarmPI;
private PendingIntent stationaryLocationPollingPI;
private long stationaryLocationPollingInterval;
private PendingIntent stationaryRegionPI;
private PendingIntent singleUpdatePI;
private Integer scaledDistanceFilter;
private Criteria criteria;
private LocationManager locationManager;
private AlarmManager alarmManager;
private boolean isStarted = false;
public DistanceFilterLocationProvider(Context context) {
super(context);
PROVIDER_ID = Config.DISTANCE_FILTER_PROVIDER;
}
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
// Stop-detection PI
stationaryAlarmPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));
// Stationary region PI
stationaryRegionPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_REGION_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));
// Stationary location monitor PI
stationaryLocationPollingPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));
// One-shot PI (TODO currently unused)
singleUpdatePI = PendingIntent.getBroadcast(mContext, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));
// Location criteria
criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
}
@Override
public void onStart() {
if (isStarted) {
return;
}
logger.info("Start recording");
scaledDistanceFilter = mConfig.getDistanceFilter();
isStarted = true;
setPace(false);
}
@Override
public void onStop() {
if (!isStarted) {
return;
}
try {
locationManager.removeUpdates(this);
locationManager.removeProximityAlert(stationaryRegionPI);
} catch (SecurityException e) {
//noop
} finally {
isStarted = false;
}
}
@Override
public void onCommand(int commandId, int arg1) {
switch(commandId) {
case CMD_SWITCH_MODE:
setPace(arg1 == BACKGROUND_MODE ? false : true);
return;
}
}
@Override
public void onConfigure(Config config) {
super.onConfigure(config);
if (isStarted) {
onStop();
onStart();
}
}
@Override
public boolean isStarted() {
return isStarted;
}
/**
*
* @param value set true to engage "aggressive", battery-consuming tracking, false for stationary-region tracking
*/
private void setPace(Boolean value) {
if (!isStarted) {
return;
}
logger.info("Setting pace: {}", value);
Boolean wasMoving = isMoving;
isMoving = value;
isAcquiringStationaryLocation = false;
isAcquiringSpeed = false;
stationaryLocation = null;
try {
locationManager.removeUpdates(this);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setHorizontalAccuracy(translateDesiredAccuracy(mConfig.getDesiredAccuracy()));
criteria.setPowerRequirement(Criteria.POWER_HIGH);
if (isMoving) {
// setPace can be called while moving, after distanceFilter has been recalculated. We don't want to re-acquire velocity in this case.
if (!wasMoving) {
isAcquiringSpeed = true;
}
} else {
isAcquiringStationaryLocation = true;
}
// Temporarily turn on super-aggressive geolocation on all providers when acquiring velocity or stationary location.
if (isAcquiringSpeed || isAcquiringStationaryLocation) {
locationAcquisitionAttempts = 0;
// Turn on each provider aggressively for a short period of time
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
if (provider != LocationManager.PASSIVE_PROVIDER) {
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
}
} else {
locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), mConfig.getInterval(), scaledDistanceFilter, this);
}
} catch (SecurityException e) {
logger.error("Security exception: {}", e.getMessage());
this.handleSecurityException(e);
}
}
/**
* Translates a number representing desired accuracy of Geolocation system from set [0, 10, 100, 1000].
* 0: most aggressive, most accurate, worst battery drain
* 1000: least aggressive, least accurate, best for battery.
*/
private Integer translateDesiredAccuracy(Integer accuracy) {
if (accuracy >= 1000) {
return Criteria.ACCURACY_LOW;
}
if (accuracy >= 100) {
return Criteria.ACCURACY_MEDIUM;
}
if (accuracy >= 10) {
return Criteria.ACCURACY_HIGH;
}
if (accuracy >= 0) {
return Criteria.ACCURACY_HIGH;
}
return Criteria.ACCURACY_MEDIUM;
}
/**
* Returns the most accurate and timely previously detected location.
* Where the last result is beyond the specified maximum distance or
* latency a one-off location update is returned via the {@link LocationListener}
* specified in {@link setChangedLocationListener}.
* @param minTime Minimum time required between location updates.
* @return The most accurate and / or timely previously detected location.
*/
public Location getLastBestLocation() {
Location bestResult = null;
String bestProvider = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
long minTime = System.currentTimeMillis() - mConfig.getInterval();
logger.info("Fetching last best location: radius={} minTime={}", mConfig.getStationaryRadius(), minTime);
try {
// Iterate through all the providers on the system, keeping
// note of the most accurate result within the acceptable time limit.
// If no result is found within maxTime, return the newest Location.
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
logger.debug("Test provider={} lat={} lon={} acy={} v={}m/s time={}", provider, location.getLatitude(), location.getLongitude(), location.getAccuracy(), location.getSpeed(), location.getTime());
float accuracy = location.getAccuracy();
long time = location.getTime();
if ((time > minTime && accuracy < bestAccuracy)) {
bestProvider = provider;
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
}
}
if (bestResult != null) {
logger.debug("Best result found provider={} lat={} lon={} acy={} v={}m/s time={}", bestProvider, bestResult.getLatitude(), bestResult.getLongitude(), bestResult.getAccuracy(), bestResult.getSpeed(), bestResult.getTime());
}
} catch (SecurityException e) {
logger.error("Security exception: {}", e.getMessage());
this.handleSecurityException(e);
}
return bestResult;
}
public void onLocationChanged(Location location) {
logger.debug("Location change: {} isMoving={}", location.toString(), isMoving);
if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation==null) {
// Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now.
setPace(false);
}
showDebugToast( "mv:" + isMoving + ",acy:" + location.getAccuracy() + ",v:" + location.getSpeed() + ",df:" + scaledDistanceFilter);
if (isAcquiringStationaryLocation) {
if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) {
stationaryLocation = location;
}
if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) {
isAcquiringStationaryLocation = false;
startMonitoringStationaryRegion(stationaryLocation);
handleStationary(stationaryLocation, stationaryRadius);
return;
} else {
// Unacceptable stationary-location: bail-out and wait for another.
playDebugTone(Tone.BEEP);
return;
}
} else if (isAcquiringSpeed) {
if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) {
// Got enough samples, assume we're confident in reported speed now. Play "woohoo" sound.
playDebugTone(Tone.DOODLY_DOO);
isAcquiringSpeed = false;
scaledDistanceFilter = calculateDistanceFilter(location.getSpeed());
setPace(true);
} else {
playDebugTone(Tone.BEEP);
return;
}
} else if (isMoving) {
playDebugTone(Tone.BEEP);
// Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped.
if ( (location.getSpeed() >= 1) && (location.getAccuracy() <= mConfig.getStationaryRadius()) ) {
resetStationaryAlarm();
}
// Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace.
Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed());
if (newDistanceFilter != scaledDistanceFilter.intValue()) {
logger.info("Updating distanceFilter: new={} old={}", newDistanceFilter, scaledDistanceFilter);
scaledDistanceFilter = newDistanceFilter;
setPace(true);
}
if (lastLocation != null && location.distanceTo(lastLocation) < mConfig.getDistanceFilter()) {
return;
}
} else if (stationaryLocation != null) {
return;
}
// Go ahead and cache, push to server
lastLocation = location;
handleLocation(location);
}
public void resetStationaryAlarm() {
alarmManager.cancel(stationaryAlarmPI);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + STATIONARY_TIMEOUT, stationaryAlarmPI); // Millisec * Second * Minute
}
private Integer calculateDistanceFilter(Float speed) {
Double newDistanceFilter = (double) mConfig.getDistanceFilter();
if (speed < 100) {
float roundedDistanceFilter = (round(speed / 5) * 5);
newDistanceFilter = pow(roundedDistanceFilter, 2) + (double) mConfig.getDistanceFilter();
}
return (newDistanceFilter.intValue() < 1000) ? newDistanceFilter.intValue() : 1000;
}
private void startMonitoringStationaryRegion(Location location) {
try {
locationManager.removeUpdates(this);
float stationaryRadius = mConfig.getStationaryRadius();
float proximityRadius = (location.getAccuracy() < stationaryRadius) ? stationaryRadius : location.getAccuracy();
stationaryLocation = location;
logger.info("startMonitoringStationaryRegion: lat={} lon={} acy={}", location.getLatitude(), location.getLongitude(), proximityRadius);
// Here be the execution of the stationary region monitor
locationManager.addProximityAlert(
location.getLatitude(),
location.getLongitude(),
proximityRadius,
(long)-1,
stationaryRegionPI
);
this.stationaryRadius = proximityRadius;
startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY);
} catch (SecurityException e) {
logger.error("Security exception: {}", e.getMessage());
this.handleSecurityException(e);
}
}
/**
* User has exit his stationary region! Initiate aggressive geolocation!
*/
public void onExitStationaryRegion(Location location) {
// Filter-out spurious region-exits: must have at least a little speed to move out of stationary-region
playDebugTone(Tone.BEEP_BEEP_BEEP);
logger.info("Exited stationary: lat={} long={} acy={}}'",
location.getLatitude(), location.getLongitude(), location.getAccuracy());
try {
// Cancel the periodic stationary location monitor alarm.
alarmManager.cancel(stationaryLocationPollingPI);
// Kill the current region-monitor we just walked out of.
locationManager.removeProximityAlert(stationaryRegionPI);
// Engage aggressive tracking.
this.setPace(true);
} catch (SecurityException e) {
logger.error("Security exception: {}", e.getMessage());
this.handleSecurityException(e);
}
}
public void startPollingStationaryLocation(long interval) {
// proximity-alerts don't seem to work while suspended in latest Android 4.42 (works in 4.03). Have to use AlarmManager to sample
// location at regular intervals with a one-shot.
stationaryLocationPollingInterval = interval;
alarmManager.cancel(stationaryLocationPollingPI);
long start = System.currentTimeMillis() + (60 * 1000);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, start, interval, stationaryLocationPollingPI);
}
public void onPollStationaryLocation(Location location) {
float stationaryRadius = mConfig.getStationaryRadius();
if (isMoving) {
return;
}
playDebugTone(Tone.BEEP);
float distance = 0.0f;
if (stationaryLocation != null) {
distance = abs(location.distanceTo(stationaryLocation) - stationaryLocation.getAccuracy() - location.getAccuracy());
}
showDebugToast("Stationary exit in " + (stationaryRadius-distance) + "m");
// TODO http://www.cse.buffalo.edu/~demirbas/publications/proximity.pdf
// determine if we're almost out of stationary-distance and increase monitoring-rate.
logger.info("Distance from stationary location: {}", distance);
if (distance > stationaryRadius) {
onExitStationaryRegion(location);
} else if (distance > 0) {
startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE);
} else if (stationaryLocationPollingInterval != STATIONARY_LOCATION_POLLING_INTERVAL_LAZY) {
startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY);
}
}
/**
* Broadcast receiver for receiving a single-update from LocationManager.
*/
private BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_LOCATION_CHANGED;
Location location = (Location)intent.getExtras().get(key);
if (location != null) {
logger.debug("Single location update: " + location.toString());
onPollStationaryLocation(location);
}
}
};
/**
* Broadcast receiver which detects a user has stopped for a long enough time to be determined as STOPPED
*/
private BroadcastReceiver stationaryAlarmReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
logger.info("stationaryAlarm fired");
setPace(false);
}
};
/**
* Broadcast receiver to handle stationaryMonitor alarm, fired at low frequency while monitoring stationary-region.
* This is required because latest Android proximity-alerts don't seem to operate while suspended. Regularly polling
* the location seems to trigger the proximity-alerts while suspended.
*/
private BroadcastReceiver stationaryLocationMonitorReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
logger.info("Stationary location monitor fired");
playDebugTone(Tone.DIALTONE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
try {
locationManager.requestSingleUpdate(criteria, singleUpdatePI);
} catch (SecurityException e) {
logger.error("Security exception: {}", e.getMessage());
}
}
};
/**
* Broadcast receiver which detects a user has exit his circular stationary-region determined by the greater of stationaryLocation.getAccuracy() OR stationaryRadius
*/
private BroadcastReceiver stationaryRegionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
logger.debug("Entering stationary region");
if (isMoving) {
setPace(false);
}
}
else {
logger.debug("Exiting stationary region");
// There MUST be a valid, recent location if this event-handler was called.
Location location = getLastBestLocation();
if (location != null) {
onExitStationaryRegion(location);
}
}
}
};
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
logger.debug("Provider {} was disabled", provider);
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
logger.debug("Provider {} was enabled", provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
logger.debug("Provider {} status changed: {}", provider, status);
}
@Override
public void onDestroy() {
logger.info("Destroying DistanceFilterLocationProvider");
this.onStop();
alarmManager.cancel(stationaryAlarmPI);
alarmManager.cancel(stationaryLocationPollingPI);
unregisterReceiver(stationaryAlarmReceiver);
unregisterReceiver(singleUpdateReceiver);
unregisterReceiver(stationaryRegionReceiver);
unregisterReceiver(stationaryLocationMonitorReceiver);
super.onDestroy();
}
}
|
package de.dytanic.cloudnet.ext.bridge.nukkit.event;
import cn.nukkit.event.HandlerList;
import de.dytanic.cloudnet.ext.bridge.player.NetworkConnectionInfo;
import de.dytanic.cloudnet.ext.bridge.player.NetworkPlayerServerInfo;
/**
* {@inheritDoc}
*/
public final class NukkitBridgeServerPlayerLoginRequestEvent extends NukkitBridgeEvent {
private static final HandlerList handlers = new HandlerList();
private final NetworkConnectionInfo networkConnectionInfo;
private final NetworkPlayerServerInfo networkPlayerServerInfo;
public NukkitBridgeServerPlayerLoginRequestEvent(NetworkConnectionInfo networkConnectionInfo, NetworkPlayerServerInfo networkPlayerServerInfo) {
this.networkConnectionInfo = networkConnectionInfo;
this.networkPlayerServerInfo = networkPlayerServerInfo;
}
public static HandlerList getHandlers() {
return NukkitBridgeServerPlayerLoginRequestEvent.handlers;
}
public NetworkConnectionInfo getNetworkConnectionInfo() {
return this.networkConnectionInfo;
}
public NetworkPlayerServerInfo getNetworkPlayerServerInfo() {
return this.networkPlayerServerInfo;
}
}
|
/**
*
*/
package com.hsjawanda.gaeobjectify.util;
import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.EMPTY;
import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.defaultString;
import static com.hsjawanda.gaeobjectify.repackaged.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.mail.internet.InternetAddress;
import com.googlecode.objectify.Key;
/**
* @author Harshdeep S Jawanda (hsjawanda@gmail.com)
*
*/
public class Strings {
private static final Logger log = Logger.getLogger(Strings.class.getName());
public static final String NULL = "null";
private Strings() {
}
@Nonnull
public static String toString(InternetAddress addr) {
return null != addr ? String.format("%s <%s>", defaultString(addr.getPersonal(), NULL),
defaultString(addr.getAddress(), NULL)) : NULL;
}
public static String toString(Key<?> key) {
return null == key ? NULL
: "Key(" + key.getKind() + ", "
+ (null == key.getName() ? Long.toString(key.getId()) : "'" + key.getName() + "'") + ")";
}
public static void append(@Nullable Appendable appendable, @Nullable Key<?> key) {
if (null == appendable)
return;
try {
appendable.append(toString(key));
} catch (IOException e) {
// Extremely unlikely
log.log(Level.WARNING, "Error appending Key<?>", e);
}
}
@Nonnull
public static String toString(Object obj) {
String retVal = null == obj ? EMPTY : obj.toString();
return null == retVal ? EMPTY : retVal;
}
public static String toString(byte[] input) {
return null == input ? NULL : new String(input);
}
public static String toString(char[] input) {
return null == input ? EMPTY : new String(input);
}
public static String toString(String input) {
return null == input ? NULL : input;
}
public static Long getAsLong(String stringValue) {
if (null == stringValue)
return null;
try {
return Long.valueOf(stringValue);
} catch (NumberFormatException e) {
log.warning("Exception converting '" + stringValue + "' to Long: "
+ System.lineSeparator() + e.getMessage());
} catch (Exception e) {
log.log(Level.WARNING, "Exception converting '" + stringValue + "' to Long...", e);
}
return null;
}
public static long getAsLong(String stringValue, long defaultValue) {
if (isNotBlank(stringValue)) {
try {
return Long.parseLong(stringValue);
} catch (NumberFormatException e) {
log.warning(
"Exception converting '" + stringValue + "' to long: " + e.getMessage());
} catch (Exception e) {
log.log(Level.WARNING,
"Exception converting '" + stringValue + "' to long. Stacktrace:", e);
}
}
return defaultValue;
}
public static int getAsInt(String stringValue, int defaultValue) {
if (isNotBlank(stringValue)) {
try {
return Integer.parseInt(stringValue);
} catch (NumberFormatException e) {
log.warning(
"Exception converting '" + stringValue + "' to int: " + e.getMessage());
} catch (Exception e) {
log.log(Level.WARNING,
"Exception converting '" + stringValue + "' to int. Stacktrace:", e);
}
}
return defaultValue;
}
public static Integer getAsInteger(String stringValue) {
if (isNotBlank(stringValue)) {
try {
return Integer.valueOf(stringValue);
} catch (NumberFormatException e) {
log.warning(
"Exception converting '" + stringValue + "' to Integer: " + e.getMessage());
} catch (Exception e) {
log.log(Level.WARNING,
"Exception converting '" + stringValue + "' to Integer. Stacktrace:", e);
}
}
return null;
}
public static Double getAsDouble(String stringValue) {
if (null == stringValue)
return null;
try {
return Double.valueOf(stringValue);
} catch (NumberFormatException e) {
log.warning("Exception converting '" + stringValue + "' to Double: "
+ System.lineSeparator() + e.getMessage());
} catch (Exception e) {
log.log(Level.WARNING, "Exception converting '" + stringValue + "' to Double...", e);
}
return null;
}
public static Boolean getAsBoolean(String stringValue) {
if (null == stringValue)
return null;
return Boolean.valueOf(stringValue);
}
}
|
package xyz.white.editor;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.kotcrab.vis.ui.VisUI;
public class MainEditor extends ApplicationAdapter {
private MainStage mainStage;
private Viewport mainViewPort;
@Override
public void create () {
this.resize(Config.width,Config.height);
// VisUI.load("skins/tixel/x1/tixel.json");
VisUI.load();
mainViewPort = new FillViewport(Config.width,Config.height);
mainStage = new MainStage(mainViewPort);
Gdx.input.setInputProcessor(mainStage);
}
@Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
mainStage.act(Gdx.graphics.getDeltaTime());
mainStage.draw();
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
if (mainViewPort!=null)mainViewPort.update(width,height,true);
}
@Override
public void dispose () {
Gdx.app.log("app","dispose-----1111-----");
EditorManager.getInstance().clearEvents();
VisUI.dispose();
mainStage.dispose();
}
}
|
package com.example.demo.autowired.nullable;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Nullable {
private List<String> nameList;
private Set<Integer> integerSet;
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
public Set<Integer> getIntegerSet() {
return integerSet;
}
public void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
// @Autowired
// public Nullable(@org.springframework.lang.Nullable List<String> nameList,
// @org.springframework.lang.Nullable Set<Integer> integerSet) {
// this.nameList = nameList;
// this.integerSet = integerSet;
// }
// @Autowired
// public Nullable(List<String> nameList, Set<Integer> integerSet) {
// this.nameList = nameList;
// this.integerSet = integerSet;
// }
@Override
public String toString() {
return "Nullable{" + "nameList=" + nameList + ", integerSet=" + integerSet + '}';
}
private static Logger log = LoggerFactory.getLogger(Nullable.class);
public static void main(String[] args) {
// AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ArrayConfigure.class,
// Nullable.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Nullable.class);
log.info("{}", context.getBean("nullable", Nullable.class));
context.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.