blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2 values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557 values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82 values | src_encoding stringclasses 28 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 5.41M | extension stringclasses 11 values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c17a0d0fa4dbdd8cecfc184e1a9391c9bd0fe0bd | c624dc1ab334ca673c2c141694d01937fcb71ccb | /src/main/java/com/chenhai/educationsystem/dto/FeeDto.java | 39e4125371a66fa74a71dc38304c6122c7a414bd | [] | no_license | shenzhiqiang1997/education-system | 12a4ad1538fde7c4414749e4bb23b6698c37cf88 | f13e51ecea76cf3a5bf820637605f5799c5b1889 | refs/heads/master | 2020-03-12T10:53:27.438916 | 2018-06-19T10:09:34 | 2018-06-19T10:09:34 | 130,583,545 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | package com.chenhai.educationsystem.dto;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
public class FeeDto {
private Integer studentId;
@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm")
private Date startTime;
@DateTimeFormat(pattern = "yyyy/MM/dd HH:mm")
private Date endTime;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}
| [
"1422537078@qq.com"
] | 1422537078@qq.com |
4c7efef60c72766756b977cf93aa6ebf38cf644d | 275ab2f38937c63a26db1c1855dc3db3c4c7adc3 | /app/src/test/java/com/example/shana/chat/ExampleUnitTest.java | 1e3caaf1d45c7dc5480ffb0119ba047ba8ab82e4 | [] | no_license | TwilightNight/AndroidLesson1_Intent | 9fee3602d78f986862d9c890cfc5478fba706680 | 01ffdfaf733c24ba4cc9c2bc34ee5096757afaf8 | refs/heads/master | 2021-01-10T15:17:50.756272 | 2015-12-16T05:11:41 | 2015-12-16T05:11:41 | 47,692,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 315 | java | package com.example.shana.chat;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"rie00002@gmail.com"
] | rie00002@gmail.com |
a588dd6e758ced6f140b41a8909c01b1d4485c57 | a6080ba0c417838cf24f03cc6e4b9b6939f8eb3e | /backend/src/main/java/com/devsuperior/dscatalog/services/ProductService.java | 9693881a2a81d34c70c4f171c61f7ca8aa32cdea | [] | no_license | JonasRF/aula-deploy-aws | d96370a1e5f56ad8180dc4460fff0e6790a63a0f | e54a2ee7fe604ecbe9beb95cb36f41f106daf5fc | refs/heads/main | 2023-08-22T04:25:13.302813 | 2021-10-22T19:41:24 | 2021-10-22T19:41:24 | 419,431,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,193 | java | package com.devsuperior.dscatalog.services;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.devsuperior.dscatalog.DTO.CategoryDTo;
import com.devsuperior.dscatalog.DTO.ProductDTo;
import com.devsuperior.dscatalog.entities.Category;
import com.devsuperior.dscatalog.entities.Product;
import com.devsuperior.dscatalog.repositories.CategoryRepository;
import com.devsuperior.dscatalog.repositories.ProductRepository;
import com.devsuperior.dscatalog.services.exceptions.DataBaseException;
import com.devsuperior.dscatalog.services.exceptions.ResourceNotFoundException;
@Service
public class ProductService {
@Autowired
private ProductRepository repository;
@Autowired
private CategoryRepository categoryRepository;
@Transactional(readOnly = true)
public Page<ProductDTo> findAllPaged(Long categoryId, String name, Pageable pegeable) {
List<Category> categories = (categoryId == 0) ? null : Arrays.asList(categoryRepository.getOne(categoryId));
Page<Product> page = repository.find(categories, name, pegeable);
repository.findProductWithCategories(page.getContent());
return page.map(x -> new ProductDTo(x, x.getCategories()));
}
@Transactional(readOnly = true)
public ProductDTo findById(Long id) {
Optional<Product> obj = repository.findById(id);
Product entity = obj.orElseThrow(() -> new ResourceNotFoundException("Entity not found"));
return new ProductDTo(entity, entity.getCategories());
}
@Transactional(readOnly = true)
public ProductDTo insert(ProductDTo dto) {
Product entity = new Product();
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new ProductDTo(entity);
}
@Transactional
public ProductDTo update(Long id, ProductDTo dto) {
try {
Product entity = repository.getOne(id);
copyDtoToEntity(dto, entity);
entity = repository.save(entity);
return new ProductDTo(entity);
} catch (EntityNotFoundException e) {
throw new ResourceNotFoundException("Id not found" + id);
}
}
public void delete(Long id) {
try {
repository.deleteById(id);
} catch (EmptyResultDataAccessException e) {
throw new DataBaseException("id not found " + id);
} catch (DataIntegrityViolationException e) {
throw new DataBaseException("Integrity violation");
}
}
private void copyDtoToEntity(ProductDTo dto, Product entity) {
entity.setName(dto.getName());
entity.setDescription(dto.getDescription());
entity.setDate(dto.getDate());
entity.setImgUrl(dto.getImgUrl());
entity.setPrice(dto.getPrice());
entity.getCategories().clear();
for (CategoryDTo catDto : dto.getCategories()) {
Category category = categoryRepository.getOne(catDto.getId());
entity.getCategories().add(category);
}
}
}
| [
"jonasribeiro41@yahoo.com.br"
] | jonasribeiro41@yahoo.com.br |
0baee2864c9eb49c1895ad745df513052dc87db4 | b6a72e96311aa855ea33700aa263ec10adccd2d8 | /javaee-impl/src/main/java/org/jboss/forge/spec/javaee/validation/provider/HibernateValidatorProvider.java | 5153deecd41c84c12cead47c57e8caa307200fde | [] | no_license | ishaikovsky/core | 00bffde68ce10005d6272e9d0531cda3db8c21da | aeb57a6e7477872f07d387440127dc418e391b6b | refs/heads/master | 2021-01-15T19:39:20.360284 | 2011-05-18T18:59:08 | 2011-05-18T18:59:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,172 | java | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.forge.spec.javaee.validation.provider;
import java.util.LinkedHashSet;
import java.util.Set;
import org.jboss.forge.project.dependencies.Dependency;
import org.jboss.forge.project.dependencies.DependencyBuilder;
import org.jboss.forge.spec.javaee.descriptor.ValidationDescriptor;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import static java.util.Collections.unmodifiableSet;
import static org.jboss.forge.project.dependencies.ScopeType.PROVIDED;
import static org.jboss.forge.project.dependencies.ScopeType.RUNTIME;
/**
* @author Kevin Pollet
*/
public class HibernateValidatorProvider implements ValidationProvider
{
private final ValidationDescriptor defaultDescriptor;
private final Set<Dependency> dependencies;
private final Set<Dependency> additionalDependencies;
public HibernateValidatorProvider()
{
// define hibernate validator default descriptor file
this.defaultDescriptor = Descriptors.create(ValidationDescriptor.class)
.defaultProvider("org.hibernate.validator.HibernateValidator")
.messageInterpolator("org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator")
.traversableResolver("org.hibernate.validator.engine.resolver.DefaultTraversableResolver")
.constraintValidatorFactory("org.hibernate.validator.engine.ConstraintValidatorFactoryImpl");
// add hibernate validator dependencies
final DependencyBuilder hibernateValidator = DependencyBuilder.create()
.setGroupId("org.hibernate")
.setArtifactId("hibernate-validator")
.setVersion("[4.1.0.Final,)")
.setScopeType(PROVIDED);
final Set<Dependency> dependenciesTmpSet = new LinkedHashSet<Dependency>();
dependenciesTmpSet.add(hibernateValidator);
this.dependencies = unmodifiableSet(dependenciesTmpSet);
// add hibernate validator additional dependencies
final DependencyBuilder seamValidationAPI = DependencyBuilder.create()
.setGroupId("org.jboss.seam.validation")
.setArtifactId("seam-validation-api")
.setVersion("[3.0.0.Final,)");
final DependencyBuilder seamValidationImpl = DependencyBuilder.create()
.setGroupId("org.jboss.seam.validation")
.setArtifactId("seam-validation-impl")
.setVersion("[3.0.0.Final,)")
.setScopeType(RUNTIME);
final Set<Dependency> additionalDependenciesTmpSet = new LinkedHashSet<Dependency>();
additionalDependenciesTmpSet.add(seamValidationAPI);
additionalDependenciesTmpSet.add(seamValidationImpl);
this.additionalDependencies = unmodifiableSet(additionalDependenciesTmpSet);
}
@Override
public ValidationDescriptor getDefaultDescriptor()
{
return defaultDescriptor;
}
@Override
public Set<Dependency> getDependencies()
{
return dependencies;
}
@Override
public Set<Dependency> getAdditionalDependencies()
{
return additionalDependencies;
}
}
| [
"lincolnbaxter@gmail.com"
] | lincolnbaxter@gmail.com |
5212f909cdb58d3117c1758c18955ee341c6ddde | 326d74a0004c6f8bf19dd09242c4736b8c5d60b8 | /src/main/java/com/cheer/designpattern/dynamicproxy/Subject.java | d03a5d0aa2c0a0b9574b8446010cd5434a852a20 | [] | no_license | Hikari41/proxy-design-pattern | 3371b9fe1b64769e1a61948251ad0d12e6c200cf | deb6ce7212996b7e23181a97050a60c82fef262f | refs/heads/master | 2020-04-08T07:15:30.241911 | 2018-11-26T08:09:54 | 2018-11-26T08:09:54 | 159,132,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 96 | java | package com.cheer.designpattern.dynamicproxy;
public interface Subject {
void request();
}
| [
"liao_0221@163.com"
] | liao_0221@163.com |
f43434ce83b36a5ffd068631d5f01e98c53eb2d7 | 40d844c1c780cf3618979626282cf59be833907f | /src/testcases/CWE129_Improper_Validation_of_Array_Index/s02/CWE129_Improper_Validation_of_Array_Index__File_array_read_no_check_72b.java | 22cce677995a6f4cb8ce8c9584c5c0be7c14fb42 | [] | no_license | rubengomez97/juliet | f9566de7be198921113658f904b521b6bca4d262 | 13debb7a1cc801977b9371b8cc1a313cd1de3a0e | refs/heads/master | 2023-06-02T00:37:24.532638 | 2021-06-23T17:22:22 | 2021-06-23T17:22:22 | 379,676,259 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,499 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE129_Improper_Validation_of_Array_Index__File_array_read_no_check_72b.java
Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml
Template File: sources-sinks-72b.tmpl.java
*/
/*
* @description
* CWE: 129 Improper Validation of Array Index
* BadSource: File Read data from file (named c:\data.txt)
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: array_read_no_check
* GoodSink: Read from array after verifying index
* BadSink : Read from array without any verification of index
* Flow Variant: 72 Data flow: data passed in a Vector from one method to another in different source files in the same package
*
* */
package testcases.CWE129_Improper_Validation_of_Array_Index.s02;
import testcasesupport.*;
import java.util.Vector;
import javax.servlet.http.*;
public class CWE129_Improper_Validation_of_Array_Index__File_array_read_no_check_72b
{
public void badSink(Vector<Integer> dataVector ) throws Throwable
{
int data = dataVector.remove(2);
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* POTENTIAL FLAW: Attempt to read from array at location data, which may be outside the array bounds */
IO.writeLine(array[data]);
}
/* goodG2B() - use GoodSource and BadSink */
public void goodG2BSink(Vector<Integer> dataVector ) throws Throwable
{
int data = dataVector.remove(2);
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* POTENTIAL FLAW: Attempt to read from array at location data, which may be outside the array bounds */
IO.writeLine(array[data]);
}
/* goodB2G() - use BadSource and GoodSink */
public void goodB2GSink(Vector<Integer> dataVector ) throws Throwable
{
int data = dataVector.remove(2);
/* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */
int array[] = { 0, 1, 2, 3, 4 };
/* FIX: Verify index before reading from array at location data */
if (data >= 0 && data < array.length)
{
IO.writeLine(array[data]);
}
else
{
IO.writeLine("Array index out of bounds");
}
}
}
| [
"you@example.com"
] | you@example.com |
ab49e80bb1faad089cb216173bfc6e9838c6f1fa | fab262e43f0644c4e9726fbff58a50338ff20b69 | /Hoytid.java | bde2394f38ccdf83b5c63a892d9f6a1eaa33682c | [] | no_license | RetinaInc/HotellBooking | 2922f1debd464fd52b64c8cd654ec8224a5e04a2 | e0e9311778a298fab4c7d121c8747c1c180f1047 | refs/heads/master | 2021-01-20T11:43:56.710304 | 2014-01-19T20:41:31 | 2014-01-19T20:41:31 | null | 0 | 0 | null | null | null | null | ISO-8859-15 | Java | false | false | 1,525 | java | /* Laget av
****Magnus Jårem Moltzau, s180473
****Anders Nødland Danielsen, s180475
****siste oppdatering: 11.04.12
****Beskrivelse:
* Hoytid.java inneholder klassen Hoytid.
*/
import java.io.Serializable;
import java.util.GregorianCalendar;
//Klassen definerer Hoytid-objekter, med fra- og tildato, samt høytidsnavn.
public class Hoytid implements Serializable{
private static final long serialVersionUID = 400L;
GregorianCalendar fraDato;
GregorianCalendar tilDato;
String navn;
//Konstruktøren oppretter nytt Hoytid-objekt med mottatt fra- og tildate og navn.
public Hoytid(GregorianCalendar f, GregorianCalendar t, String n){
fraDato=f;
tilDato=t;
navn=n;
}
public String getNavn(){ //Returnerer navnet på høytiden.
return navn;
}
public GregorianCalendar getFraDato(){ //Returnerer starten på høytiden.
return fraDato;
}
public GregorianCalendar getTilDato(){ //Returnerer slutten på høytiden.
return tilDato;
}
/*Definerer equalsmetoden for objektet, som returnerer om objektet mottat som
* parameter er likt dette objektet eller ikke.*/
public boolean equals(Hoytid h){
return navn.equals(h.getNavn());
}
//Returnerer en tekststreng med informasjon om høytiden.
@Override
public String toString(){
return navn.toUpperCase() + "\n" +
"Fra: " + fraDato + " Til: " + tilDato + "\n";
}
} //Slutt på klassen Hoytid. | [
"andersndanielsen@gmail.com"
] | andersndanielsen@gmail.com |
d88185d970b92f855130be303f57fd987c3cb657 | 42954001028f2775b1d3a70663a92b9c8c4f36a6 | /Hello/program/src/program/Palindromprogram.java | 84c9da65db198eb95b24e7eb6eccab79bab427ff | [] | no_license | shikhamca/corejava | 1925fee82ddc042abafe5eba764393d1b6bd16a5 | 66878a8fd927e99d436e0a01789bcb2bfce5ab46 | refs/heads/master | 2020-12-04T21:32:08.166324 | 2020-03-16T12:31:40 | 2020-03-16T12:31:40 | 231,908,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 671 | java | package program;
public class Palindromprogram {
public static void main(String[] args) {
int rem, rev= 0, temp;
int n=121; // user defined number to be checked for palindrome
temp = n;
// reversed integer is stored in variable
while( n != 0 )
{
rem= n % 10;
rev= rev * 10 + rem;
n=n/10;
}
// palindrome if orignalInteger(temp) and reversedInteger(rev) are equal
if (temp == rev)
System.out.println(temp + " is a palindrome.");
else
System.out.println(temp + " is not a palindrome.");
}
}
| [
"shikhamca"
] | shikhamca |
82e6150bc338a7b12675bfa7aedf1c77a090cddb | 811e44a12484ba80aa534ff9e6561bd97241c82a | /StarBattle_ServerGame/src/com/starbattle/gameserver/game/mode/impl/DeathMatch.java | 997beb79820a635cf24b08aa31fac8fa7169ad08 | [] | no_license | Seiseikatsu/dhbwStarbattle | 41ba32502426c582e858609ad8b5b8e6a004a811 | 2d1e39d66213bf31112646e970979d9d51f5e5b4 | refs/heads/master | 2020-06-02T08:01:45.033812 | 2015-07-02T19:05:46 | 2015-07-02T19:05:46 | 24,839,183 | 2 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,443 | java | package com.starbattle.gameserver.game.mode.impl;
import com.starbattle.gameserver.game.Team;
import com.starbattle.gameserver.game.action.Damage;
import com.starbattle.gameserver.game.item.GameItem;
import com.starbattle.gameserver.game.mode.GameMode;
import com.starbattle.gameserver.player.GamePlayer;
public class DeathMatch extends GameMode {
private int respawnTime = 5;
public DeathMatch(int pointLimit) {
this.pointLimit = pointLimit;
}
@Override
public void onTakingDamage(GamePlayer player, Damage damage) {
int pointsLose = 1;
int killerPointsWin = 2;
// default respawn and damage
defaultDamageProcess(player, damage, pointsLose, killerPointsWin);
defaulPlayerEndCheck(pointLimit);
}
@Override
protected int getRespawnTime(GamePlayer player) {
//increase respawnTime with every death
return respawnTime++;
}
@Override
public void onCollectingItem(GamePlayer player, GameItem item) {
}
@Override
public void onEnteringTile(GamePlayer player, int tileID) {
}
@Override
public void onLandingOnTile(GamePlayer player, int tileID) {
}
@Override
public void onPlayerRespawn(GamePlayer player) {
}
@Override
public void onFallingOutOfMap(GamePlayer player) {
defaultKillPlayer(player, 1);
}
@Override
public void onSuffocation(GamePlayer player) {
defaultKillPlayer(player, 1);
}
@Override
public Team[] initTeams(int players) {
return defaultNoTeamsInit(players);
}
}
| [
"roll2@web.de"
] | roll2@web.de |
e64f1974032b5955151622f8be86205c49542def | 44e7adc9a1c5c0a1116097ac99c2a51692d4c986 | /aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/transform/UpdateApprovalRuleTemplateDescriptionRequestProtocolMarshaller.java | 436068ca351ef12566cde212f6039f86be4af35f | [
"Apache-2.0"
] | permissive | QiAnXinCodeSafe/aws-sdk-java | f93bc97c289984e41527ae5bba97bebd6554ddbe | 8251e0a3d910da4f63f1b102b171a3abf212099e | refs/heads/master | 2023-01-28T14:28:05.239019 | 2020-12-03T22:09:01 | 2020-12-03T22:09:01 | 318,460,751 | 1 | 0 | Apache-2.0 | 2020-12-04T10:06:51 | 2020-12-04T09:05:03 | null | UTF-8 | Java | false | false | 3,035 | java | /*
* 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.codecommit.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codecommit.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateApprovalRuleTemplateDescriptionRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateApprovalRuleTemplateDescriptionRequestProtocolMarshaller implements
Marshaller<Request<UpdateApprovalRuleTemplateDescriptionRequest>, UpdateApprovalRuleTemplateDescriptionRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("CodeCommit_20150413.UpdateApprovalRuleTemplateDescription").serviceName("AWSCodeCommit").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateApprovalRuleTemplateDescriptionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateApprovalRuleTemplateDescriptionRequest> marshall(
UpdateApprovalRuleTemplateDescriptionRequest updateApprovalRuleTemplateDescriptionRequest) {
if (updateApprovalRuleTemplateDescriptionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateApprovalRuleTemplateDescriptionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, updateApprovalRuleTemplateDescriptionRequest);
protocolMarshaller.startMarshalling();
UpdateApprovalRuleTemplateDescriptionRequestMarshaller.getInstance().marshall(updateApprovalRuleTemplateDescriptionRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| [
""
] | |
07f3c6b2d97e873da172b6e144af482f49ec90cb | 7b33780ea9369f8fd0a3c43b25b137667c0e78ed | /src/main/java/com/example/demo/service/ViaCepClient.java | 15a0591403eefa0ee711af9acc3aed800939b64a | [] | no_license | Ratkovski/poc-orange | 0ab6184735bb73a9b6fada5440e5cbd9f032a41c | 3bef3581c5c1dc43d9eba245f95faca20f58ff99 | refs/heads/main | 2023-08-22T01:46:38.855294 | 2021-10-07T12:52:51 | 2021-10-07T12:52:51 | 413,867,958 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 579 | java | package com.example.demo.service;
import com.example.demo.dto.ViaCepDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value="viacep", url="https://viacep.com.br/ws/")
public interface ViaCepClient {
@RequestMapping(method = RequestMethod.GET, value = "{cep}/json", produces = "appication/json")
ViaCepDto getViacep(@PathVariable("cep")final String cep);
}
| [
"drezcry@hotmail.com"
] | drezcry@hotmail.com |
40a468240623eea405c9fbe22b793b7b8984e65c | 10ae621945c715d8d10637c9ec7511e6a33c6cb4 | /src/main/java/app/dao/entity/Vote.java | 66585af8887edf578e0dc51f551cae6b7391c20a | [] | no_license | menesbatto/FantaSfigaWeb | e52156280299aa759e999387be1635511287b7ec | 1d10e83cd8133463d79abd51449ba94a6ccf4c8e | refs/heads/master | 2021-05-14T18:26:53.726873 | 2018-03-05T11:04:54 | 2018-03-05T11:04:54 | 116,073,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,554 | java | package app.dao.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Vote {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private static final long serialVersionUID = -8182568610565154395L;
private String source; // I (Italia), F (Fantagazzetta, ex Napoli), S (Statistico)
private Integer serieASeasonDay;
private String name;
private String team;
private String role;
private Double vote;
private Boolean yellowCard;
private Boolean redCard;
private Double scoredGoals;
private Double scoredPenalties;
private Double movementAssists;
private Double stationaryAssists;
private Double autogoals;
private Double missedPenalties;
private Double savedPenalties;
private Double takenGoals;
private Boolean winGoal;
private Boolean evenGoal;
private Boolean subIn;
private Boolean subOut;
public Vote() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Integer getSerieASeasonDay() {
return serieASeasonDay;
}
public void setSerieASeasonDay(Integer serieASeasonDay) {
this.serieASeasonDay = serieASeasonDay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Double getVote() {
return vote;
}
public void setVote(Double vote) {
this.vote = vote;
}
public Boolean getYellowCard() {
return yellowCard;
}
public void setYellowCard(Boolean yellowCard) {
this.yellowCard = yellowCard;
}
public Boolean getRedCard() {
return redCard;
}
public void setRedCard(Boolean redCard) {
this.redCard = redCard;
}
public Double getScoredGoals() {
return scoredGoals;
}
public void setScoredGoals(Double scoredGoals) {
this.scoredGoals = scoredGoals;
}
public Double getScoredPenalties() {
return scoredPenalties;
}
public void setScoredPenalties(Double scoredPenalties) {
this.scoredPenalties = scoredPenalties;
}
public Double getMovementAssists() {
return movementAssists;
}
public void setMovementAssists(Double movementAssists) {
this.movementAssists = movementAssists;
}
public Double getStationaryAssists() {
return stationaryAssists;
}
public void setStationaryAssists(Double stationaryAssists) {
this.stationaryAssists = stationaryAssists;
}
public Double getAutogoals() {
return autogoals;
}
public void setAutogoals(Double autogoals) {
this.autogoals = autogoals;
}
public Double getMissedPenalties() {
return missedPenalties;
}
public void setMissedPenalties(Double missedPenalties) {
this.missedPenalties = missedPenalties;
}
public Double getSavedPenalties() {
return savedPenalties;
}
public void setSavedPenalties(Double savedPenalties) {
this.savedPenalties = savedPenalties;
}
public Double getTakenGoals() {
return takenGoals;
}
public void setTakenGoals(Double takenGoals) {
this.takenGoals = takenGoals;
}
public Boolean getWinGoal() {
return winGoal;
}
public void setWinGoal(Boolean winGoal) {
this.winGoal = winGoal;
}
public Boolean getEvenGoal() {
return evenGoal;
}
public void setEvenGoal(Boolean evenGoal) {
this.evenGoal = evenGoal;
}
public Boolean getSubIn() {
return subIn;
}
public void setSubIn(Boolean subIn) {
this.subIn = subIn;
}
public Boolean getSubOut() {
return subOut;
}
public void setSubOut(Boolean subOut) {
this.subOut = subOut;
}
@Override
public String toString() {
return "Vote [id=" + id + ", source=" + source + ", serieASeasonDay=" + serieASeasonDay + ", name=" + name
+ ", team=" + team + ", role=" + role + ", vote=" + vote + ", yellowCard=" + yellowCard + ", redCard="
+ redCard + ", scoredGoals=" + scoredGoals + ", scoredPenalties=" + scoredPenalties
+ ", movementAssists=" + movementAssists + ", stationaryAssists=" + stationaryAssists + ", autogoals="
+ autogoals + ", missedPenalties=" + missedPenalties + ", savedPenalties=" + savedPenalties
+ ", takenGoals=" + takenGoals + ", winGoal=" + winGoal + ", evenGoal=" + evenGoal + ", subIn=" + subIn
+ ", subOut=" + subOut + "]";
}
}
| [
"valerio.meneguzzo.85@gmail.com"
] | valerio.meneguzzo.85@gmail.com |
70806395001e4aae4c67c2bdea54b2bae040f3d7 | 21eea24582e69765e9055f94836ef3efe8999f8b | /central/src/main/java/org/glowroot/central/repo/SchemaUpgrade.java | 4df57634584acb4a8ada4f2cae5dfb13eaed2ac9 | [
"Apache-2.0"
] | permissive | qingzhou413/glowroot | a59656d5054b24e3243004286eb8fcf83071c997 | a5b22e5ac7889c5b73efd28303040d23be3e2ea5 | refs/heads/master | 2020-03-10T11:54:14.546482 | 2018-04-12T20:27:45 | 2018-04-13T01:55:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 137,720 | java | /*
* Copyright 2016-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.central.repo;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.exceptions.InvalidConfigurationInQueryException;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import com.datastax.driver.core.utils.UUIDs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.InvalidProtocolBufferException;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.immutables.value.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.glowroot.central.util.MoreFutures;
import org.glowroot.central.util.Session;
import org.glowroot.common.ConfigDefaults;
import org.glowroot.common.Constants;
import org.glowroot.common.util.CaptureTimes;
import org.glowroot.common.util.Clock;
import org.glowroot.common.util.ObjectMappers;
import org.glowroot.common.util.PropertiesFiles;
import org.glowroot.common.util.Styles;
import org.glowroot.common2.config.CentralStorageConfig;
import org.glowroot.common2.config.ImmutableCentralStorageConfig;
import org.glowroot.common2.config.ImmutableCentralWebConfig;
import org.glowroot.common2.config.PermissionParser;
import org.glowroot.common2.repo.util.RollupLevelService;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AdvancedConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AlertConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AlertConfig.AlertCondition.HeartbeatCondition;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AlertConfig.AlertCondition.MetricCondition;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AlertConfig.AlertCondition.SyntheticMonitorCondition;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.GeneralConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.OldAlertConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.UiConfig;
import org.glowroot.wire.api.model.Proto.OptionalInt32;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
public class SchemaUpgrade {
private static final Logger logger = LoggerFactory.getLogger(SchemaUpgrade.class);
// log startup messages using logger name "org.glowroot"
private static final Logger startupLogger = LoggerFactory.getLogger("org.glowroot");
private static final ObjectMapper mapper = ObjectMappers.create();
private static final int CURR_SCHEMA_VERSION = 76;
private final Session session;
private final KeyspaceMetadata keyspaceMetadata;
private final Clock clock;
private final boolean servlet;
private final PreparedStatement insertIntoSchemVersionPS;
private final @Nullable Integer initialSchemaVersion;
private boolean reloadCentralConfiguration;
public SchemaUpgrade(Session session, KeyspaceMetadata keyspaceMetadata, Clock clock,
boolean servlet) throws Exception {
this.session = session;
this.keyspaceMetadata = keyspaceMetadata;
this.clock = clock;
this.servlet = servlet;
session.createTableWithLCS("create table if not exists schema_version (one int,"
+ " schema_version int, primary key (one))");
insertIntoSchemVersionPS =
session.prepare("insert into schema_version (one, schema_version) values (1, ?)");
initialSchemaVersion = getSchemaVersion(session, keyspaceMetadata);
}
public @Nullable Integer getInitialSchemaVersion() {
return initialSchemaVersion;
}
public void upgrade() throws Exception {
checkNotNull(initialSchemaVersion);
if (initialSchemaVersion == CURR_SCHEMA_VERSION) {
return;
}
if (initialSchemaVersion > CURR_SCHEMA_VERSION) {
startupLogger.warn("running an older version of glowroot central on a newer glowroot"
+ " central schema (expecting glowroot central schema version <= {} but found"
+ " version {}), this could be problematic", CURR_SCHEMA_VERSION,
initialSchemaVersion);
return;
}
startupLogger.info("upgrading glowroot central schema from version {} to version {} ...",
initialSchemaVersion, CURR_SCHEMA_VERSION);
// 0.9.1 to 0.9.2
if (initialSchemaVersion < 2) {
renameAgentColumnFromSystemInfoToEnvironment();
updateSchemaVersion(2);
}
if (initialSchemaVersion < 3) {
updateRoles();
updateSchemaVersion(3);
}
if (initialSchemaVersion < 4) {
addConfigUpdateColumns();
updateSchemaVersion(4);
}
// 0.9.2 to 0.9.3
if (initialSchemaVersion < 6) {
revertCompressionChunkLength();
addTraceEntryColumns();
updateSchemaVersion(6);
}
// 0.9.5 to 0.9.6
if (initialSchemaVersion < 7) {
renameServerConfigTable();
updateSchemaVersion(7);
}
if (initialSchemaVersion < 8) {
addAgentOneTable();
updateSchemaVersion(8);
}
if (initialSchemaVersion < 9) {
addAgentRollupColumn();
updateSchemaVersion(9);
}
// 0.9.6 to 0.9.7
if (initialSchemaVersion < 11) {
updateTwcsDtcsGcSeconds();
updateSchemaVersion(11);
}
if (initialSchemaVersion < 12) {
updateNeedsRollupGcSeconds();
updateSchemaVersion(12);
}
if (initialSchemaVersion < 13) {
updateAgentRollup();
updateSchemaVersion(13);
}
if (initialSchemaVersion < 14) {
addTracePointPartialColumn();
updateSchemaVersion(14);
}
// 0.9.9 to 0.9.10
if (initialSchemaVersion < 15) {
splitUpAgentTable();
updateSchemaVersion(15);
}
if (initialSchemaVersion < 16) {
initialPopulationOfConfigForRollups();
updateSchemaVersion(16);
}
if (initialSchemaVersion < 17) {
redoOnTriggeredAlertTable();
updateSchemaVersion(17);
}
// 0.9.10 to 0.9.11
if (initialSchemaVersion < 18) {
addSyntheticMonitorAndAlertPermissions();
updateSchemaVersion(18);
}
if (initialSchemaVersion < 19) {
redoOnTriggeredAlertTable();
updateSchemaVersion(19);
}
// 0.9.15 to 0.9.16
if (initialSchemaVersion < 20) {
redoOnTriggeredAlertTable();
updateSchemaVersion(20);
}
if (initialSchemaVersion < 21) {
updateWebConfig();
updateSchemaVersion(21);
}
// 0.9.16 to 0.9.17
if (initialSchemaVersion < 22) {
removeInvalidAgentRollupRows();
updateSchemaVersion(22);
}
// 0.9.17 to 0.9.18
if (initialSchemaVersion < 23) {
renameConfigTable();
updateSchemaVersion(23);
}
if (initialSchemaVersion < 24) {
upgradeAlertConfigs();
updateSchemaVersion(24);
}
if (initialSchemaVersion < 25) {
addAggregateThroughputColumn();
updateSchemaVersion(25);
}
if (initialSchemaVersion < 26) {
// this is needed due to change from OldAlertConfig to AlertConfig in schema version 24
redoOnTriggeredAlertTable();
updateSchemaVersion(26);
}
// 0.9.19 to 0.9.20
if (initialSchemaVersion < 27) {
updateRolePermissionName();
updateSchemaVersion(27);
}
if (initialSchemaVersion < 28) {
updateSmtpConfig();
updateSchemaVersion(28);
}
// 0.9.21 to 0.9.22
if (initialSchemaVersion == 28) {
// only applies when upgrading from immediately prior schema version
// (to fix bad upgrade in 28 that inserted 'smtp' config row into 'web' config row)
updateSmtpConfig();
sortOfFixWebConfig();
updateSchemaVersion(29);
} else if (initialSchemaVersion < 29) {
updateSchemaVersion(29);
}
// 0.9.22 to 0.9.23
if (initialSchemaVersion < 30) {
addDefaultGaugeNameToUiConfigs();
updateSchemaVersion(30);
}
// 0.9.24 to 0.9.25
if (initialSchemaVersion < 31) {
// this is needed due to change from triggered_alert to open_incident/resolved_incident
redoOnTriggeredAlertTable();
updateSchemaVersion(31);
}
if (initialSchemaVersion < 32) {
redoOnHeartbeatTable();
updateSchemaVersion(32);
}
// 0.9.26 to 0.9.27
if (initialSchemaVersion < 33) {
addSyntheticResultErrorIntervalsColumn();
updateSchemaVersion(33);
}
// 0.9.28 to 0.10.0
if (initialSchemaVersion < 34) {
populateGaugeNameTable();
updateSchemaVersion(34);
}
if (initialSchemaVersion == 34) {
// only applies when upgrading from immediately prior schema version
// (to fix bad upgrade in 34 that populated the gauge_name table based on
// gauge_value_rollup_3 instead of gauge_value_rollup_4)
populateGaugeNameTable();
updateSchemaVersion(35);
} else if (initialSchemaVersion < 35) {
updateSchemaVersion(35);
}
if (initialSchemaVersion < 36) {
populateAgentConfigGeneral();
updateSchemaVersion(36);
}
if (initialSchemaVersion < 37) {
populateV09AgentCheckTable();
updateSchemaVersion(37);
}
if (initialSchemaVersion < 38) {
populateAgentHistoryTable();
updateSchemaVersion(38);
}
if (initialSchemaVersion < 39) {
rewriteAgentConfigTablePart1();
updateSchemaVersion(39);
}
if (initialSchemaVersion < 40) {
rewriteAgentConfigTablePart2();
updateSchemaVersion(40);
}
if (initialSchemaVersion < 41) {
rewriteEnvironmentTablePart1();
updateSchemaVersion(41);
}
if (initialSchemaVersion < 42) {
rewriteEnvironmentTablePart2();
updateSchemaVersion(42);
}
if (initialSchemaVersion < 43) {
rewriteOpenIncidentTablePart1();
updateSchemaVersion(43);
}
if (initialSchemaVersion < 44) {
rewriteOpenIncidentTablePart2();
updateSchemaVersion(44);
}
if (initialSchemaVersion < 45) {
rewriteResolvedIncidentTablePart1();
updateSchemaVersion(45);
}
if (initialSchemaVersion < 46) {
rewriteResolvedIncidentTablePart2();
updateSchemaVersion(46);
}
if (initialSchemaVersion < 47) {
rewriteRoleTablePart1();
updateSchemaVersion(47);
}
if (initialSchemaVersion < 48) {
rewriteRoleTablePart2();
updateSchemaVersion(48);
}
if (initialSchemaVersion < 49) {
rewriteHeartbeatTablePart1();
updateSchemaVersion(49);
}
if (initialSchemaVersion < 50) {
rewriteHeartbeatTablePart2();
updateSchemaVersion(50);
}
if (initialSchemaVersion < 51) {
rewriteTransactionTypeTablePart1();
updateSchemaVersion(51);
}
if (initialSchemaVersion < 52) {
rewriteTransactionTypeTablePart2();
updateSchemaVersion(52);
}
if (initialSchemaVersion < 53) {
rewriteTraceAttributeNameTablePart1();
updateSchemaVersion(53);
}
if (initialSchemaVersion < 54) {
rewriteTraceAttributeNameTablePart2();
updateSchemaVersion(54);
}
if (initialSchemaVersion < 55) {
rewriteGaugeNameTablePart1();
updateSchemaVersion(55);
}
if (initialSchemaVersion < 56) {
rewriteGaugeNameTablePart2();
updateSchemaVersion(56);
}
if (initialSchemaVersion < 57) {
populateV09AgentRollupTable();
updateSchemaVersion(57);
}
if (initialSchemaVersion < 58) {
finishV09AgentIdUpdate();
updateSchemaVersion(58);
}
// 0.10.0 to 0.10.1
if (initialSchemaVersion < 59) {
removeTraceTtErrorCountPartialColumn();
updateSchemaVersion(59);
}
if (initialSchemaVersion < 60) {
removeTraceTnErrorCountPartialColumn();
updateSchemaVersion(60);
}
if (initialSchemaVersion < 61) {
populateTraceTtSlowCountAndPointPartialPart1();
updateSchemaVersion(61);
}
if (initialSchemaVersion < 62) {
populateTraceTtSlowCountAndPointPartialPart2();
updateSchemaVersion(62);
}
if (initialSchemaVersion < 63) {
populateTraceTnSlowCountAndPointPartialPart1();
updateSchemaVersion(63);
}
if (initialSchemaVersion < 64) {
populateTraceTnSlowCountAndPointPartialPart2();
updateSchemaVersion(64);
}
if (initialSchemaVersion < 65) {
updateTwcsDtcsGcSeconds();
updateSchemaVersion(65);
}
if (initialSchemaVersion < 66) {
updateNeedsRollupGcSeconds();
updateSchemaVersion(66);
}
if (initialSchemaVersion < 67) {
updateLcsUncheckedTombstoneCompaction();
updateSchemaVersion(67);
}
// 0.10.2 to 0.10.3
if (initialSchemaVersion < 68) {
updateStcsUncheckedTombstoneCompaction();
updateSchemaVersion(68);
}
if (initialSchemaVersion < 69) {
optimizeTwcsTables();
updateSchemaVersion(69);
}
if (initialSchemaVersion < 70) {
changeV09TablesToLCS();
updateSchemaVersion(70);
}
if (initialSchemaVersion < 71) {
updateCentralStorageConfig();
updateSchemaVersion(71);
}
// 0.10.3 to 0.10.4
if (initialSchemaVersion < 72) {
rewriteV09AgentRollupPart1();
updateSchemaVersion(72);
}
if (initialSchemaVersion < 73) {
rewriteV09AgentRollupPart2();
updateSchemaVersion(73);
}
// 0.10.4 to 0.10.5
if (initialSchemaVersion >= 69 && initialSchemaVersion < 74) {
optimizeTwcsTables();
updateSchemaVersion(74);
}
// 0.10.5 to 0.10.6
if (initialSchemaVersion < 75) {
updateTraceAttributeNamePartitionKeyPart1();
updateSchemaVersion(75);
}
if (initialSchemaVersion < 76) {
updateTraceAttributeNamePartitionKeyPart2();
updateSchemaVersion(76);
}
// when adding new schema upgrade, make sure to update CURR_SCHEMA_VERSION above
startupLogger.info("upgraded glowroot central schema from version {} to version {}",
initialSchemaVersion, CURR_SCHEMA_VERSION);
}
public boolean reloadCentralConfiguration() {
return reloadCentralConfiguration;
}
public void updateSchemaVersionToCurent() throws Exception {
updateSchemaVersion(CURR_SCHEMA_VERSION);
}
public int getCurrentSchemaVersion() {
return CURR_SCHEMA_VERSION;
}
public void updateToMoreRecentCassandraOptions(CentralStorageConfig storageConfig)
throws Exception {
List<String> snappyTableNames = new ArrayList<>();
List<String> dtcsTableNames = new ArrayList<>();
for (TableMetadata table : keyspaceMetadata.getTables()) {
String compressionClass = table.getOptions().getCompression().get("class");
if (compressionClass != null && compressionClass
.equals("org.apache.cassandra.io.compress.SnappyCompressor")) {
snappyTableNames.add(compressionClass);
}
String compactionClass = table.getOptions().getCompaction().get("class");
if (compactionClass != null && compactionClass
.equals("org.apache.cassandra.db.compaction.DateTieredCompactionStrategy")) {
dtcsTableNames.add(table.getName());
}
if (table.getName().startsWith("trace_") && table.getName().endsWith("_partial")
&& compactionClass != null && compactionClass.equals(
"org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy")) {
// these need to be updated to TWCS also
dtcsTableNames.add(table.getName());
}
}
int snappyUpdatedCount = 0;
for (String tableName : snappyTableNames) {
session.execute("alter table " + tableName
+ " with compression = { 'class' : 'LZ4Compressor' }");
if (snappyUpdatedCount++ == 0) {
startupLogger.info("upgrading from Snappy to LZ4 compression ...");
}
}
if (snappyUpdatedCount > 0) {
startupLogger.info("upgraded {} tables from Snappy to LZ4 compression",
snappyUpdatedCount);
}
int dtcsUpdatedCount = 0;
for (String tableName : dtcsTableNames) {
try {
int expirationHours =
RepoAdminImpl.getExpirationHoursForTable(tableName, storageConfig);
if (expirationHours == -1) {
// warning already logged above inside getExpirationHoursForTable()
continue;
}
session.updateTableTwcsProperties(tableName, expirationHours);
if (dtcsUpdatedCount++ == 0) {
startupLogger.info("upgrading from DateTieredCompactionStrategy to"
+ " TimeWindowCompactionStrategy compression ...");
}
} catch (InvalidConfigurationInQueryException e) {
logger.debug(e.getMessage(), e);
// TimeWindowCompactionStrategy is only supported by Cassandra 3.8+
break;
}
}
if (dtcsUpdatedCount > 0) {
startupLogger.info("upgraded {} tables from DateTieredCompactionStrategy to"
+ " TimeWindowCompactionStrategy compaction", dtcsUpdatedCount);
}
}
private void updateSchemaVersion(int schemaVersion) throws Exception {
BoundStatement boundStatement = insertIntoSchemVersionPS.bind();
boundStatement.setInt(0, schemaVersion);
session.execute(boundStatement);
}
private void renameAgentColumnFromSystemInfoToEnvironment() throws Exception {
if (!columnExists("agent", "system_info")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
addColumnIfNotExists("agent", "environment", "blob");
ResultSet results = session.execute("select agent_id, system_info from agent");
PreparedStatement preparedStatement =
session.prepare("insert into agent (agent_id, environment) values (?, ?)");
for (Row row : results) {
BoundStatement boundStatement = preparedStatement.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setBytes(1, row.getBytes(1));
session.execute(boundStatement);
}
session.execute("alter table agent drop system_info");
}
private void updateRoles() throws Exception {
PreparedStatement insertPS =
session.prepare("insert into role (name, permissions) values (?, ?)");
ResultSet results = session.execute("select name, permissions from role");
for (Row row : results) {
String name = row.getString(0);
Set<String> permissions = row.getSet(1, String.class);
Set<String> upgradedPermissions = upgradePermissions(permissions);
if (upgradedPermissions == null) {
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, name);
boundStatement.setSet(1, upgradedPermissions, String.class);
session.execute(boundStatement);
}
}
private void addConfigUpdateColumns() throws Exception {
addColumnIfNotExists("agent", "config_update", "boolean");
addColumnIfNotExists("agent", "config_update_token", "uuid");
}
private void revertCompressionChunkLength() throws Exception {
try {
// try with compression options for Cassandra 3.x
// see https://docs.datastax.com/en/cql/3.3/cql/cql_reference/compressSubprop.html
session.execute("alter table trace_entry with compression = {'class':"
+ " 'org.apache.cassandra.io.compress.LZ4Compressor', 'chunk_length_kb' :"
+ " 64};");
} catch (InvalidConfigurationInQueryException e) {
logger.debug(e.getMessage(), e);
// try with compression options for Cassandra 2.x
// see https://docs.datastax.com/en/cql/3.1/cql/cql_reference/compressSubprop.html
session.execute("alter table trace_entry with compression"
+ " = {'sstable_compression': 'SnappyCompressor', 'chunk_length_kb' : 64};");
}
}
private void addTraceEntryColumns() throws Exception {
addColumnIfNotExists("trace_entry", "shared_query_text_index", "int");
addColumnIfNotExists("trace_entry", "query_message_prefix", "varchar");
addColumnIfNotExists("trace_entry", "query_message_suffix", "varchar");
}
private void renameServerConfigTable() throws Exception {
if (!tableExists("server_config")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists central_config (key varchar,"
+ " value varchar, primary key (key))");
ResultSet results = session.execute("select key, value from server_config");
PreparedStatement insertPS =
session.prepare("insert into central_config (key, value) values (?, ?)");
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
session.execute(boundStatement);
}
dropTableIfExists("server_config");
}
private void addAgentOneTable() throws Exception {
if (!tableExists("agent_rollup")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists agent_one (one int, agent_id"
+ " varchar, agent_rollup varchar, primary key (one, agent_id))");
ResultSet results = session.execute("select agent_rollup from agent_rollup");
PreparedStatement insertPS =
session.prepare("insert into agent_one (one, agent_id) values (1, ?)");
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
session.execute(boundStatement);
}
dropTableIfExists("agent_rollup");
}
private void addAgentRollupColumn() throws Exception {
addColumnIfNotExists("agent", "agent_rollup", "varchar");
}
private void updateTwcsDtcsGcSeconds() throws Exception {
logger.info("updating gc_grace_seconds on TWCS/DTCS tables ...");
for (TableMetadata table : keyspaceMetadata.getTables()) {
String compactionClass = table.getOptions().getCompaction().get("class");
if (compactionClass == null) {
continue;
}
if (compactionClass
.equals("org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy")
|| compactionClass.equals(
"org.apache.cassandra.db.compaction.DateTieredCompactionStrategy")) {
// see gc_grace_seconds related comments in Sessions.createTableWithTWCS()
// for reasoning behind the value of 4 hours
session.execute("alter table " + table.getName() + " with gc_grace_seconds = "
+ HOURS.toSeconds(4));
}
}
logger.info("updating gc_grace_seconds on TWCS/DTCS tables - complete");
}
private void updateNeedsRollupGcSeconds() throws Exception {
logger.info("updating gc_grace_seconds on \"needs rollup\" tables ...");
// reduce from default 10 days to 4 hours
//
// since rollup operations are idempotent, any records resurrected after gc_grace_seconds
// would just create extra work, but not have any other effect
//
// not using gc_grace_seconds of 0 since that disables hinted handoff
// (http://www.uberobert.com/cassandra_gc_grace_disables_hinted_handoff)
//
// it seems any value over max_hint_window_in_ms (which defaults to 3 hours) is good
long gcGraceSeconds = HOURS.toSeconds(4);
if (tableExists("aggregate_needs_rollup_from_child")) {
session.execute("alter table aggregate_needs_rollup_from_child with gc_grace_seconds = "
+ gcGraceSeconds);
}
session.execute(
"alter table aggregate_needs_rollup_1 with gc_grace_seconds = " + gcGraceSeconds);
session.execute(
"alter table aggregate_needs_rollup_2 with gc_grace_seconds = " + gcGraceSeconds);
session.execute(
"alter table aggregate_needs_rollup_3 with gc_grace_seconds = " + gcGraceSeconds);
if (tableExists("gauge_needs_rollup_from_child")) {
session.execute("alter table gauge_needs_rollup_from_child with gc_grace_seconds = "
+ gcGraceSeconds);
}
session.execute(
"alter table gauge_needs_rollup_1 with gc_grace_seconds = " + gcGraceSeconds);
session.execute(
"alter table gauge_needs_rollup_2 with gc_grace_seconds = " + gcGraceSeconds);
session.execute(
"alter table gauge_needs_rollup_3 with gc_grace_seconds = " + gcGraceSeconds);
session.execute(
"alter table gauge_needs_rollup_4 with gc_grace_seconds = " + gcGraceSeconds);
logger.info("updating gc_grace_seconds on \"needs rollup\" tables - complete");
}
private void updateAgentRollup() throws Exception {
if (!tableExists("agent_one")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists agent_rollup (one int,"
+ " agent_rollup_id varchar, parent_agent_rollup_id varchar, agent boolean,"
+ " display varchar, last_capture_time timestamp, primary key (one,"
+ " agent_rollup_id))");
ResultSet results =
session.execute("select agent_id, agent_rollup from agent_one");
PreparedStatement insertPS = session.prepare("insert into agent_rollup (one,"
+ " agent_rollup_id, parent_agent_rollup_id, agent) values (1, ?, ?, ?)");
Set<String> parentAgentRollupIds = new HashSet<>();
for (Row row : results) {
String agentRollupId = row.getString(0);
String parentAgentRollupId = row.getString(1);
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setString(i++, parentAgentRollupId);
boundStatement.setBool(i++, true);
session.execute(boundStatement);
if (parentAgentRollupId != null) {
parentAgentRollupIds.addAll(getAgentRollupIds(parentAgentRollupId));
}
}
for (String parentAgentRollupId : parentAgentRollupIds) {
int index = parentAgentRollupId.lastIndexOf('/');
String parentOfParentAgentRollupId =
index == -1 ? null : parentAgentRollupId.substring(0, index);
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, parentAgentRollupId);
boundStatement.setString(i++, parentOfParentAgentRollupId);
boundStatement.setBool(i++, false);
session.execute(boundStatement);
}
session.execute("alter table agent drop agent_rollup");
dropTableIfExists("agent_one");
}
private static List<String> getAgentRollupIds(String agentRollupId) {
List<String> agentRollupIds = new ArrayList<>();
int lastFoundIndex = -1;
int nextFoundIndex;
while ((nextFoundIndex = agentRollupId.indexOf('/', lastFoundIndex + 1)) != -1) {
agentRollupIds.add(agentRollupId.substring(0, nextFoundIndex));
lastFoundIndex = nextFoundIndex;
}
agentRollupIds.add(agentRollupId);
return agentRollupIds;
}
private void addTracePointPartialColumn() throws Exception {
addColumnIfNotExists("trace_tt_slow_point", "partial", "boolean");
addColumnIfNotExists("trace_tn_slow_point", "partial", "boolean");
addColumnIfNotExists("trace_tt_error_point", "partial", "boolean");
addColumnIfNotExists("trace_tn_error_point", "partial", "boolean");
}
private void splitUpAgentTable() throws Exception {
session.createTableWithLCS("create table if not exists config (agent_rollup_id varchar,"
+ " config blob, config_update boolean, config_update_token uuid, primary key"
+ " (agent_rollup_id))");
session.createTableWithLCS("create table if not exists environment (agent_id varchar,"
+ " environment blob, primary key (agent_id))");
ResultSet results =
session.execute("select agent_rollup_id, agent from agent_rollup where one = 1");
List<String> agentIds = new ArrayList<>();
for (Row row : results) {
if (row.getBool(1)) {
agentIds.add(checkNotNull(row.getString(0)));
}
}
PreparedStatement readPS = session.prepare("select environment, config, config_update,"
+ " config_update_token from agent where agent_id = ?");
PreparedStatement insertEnvironmentPS =
session.prepare("insert into environment (agent_id, environment) values (?, ?)");
PreparedStatement insertConfigPS = session.prepare("insert into config (agent_rollup_id,"
+ " config, config_update, config_update_token) values (?, ?, ?, ?)");
for (String agentId : agentIds) {
BoundStatement boundStatement = readPS.bind();
boundStatement.setString(0, agentId);
results = session.execute(boundStatement);
Row row = results.one();
if (row == null) {
logger.warn("agent record not found for agent id: {}", agentId);
continue;
}
int i = 0;
ByteBuffer environmentBytes = checkNotNull(row.getBytes(i++));
ByteBuffer configBytes = checkNotNull(row.getBytes(i++));
boolean configUpdate = row.getBool(i++);
UUID configUpdateToken = row.getUUID(i++);
boundStatement = insertEnvironmentPS.bind();
boundStatement.setString(0, agentId);
boundStatement.setBytes(1, environmentBytes);
session.execute(boundStatement);
boundStatement = insertConfigPS.bind();
i = 0;
boundStatement.setString(i++, agentId);
boundStatement.setBytes(i++, configBytes);
boundStatement.setBool(i++, configUpdate);
boundStatement.setUUID(i++, configUpdateToken);
session.execute(boundStatement);
}
dropTableIfExists("agent");
}
private void initialPopulationOfConfigForRollups() throws Exception {
ResultSet results = session.execute("select agent_rollup_id,"
+ " parent_agent_rollup_id, agent from agent_rollup where one = 1");
List<String> agentRollupIds = new ArrayList<>();
Multimap<String, String> childAgentIds = ArrayListMultimap.create();
for (Row row : results) {
int i = 0;
String agentRollupId = row.getString(i++);
String parentAgentRollupId = row.getString(i++);
boolean agent = row.getBool(i++);
if (!agent) {
agentRollupIds.add(checkNotNull(agentRollupId));
}
if (parentAgentRollupId != null) {
childAgentIds.put(parentAgentRollupId, agentRollupId);
}
}
AgentConfig defaultAgentConfig = AgentConfig.newBuilder()
.setUiConfig(UiConfig.newBuilder()
.setDefaultTransactionType(ConfigDefaults.UI_DEFAULT_TRANSACTION_TYPE)
.addAllDefaultPercentile(ConfigDefaults.UI_DEFAULT_PERCENTILES))
.setAdvancedConfig(AdvancedConfig.newBuilder()
.setMaxQueryAggregates(OptionalInt32.newBuilder()
.setValue(ConfigDefaults.ADVANCED_MAX_QUERY_AGGREGATES))
.setMaxServiceCallAggregates(OptionalInt32.newBuilder()
.setValue(ConfigDefaults.ADVANCED_MAX_SERVICE_CALL_AGGREGATES)))
.build();
PreparedStatement readPS =
session.prepare("select config from config where agent_rollup_id = ?");
PreparedStatement insertPS =
session.prepare("insert into config (agent_rollup_id, config) values (?, ?)");
for (String agentRollupId : agentRollupIds) {
Iterator<String> iterator = childAgentIds.get(agentRollupId).iterator();
if (!iterator.hasNext()) {
logger.warn("could not find a child agent for rollup: {}", agentRollupId);
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, agentRollupId);
boundStatement.setBytes(1, ByteBuffer.wrap(defaultAgentConfig.toByteArray()));
session.execute(boundStatement);
continue;
}
String childAgentId = iterator.next();
BoundStatement boundStatement = readPS.bind();
boundStatement.setString(0, childAgentId);
Row row = session.execute(boundStatement).one();
boundStatement = insertPS.bind();
boundStatement.setString(0, agentRollupId);
if (row == null) {
logger.warn("could not find config for agent id: {}", childAgentId);
boundStatement.setBytes(1, ByteBuffer.wrap(defaultAgentConfig.toByteArray()));
} else {
try {
AgentConfig agentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(0)));
AdvancedConfig advancedConfig = agentConfig.getAdvancedConfig();
AgentConfig updatedAgentConfig = AgentConfig.newBuilder()
.setUiConfig(agentConfig.getUiConfig())
.setAdvancedConfig(AdvancedConfig.newBuilder()
.setMaxQueryAggregates(advancedConfig.getMaxQueryAggregates())
.setMaxServiceCallAggregates(
advancedConfig.getMaxServiceCallAggregates()))
.build();
boundStatement.setBytes(1, ByteBuffer.wrap(updatedAgentConfig.toByteArray()));
} catch (InvalidProtocolBufferException e) {
logger.error(e.getMessage(), e);
boundStatement.setBytes(1, ByteBuffer.wrap(defaultAgentConfig.toByteArray()));
}
}
session.execute(boundStatement);
}
}
private void redoOnTriggeredAlertTable() throws Exception {
dropTableIfExists("triggered_alert");
}
private void addSyntheticMonitorAndAlertPermissions() throws Exception {
PreparedStatement insertPS =
session.prepare("insert into role (name, permissions) values (?, ?)");
ResultSet results = session.execute("select name, permissions from role");
for (Row row : results) {
String name = row.getString(0);
Set<String> permissions = row.getSet(1, String.class);
Set<String> permissionsToBeAdded = upgradePermissions2(permissions);
if (permissionsToBeAdded.isEmpty()) {
continue;
}
permissions.addAll(permissionsToBeAdded);
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, name);
boundStatement.setSet(1, permissions, String.class);
session.execute(boundStatement);
}
}
private void updateWebConfig() throws Exception {
ResultSet results =
session.execute("select value from central_config where key = 'web'");
Row row = results.one();
JsonNode webConfigNode;
if (row == null) {
webConfigNode = mapper.createObjectNode();
} else {
String webConfigText = row.getString(0);
if (webConfigText == null) {
webConfigNode = mapper.createObjectNode();
} else {
webConfigNode = mapper.readTree(webConfigText);
}
}
if (!servlet && updateCentralConfigurationPropertiesFile(webConfigNode)) {
reloadCentralConfiguration = true;
}
ImmutableCentralWebConfig.Builder builder = ImmutableCentralWebConfig.builder();
JsonNode sessionTimeoutMinutesNode = webConfigNode.get("sessionTimeoutMinutes");
if (sessionTimeoutMinutesNode != null) {
builder.sessionTimeoutMinutes(sessionTimeoutMinutesNode.intValue());
}
JsonNode sessionCookieNameNode = webConfigNode.get("sessionCookieName");
if (sessionCookieNameNode != null) {
builder.sessionCookieName(sessionCookieNameNode.asText());
}
String updatedWebConfigText = mapper.writeValueAsString(builder.build());
PreparedStatement preparedStatement =
session.prepare("insert into central_config (key, value) values ('web', ?)");
BoundStatement boundStatement = preparedStatement.bind();
boundStatement.setString(0, updatedWebConfigText);
session.execute(boundStatement);
}
private void removeInvalidAgentRollupRows() throws Exception {
ResultSet results =
session.execute("select agent_rollup_id, agent from agent_rollup");
PreparedStatement deletePS =
session.prepare("delete from agent_rollup where one = 1 and agent_rollup_id = ?");
for (Row row : results) {
if (row.isNull(1)) {
BoundStatement boundStatement = deletePS.bind();
boundStatement.setString(0, checkNotNull(row.getString(0)));
session.execute(boundStatement);
}
}
}
private void renameConfigTable() throws Exception {
if (!tableExists("config")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
session.createTableWithLCS("create table if not exists agent_config (agent_rollup_id"
+ " varchar, config blob, config_update boolean, config_update_token uuid,"
+ " primary key (agent_rollup_id))");
ResultSet results = session.execute("select agent_rollup_id, config,"
+ " config_update, config_update_token from config");
PreparedStatement insertPS =
session.prepare("insert into agent_config (agent_rollup_id, config, config_update,"
+ " config_update_token) values (?, ?, ?, ?)");
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setBool(2, row.getBool(2));
boundStatement.setUUID(3, row.getUUID(3));
session.execute(boundStatement);
}
dropTableIfExists("config");
}
private void upgradeAlertConfigs() throws Exception {
PreparedStatement insertPS = session.prepare("insert into agent_config (agent_rollup_id,"
+ " config, config_update, config_update_token) values (?, ?, ?, ?)");
ResultSet results = session.execute("select agent_rollup_id, config from agent_config");
for (Row row : results) {
String agentRollupId = row.getString(0);
AgentConfig oldAgentConfig;
try {
oldAgentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(1)));
} catch (InvalidProtocolBufferException e) {
logger.error(e.getMessage(), e);
continue;
}
List<OldAlertConfig> oldAlertConfigs = oldAgentConfig.getOldAlertConfigList();
if (oldAlertConfigs.isEmpty()) {
continue;
}
AgentConfig agentConfig = upgradeOldAgentConfig(oldAgentConfig);
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setBytes(i++, ByteBuffer.wrap(agentConfig.toByteArray()));
boundStatement.setBool(i++, true);
boundStatement.setUUID(i++, UUIDs.random());
session.execute(boundStatement);
}
}
private void addAggregateThroughputColumn() throws Exception {
addColumnIfNotExists("aggregate_tt_throughput_rollup_0", "error_count", "bigint");
addColumnIfNotExists("aggregate_tt_throughput_rollup_1", "error_count", "bigint");
addColumnIfNotExists("aggregate_tt_throughput_rollup_2", "error_count", "bigint");
addColumnIfNotExists("aggregate_tt_throughput_rollup_3", "error_count", "bigint");
addColumnIfNotExists("aggregate_tn_throughput_rollup_0", "error_count", "bigint");
addColumnIfNotExists("aggregate_tn_throughput_rollup_1", "error_count", "bigint");
addColumnIfNotExists("aggregate_tn_throughput_rollup_2", "error_count", "bigint");
addColumnIfNotExists("aggregate_tn_throughput_rollup_3", "error_count", "bigint");
}
private void updateRolePermissionName() throws Exception {
PreparedStatement insertPS =
session.prepare("insert into role (name, permissions) values (?, ?)");
ResultSet results = session.execute("select name, permissions from role");
for (Row row : results) {
String name = row.getString(0);
Set<String> permissions = row.getSet(1, String.class);
boolean updated = false;
Set<String> upgradedPermissions = new HashSet<>();
for (String permission : permissions) {
PermissionParser parser = new PermissionParser(permission);
parser.parse();
if (parser.getPermission().equals("agent:alert")) {
upgradedPermissions.add("agent:"
+ PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
+ ":incident");
updated = true;
} else {
upgradedPermissions.add(permission);
}
}
if (updated) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, name);
boundStatement.setSet(1, upgradedPermissions, String.class);
session.execute(boundStatement);
}
}
}
private void updateSmtpConfig() throws Exception {
ResultSet results =
session.execute("select value from central_config where key = 'smtp'");
Row row = results.one();
if (row == null) {
return;
}
String smtpConfigText = row.getString(0);
if (smtpConfigText == null) {
return;
}
JsonNode jsonNode = mapper.readTree(smtpConfigText);
if (jsonNode == null || !jsonNode.isObject()) {
return;
}
ObjectNode smtpConfigNode = (ObjectNode) jsonNode;
JsonNode sslNode = smtpConfigNode.remove("ssl");
if (sslNode != null && sslNode.isBoolean() && sslNode.asBoolean()) {
smtpConfigNode.put("connectionSecurity", "ssl-tls");
}
String updatedWebConfigText = mapper.writeValueAsString(smtpConfigNode);
PreparedStatement preparedStatement =
session.prepare("insert into central_config (key, value) values ('smtp', ?)");
BoundStatement boundStatement = preparedStatement.bind();
boundStatement.setString(0, updatedWebConfigText);
session.execute(boundStatement);
}
private void addDefaultGaugeNameToUiConfigs() throws Exception {
PreparedStatement insertPS = session.prepare("insert into agent_config (agent_rollup_id,"
+ " config, config_update, config_update_token) values (?, ?, ?, ?)");
ResultSet results = session.execute("select agent_rollup_id, config from agent_config");
for (Row row : results) {
String agentRollupId = row.getString(0);
AgentConfig oldAgentConfig;
try {
oldAgentConfig = AgentConfig.parseFrom(checkNotNull(row.getBytes(1)));
} catch (InvalidProtocolBufferException e) {
logger.error(e.getMessage(), e);
continue;
}
AgentConfig agentConfig = oldAgentConfig.toBuilder()
.setUiConfig(oldAgentConfig.getUiConfig().toBuilder()
.addAllDefaultGaugeName(ConfigDefaults.UI_DEFAULT_GAUGE_NAMES))
.build();
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, agentRollupId);
boundStatement.setBytes(i++, ByteBuffer.wrap(agentConfig.toByteArray()));
boundStatement.setBool(i++, true);
boundStatement.setUUID(i++, UUIDs.random());
session.execute(boundStatement);
}
}
// fix bad upgrade that inserted 'smtp' config row into 'web' config row
private void sortOfFixWebConfig() throws Exception {
ResultSet results =
session.execute("select value from central_config where key = 'web'");
Row row = results.one();
if (row == null) {
return;
}
String webConfigText = row.getString(0);
if (webConfigText == null) {
return;
}
JsonNode jsonNode = mapper.readTree(webConfigText);
if (jsonNode == null || !jsonNode.isObject()) {
return;
}
ObjectNode webConfigNode = (ObjectNode) jsonNode;
if (webConfigNode.has("host")) {
// remove 'web' config row which has 'smtp' config (old 'web' config row is lost)
session.execute("delete from central_config where key = 'web'");
}
}
private void redoOnHeartbeatTable() throws Exception {
dropTableIfExists("heartbeat");
}
private void addSyntheticResultErrorIntervalsColumn() throws Exception {
addColumnIfNotExists("synthetic_result_rollup_0", "error_intervals", "blob");
addColumnIfNotExists("synthetic_result_rollup_1", "error_intervals", "blob");
addColumnIfNotExists("synthetic_result_rollup_2", "error_intervals", "blob");
addColumnIfNotExists("synthetic_result_rollup_3", "error_intervals", "blob");
}
private void populateGaugeNameTable() throws Exception {
logger.info("populating new gauge name history table - this could take several minutes on"
+ " large data sets ...");
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
int maxRollupHours = storageConfig.getMaxRollupHours();
dropTableIfExists("gauge_name");
session.createTableWithTWCS("create table gauge_name (agent_rollup_id varchar, capture_time"
+ " timestamp, gauge_name varchar, primary key (agent_rollup_id, capture_time,"
+ " gauge_name))", maxRollupHours);
PreparedStatement insertPS = session.prepare("insert into gauge_name (agent_rollup_id,"
+ " capture_time, gauge_name) values (?, ?, ?) using ttl ?");
Multimap<Long, AgentRollupIdGaugeNamePair> rowsPerCaptureTime = HashMultimap.create();
ResultSet results = session
.execute("select agent_rollup, gauge_name, capture_time from gauge_value_rollup_4");
for (Row row : results) {
int i = 0;
String agentRollupId = checkNotNull(row.getString(i++));
String gaugeName = checkNotNull(row.getString(i++));
long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
long millisPerDay = DAYS.toMillis(1);
long rollupCaptureTime = CaptureTimes.getRollup(captureTime, millisPerDay);
rowsPerCaptureTime.put(rollupCaptureTime,
ImmutableAgentRollupIdGaugeNamePair.of(agentRollupId, gaugeName));
}
// read from 1-min gauge values to get not-yet-rolled-up data
// (not using 5-second gauge values since those don't exist for agent rollups)
results = session
.execute("select agent_rollup, gauge_name, capture_time from gauge_value_rollup_1");
for (Row row : results) {
int i = 0;
String agentRollupId = checkNotNull(row.getString(i++));
String gaugeName = checkNotNull(row.getString(i++));
long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
long millisPerDay = DAYS.toMillis(1);
long rollupCaptureTime = CaptureTimes.getRollup(captureTime, millisPerDay);
rowsPerCaptureTime.put(rollupCaptureTime,
ImmutableAgentRollupIdGaugeNamePair.of(agentRollupId, gaugeName));
}
int maxRollupTTL = storageConfig.getMaxRollupTTL();
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
List<Long> sortedCaptureTimes =
Ordering.natural().sortedCopy(rowsPerCaptureTime.keySet());
for (long captureTime : sortedCaptureTimes) {
int adjustedTTL = Common.getAdjustedTTL(maxRollupTTL, captureTime, clock);
for (AgentRollupIdGaugeNamePair row : rowsPerCaptureTime.get(captureTime)) {
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, row.agentRollupId());
boundStatement.setTimestamp(i++, new Date(captureTime));
boundStatement.setString(i++, row.gaugeName());
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
}
MoreFutures.waitForAll(futures);
logger.info("populating new gauge name history table - complete");
}
private void populateAgentConfigGeneral() throws Exception {
if (!columnExists("agent_rollup", "display")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
ResultSet results =
session.execute("select agent_rollup_id, display from agent_rollup where one = 1");
PreparedStatement readConfigPS =
session.prepare("select config from agent_config where agent_rollup_id = ?");
PreparedStatement insertConfigPS =
session.prepare("insert into agent_config (agent_rollup_id, config) values (?, ?)");
for (Row row : results) {
String agentRollupId = row.getString(0);
String display = row.getString(1);
if (display == null) {
continue;
}
BoundStatement boundStatement = readConfigPS.bind();
boundStatement.setString(0, agentRollupId);
Row configRow = session.execute(boundStatement).one();
if (configRow == null) {
logger.warn("could not find config for agent rollup id: {}", agentRollupId);
continue;
}
AgentConfig agentConfig = AgentConfig.parseFrom(checkNotNull(configRow.getBytes(0)));
AgentConfig updatedAgentConfig = agentConfig.toBuilder()
.setGeneralConfig(GeneralConfig.newBuilder()
.setDisplay(display))
.build();
boundStatement = insertConfigPS.bind();
boundStatement.setString(0, agentRollupId);
boundStatement.setBytes(1, ByteBuffer.wrap(updatedAgentConfig.toByteArray()));
session.execute(boundStatement);
}
dropColumnIfExists("agent_rollup", "display");
}
private void populateV09AgentCheckTable() throws Exception {
int fullQueryTextExpirationHours = getFullQueryTextExpirationHours();
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
PreparedStatement insertV09AgentCheckPS = null;
for (V09AgentRollup v09AgentRollup : v09AgentRollups.values()) {
if (v09AgentRollup.agent() && v09AgentRollup.hasRollup()) {
// only create v09_agent_check and v09_last_capture_time tables if needed
if (insertV09AgentCheckPS == null) {
dropTableIfExists("v09_last_capture_time");
session.createTableWithLCS("create table v09_last_capture_time (one int,"
+ " v09_last_capture_time timestamp, v09_fqt_last_expiration_time"
+ " timestamp, v09_trace_last_expiration_time timestamp,"
+ " v09_aggregate_last_expiration_time timestamp, primary key (one))");
BoundStatement boundStatement = session.prepare("insert into"
+ " v09_last_capture_time (one, v09_last_capture_time,"
+ " v09_fqt_last_expiration_time, v09_trace_last_expiration_time,"
+ " v09_aggregate_last_expiration_time) values (1, ?, ?, ?, ?)")
.bind();
long nextDailyRollup = RollupLevelService.getCeilRollupTime(
clock.currentTimeMillis(), DAYS.toMillis(1));
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
long v09FqtLastExpirationTime =
addExpirationHours(nextDailyRollup, fullQueryTextExpirationHours);
long v09TraceLastExpirationTime = addExpirationHours(nextDailyRollup,
storageConfig.traceExpirationHours());
long v09AggregateLastExpirationTime = addExpirationHours(nextDailyRollup,
storageConfig.getMaxRollupHours());
int i = 0;
boundStatement.setTimestamp(i++, new Date(nextDailyRollup));
boundStatement.setTimestamp(i++, new Date(v09FqtLastExpirationTime));
boundStatement.setTimestamp(i++, new Date(v09TraceLastExpirationTime));
boundStatement.setTimestamp(i++, new Date(v09AggregateLastExpirationTime));
session.execute(boundStatement);
dropTableIfExists("v09_agent_check");
session.createTableWithLCS("create table v09_agent_check (one int, agent_id"
+ " varchar, primary key (one, agent_id))");
insertV09AgentCheckPS = session.prepare(
"insert into v09_agent_check (one, agent_id) values (1, ?)");
}
BoundStatement boundStatement = insertV09AgentCheckPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
session.execute(boundStatement);
}
}
}
private int getFullQueryTextExpirationHours() throws Exception {
// since fullQueryTextExpirationHours is no longer part of CentralStorageConfig (starting
// with 0.10.3, it must be pulled from json
ResultSet results =
session.execute("select value from central_config where key = 'storage'");
Row row = results.one();
if (row == null) {
// 2 weeks was the default
return 24 * 14;
}
String storageConfigText = row.getString(0);
if (storageConfigText == null) {
// 2 weeks was the default
return 24 * 14;
}
try {
JsonNode node = mapper.readTree(storageConfigText);
// 2 weeks was the default
return node.path("fullQueryTextExpirationHours").asInt(24 * 14);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
// 2 weeks was the default
return 24 * 14;
}
}
private void populateAgentHistoryTable() throws Exception {
logger.info("populating new agent history table - this could take a several minutes on"
+ " large data sets ...");
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
dropTableIfExists("agent");
session.createTableWithTWCS("create table agent (one int, capture_time timestamp, agent_id"
+ " varchar, primary key (one, capture_time, agent_id))",
storageConfig.getMaxRollupHours());
PreparedStatement insertPS = session.prepare("insert into agent (one, capture_time,"
+ " agent_id) values (1, ?, ?) using ttl ?");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
Multimap<Long, String> agentIdsPerCaptureTime = HashMultimap.create();
ResultSet results = session
.execute("select agent_rollup, capture_time from aggregate_tt_throughput_rollup_3");
for (Row row : results) {
String v09AgentId = checkNotNull(row.getString(0));
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentId);
if (v09AgentRollup == null || !v09AgentRollup.agent()) {
// v09AgentId is not an agent, or it was manually deleted (via the UI) from the
// agent_rollup table in which case its parent is no longer known and best to ignore
continue;
}
String agentId = v09AgentRollup.agentRollupId();
long captureTime = checkNotNull(row.getTimestamp(1)).getTime();
long millisPerDay = DAYS.toMillis(1);
long rollupCaptureTime = CaptureTimes.getRollup(captureTime, millisPerDay);
agentIdsPerCaptureTime.put(rollupCaptureTime, agentId);
}
// read from 1-min aggregates to get not-yet-rolled-up data
results = session
.execute("select agent_rollup, capture_time from aggregate_tt_throughput_rollup_0");
for (Row row : results) {
String v09AgentId = checkNotNull(row.getString(0));
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentId);
if (v09AgentRollup == null || !v09AgentRollup.agent()) {
// v09AgentId is not an agent, or it was manually deleted (via the UI) from the
// agent_rollup table in which case its parent is no longer known and best to ignore
continue;
}
String agentId = v09AgentRollup.agentRollupId();
long captureTime = checkNotNull(row.getTimestamp(1)).getTime();
long millisPerDay = DAYS.toMillis(1);
long rollupCaptureTime = CaptureTimes.getRollup(captureTime, millisPerDay);
agentIdsPerCaptureTime.put(rollupCaptureTime, agentId);
}
int maxRollupTTL = storageConfig.getMaxRollupTTL();
List<Long> sortedCaptureTimes =
Ordering.natural().sortedCopy(agentIdsPerCaptureTime.keySet());
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (long captureTime : sortedCaptureTimes) {
int adjustedTTL = Common.getAdjustedTTL(maxRollupTTL, captureTime, clock);
for (String agentId : agentIdsPerCaptureTime.get(captureTime)) {
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setTimestamp(i++, new Date(captureTime));
boundStatement.setString(i++, agentId);
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
}
MoreFutures.waitForAll(futures);
logger.info("populating new agent history table - complete");
}
private void rewriteAgentConfigTablePart1() throws Exception {
dropTableIfExists("agent_config_temp");
session.execute("create table agent_config_temp (agent_rollup_id varchar, config blob,"
+ " config_update boolean, config_update_token uuid, primary key"
+ " (agent_rollup_id))");
PreparedStatement insertTempPS = session.prepare("insert into agent_config_temp"
+ " (agent_rollup_id, config, config_update, config_update_token) values"
+ " (?, ?, ?, ?)");
ResultSet results = session.execute("select agent_rollup_id, config, config_update,"
+ " config_update_token from agent_config");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setBool(2, row.getBool(2));
boundStatement.setUUID(3, row.getUUID(3));
session.execute(boundStatement);
}
}
private void rewriteAgentConfigTablePart2() throws Exception {
if (!tableExists("agent_config_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("agent_config");
session.createTableWithLCS("create table agent_config (agent_rollup_id varchar, config"
+ " blob, config_update boolean, config_update_token uuid, primary key"
+ " (agent_rollup_id))");
PreparedStatement insertPS = session.prepare("insert into agent_config"
+ " (agent_rollup_id, config, config_update, config_update_token) values"
+ " (?, ?, ?, ?)");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
ResultSet results = session.execute("select agent_rollup_id, config, config_update,"
+ " config_update_token from agent_config_temp");
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setBool(2, row.getBool(2));
boundStatement.setUUID(3, row.getUUID(3));
session.execute(boundStatement);
}
dropTableIfExists("agent_config_temp");
}
private void rewriteEnvironmentTablePart1() throws Exception {
dropTableIfExists("environment_temp");
session.execute("create table environment_temp (agent_id varchar, environment blob,"
+ " primary key (agent_id))");
PreparedStatement insertTempPS = session
.prepare("insert into environment_temp (agent_id, environment) values (?, ?)");
ResultSet results = session.execute("select agent_id, environment from environment");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setBytes(1, row.getBytes(1));
session.execute(boundStatement);
}
}
private void rewriteEnvironmentTablePart2() throws Exception {
if (!tableExists("environment_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("environment");
session.createTableWithLCS("create table environment (agent_id varchar, environment blob,"
+ " primary key (agent_id))");
PreparedStatement insertPS = session
.prepare("insert into environment (agent_id, environment) values (?, ?)");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
ResultSet results = session.execute("select agent_id, environment from environment_temp");
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setBytes(1, row.getBytes(1));
session.execute(boundStatement);
}
dropTableIfExists("environment_temp");
}
private void rewriteOpenIncidentTablePart1() throws Exception {
dropTableIfExists("open_incident_temp");
session.execute("create table open_incident_temp (one int, agent_rollup_id varchar,"
+ " condition blob, severity varchar, notification blob, open_time timestamp,"
+ " primary key (one, agent_rollup_id, condition, severity))");
PreparedStatement insertTempPS = session.prepare("insert into open_incident_temp (one,"
+ " agent_rollup_id, condition, severity, notification, open_time) values"
+ " (1, ?, ?, ?, ?, ?)");
ResultSet results = session.execute("select agent_rollup_id, condition, severity,"
+ " notification, open_time from open_incident where one = 1");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setString(2, row.getString(2));
boundStatement.setBytes(3, row.getBytes(3));
boundStatement.setTimestamp(4, row.getTimestamp(4));
session.execute(boundStatement);
}
}
private void rewriteOpenIncidentTablePart2() throws Exception {
if (!tableExists("open_incident_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("open_incident");
session.createTableWithLCS("create table open_incident (one int, agent_rollup_id varchar,"
+ " condition blob, severity varchar, notification blob, open_time timestamp,"
+ " primary key (one, agent_rollup_id, condition, severity))");
PreparedStatement insertPS = session.prepare("insert into open_incident (one,"
+ " agent_rollup_id, condition, severity, notification, open_time) values"
+ " (1, ?, ?, ?, ?, ?)");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
ResultSet results = session.execute("select agent_rollup_id, condition, severity,"
+ " notification, open_time from open_incident_temp where one = 1");
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setBytes(1, row.getBytes(1));
boundStatement.setString(2, row.getString(2));
boundStatement.setBytes(3, row.getBytes(3));
boundStatement.setTimestamp(4, row.getTimestamp(4));
session.execute(boundStatement);
}
dropTableIfExists("open_incident_temp");
}
private void rewriteResolvedIncidentTablePart1() throws Exception {
dropTableIfExists("resolved_incident_temp");
session.execute("create table resolved_incident_temp (one int, resolve_time"
+ " timestamp, agent_rollup_id varchar, condition blob, severity varchar,"
+ " notification blob, open_time timestamp, primary key (one, resolve_time,"
+ " agent_rollup_id, condition)) with clustering order by (resolve_time desc)");
PreparedStatement insertTempPS = session.prepare("insert into resolved_incident_temp"
+ " (one, resolve_time, agent_rollup_id, condition, severity, notification,"
+ " open_time) values (1, ?, ?, ?, ?, ?, ?)");
ResultSet results = session.execute("select resolve_time, agent_rollup_id, condition,"
+ " severity, notification, open_time from resolved_incident where one = 1");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setTimestamp(0, row.getTimestamp(0));
boundStatement.setString(1, row.getString(1));
boundStatement.setBytes(2, row.getBytes(2));
boundStatement.setString(3, row.getString(3));
boundStatement.setBytes(4, row.getBytes(4));
boundStatement.setTimestamp(5, row.getTimestamp(5));
session.execute(boundStatement);
}
}
private void rewriteResolvedIncidentTablePart2() throws Exception {
if (!tableExists("resolved_incident_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("resolved_incident");
session.createTableWithTWCS("create table resolved_incident (one int, resolve_time"
+ " timestamp, agent_rollup_id varchar, condition blob, severity varchar,"
+ " notification blob, open_time timestamp, primary key (one, resolve_time,"
+ " agent_rollup_id, condition)) with clustering order by (resolve_time desc)",
Constants.RESOLVED_INCIDENT_EXPIRATION_HOURS, true);
PreparedStatement insertPS = session.prepare("insert into resolved_incident (one,"
+ " resolve_time, agent_rollup_id, condition, severity, notification,"
+ " open_time) values (1, ?, ?, ?, ?, ?, ?) using ttl ?");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
int ttl = Ints.saturatedCast(
HOURS.toSeconds(Constants.RESOLVED_INCIDENT_EXPIRATION_HOURS));
ResultSet results = session.execute("select resolve_time, agent_rollup_id, condition,"
+ " severity, notification, open_time from resolved_incident_temp where one = 1");
for (Row row : results) {
String v09AgentRollupId = row.getString(1);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
Date resolveTime = checkNotNull(row.getTimestamp(0));
int adjustedTTL = Common.getAdjustedTTL(ttl, resolveTime.getTime(), clock);
BoundStatement boundStatement = insertPS.bind();
boundStatement.setTimestamp(0, resolveTime);
boundStatement.setString(1, v09AgentRollup.agentRollupId());
boundStatement.setBytes(2, row.getBytes(2));
boundStatement.setString(3, row.getString(3));
boundStatement.setBytes(4, row.getBytes(4));
boundStatement.setTimestamp(5, row.getTimestamp(5));
boundStatement.setInt(6, adjustedTTL);
session.execute(boundStatement);
}
dropTableIfExists("resolved_incident_temp");
}
private void rewriteRoleTablePart1() throws Exception {
dropTableIfExists("role_temp");
session.execute("create table role_temp (name varchar, permissions set<varchar>,"
+ " primary key (name))");
PreparedStatement insertTempPS =
session.prepare("insert into role_temp (name, permissions) values (?, ?)");
ResultSet results = session.execute("select name, permissions from role");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setSet(1, row.getSet(1, String.class));
session.execute(boundStatement);
}
}
private void rewriteRoleTablePart2() throws Exception {
if (!tableExists("role_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("role");
session.createTableWithLCS("create table role (name varchar, permissions set<varchar>,"
+ " primary key (name))");
PreparedStatement insertPS =
session.prepare("insert into role (name, permissions) values (?, ?)");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
ResultSet results = session.execute("select name, permissions from role_temp");
for (Row row : results) {
Set<String> v09Permissions = row.getSet(1, String.class);
Set<String> permissions = Sets.newLinkedHashSet();
for (String v09Permission : v09Permissions) {
if (!v09Permission.startsWith("agent:")) {
// non-agent permission, no need for conversion
permissions.add(v09Permission);
continue;
}
if (v09Permission.equals("agent:") || v09Permission.startsWith("agent::")
|| v09Permission.equals("agent:*")
|| v09Permission.startsWith("agent:*:")) {
// special cases, no need for conversion
permissions.add(v09Permission);
continue;
}
PermissionParser parser = new PermissionParser(v09Permission);
parser.parse();
List<String> v09AgentRollupIds = parser.getAgentRollupIds();
String perm = parser.getPermission();
if (v09AgentRollupIds.isEmpty()) {
// this shouldn't happen since v09Permission doesn't start with "agent::"
// (see condition above)
logger.warn("found agent permission without any agents: {}", v09Permission);
continue;
}
List<String> agentRollupIds = new ArrayList<>();
for (String v09AgentRollupId : v09AgentRollupIds) {
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the
// agent_rollup table in which case its parent is no longer known
// and best to ignore
continue;
}
agentRollupIds.add(v09AgentRollup.agentRollupId());
}
if (agentRollupIds.isEmpty()) {
// all v09AgentRollupIds were manually deleted (see comment above)
continue;
}
if (perm.isEmpty()) {
permissions.add(
"agent:" + PermissionParser.quoteIfNeededAndJoin(v09AgentRollupIds));
} else {
permissions.add("agent:" + PermissionParser.quoteIfNeededAndJoin(agentRollupIds)
+ ":" + perm.substring("agent:".length()));
}
}
if (permissions.isEmpty()) {
// all v09AgentRollupIds for all permissions were manually deleted (see comments
// above)
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setSet(1, permissions);
session.execute(boundStatement);
}
dropTableIfExists("role_temp");
}
private void rewriteHeartbeatTablePart1() throws Exception {
logger.info("rewriting heartbeat table (part 1) ...");
dropTableIfExists("heartbeat_temp");
session.execute("create table heartbeat_temp (agent_id varchar, central_capture_time"
+ " timestamp, primary key (agent_id, central_capture_time))");
PreparedStatement insertTempPS = session.prepare("insert into heartbeat_temp (agent_id,"
+ " central_capture_time) values (?, ?)");
ResultSet results = session.execute("select agent_id, central_capture_time from heartbeat");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setTimestamp(1, row.getTimestamp(1));
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
logger.info("rewriting heartbeat table (part 1) - complete");
}
private void rewriteHeartbeatTablePart2() throws Exception {
if (!tableExists("heartbeat_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
logger.info("rewriting heartbeat table (part 2) ...");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
dropTableIfExists("heartbeat");
session.createTableWithTWCS("create table heartbeat (agent_id varchar, central_capture_time"
+ " timestamp, primary key (agent_id, central_capture_time))",
HeartbeatDao.EXPIRATION_HOURS);
PreparedStatement insertPS = session.prepare("insert into heartbeat (agent_id,"
+ " central_capture_time) values (?, ?) using ttl ?");
int ttl = Ints.saturatedCast(HOURS.toSeconds(HeartbeatDao.EXPIRATION_HOURS));
ResultSet results =
session.execute("select agent_id, central_capture_time from heartbeat_temp");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
Date centralCaptureDate = checkNotNull(row.getTimestamp(1));
int adjustedTTL = Common.getAdjustedTTL(ttl, centralCaptureDate.getTime(), clock);
BoundStatement boundStatement = insertPS.bind();
int i = 0;
boundStatement.setString(i++, v09AgentRollup.agentRollupId());
boundStatement.setTimestamp(i++, centralCaptureDate);
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
dropTableIfExists("heartbeat_temp");
logger.info("rewriting heartbeat table (part 2) - complete");
}
private void rewriteTransactionTypeTablePart1() throws Exception {
dropTableIfExists("transaction_type_temp");
session.execute("create table transaction_type_temp (one int, agent_rollup varchar,"
+ " transaction_type varchar, primary key (one, agent_rollup, transaction_type))");
PreparedStatement insertTempPS = session.prepare("insert into transaction_type_temp (one,"
+ " agent_rollup, transaction_type) values (1, ?, ?)");
ResultSet results = session.execute(
"select agent_rollup, transaction_type from transaction_type where one = 1");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
session.execute(boundStatement);
}
}
private void rewriteTransactionTypeTablePart2() throws Exception {
if (!tableExists("transaction_type_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("transaction_type");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
session.createTableWithLCS("create table transaction_type (one int, agent_rollup varchar,"
+ " transaction_type varchar, primary key (one, agent_rollup, transaction_type))");
PreparedStatement insertPS = session.prepare("insert into transaction_type (one,"
+ " agent_rollup, transaction_type) values (1, ?, ?) using ttl ?");
int ttl = getCentralStorageConfig(session).getMaxRollupTTL();
ResultSet results = session.execute(
"select agent_rollup, transaction_type from transaction_type_temp where one = 1");
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setString(1, row.getString(1));
boundStatement.setInt(2, ttl);
session.execute(boundStatement);
}
dropTableIfExists("transaction_type_temp");
}
private void rewriteTraceAttributeNameTablePart1() throws Exception {
dropTableIfExists("trace_attribute_name_temp");
session.execute("create table trace_attribute_name_temp (agent_rollup varchar,"
+ " transaction_type varchar, trace_attribute_name varchar, primary key"
+ " ((agent_rollup, transaction_type), trace_attribute_name))");
PreparedStatement insertTempPS = session.prepare("insert into trace_attribute_name_temp"
+ " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?)");
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " trace_attribute_name from trace_attribute_name");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
boundStatement.setString(2, row.getString(2));
session.execute(boundStatement);
}
}
private void rewriteTraceAttributeNameTablePart2() throws Exception {
if (!tableExists("trace_attribute_name_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("trace_attribute_name");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
session.createTableWithLCS("create table trace_attribute_name (agent_rollup varchar,"
+ " transaction_type varchar, trace_attribute_name varchar, primary key"
+ " ((agent_rollup, transaction_type), trace_attribute_name))");
PreparedStatement insertPS = session.prepare("insert into trace_attribute_name"
+ " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?) using"
+ " ttl ?");
int ttl = getCentralStorageConfig(session).getTraceTTL();
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " trace_attribute_name from trace_attribute_name_temp");
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setString(1, row.getString(1));
boundStatement.setString(2, row.getString(2));
boundStatement.setInt(3, ttl);
session.execute(boundStatement);
}
dropTableIfExists("trace_attribute_name_temp");
}
private void rewriteGaugeNameTablePart1() throws Exception {
logger.info("rewriting gauge_name table (part 1) - this could take several minutes on large"
+ " data sets ...");
dropTableIfExists("gauge_name_temp");
session.execute("create table gauge_name_temp (agent_rollup_id varchar, capture_time"
+ " timestamp, gauge_name varchar, primary key (agent_rollup_id, capture_time,"
+ " gauge_name))");
PreparedStatement insertTempPS = session.prepare("insert into gauge_name_temp"
+ " (agent_rollup_id, capture_time, gauge_name) values (?, ?, ?) using ttl ?");
ResultSet results =
session.execute("select agent_rollup_id, capture_time, gauge_name from gauge_name");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setTimestamp(1, row.getTimestamp(1));
boundStatement.setString(2, row.getString(2));
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
logger.info("rewriting gauge_name table (part 1) - complete");
}
private void rewriteGaugeNameTablePart2() throws Exception {
if (!tableExists("gauge_name_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
logger.info("rewriting gauge_name table (part 2) - this could take several minutes on large"
+ " data sets ...");
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
dropTableIfExists("gauge_name");
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
session.createTableWithTWCS("create table gauge_name (agent_rollup_id varchar, capture_time"
+ " timestamp, gauge_name varchar, primary key (agent_rollup_id, capture_time,"
+ " gauge_name))", storageConfig.getMaxRollupHours());
PreparedStatement insertPS = session.prepare("insert into gauge_name (agent_rollup_id,"
+ " capture_time, gauge_name) values (?, ?, ?) using ttl ?");
int ttl = getCentralStorageConfig(session).getMaxRollupTTL();
ResultSet results = session
.execute("select agent_rollup_id, capture_time, gauge_name from gauge_name_temp");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
String v09AgentRollupId = row.getString(0);
V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
if (v09AgentRollup == null) {
// v09AgentRollupId was manually deleted (via the UI) from the agent_rollup
// table in which case its parent is no longer known and best to ignore
continue;
}
Date captureDate = checkNotNull(row.getTimestamp(1));
int adjustedTTL = Common.getAdjustedTTL(ttl, captureDate.getTime(), clock);
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
boundStatement.setTimestamp(1, captureDate);
boundStatement.setString(2, row.getString(2));
boundStatement.setInt(3, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
dropTableIfExists("gauge_name_temp");
logger.info("rewriting gauge_name table (part 2) - complete");
}
private void populateV09AgentRollupTable() throws Exception {
Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
PreparedStatement insertPS = null;
for (V09AgentRollup v09AgentRollup : v09AgentRollups.values()) {
if (v09AgentRollup.agent() && v09AgentRollup.hasRollup()) {
// only create v09_agent_check and v09_last_capture_time tables if needed
if (insertPS == null) {
dropTableIfExists("v09_agent_rollup");
session.createTableWithLCS("create table v09_agent_rollup (one int,"
+ " v09_agent_id varchar, v09_agent_rollup_id varchar, primary key"
+ " (one, v09_agent_id, v09_agent_rollup_id))");
insertPS = session.prepare("insert into v09_agent_rollup"
+ " (one, v09_agent_id, v09_agent_rollup_id) values (1, ?, ?)");
}
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, v09AgentRollup.agentRollupId());
int i = 0;
boundStatement.setString(i++, v09AgentRollup.v09AgentRollupId());
boundStatement.setString(i++,
checkNotNull(v09AgentRollup.v09ParentAgentRollupId()));
session.execute(boundStatement);
}
}
}
private Map<String, V09AgentRollup> getV09AgentRollupsFromAgentRollupTable() throws Exception {
Map<String, V09AgentRollup> v09AgentRollupIds = new HashMap<>();
ResultSet results = session.execute("select agent_rollup_id, parent_agent_rollup_id, agent"
+ " from agent_rollup where one = 1");
for (Row row : results) {
int i = 0;
String v09AgentRollupId = checkNotNull(row.getString(i++));
String v09ParentAgentRollupId = row.getString(i++);
boolean agent = row.getBool(i++);
boolean hasRollup = v09ParentAgentRollupId != null;
String agentRollupId;
if (agent) {
if (v09ParentAgentRollupId == null) {
agentRollupId = v09AgentRollupId;
} else {
agentRollupId =
v09ParentAgentRollupId.replace("/", "::") + "::" + v09AgentRollupId;
}
} else {
agentRollupId = v09AgentRollupId.replace("/", "::") + "::";
}
v09AgentRollupIds.put(v09AgentRollupId, ImmutableV09AgentRollup.builder()
.agent(agent)
.hasRollup(hasRollup)
.agentRollupId(agentRollupId)
.v09AgentRollupId(v09AgentRollupId)
.v09ParentAgentRollupId(v09ParentAgentRollupId)
.build());
}
return v09AgentRollupIds;
}
private void finishV09AgentIdUpdate() throws Exception {
dropTableIfExists("trace_check");
// TODO at some point in the future drop agent_rollup
// (intentionally not dropping it for now, in case any upgrade corrections are needed post
// v0.10.0)
}
private void removeTraceTtErrorCountPartialColumn() throws Exception {
// this column is unused
dropColumnIfExists("trace_tt_error_point", "partial");
}
private void removeTraceTnErrorCountPartialColumn() throws Exception {
// this column is unused
dropColumnIfExists("trace_tn_error_point", "partial");
}
private void populateTraceTtSlowCountAndPointPartialPart1() throws Exception {
logger.info("populating trace_tt_slow_count_partial and trace_tt_slow_point_partial tables"
+ " - this could take several minutes on large data sets ...");
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
dropTableIfExists("trace_tt_slow_count_partial");
dropTableIfExists("trace_tt_slow_point_partial");
session.createTableWithTWCS("create table if not exists trace_tt_slow_count_partial"
+ " (agent_rollup varchar, transaction_type varchar, capture_time timestamp,"
+ " agent_id varchar, trace_id varchar, primary key ((agent_rollup,"
+ " transaction_type), capture_time, agent_id, trace_id))",
storageConfig.traceExpirationHours(), false, true);
session.createTableWithTWCS("create table if not exists trace_tt_slow_point_partial"
+ " (agent_rollup varchar, transaction_type varchar, capture_time timestamp,"
+ " agent_id varchar, trace_id varchar, duration_nanos bigint, error boolean,"
+ " headline varchar, user varchar, attributes blob, primary key ((agent_rollup,"
+ " transaction_type), capture_time, agent_id, trace_id))",
storageConfig.traceExpirationHours(), false, true);
PreparedStatement insertCountPartialPS = session.prepare("insert into"
+ " trace_tt_slow_count_partial (agent_rollup, transaction_type, capture_time,"
+ " agent_id, trace_id) values (?, ?, ?, ?, ?) using ttl ?");
PreparedStatement insertPointPartialPS = session.prepare("insert into"
+ " trace_tt_slow_point_partial (agent_rollup, transaction_type, capture_time,"
+ " agent_id, trace_id, duration_nanos, error, headline, user, attributes) values"
+ " (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?");
int ttl = getCentralStorageConfig(session).getTraceTTL();
ResultSet results = session.execute("select agent_rollup, transaction_type, capture_time,"
+ " agent_id, trace_id, duration_nanos, error, headline, user, attributes, partial"
+ " from trace_tt_slow_point");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
Stopwatch stopwatch = Stopwatch.createStarted();
int rowCount = 0;
for (Row row : results) {
if (!row.getBool(10)) { // partial
// unfortunately cannot use "where partial = true allow filtering" in the query
// above as that leads to ReadTimeoutException
continue;
}
BoundStatement boundStatement = insertCountPartialPS.bind();
int i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
Date captureDate = checkNotNull(row.getTimestamp(i));
int adjustedTTL = Common.getAdjustedTTL(ttl, captureDate.getTime(), clock);
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
boundStatement = insertPointPartialPS.bind();
i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
copyLong(row, boundStatement, i++); // duration_nanos
copyBool(row, boundStatement, i++); // error
copyString(row, boundStatement, i++); // headline
copyString(row, boundStatement, i++); // user
copyBytes(row, boundStatement, i++); // attributes
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
rowCount++;
if (stopwatch.elapsed(SECONDS) > 60) {
logger.info("processed {} records", rowCount);
stopwatch.reset().start();
}
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
logger.info("populating trace_tt_slow_count_partial and trace_tt_slow_point_partial tables"
+ " - complete");
}
private void populateTraceTtSlowCountAndPointPartialPart2() throws Exception {
if (!columnExists("trace_tt_slow_point", "partial")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
PreparedStatement deleteCountPS = session.prepare("delete from trace_tt_slow_count where"
+ " agent_rollup = ? and transaction_type = ? and capture_time = ? and agent_id = ?"
+ " and trace_id = ?");
PreparedStatement deletePointPS = session.prepare("delete from trace_tt_slow_point where"
+ " agent_rollup = ? and transaction_type = ? and capture_time = ? and agent_id = ?"
+ " and trace_id = ?");
ResultSet results = session.execute("select agent_rollup, transaction_type, capture_time,"
+ " agent_id, trace_id from trace_tt_slow_count_partial");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = deleteCountPS.bind();
int i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
futures.add(session.executeAsync(boundStatement));
boundStatement = deletePointPS.bind();
i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
dropColumnIfExists("trace_tt_slow_point", "partial");
}
private void populateTraceTnSlowCountAndPointPartialPart1() throws Exception {
logger.info("populating trace_tn_slow_count_partial and trace_tn_slow_point_partial tables"
+ " - this could take several minutes on large data sets ...");
CentralStorageConfig storageConfig = getCentralStorageConfig(session);
dropTableIfExists("trace_tn_slow_count_partial");
dropTableIfExists("trace_tn_slow_point_partial");
session.createTableWithTWCS("create table if not exists trace_tn_slow_count_partial"
+ " (agent_rollup varchar, transaction_type varchar, transaction_name varchar,"
+ " capture_time timestamp, agent_id varchar, trace_id varchar, primary key"
+ " ((agent_rollup, transaction_type, transaction_name), capture_time, agent_id,"
+ " trace_id))", storageConfig.traceExpirationHours(), false, true);
session.createTableWithTWCS("create table if not exists trace_tn_slow_point_partial"
+ " (agent_rollup varchar, transaction_type varchar, transaction_name varchar,"
+ " capture_time timestamp, agent_id varchar, trace_id varchar, duration_nanos"
+ " bigint, error boolean, headline varchar, user varchar, attributes blob, primary"
+ " key ((agent_rollup, transaction_type, transaction_name), capture_time,"
+ " agent_id, trace_id))", storageConfig.traceExpirationHours(), false, true);
PreparedStatement insertCountPartialPS = session.prepare("insert into"
+ " trace_tn_slow_count_partial (agent_rollup, transaction_type, transaction_name,"
+ " capture_time, agent_id, trace_id) values (?, ?, ?, ?, ?, ?) using ttl ?");
PreparedStatement insertPointPartialPS = session.prepare("insert into"
+ " trace_tn_slow_point_partial (agent_rollup, transaction_type, transaction_name,"
+ " capture_time, agent_id, trace_id, duration_nanos, error, headline, user,"
+ " attributes) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) using ttl ?");
int ttl = getCentralStorageConfig(session).getTraceTTL();
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " transaction_name, capture_time, agent_id, trace_id, duration_nanos, error,"
+ " headline, user, attributes, partial from trace_tn_slow_point");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
Stopwatch stopwatch = Stopwatch.createStarted();
int rowCount = 0;
for (Row row : results) {
if (!row.getBool(11)) { // partial
// unfortunately cannot use "where partial = true allow filtering" in the query
// above as that leads to ReadTimeoutException
continue;
}
BoundStatement boundStatement = insertCountPartialPS.bind();
int i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyString(row, boundStatement, i++); // transaction_name
Date captureDate = checkNotNull(row.getTimestamp(i));
int adjustedTTL = Common.getAdjustedTTL(ttl, captureDate.getTime(), clock);
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
boundStatement = insertPointPartialPS.bind();
i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyString(row, boundStatement, i++); // transaction_name
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
copyLong(row, boundStatement, i++); // duration_nanos
copyBool(row, boundStatement, i++); // error
copyString(row, boundStatement, i++); // headline
copyString(row, boundStatement, i++); // user
copyBytes(row, boundStatement, i++); // attributes
boundStatement.setInt(i++, adjustedTTL);
futures.add(session.executeAsync(boundStatement));
rowCount++;
if (stopwatch.elapsed(SECONDS) > 60) {
logger.info("processed {} records", rowCount);
stopwatch.reset().start();
}
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
logger.info("populating trace_tn_slow_count_partial and trace_tn_slow_point_partial tables"
+ " - complete");
}
private void populateTraceTnSlowCountAndPointPartialPart2() throws Exception {
if (!columnExists("trace_tn_slow_point", "partial")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
PreparedStatement deleteCountPS = session.prepare("delete from trace_tn_slow_count where"
+ " agent_rollup = ? and transaction_type = ? and transaction_name = ? and"
+ " capture_time = ? and agent_id = ? and trace_id = ?");
PreparedStatement deletePointPS = session.prepare("delete from trace_tn_slow_point where"
+ " agent_rollup = ? and transaction_type = ? and transaction_name = ? and"
+ " capture_time = ? and agent_id = ? and trace_id = ?");
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " transaction_name, capture_time, agent_id, trace_id from"
+ " trace_tn_slow_count_partial");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = deleteCountPS.bind();
int i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyString(row, boundStatement, i++); // transaction_name
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
futures.add(session.executeAsync(boundStatement));
boundStatement = deletePointPS.bind();
i = 0;
copyString(row, boundStatement, i++); // agent_rollup
copyString(row, boundStatement, i++); // transaction_type
copyString(row, boundStatement, i++); // transaction_name
copyTimestamp(row, boundStatement, i++); // capture_time
copyString(row, boundStatement, i++); // agent_id
copyString(row, boundStatement, i++); // trace_id
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
dropColumnIfExists("trace_tn_slow_point", "partial");
}
private void updateLcsUncheckedTombstoneCompaction() throws Exception {
for (TableMetadata table : keyspaceMetadata.getTables()) {
String compactionClass = table.getOptions().getCompaction().get("class");
if (compactionClass != null && compactionClass
.equals("org.apache.cassandra.db.compaction.LeveledCompactionStrategy")) {
session.execute("alter table " + table.getName() + " with compaction = { 'class'"
+ " : 'LeveledCompactionStrategy', 'unchecked_tombstone_compaction'"
+ " : true }");
}
}
}
private void updateStcsUncheckedTombstoneCompaction() throws Exception {
for (TableMetadata table : keyspaceMetadata.getTables()) {
String compactionClass = table.getOptions().getCompaction().get("class");
if (compactionClass != null && compactionClass
.equals("org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy")) {
session.execute("alter table " + table.getName() + " with compaction = { 'class'"
+ " : 'SizeTieredCompactionStrategy', 'unchecked_tombstone_compaction'"
+ " : true }");
}
}
}
private void optimizeTwcsTables() throws Exception {
for (TableMetadata table : keyspaceMetadata.getTables()) {
Map<String, String> compaction = table.getOptions().getCompaction();
String compactionClass = compaction.get("class");
if (compactionClass != null && compactionClass
.equals("org.apache.cassandra.db.compaction.TimeWindowCompactionStrategy")) {
String compactionWindowUnit = compaction.get("compaction_window_unit");
if (compactionWindowUnit == null) {
logger.warn("compaction_window_unit missing for table: {}", table.getName());
continue;
}
String compactionWindowSizeText = compaction.get("compaction_window_size");
if (compactionWindowSizeText == null) {
logger.warn("compaction_window_size missing for table: {}", table.getName());
continue;
}
int compactionWindowSize;
try {
compactionWindowSize = Integer.parseInt(compactionWindowSizeText);
} catch (NumberFormatException e) {
logger.warn("unable to parse compaction_window_size value: {}",
compactionWindowSizeText);
continue;
}
session.updateTableTwcsProperties(table.getName(), compactionWindowUnit,
compactionWindowSize);
}
}
}
private void changeV09TablesToLCS() throws Exception {
if (tableExists("v09_last_capture_time")) {
session.execute("alter table v09_last_capture_time with compaction = { 'class'"
+ " : 'LeveledCompactionStrategy', 'unchecked_tombstone_compaction' : true }");
}
if (tableExists("v09_agent_check")) {
session.execute("alter table v09_agent_check with compaction = { 'class'"
+ " : 'LeveledCompactionStrategy', 'unchecked_tombstone_compaction' : true }");
}
}
private void updateCentralStorageConfig() throws Exception {
ResultSet results =
session.execute("select value from central_config where key = 'storage'");
Row row = results.one();
if (row == null) {
return;
}
String storageConfigText = row.getString(0);
if (storageConfigText == null) {
return;
}
CentralStorageConfig storageConfig;
try {
ObjectNode node = (ObjectNode) mapper.readTree(storageConfigText);
node.remove("fullQueryTextExpirationHours");
storageConfig = mapper.readValue(mapper.treeAsTokens(node),
ImmutableCentralStorageConfig.class);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return;
}
PreparedStatement insertPS =
session.prepare("insert into central_config (key, value) values (?, ?)");
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, "storage");
boundStatement.setString(1, mapper.writeValueAsString(storageConfig));
session.execute(boundStatement);
}
private void rewriteV09AgentRollupPart1() throws Exception {
dropTableIfExists("v09_agent_rollup_temp");
session.createTableWithLCS("create table if not exists v09_agent_rollup_temp (one int,"
+ " v09_agent_id varchar, v09_agent_rollup_id varchar, primary key (one,"
+ " v09_agent_id))");
PreparedStatement insertTempPS = session.prepare("insert into v09_agent_rollup_temp (one,"
+ " v09_agent_id, v09_agent_rollup_id) values (1, ?, ?)");
ResultSet results = session.execute(
"select v09_agent_id, v09_agent_rollup_id from v09_agent_rollup where one = 1");
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
session.execute(boundStatement);
}
}
private void rewriteV09AgentRollupPart2() throws Exception {
if (!tableExists("v09_agent_rollup_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("v09_agent_rollup");
session.createTableWithLCS("create table if not exists v09_agent_rollup (one int,"
+ " v09_agent_id varchar, v09_agent_rollup_id varchar, primary key (one,"
+ " v09_agent_id))");
PreparedStatement insertPS = session.prepare("insert into v09_agent_rollup (one,"
+ " v09_agent_id, v09_agent_rollup_id) values (1, ?, ?)");
ResultSet results = session.execute("select v09_agent_id, v09_agent_rollup_id from"
+ " v09_agent_rollup_temp where one = 1");
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
session.execute(boundStatement);
}
dropTableIfExists("v09_agent_rollup_temp");
}
private void updateTraceAttributeNamePartitionKeyPart1() throws Exception {
dropTableIfExists("trace_attribute_name_temp");
session.execute("create table trace_attribute_name_temp (agent_rollup varchar,"
+ " transaction_type varchar, trace_attribute_name varchar, primary key"
+ " (agent_rollup, transaction_type, trace_attribute_name))");
PreparedStatement insertTempPS = session.prepare("insert into trace_attribute_name_temp"
+ " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?)");
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " trace_attribute_name from trace_attribute_name");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = insertTempPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
boundStatement.setString(2, row.getString(2));
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
}
private void updateTraceAttributeNamePartitionKeyPart2() throws Exception {
if (!tableExists("trace_attribute_name_temp")) {
// previously failed mid-upgrade prior to updating schema version
return;
}
dropTableIfExists("trace_attribute_name");
session.createTableWithLCS("create table trace_attribute_name (agent_rollup varchar,"
+ " transaction_type varchar, trace_attribute_name varchar, primary key"
+ " (agent_rollup, transaction_type, trace_attribute_name))");
PreparedStatement insertPS = session.prepare("insert into trace_attribute_name"
+ " (agent_rollup, transaction_type, trace_attribute_name) values (?, ?, ?) using"
+ " ttl ?");
int ttl = getCentralStorageConfig(session).getTraceTTL();
ResultSet results = session.execute("select agent_rollup, transaction_type,"
+ " trace_attribute_name from trace_attribute_name_temp");
// using linked list to make it fast to remove elements from the front
LinkedList<ListenableFuture<ResultSet>> futures = new LinkedList<>();
for (Row row : results) {
BoundStatement boundStatement = insertPS.bind();
boundStatement.setString(0, row.getString(0));
boundStatement.setString(1, row.getString(1));
boundStatement.setString(2, row.getString(2));
boundStatement.setInt(3, ttl);
futures.add(session.executeAsync(boundStatement));
waitForSome(futures);
}
MoreFutures.waitForAll(futures);
dropTableIfExists("trace_attribute_name_temp");
}
private void addColumnIfNotExists(String tableName, String columnName, String cqlType)
throws Exception {
if (!columnExists(tableName, columnName)) {
session.execute("alter table " + tableName + " add " + columnName + " " + cqlType);
}
}
private void dropColumnIfExists(String tableName, String columnName) throws Exception {
if (columnExists(tableName, columnName)) {
session.execute("alter table " + tableName + " drop " + columnName);
}
}
private boolean tableExists(String tableName) {
return keyspaceMetadata.getTable(tableName) != null;
}
private boolean columnExists(String tableName, String columnName) {
TableMetadata tableMetadata = keyspaceMetadata.getTable(tableName);
return tableMetadata != null && tableMetadata.getColumn(columnName) != null;
}
// drop table can timeout, throwing NoHostAvailableException
// (see https://github.com/glowroot/glowroot/issues/125)
private void dropTableIfExists(String tableName) throws Exception {
Stopwatch stopwatch = Stopwatch.createStarted();
while (stopwatch.elapsed(SECONDS) < 60) {
try {
session.execute("drop table if exists " + tableName);
return;
} catch (NoHostAvailableException e) {
logger.debug(e.getMessage(), e);
}
Thread.sleep(1000);
}
// try one last time and let exception bubble up
session.execute("drop table if exists " + tableName);
}
// this is needed to prevent OOM due to ever expanding list of futures (and the result sets that
// they retain)
private static void waitForSome(LinkedList<ListenableFuture<ResultSet>> futures)
throws Exception {
while (futures.size() > 1000) {
futures.removeFirst().get();
}
}
public static AgentConfig upgradeOldAgentConfig(AgentConfig oldAgentConfig) {
AgentConfig.Builder builder = oldAgentConfig.toBuilder()
.clearOldAlertConfig();
for (OldAlertConfig oldAlertConfig : oldAgentConfig.getOldAlertConfigList()) {
AlertConfig.Builder alertConfigBuilder = AlertConfig.newBuilder();
switch (oldAlertConfig.getKind()) {
case TRANSACTION:
alertConfigBuilder.getConditionBuilder().setMetricCondition(
createTransactionTimeCondition(oldAlertConfig));
break;
case GAUGE:
alertConfigBuilder.getConditionBuilder().setMetricCondition(
createGaugeCondition(oldAlertConfig));
break;
case SYNTHETIC_MONITOR:
alertConfigBuilder.getConditionBuilder().setSyntheticMonitorCondition(
createSyntheticMonitorCondition(oldAlertConfig));
break;
case HEARTBEAT:
alertConfigBuilder.getConditionBuilder().setHeartbeatCondition(
createHeartbeatCondition(oldAlertConfig));
break;
default:
logger.error("unexpected alert kind: {}", oldAlertConfig.getKind());
continue;
}
alertConfigBuilder.getNotificationBuilder().getEmailNotificationBuilder()
.addAllEmailAddress(oldAlertConfig.getEmailAddressList());
builder.addAlertConfig(alertConfigBuilder);
}
return builder.build();
}
private static MetricCondition createTransactionTimeCondition(
OldAlertConfig oldAlertConfig) {
return MetricCondition.newBuilder()
.setMetric("transaction:x-percentile")
.setTransactionType(oldAlertConfig.getTransactionType())
.setPercentile(oldAlertConfig.getTransactionPercentile())
.setThreshold(oldAlertConfig.getThresholdMillis().getValue())
.setTimePeriodSeconds(oldAlertConfig.getTimePeriodSeconds())
.setMinTransactionCount(oldAlertConfig.getMinTransactionCount().getValue())
.build();
}
private static MetricCondition createGaugeCondition(OldAlertConfig oldAlertConfig) {
return MetricCondition.newBuilder()
.setMetric("gauge:" + oldAlertConfig.getGaugeName())
.setThreshold(oldAlertConfig.getGaugeThreshold().getValue())
.setTimePeriodSeconds(oldAlertConfig.getTimePeriodSeconds())
.build();
}
private static SyntheticMonitorCondition createSyntheticMonitorCondition(
OldAlertConfig oldAlertConfig) {
return SyntheticMonitorCondition.newBuilder()
.setSyntheticMonitorId(oldAlertConfig.getSyntheticMonitorId())
.setThresholdMillis(oldAlertConfig.getThresholdMillis().getValue())
.build();
}
private static HeartbeatCondition createHeartbeatCondition(OldAlertConfig oldAlertConfig) {
return HeartbeatCondition.newBuilder()
.setTimePeriodSeconds(oldAlertConfig.getTimePeriodSeconds())
.build();
}
@VisibleForTesting
static @Nullable Set<String> upgradePermissions(Set<String> permissions) {
Set<String> updatedPermissions = new HashSet<>();
ListMultimap<String, String> agentPermissions = ArrayListMultimap.create();
boolean needsUpgrade = false;
for (String permission : permissions) {
if (permission.startsWith("agent:")) {
PermissionParser parser = new PermissionParser(permission);
parser.parse();
String perm = parser.getPermission();
agentPermissions.put(
PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds()), perm);
if (perm.equals("agent:view")) {
needsUpgrade = true;
}
} else if (permission.equals("admin") || permission.startsWith("admin:")) {
updatedPermissions.add(permission);
} else {
logger.error("unexpected permission: {}", permission);
}
}
if (!needsUpgrade) {
return null;
}
for (Map.Entry<String, List<String>> entry : Multimaps.asMap(agentPermissions).entrySet()) {
List<String> perms = entry.getValue();
PermissionParser.upgradeAgentPermissionsFrom_0_9_1_to_0_9_2(perms);
for (String perm : perms) {
updatedPermissions
.add("agent:" + entry.getKey() + ":" + perm.substring("agent:".length()));
}
}
if (updatedPermissions.contains("admin:view")
&& updatedPermissions.contains("admin:edit")) {
updatedPermissions.remove("admin:view");
updatedPermissions.remove("admin:edit");
updatedPermissions.add("admin");
}
return updatedPermissions;
}
@VisibleForTesting
static Set<String> upgradePermissions2(Set<String> permissions) {
Set<String> permissionsToBeAdded = new HashSet<>();
for (String permission : permissions) {
if (!permission.startsWith("agent:")) {
continue;
}
PermissionParser parser = new PermissionParser(permission);
parser.parse();
String perm = parser.getPermission();
if (perm.equals("agent:transaction")) {
permissionsToBeAdded.add("agent:"
+ PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
+ ":syntheticMonitor");
permissionsToBeAdded.add("agent:"
+ PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
+ ":alert");
}
}
return permissionsToBeAdded;
}
private static boolean updateCentralConfigurationPropertiesFile(JsonNode webConfigNode)
throws IOException {
String bindAddressText = "";
JsonNode bindAddressNode = webConfigNode.get("bindAddress");
if (bindAddressNode != null && !bindAddressNode.asText().equals("0.0.0.0")) {
bindAddressText = bindAddressNode.asText();
}
String portText = "";
JsonNode portNode = webConfigNode.get("port");
if (portNode != null && portNode.intValue() != 4000) {
portText = portNode.asText();
}
String httpsText = "";
JsonNode httpsNode = webConfigNode.get("https");
if (httpsNode != null && httpsNode.booleanValue()) {
httpsText = "true";
}
String contextPathText = "";
JsonNode contextPathNode = webConfigNode.get("contextPath");
if (contextPathNode != null && !contextPathNode.asText().equals("/")) {
contextPathText = contextPathNode.asText();
}
File propFile = new File("glowroot-central.properties");
if (!propFile.exists()) {
startupLogger.warn("glowroot-central.properties file does not exist, so not populating"
+ " ui properties");
return false;
}
Properties props = PropertiesFiles.load(propFile);
StringBuilder sb = new StringBuilder();
if (!props.containsKey("ui.bindAddress")) {
sb.append("\n");
sb.append("# default is ui.bindAddress=0.0.0.0\n");
sb.append("ui.bindAddress=");
sb.append(bindAddressText);
sb.append("\n");
}
if (!props.containsKey("ui.port")) {
sb.append("\n");
sb.append("# default is ui.port=4000\n");
sb.append("ui.port=");
sb.append(portText);
sb.append("\n");
}
if (!props.containsKey("ui.https")) {
sb.append("\n");
sb.append("# default is ui.https=false\n");
sb.append("# set this to \"true\" to serve the UI over HTTPS\n");
sb.append("# the certificate and private key to be used must be placed in the same"
+ " directory as this properties\n");
sb.append("# file, with filenames \"ui-cert.pem\" and \"ui-key.pem\", where ui-cert.pem"
+ " is a PEM encoded X.509\n");
sb.append("# certificate chain, and ui-key.pem is a PEM encoded PKCS#8 private key"
+ " without a passphrase (for\n");
sb.append("# example, a self signed certificate can be generated at the command line"
+ " meeting the above\n");
sb.append("# requirements using OpenSSL 1.0.0 or later:\n");
sb.append("# \"openssl req -new -x509 -nodes -days 365 -out ui-cert.pem -keyout"
+ " ui-key.pem\")\n");
sb.append("ui.https=");
sb.append(httpsText);
sb.append("\n");
}
if (!props.containsKey("ui.contextPath")) {
sb.append("\n");
sb.append("# default is ui.contextPath=/\n");
sb.append("# this only needs to be changed if reverse proxying the UI behind a non-root"
+ " context path\n");
sb.append("ui.contextPath=");
sb.append(contextPathText);
sb.append("\n");
}
if (sb.length() == 0) {
// glowroot-central.properties file has been updated
return false;
}
if (props.containsKey("jgroups.configurationFile")) {
startupLogger.error("When running in a cluster, you must manually upgrade"
+ " the glowroot-central.properties files on each node to add the following"
+ " properties:\n\n" + sb + "\n\n");
throw new IllegalStateException(
"Glowroot central could not start, see error message above for instructions");
}
try (FileWriter out = new FileWriter(propFile, true)) {
out.write(sb.toString());
}
return true;
}
private static CentralStorageConfig getCentralStorageConfig(Session session) throws Exception {
ResultSet results =
session.execute("select value from central_config where key = 'storage'");
Row row = results.one();
if (row == null) {
return ImmutableCentralStorageConfig.builder().build();
}
String storageConfigText = row.getString(0);
if (storageConfigText == null) {
return ImmutableCentralStorageConfig.builder().build();
}
try {
return mapper.readValue(storageConfigText, ImmutableCentralStorageConfig.class);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
return ImmutableCentralStorageConfig.builder().build();
}
}
private static long addExpirationHours(long timeInMillis, int expirationHours) {
if (expirationHours == 0) {
// 100 years from now is the same thing as never expire (0)
return timeInMillis + DAYS.toMillis(365 * 100L);
} else {
return timeInMillis + HOURS.toMillis(expirationHours);
}
}
private static void copyString(Row row, BoundStatement boundStatement, int i) {
boundStatement.setString(i, row.getString(i));
}
private static void copyLong(Row row, BoundStatement boundStatement, int i) {
boundStatement.setLong(i, row.getLong(i));
}
private static void copyBool(Row row, BoundStatement boundStatement, int i) {
boundStatement.setBool(i, row.getBool(i));
}
private static void copyTimestamp(Row row, BoundStatement boundStatement, int i) {
boundStatement.setTimestamp(i, row.getTimestamp(i));
}
private static void copyBytes(Row row, BoundStatement boundStatement, int i) {
boundStatement.setBytes(i, row.getBytes(i));
}
private static @Nullable Integer getSchemaVersion(Session session, KeyspaceMetadata keyspace)
throws Exception {
ResultSet results =
session.execute("select schema_version from schema_version where one = 1");
Row row = results.one();
if (row != null) {
return row.getInt(0);
}
TableMetadata agentTable = keyspace.getTable("agent");
if (agentTable != null && agentTable.getColumn("system_info") != null) {
// special case, this is glowroot version 0.9.1, the only version supporting upgrades
// prior to schema_version table
return 1;
}
// new installation
return null;
}
@Value.Immutable
@Styles.AllParameters
interface AgentRollupIdGaugeNamePair {
String agentRollupId();
String gaugeName();
}
@Value.Immutable
interface V09AgentRollup {
boolean agent();
boolean hasRollup();
String agentRollupId();
String v09AgentRollupId();
@Nullable
String v09ParentAgentRollupId();
}
}
| [
"trask.stalnaker@gmail.com"
] | trask.stalnaker@gmail.com |
5f198435f8e28dab69182f5b0ad4ab4b3d89cc10 | 68751ef2c0e4be18ae9f2ce1100886d3f59aa0ad | /src/main/java/musics/arts/controller/SongController.java | 7f1335f8f030df2345e2218b07a07f7f14dd1712 | [] | no_license | miftahnz/my-project | 3cc4dc7e5e160e25ccc4927ee09e8b020947cc4f | a1c1c5425a08bec664833134c71bda38511797bb | refs/heads/master | 2020-12-21T14:22:26.317256 | 2020-01-27T09:44:03 | 2020-01-27T09:44:03 | 236,458,325 | 0 | 0 | null | 2020-10-13T19:05:30 | 2020-01-27T09:41:17 | Java | UTF-8 | Java | false | false | 1,132 | java | package musics.arts.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import musics.arts.models.Song;
import musics.arts.services.SongService;
@RestController
@RequestMapping("/music")
public class SongController {
@Autowired
SongService songService;
@GetMapping("/song")
public List<Song> findAll(){
return songService.findAll();
}
@GetMapping("/song/{id}")
public Song findById(@PathVariable Integer id) {
return songService.findById(id);
}
@PostMapping("/song")
public Song save(@RequestBody Song song) {
return songService.save(song);
}
@GetMapping("/song/artist/{id}")
public List<Song> findSongByArtist(@PathVariable Integer id){
return songService.findSongByArtistId(id);
}
}
| [
"miftahnurzanah30@gmail.com"
] | miftahnurzanah30@gmail.com |
e93b73af61db7230b6d64eced7f19f52ad533023 | 77e8904e256910206d9c86ee92a397e6dc7f8e4f | /src/main/java/dao/DaoGeneric.java | c3363fa4db754d375042e30455cf56a4ceb0bd63 | [] | no_license | LorranPdS/projeto-jsf-jpa | 9b19582411005b0508693e58fc448c95eb05034c | f9b4a0ca4d5fdf6d0fc17eb2dee1ba683a0706e3 | refs/heads/master | 2023-01-06T19:14:39.287530 | 2020-10-30T01:37:39 | 2020-10-30T01:37:39 | 295,416,796 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,554 | java | package dao;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import jpautil.JPAUtil;
@Named
public class DaoGeneric<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private EntityManager entityManager;
@Inject
private JPAUtil jpaUtil;
public T salvar(T entidade) {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
T ent = entityManager.merge(entidade);
transaction.commit();
return ent;
}
public void deletarPorId(T entidade) {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
Object id = jpaUtil.getPrimaryKey(entidade);
entityManager.createQuery("delete from " + entidade.getClass().getCanonicalName() + " where id = " + id)
.executeUpdate();
transaction.commit();
}
@SuppressWarnings("unchecked")
public List<T> listarTodos(T entidade) {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
List<T> lista = entityManager.createQuery("from " + entidade.getClass().getCanonicalName()).getResultList();
transaction.commit();
return lista;
}
public T consultar(Class<T> entidade, String codigo) {
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
T objeto = (T) entityManager.find(entidade, Long.parseLong(codigo));
transaction.commit();
return objeto;
}
}
| [
"lorransantospereira@yahoo.com.br"
] | lorransantospereira@yahoo.com.br |
129ffcf981930eb2042af68b793f4aa6e24ef71d | 8ff9595df20f426d7060a715a435e2a1b0e78125 | /app/src/main/java/com/example/maria/proyectofinal_v3/MenuUsuario.java | 29e31f0dbc594ca7f80f6fd3277a72ac8834d1a5 | [] | no_license | eltoboso/ProyectoFinal | 4a97c83b2573ed8bc3d1dc52d399d45f99f70c28 | 5b8b6a0e8f6192169da545869bff4ae9787d7910 | refs/heads/master | 2021-01-20T05:09:07.150245 | 2017-04-29T00:24:17 | 2017-04-29T00:24:17 | 89,754,373 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 825 | java | package com.example.maria.proyectofinal_v3;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MenuUsuario extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_usuario);
}
public void misServicios(View v){
//Lanza la actividad HistorialUsuario
Intent intent=new Intent(this, HistorialUsuario.class);
startActivity(intent);
}
//cada uno de estos métodos (imagebutton) lanza la actividad CategoriaUsuario
public void fontanero(View v){
Intent intent=new Intent(this, CategoriaUsuario.class);
startActivity(intent);
}
}
| [
"perezeruizmaria@gmail.com"
] | perezeruizmaria@gmail.com |
3669dd82895061a394a888b2c63652ff992b951e | 58c5fb06b5d63a4d39b6bd174fa5b74a7661207c | /src/main/java/design/abstractFactory/VehicleFactory.java | 3c588b7a6daea52b961cbca5d171556142b9b378 | [] | no_license | meenakshisund/core-java | 644bc4fc62c4dc471c4a6fe4569bd9aff1d37991 | 185f54b91a69d53e297acdfb8f30cf41fea71260 | refs/heads/master | 2021-02-27T09:07:04.951596 | 2020-04-12T09:26:41 | 2020-04-12T09:26:41 | 245,595,838 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 170 | java | package design.abstractFactory;
class VehicleFactory {
static Vehicle createVehicle(VehicleAbstractFactory factory) {
return factory.createVehicle();
}
} | [
"meenakshisundaraja@gmail.com"
] | meenakshisundaraja@gmail.com |
73dc6e5d368cac093b61de3bbb2267fb2e6558ad | 520ba55917024b08041ad9d520b42a027e869ec4 | /src/addTwoBinaryNumbers.java | b86d14e1cb72aadfda8cb87cb0c876509ff90cae | [] | no_license | BackEndFrontEndChallenges/Scaler_DSA | d641a50ffe9c2f2ee80755d8a46dbabd6d574ddf | 7e2cc4ee4ef2fb18ec632d9f8d987076a4185ef1 | refs/heads/master | 2023-09-02T18:50:30.439574 | 2021-11-21T18:56:46 | 2021-11-21T18:56:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,005 | java | import java.util.Scanner;
public class addTwoBinaryNumbers {
public static void main(String[] args) {
String first = getIntFromUser().toString();
String second = getIntFromUser().toString();
System.out.println(addBinary(first, second));
}
private static String getIntFromUser(){
Scanner s = new Scanner(System.in);
return s.nextLine();
}
private static String addBinary(String num1, String num2) {
int len1 = num1.length();
int len2 = num2.length();
int carryover = 0;
String res = "";
int maxLen = Math.max(len1, len2);
for (int currPlace=0; currPlace < maxLen; currPlace++){
int a = currPlace < len1 ? num1.charAt(len1-1-currPlace)-'0':0;
int b = currPlace < len2 ? num2.charAt(len2-1-currPlace)-'0':0;
int temp = a + b + carryover;
carryover = temp/2;
res = temp%2 + res;
}
return (carryover==0) ? res:"1"+ res;
}
}
| [
"rajeev.nov89@gmail.com"
] | rajeev.nov89@gmail.com |
17b3fccb8828f9d9d1f8ef53417925a7dafceb19 | 68ff808ae184158a4df4f6449e61621c8db72f61 | /Java Advanced/Java OOP Advanced/Exercise SOLID - Boat Racing Simulator/src/main/java/repository/BoatRepository.java | 10950a3b9763111151dacc092927a220f1bd52d4 | [
"Apache-2.0"
] | permissive | Valentin9003/Java | eb2ee75468091136b49e5f0b902159bbb8276eca | 9d263063685ba60ab75dc9efd25554b715a7980a | refs/heads/master | 2020-04-02T13:28:24.713200 | 2019-11-13T10:30:05 | 2019-11-13T10:30:05 | 154,482,638 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 981 | java | package repository;
import Utility.Constants;
import contracts.Boat;
import contracts.Repository;
import exeptions.DuplicateModelException;
import exeptions.NonExistentModelException;
import java.util.LinkedHashMap;
import java.util.Map;
public class BoatRepository implements Repository<Boat> {
private Map<String, Boat> boats;
public BoatRepository() {
this.boats = new LinkedHashMap<>();
}
@Override
public void add(Boat item) throws DuplicateModelException {
if (this.boats.containsKey(item.getModel())) {
throw new DuplicateModelException(Constants.DUPLICATE_MODEL_MESSAGE);
}
this.boats.put(item.getModel(), item);
}
@Override
public Boat getItemByModel(String model) throws NonExistentModelException {
if (!this.boats.containsKey(model)) {
throw new NonExistentModelException(Constants.NON_EXISTENT_MODEL_MESSAGE);
}
return this.boats.get(model);
}
}
| [
"valio_180@abv.bg"
] | valio_180@abv.bg |
5ee152ef4a4a416b1a8de5856a96d732a16f8fbf | 720ede9ff6c3115db345c5f12e245c20e4f1bacf | /app/src/main/java/com/app/dropshipbox1/activities/ActivityHistory.java | 3a44d865d2e2826352625ab1958d716ed98352ff | [] | no_license | ibalm9/dropship_box | fd960d3a23a2d8a707bad13b9f06e469b29ec69d | 8d555f0c94f3674f3c073c07769c5cf6711f2e7f | refs/heads/master | 2022-11-11T18:57:26.699275 | 2020-07-10T08:40:04 | 2020-07-10T08:40:04 | 278,260,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,458 | java | package com.app.dropshipbox1.activities;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.dropshipbox1.Config;
import com.app.dropshipbox1.R;
import com.app.dropshipbox1.adapters.RecyclerAdapterHistory;
import com.app.dropshipbox1.models.History;
import com.app.dropshipbox1.utilities.DBHelper;
import com.app.dropshipbox1.utilities.MyDividerItemDecoration;
import com.app.dropshipbox1.utilities.Utils;
import java.util.ArrayList;
import java.util.List;
public class ActivityHistory extends AppCompatActivity {
RecyclerView recyclerView;
View lyt_empty_history;
RelativeLayout lyt_history;
DBHelper dbhelper;
RecyclerAdapterHistory recyclerAdapterHistory;
final int CLEAR_ALL_ORDER = 0;
final int CLEAR_ONE_ORDER = 1;
int FLAG;
int ID;
ArrayList<ArrayList<Object>> data;
public static ArrayList<Integer> id = new ArrayList<Integer>();
public static ArrayList<String> code = new ArrayList<String>();
public static ArrayList<String> order_list = new ArrayList<String>();
public static ArrayList<String> order_total = new ArrayList<String>();
public static ArrayList<String> date_time = new ArrayList<String>();
List<History> arrayItemHistory;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
View view, bottom_sheet;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.title_history);
}
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
recyclerView = findViewById(R.id.recycler_view);
lyt_empty_history = findViewById(R.id.lyt_empty_history);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new MyDividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL, 0));
recyclerView.setItemAnimator(new DefaultItemAnimator());
lyt_history = findViewById(R.id.lyt_history);
recyclerAdapterHistory = new RecyclerAdapterHistory(this, arrayItemHistory);
dbhelper = new DBHelper(this);
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
@Override
public void onClick(View view, final int position) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
showBottomSheetDialog(position);
}
}, 400);
}
@Override
public void onLongClick(View view, final int position) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
showClearDialog(CLEAR_ONE_ORDER, id.get(position));
}
}, 400);
}
}));
new getDataTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_cart, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.clear:
if (id.size() > 0) {
showClearDialog(CLEAR_ALL_ORDER, 1111);
} else {
Snackbar.make(view, R.string.msg_no_history, Snackbar.LENGTH_SHORT).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showClearDialog(int flag, int id) {
FLAG = flag;
ID = id;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.confirm);
switch (FLAG) {
case 0:
builder.setMessage(getString(R.string.clear_all_order));
break;
case 1:
builder.setMessage(getString(R.string.clear_one_order));
break;
}
builder.setCancelable(false);
builder.setPositiveButton(getResources().getString(R.string.dialog_option_yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (FLAG) {
case 0:
dbhelper.deleteAllDataHistory();
clearData();
new getDataTask().execute();
break;
case 1:
dbhelper.deleteDataHistory(ID);
clearData();
new getDataTask().execute();
break;
}
}
});
builder.setNegativeButton(getResources().getString(R.string.dialog_option_no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void clearData() {
id.clear();
code.clear();
order_list.clear();
order_total.clear();
date_time.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
getDataFromDatabase();
return null;
}
@Override
protected void onPostExecute(Void result) {
if (id.size() > 0) {
lyt_history.setVisibility(View.VISIBLE);
recyclerView.setAdapter(recyclerAdapterHistory);
} else {
lyt_empty_history.setVisibility(View.VISIBLE);
}
}
}
public void getDataFromDatabase() {
clearData();
data = dbhelper.getAllDataHistory();
for (int i = 0; i < data.size(); i++) {
ArrayList<Object> row = data.get(i);
id.add(Integer.parseInt(row.get(0).toString()));
code.add(row.get(1).toString());
order_list.add(row.get(2).toString());
order_total.add(row.get(3).toString());
date_time.add(row.get(4).toString());
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
private void showBottomSheetDialog(final int position) {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.item_bottom_sheet, null);
((TextView) view.findViewById(R.id.sheet_code)).setText(code.get(position));
((TextView) view.findViewById(R.id.sheet_date)).setText(Utils.getFormatedDate(date_time.get(position)));
((TextView) view.findViewById(R.id.sheet_order_list)).setText(order_list.get(position));
((TextView) view.findViewById(R.id.sheet_order_total)).setText(order_total.get(position));
((ImageView) view.findViewById(R.id.img_copy)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Order Id", code.get(position));
clipboard.setPrimaryClip(clip);
Toast.makeText(ActivityHistory.this, R.string.msg_copy, Toast.LENGTH_SHORT).show();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
}
} | [
"ibalmaulana9@gmail.com"
] | ibalmaulana9@gmail.com |
8836a3ca3fc394ece1038d74312103c4a202f1aa | 32b72e1dc8b6ee1be2e80bb70a03a021c83db550 | /ast_results/rdoeffinger_Dictionary/src/com/hughes/android/dictionary/CollatorWrapper.java | 6f5b8df0392ea49ed12a2b9b28621613154377e9 | [] | no_license | cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning | d90c41a17e88fcd99d543124eeb6e93f9133cb4a | 0564143d92f8024ff5fa6b659c2baebf827582b1 | refs/heads/master | 2020-07-13T13:53:40.297493 | 2019-01-11T11:51:18 | 2019-01-11T11:51:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 449 | java | // isComment
package com.hughes.android.dictionary;
import java.util.Locale;
import java.text.Collator;
public final class isClassOrIsInterface {
public static Collator isMethod() {
return isNameExpr.isMethod();
}
public static Collator isMethod(Locale isParameter) {
Collator isVariable = isNameExpr.isMethod(isNameExpr);
isNameExpr.isMethod(isNameExpr.isFieldAccessExpr);
return isNameExpr;
}
}
| [
"matheus@melsolucoes.net"
] | matheus@melsolucoes.net |
4fdd143340a91b850fe29361f67e3e3810b32b48 | 2bdf9b0b0f4495688f015dd70f569c0256fae911 | /src/main/java/com/yoshopping/controller/LoginController.java | db1dcde804cf7c521b7d3334a2de761573492269 | [] | no_license | ArmonNie/WebYoShopping | 57315dae0ba09ff0ae738c4d84eced38316062a9 | b0ffc70c10b5838aef92c118de547cae346c998c | refs/heads/master | 2022-12-20T00:50:59.891170 | 2020-01-01T14:16:57 | 2020-01-01T14:16:57 | 176,685,078 | 0 | 0 | null | 2022-12-16T11:06:54 | 2019-03-20T08:08:53 | Java | UTF-8 | Java | false | false | 1,877 | java | package com.yoshopping.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.yoshopping.myinterfaces.MyLogger;
/*
* 注解形式所用Controller与实现接口形式的Controller不是同一个包
*/
import org.springframework.stereotype.Controller;
//import org.springframework.web.servlet.mvc.Controller;
/*
* Controller实现方法之一,实现Controller接口
* 关键是实例化ModelAndView对象,并返回
*/
/*public class LoginController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
ModelAndView mav = new ModelAndView();
mav.setViewName("/index.jsp");
return mav;
}
}*/
/*
* Controller实现方法之二,注解方式(前提是配置文件配置了扫描)
*/
@Controller
public class LoginController{
@RequestMapping("/LoginController")
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
ModelAndView mav = new ModelAndView();
/*ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User)applicationContext.getBean("user");
user.setUser_login_name("Tom");*/
List<String> l = new ArrayList<String>();
//parameternum代表前台返回参数的个数
/*int parameternum = Integer.parseInt(arg0.getParameter("ParameterNum"));
for(int i = 0;i < parameternum;i++) {
}*/
mav.addObject("name", arg0.getParameter("username"));
mav.setViewName("/WEB-INF/page/managebase.jsp");
return mav;
}
}
| [
"2548079361@qq.com"
] | 2548079361@qq.com |
6eb15bb62d4258e61847cb9e98556b3a7cb3de93 | 5e9a8e2aa22e6758006f3105c126fa48d1b81e60 | /userVoiceSDK/src/main/java/com/uservoice/uservoicesdk/ui/LoadAllAdapter.java | dfb7181cb3a2afa7f20b1f1fdc5ed48ffac15a23 | [
"Apache-2.0"
] | permissive | adrianritchie/android-discourse | f4966a4ec9f5b8d88d229900d06008da18e895e0 | b80528d5a4614af25e1151a303554f7878b5637c | refs/heads/master | 2021-01-16T20:49:46.318202 | 2015-02-19T09:21:22 | 2015-02-19T09:21:22 | 30,915,482 | 0 | 1 | null | 2015-02-17T12:11:16 | 2015-02-17T12:11:16 | null | UTF-8 | Java | false | false | 831 | java | package com.uservoice.uservoicesdk.ui;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public abstract class LoadAllAdapter<T> extends ModelAdapter<T> {
public LoadAllAdapter(Context context, int layoutId, List<T> objects) {
super(context, layoutId, objects);
loadAll();
}
private void loadAll() {
loading = true;
notifyDataSetChanged();
loadPage(1, new DefaultCallback<List<T>>(context) {
@Override
public void onModel(List<T> model) {
objects.addAll(model);
loading = false;
notifyDataSetChanged();
}
});
}
public void reload() {
if (loading)
return;
objects = new ArrayList<T>();
loadAll();
}
}
| [
"admin@goodev.org"
] | admin@goodev.org |
0d021f1e716b8fc2a5484a9e04861eb99c84dc10 | fe73afe611e9344a6f7d6dd4fead95684b411ca3 | /src/test/java/com/thoughtworks/basic/PersonIntroduceTest.java | 9bb719e001f2ae24f4dfd31ade54a2dcf7cd3c35 | [] | no_license | zxl0526/oo-step-by-step-2020-7-8-10-2-43-653-master | b9abd1d782d31636cabeb5cf30cc6d8aea7b9451 | 1f1ec92f1c738d39b3440f3c6b2b764ffd44ad2c | refs/heads/master | 2022-12-28T20:03:00.283161 | 2020-07-13T10:15:39 | 2020-07-13T10:15:39 | 279,238,209 | 1 | 0 | null | 2020-10-13T23:31:45 | 2020-07-13T08:13:33 | Java | UTF-8 | Java | false | false | 466 | java | package com.thoughtworks.basic;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PersonIntroduceTest {
@Test
public void when_give_Name_IS_TOM_AGE_IS_21_should_introduce() {
//given
String name="Tom";
int age=21;
// when
String introduceResult=PersonIntroduce.introduce(name,age);
//then
assertEquals(introduceResult,"My name is Tom. I am 21 years old.");
}
}
| [
"851450219@qq.com"
] | 851450219@qq.com |
285b29617ad6002154bd22f1ec540227078c5b92 | cf7704d9ef0a34aff366adbbe382597473ab509d | /src/net/sourceforge/plantuml/graphic/HtmlColorGradient.java | d9b44ec0e5f53532a31bda2149416e917bff8d1f | [] | no_license | maheeka/plantuml-esb | 0fa14b60af513c9dedc22627996240eaf3802c5a | 07c7c7d78bae29d9c718a43229996c068386fccd | refs/heads/master | 2021-01-10T07:49:10.043639 | 2016-02-23T17:36:33 | 2016-02-23T17:36:33 | 52,347,881 | 0 | 4 | null | null | null | null | UTF-8 | Java | false | false | 2,515 | java | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML 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 3 of the License, or
* (at your option) any later version.
*
* PlantUML 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 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.]
*
* Original Author: Arnaud Roques
*
*/
package net.sourceforge.plantuml.graphic;
import java.awt.Color;
import net.sourceforge.plantuml.ugraphic.ColorMapper;
public class HtmlColorGradient implements HtmlColor {
private final HtmlColor color1;
private final HtmlColor color2;
private final char policy;
public HtmlColorGradient(HtmlColor color1, HtmlColor color2, char policy) {
if (color1 == null || color2 == null) {
throw new IllegalArgumentException();
}
this.color1 = color1;
this.color2 = color2;
this.policy = policy;
}
public final HtmlColor getColor1() {
return color1;
}
public final HtmlColor getColor2() {
return color2;
}
public final Color getColor(ColorMapper mapper, double coeff) {
if (coeff > 1 || coeff < 0) {
throw new IllegalArgumentException("c=" + coeff);
}
final Color c1 = mapper.getMappedColor(color1);
final Color c2 = mapper.getMappedColor(color2);
final int vred = c2.getRed() - c1.getRed();
final int vgreen = c2.getGreen() - c1.getGreen();
final int vblue = c2.getBlue() - c1.getBlue();
final int red = c1.getRed() + (int) (coeff * vred);
final int green = c1.getGreen() + (int) (coeff * vgreen);
final int blue = c1.getBlue() + (int) (coeff * vblue);
return new Color(red, green, blue);
}
public final char getPolicy() {
return policy;
}
}
| [
"maheeka@wso2.com"
] | maheeka@wso2.com |
6e6073b4cc14d1248ac789903ef8434afd5d5f37 | 0814a80aa1ea8a4cfabdaa4e98a22fe68feaaa0b | /core/source/com/yeep/study/patterns/factory/simpleFactory/CheesePizza.java | ae524b4bd2472c5a472576949b28288bf618f708 | [] | no_license | rogeryee/Study | feef0d12800456046dd2c8d74298355247bf4163 | a8451b40ac9b15c884153e6b1dd93600100dbdc1 | refs/heads/master | 2020-04-01T13:39:34.624509 | 2014-04-15T07:12:16 | 2014-04-15T07:12:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 208 | java | package com.yeep.study.patterns.factory.simpleFactory;
/**
* Cheese Pizza
*/
public class CheesePizza implements Pizza
{
public void cook()
{
System.out.println("Cook for the Cheese Pizza");
}
}
| [
"roger.yee@hotmail.com"
] | roger.yee@hotmail.com |
c3f9af4458e8c0fec1bde69072a1b9017a506077 | a3e9b872a437e2cfc1f1bf953b6fbf7a18f00c0b | /FitnessTracker/src/main/java/com/pluralsight/controller/GoalController.java | e20202bcca64e2b1db4b3c38a13eddb56eceaab6 | [] | no_license | arunmech28/SpringPractice | 08dc4fb1149027458c15ced8929e0fe8ebd93815 | 3e0aa768402d69f6b903f669efd3cde6a80a8334 | refs/heads/master | 2020-03-29T22:08:23.673612 | 2018-09-26T11:48:52 | 2018-09-26T11:48:52 | 150,404,866 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,192 | java | package com.pluralsight.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.pluralsight.model.Goal;
@Controller
@SessionAttributes("goal")
public class GoalController {
@RequestMapping(value="addGoal", method=RequestMethod.GET)
public String addGoal(Model model) {
Goal goal = new Goal();
goal.setMinutes(10);
model.addAttribute("goal", goal);
return "addGoal";
}
@RequestMapping(value="addGoal", method=RequestMethod.POST)
public String updateGoal(@Valid @ModelAttribute("goal") Goal goal, BindingResult result) {
System.out.println("result has errors" + result.hasErrors());
System.out.println("Minutes update "+goal.getMinutes());
if(result.hasErrors()) {
return "addGoal";
}
return "redirect:addMinutes.html";
}
}
| [
"538768@PC380387.cts.com"
] | 538768@PC380387.cts.com |
4904e2b1cd941319f2f568965e1588b54aaeb321 | 9757bbb318fa245dcdb099ce356ddbeff5f2fbaf | /src/test/java/g1301_1400/s1351_count_negative_numbers_in_a_sorted_matrix/SolutionTest.java | c85ef0ff81b71c173100ab4a3e2746d47294db56 | [
"MIT"
] | permissive | javadev/LeetCode-in-Java | 181aebf56caa51a4442f07466e89b869aa217424 | 413de2cb56123d3844a1b142eec7e9a8182c78fb | refs/heads/main | 2023-08-31T01:46:52.740790 | 2023-08-30T08:45:06 | 2023-08-30T08:45:06 | 426,947,282 | 103 | 57 | MIT | 2023-09-14T08:08:08 | 2021-11-11T09:46:12 | Java | UTF-8 | Java | false | false | 716 | java | package g1301_1400.s1351_count_negative_numbers_in_a_sorted_matrix;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void countNegatives() {
assertThat(
new Solution()
.countNegatives(
new int[][] {
{4, 3, 2, -1}, {3, 2, 1, -1}, {1, 1, -1, -2}, {-1, -1, -2, -3}
}),
equalTo(8));
}
@Test
void countNegatives2() {
assertThat(new Solution().countNegatives(new int[][] {{3, 2}, {1, 0}}), equalTo(0));
}
}
| [
"noreply@github.com"
] | noreply@github.com |
b02a5ffbab87f310d7b936914f942764541aaeff | 43f74ea498cb0dae05bf2390b448d16f398a0a2b | /workspace/ncp_cmp/src/main/java/com/plgrim/ncp/biz/claim/data/LgsDlvExtendForGlobalCancel.java | b0e4f950f7ca33aaf580d2ea117356ca88cdcf06 | [] | no_license | young-hee/pc_mlb | 2bdf5813418c14be2d7e2de78f0f294ed8264dde | 708417eada78eed398e068460bda44adea16cbdf | refs/heads/master | 2022-11-22T00:11:05.335853 | 2020-07-22T08:27:03 | 2020-07-22T09:10:07 | 281,615,442 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 672 | java | /**
* @package : com.plgrim.ncp.base.entities..lgs
* @author : jackie(jackie)
* @date : 20150526
* @version : 1.0
* @desc :
*/
package com.plgrim.ncp.biz.claim.data;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.ibatis.type.Alias;
import com.plgrim.ncp.base.entities.datasource1.lgs.LgsDlv;
/**
* 물류 배송
*/
@Data
@EqualsAndHashCode(callSuper=false)
@Alias("lgsDlvExtendForClm")
public class LgsDlvExtendForGlobalCancel extends LgsDlv{
/**
*
*/
private static final long serialVersionUID = -6756139506616552289L;
/**
* 잔여결제환율적용금액
*/
private java.math.BigDecimal remainPayExchgRtCrncyAmt;
}
| [
"aksla79@gmail.com"
] | aksla79@gmail.com |
b1e4f9dc1587076fa19323df7cc5215c693d3890 | d2c0542b922c6fb041536b5fc3adcb29a4f3e7e0 | /app/src/main/java/com/cpxiao/optical/illusions/wallpapers/fragment/FullscreenFragment.java | c8d2fefc87eaca9181d5155606ca0a029bdc7dbe | [
"Apache-2.0"
] | permissive | cpxiao/OpticalIllusions-3DWallpaper | 004452851d2262c4d11e496b685a57625e3e665f | a5ac159f5002828db823153da3390e15641cc8f0 | refs/heads/master | 2021-04-15T12:31:38.505565 | 2018-03-25T12:50:02 | 2018-03-25T12:50:02 | 126,696,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,630 | java | package com.cpxiao.optical.illusions.wallpapers.fragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.cpxiao.R;
import com.cpxiao.gamelib.fragment.BaseZAdsFragment;
import com.cpxiao.zads.core.ZAdPosition;
/**
* @author cpxiao on 2017/09/01.
*/
public class FullscreenFragment extends BaseZAdsFragment {
public static final String RESOURCE_ID = "RESOURCE_ID";
private ImageView mImageView;
public static FullscreenFragment newInstance(Bundle bundle) {
FullscreenFragment fragment = new FullscreenFragment();
if (bundle != null) {
fragment.setArguments(bundle);
}
return fragment;
}
@Override
protected void initView(View view, Bundle savedInstanceState) {
loadZAds(ZAdPosition.POSITION_GAME);
mImageView = (ImageView) view.findViewById(R.id.gif_image_view);
Bundle bundle = getArguments();
if (bundle != null) {
int resourceId = bundle.getInt(RESOURCE_ID, -1);
if (resourceId != -1) {
Glide.with(getHoldingActivity())
.load(resourceId)
.into(mImageView);
} else {
onDestroy();
}
}
}
@Override
protected int getLayoutId() {
return R.layout.fragment_fullscreen;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
mImageView.clearAnimation();
mImageView.destroyDrawingCache();
}
}
}
| [
"xchp2008@126.com"
] | xchp2008@126.com |
437cd0c5e28af418e583086198013afd6bfdbc81 | ac092e68a74827f8444a02e863060dd6a293453c | /music-server/src/main/java/com/hjf/music/dao/AdminDao.java | 717227640b70e9207bb3a99db76a3756062e89c1 | [] | no_license | BloothOfYouth/MusicManagementPlatform | 37667a95dc54f8480e426f59ea2f7ee2618044a1 | 02dbe99e123ae7f53069df7200a70b965f222133 | refs/heads/main | 2023-02-01T11:56:00.375830 | 2020-12-16T16:15:02 | 2020-12-16T16:15:02 | 321,742,799 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 289 | java | package com.hjf.music.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hjf.music.entity.Admin;
import org.springframework.stereotype.Repository;
/**
* @author hjf
* @create 2020-10-26 23:04
*/
@Repository
public interface AdminDao extends BaseMapper<Admin> {
}
| [
"1042488120@qq.com"
] | 1042488120@qq.com |
7340e05fdfcf9916cd8784b720a0be7cf2539430 | 9d5714f657d15b1e4e9163581800c6151fabb6a0 | /app/models/Account.java | 2a0db78306b4e368b997d4f09ddb0c7a5e6c5b67 | [] | no_license | RUAN0007/Crisis_Management_System | c282057cd8b899a6062ae2de46c52f61775771ba | 4967cfd4eb6256bfe82fcff15c146082b4596a6f | refs/heads/master | 2020-05-04T14:55:44.349252 | 2014-11-01T15:04:08 | 2014-11-01T15:04:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,030 | java | package models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
@Entity
public class Account extends Model {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Required
private String type;
@Required
private String accountName;
@Required
private String password;
public static Finder<Long, Account> find = new Finder<Long, Account>(
Long.class, Account.class
);
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String account) {
this.accountName = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| [
"ruanpingcheng@gmail.com"
] | ruanpingcheng@gmail.com |
146bc11e52c7bcdbfbd3cd597c10f6907423ec1c | 62c3b0b028b84c5019f0e908c0b221110ea3506d | /ExampleSomethings/src/com/sunday/StudentManagement/openSystem.java | ff7226d7f8f48a20a6db9874be981d2bf02182b1 | [] | no_license | NekoSunday/JavaSELasson | af3b544b070d368f6f3bf2e7e02c1e6a4612c6dc | 69828d7105689fb5fac76f056d410b3cffc8ecd0 | refs/heads/master | 2023-03-03T06:18:54.414314 | 2021-02-19T08:50:59 | 2021-02-19T08:50:59 | 329,244,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,381 | java | package com.sunday.StudentManagement;
import java.util.Scanner;
public class openSystem {
public static void main(String[] args) {
System.out.println("------------------欢迎使用学生管理系统-------------------");
printMenu();
selectMenu();
}
private static void selectMenu() {
String enterOption = new Scanner(System.in).next();
if (!(enterOption.equals("1") || enterOption.equals("2") || enterOption.equals("3"))) {
System.out.println("输入错误请重新输入选项:");
selectMenu();
}
int optionIndex = Integer.parseInt(enterOption);
switch (optionIndex) {
case 1:
enterStudents();
selectMenu();
break;
case 2:
printStudents();
selectMenu();
break;
case 3:
closeSystem();
break;
}
}
private static void closeSystem() {
System.out.println("学生系统已经退出,再见。");
}
private static void printStudents() {
Management.loadFile();
}
public static void enterStudents() {
}
private static void printMenu() {
System.out.println("1、录入学生信息 2、输出学生信息 3、退出系统");
}
}
| [
"819085406@qq.com"
] | 819085406@qq.com |
8d358d556144c4e56d56b66df9db011d5c2956c5 | 7f67b7c04fd023c52231b13ee493a7895fcc60a2 | /app/src/test/java/com/example/dx/xposedhook/ExampleUnitTest.java | f786a63152531c2539f972292f222ebb72285954 | [] | no_license | darlk/XposedHook | 1ee64581c93f23e94ca5c4c2a50ef9c36d424db3 | 2e5e1ee7180cc286db73a1ca321681e043ee87f7 | refs/heads/master | 2022-02-15T20:47:15.183583 | 2019-07-22T15:45:34 | 2019-07-22T15:45:34 | 197,931,061 | 0 | 0 | null | 2019-07-20T13:02:07 | 2019-07-20T13:02:07 | null | UTF-8 | Java | false | false | 403 | java | package com.example.dx.xposedhook;
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() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"1796581057@qq.com"
] | 1796581057@qq.com |
6aaea5f3c0b6c329c294461bd45a5b332aa726b9 | dbcfbf8fd121e1d7372ab7f1c6a46bf5992424db | /Ovinger/Oving 4/Rom.java | ca9f318b6e369b8e98c27215f6c53e5b387c8452 | [] | no_license | maxschau/TDAT1005-Databaser-med-Videreg-ende-Programmering | 05cf3e6a6e1cbcdea8de477d62bcb69f581a8ac8 | 4b679c61b763d1b83a178f2889f95b4d27868950 | refs/heads/master | 2022-10-15T15:15:52.498499 | 2019-09-12T11:31:18 | 2019-09-12T11:31:18 | 208,035,714 | 0 | 0 | null | 2022-10-04T23:53:07 | 2019-09-12T11:30:40 | Java | UTF-8 | Java | false | false | 1,909 | java | import java.util.*;
class Rom {
private int nr;
private int storrelse;
private ArrayList<Reservasjon> reservasjoner;
public Rom(int nr, int storrelse) {
this.nr = nr;
this.storrelse = storrelse;
reservasjoner = new ArrayList<Reservasjon>();
}
public int getNr(){
return nr;
}
public int getStorrelse() {
return storrelse;
}
public boolean equals(Object obj) {
if (!(obj instanceof Rom)) {
return false;
}
if (this == obj) {
return true;
}
Rom instance = (Rom) obj;
if (instance.getNr() == nr) {
return true;
}
return false;
}
public boolean sjekkLedighet(Reservasjon r1) {
for (int i = 0; i< reservasjoner.size(); i++) {
if (reservasjoner.get(i).overlapp(r1.getFraTid(), r1.getTilTid())) { //Returnerer false dersom det ikke er ledig
return false;
}
}
return true;
}
public void addReservasjon(Reservasjon r1) { //Legger til en reservasjon i tabellen
reservasjoner.add(r1);
}
public String toString() {
String res = "Rom " + getNr() + "\n";
for (int i = 0; i < reservasjoner.size();i++) {
res += reservasjoner.get(i).toString() + "\n";
}
return res;
}
public static void main(String[] args) {
Rom rom1 = new Rom(1,4);
Kunde k1 = new Kunde("Max Schau", "91782159");
Kunde k2 = new Kunde("Gunnar Gunnersen", "480127221");
Tidspunkt t1 = new Tidspunkt(200301201200L);
Tidspunkt t2 = new Tidspunkt(200301281200L);
Tidspunkt t3 = new Tidspunkt(200302011200L);
Tidspunkt t4 = new Tidspunkt(200302051200L);
Reservasjon r1 = new Reservasjon(t1,t2,k1);
Reservasjon r2 = new Reservasjon(t3,t4,k1);
System.out.println(rom1.sjekkLedighet(r1));
rom1.addReservasjon(r1);
System.out.println(rom1.sjekkLedighet(r1));
System.out.println(rom1.sjekkLedighet(r2));
rom1.addReservasjon(r2);
System.out.println(rom1.sjekkLedighet(r2));
}
}
| [
"max.torre.schau@gmail.com"
] | max.torre.schau@gmail.com |
0e97fa6099988df57e47910866bf5dfbc33ab548 | e8a39c3245d5a9b92492442d7693e8ea92d5e332 | /src/ui/menuBar/SizeMenu.java | 90823cff996036604bb65f1f29077e1d940a979a | [] | no_license | BilgeSakal/SlidingPuzzle | e684e268ab04cedfdeb28631e8c23036082c9520 | 1ab4b022cf32972e2abe981b4374995ec5c9e1e3 | refs/heads/master | 2020-09-02T06:31:38.987277 | 2019-11-07T21:51:48 | 2019-11-07T21:51:48 | 169,264,898 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,093 | java | package ui.menuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import ui.GameWindow;
import ui.input.RowColReader;
public class SizeMenu extends JMenu {
private static final long serialVersionUID = 3848000767250714142L;
private GameWindow gameWindow;
public SizeMenu(GameWindow gameWindow) {
this.gameWindow = gameWindow;
setText("Size");
initMenu();
}
private void initMenu() {
for (int i = 3; i <= 5; ++i) {
JMenuItem item = new JMenuItem(i + "x" + i);
int size = i;
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gameWindow.newGame(size, size, gameWindow.getCurrImage());
}
});
add(item);
}
JMenuItem customSize = new JMenuItem("Custom Size");
customSize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RowColReader rowColReader = new RowColReader(gameWindow);
rowColReader.createAndShowUI();
}
});
add(customSize);
}
}
| [
"bilgekagansevindik@gmail.com"
] | bilgekagansevindik@gmail.com |
568a88afab2da0e6b50d3d81d425ca91f113ad97 | c8f2e3ad456d4cb2530090897759949f4bd593d0 | /kd-mall-third-party/src/main/java/cn/my/kdmall/thirdparty/KdmallThirdPartyApplication.java | ce059c7fc2cdbd0409402164f5110fd95b9fe2e0 | [
"Apache-2.0"
] | permissive | lvr1997/kd-mall | 66d63ea1f235e680199f4863799df0d92516e406 | 256c285b2f9ca0070a28096ac5b1a1e26e851a13 | refs/heads/master | 2022-12-05T07:00:55.220719 | 2020-08-27T12:52:45 | 2020-08-27T12:52:45 | 274,113,786 | 0 | 0 | Apache-2.0 | 2020-08-27T12:52:46 | 2020-06-22T11:02:48 | JavaScript | UTF-8 | Java | false | false | 444 | java | package cn.my.kdmall.thirdparty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class KdmallThirdPartyApplication {
public static void main(String[] args) {
SpringApplication.run(KdmallThirdPartyApplication.class, args);
}
}
| [
"377017195@qq.com"
] | 377017195@qq.com |
7e7e0a75e0e1d8471bd8c83633d848fe100976f4 | 2c72ba9a6f3b5be749737ee6180210b6204eb026 | /DatCon/src/DatConRecs/FromViewer/waypoint_debug_160.java | 656ad880a303b796ab6d777c50cd811aa8e37e79 | [] | no_license | sin5678/DatCon | 3be414a0d082e982857dab1b0627d69ab507ca07 | 6cf2ac6f8f22c418e886b05169390b096f6af41c | refs/heads/master | 2021-09-04T02:55:02.677903 | 2018-01-15T00:37:30 | 2018-01-15T00:37:30 | 118,139,118 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,556 | java | package src.DatConRecs.FromViewer;
import src.DatConRecs.*;
import src.Files.ConvertDat;
import src.Files.ConvertDat.lineType;
import src.Files.DatConLog;
import src.Files.Signal;
import src.Files.Units;
public class waypoint_debug_160 extends Record {
protected boolean valid = false;
protected short wp_mission_status = (short)0;
protected short wp_cur_num = (short)0;
protected int wp_tgt_vel = (int)0;
public waypoint_debug_160(ConvertDat convertDat) {
super(convertDat, 160, 4);
}
@Override
public void process(Payload _payload) {
super.process(_payload);
try {
valid = true;
wp_mission_status = _payload.getUnsignedByte(0);
wp_cur_num = _payload.getUnsignedByte(1);
wp_tgt_vel = _payload.getUnsignedShort(2);
} catch (Exception e) {RecordException(e);}}
protected static Signal waypoint_debugIntSig = Signal
.SeriesInt("waypoint_debug", "", null, Units.noUnits);
protected static Signal waypoint_debugFloatSig = Signal
.SeriesFloat("waypoint_debug", "", null, Units.noUnits);
protected static Signal waypoint_debugDoubleSig = Signal
.SeriesDouble("waypoint_debug", "", null, Units.noUnits);
public void printCols(lineType lineT) {
try {
printCsvValue(wp_mission_status, waypoint_debugIntSig, "wp_mission_status",lineT, valid);
printCsvValue(wp_cur_num, waypoint_debugIntSig, "wp_cur_num",lineT, valid);
printCsvValue(wp_tgt_vel, waypoint_debugIntSig, "wp_tgt_vel",lineT, valid);
} catch (Exception e) {
DatConLog.Exception(e);
}
}
}
| [
"rowland@lascanadas.org"
] | rowland@lascanadas.org |
3ea5e9706f562f336ac496a82c21cb8a34b25c4f | 80ce89f99582725ddffe2fc02eca6beee98af7b2 | /src/test/java/com/caxerx/memoryvisualizer4j/test/JOLTestModule.java | 700da40f46b05eedafceebd9fe8f8e7e0a2e4654 | [] | no_license | caxerx/MemoryVisualizer4J | 7c8a90082a84d33f48c8738db58ca66e902e4e51 | 9ce4726b6e631c7df8d9bb23d07c6de8af97776d | refs/heads/master | 2023-04-09T22:38:26.113334 | 2021-04-12T08:13:20 | 2021-04-12T08:13:20 | 343,232,803 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 740 | java | package com.caxerx.memoryvisualizer4j.test;
import com.caxerx.memoryvisualizer4j.api.LayoutGenerator;
import com.caxerx.memoryvisualizer4j.api.ObjectMapGenerator;
import com.caxerx.memoryvisualizer4j.implementation.jol.JOLLayoutGenerator;
import com.caxerx.memoryvisualizer4j.implementation.jol.JOLObjectMapGenerator;
import com.google.inject.AbstractModule;
import org.openjdk.jol.vm.VM;
import org.openjdk.jol.vm.VirtualMachine;
public class JOLTestModule extends AbstractModule {
@Override
protected void configure() {
bind(LayoutGenerator.class).to(JOLLayoutGenerator.class);
bind(ObjectMapGenerator.class).to(JOLObjectMapGenerator.class);
bind(VirtualMachine.class).toInstance(VM.current());
}
}
| [
"webmaster@caxerx.com"
] | webmaster@caxerx.com |
58355e872fb08deb6b63830ffe5ba8a6ae1e4a20 | a1a5e030a13a3d4539938086cf78b1979b0b7805 | /src/main/java/com/porpoise/common/metadata/PathElement.java | 1587e7c6b0797832002057865c63e97415a9a8b2 | [
"Apache-2.0"
] | permissive | gspandy/common | b1b0fd9002f7181bc6d85113b93e9b922b6dfc96 | c8812c4be0d0ae49409c4c491107ffa4dc1757d5 | refs/heads/master | 2023-08-18T00:59:17.039361 | 2011-07-29T22:11:30 | 2011-07-29T22:11:30 | 4,232,109 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,181 | java | package com.porpoise.common.metadata;
import com.google.common.base.Preconditions;
/**
* @param <T>
* The source object type - the delta type
* @param <P>
* The type returned by this element's metadata's accessor
*/
public class PathElement<T, P> {
private final Delta<T> delta;
private final PathElement<?, T> parent;
/**
* @param parent
* @param prop
* @param leftValue
* @param rightValue
*
*/
PathElement(final PathElement<?, T> parent, final Delta<T> owner) {
this.parent = parent;
this.delta = Preconditions.checkNotNull(owner);
}
/**
* @return the propertyName
*/
@SuppressWarnings("unchecked")
public Metadata<T, P> getProperty() {
return (Metadata<T, P>) this.delta.getProperty();
}
/**
* @return the left
*/
public T getLeft() {
return this.delta.getLeft();
}
private String getLeftString() {
return this.delta.getLeftString();
}
private String getRightString() {
return this.delta.getRightString();
}
/**
* @return the right
*/
public T getRight() {
return this.delta.getRight();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getLeafValueString();
}
/**
* @return the path string for this element
*/
public String getPathString() {
if (this.parent != null) {
return String.format("%s.%s", this.parent.getPathString(), getPropertyName());
}
return getPropertyName();
}
/**
* @return the property name
*/
public String getPropertyName() {
return this.delta.getPropertyName();
}
/**
* @return the path string for this element
*/
public String getPathValueString() {
String prefix = "";
if (this.parent != null) {
prefix = String.format("%s.", this.parent.getPathValueString());
}
return String.format("%s%s{%s != %s}", prefix, getProperty().propertyName(), getLeft(), getRight());
}
/**
* @return the path string for this element
*/
public String getLeafValueString() {
String prefix = "";
if (this.parent != null) {
prefix = String.format("%s.", this.parent.getPathString());
}
return String.format("%s%s{%s != %s}", prefix, getPropertyName(), getLeftString(), getRightString());
}
/**
* @return the parent
*/
public PathElement<?, ?> getParent() {
return this.parent;
}
/**
* @return the root path element parent
*/
public PathElement<?, ?> getRoot() {
if (this.parent == null) {
return this;
}
return this.parent.getRoot();
}
/**
* @param property
* @return true if this path element contains the given property within its chain
*/
public boolean contains(Metadata<?, ?> property) {
return getProperty() == property || getParent() != null && getParent().contains(property);
}
}
| [
"aaron@porpoiseltd.com"
] | aaron@porpoiseltd.com |
a183b7cb195718fb5062c12735f40e01cfd07d0e | c2deee0904573021f78fc51110095eb0f5e2b228 | /src/spring-boot-mockito/src/main/java/com/learn/springbootmockito/service/AccountService.java | 258ca8c4eeeb53cde783078e5eae7b44995cabb0 | [] | no_license | brightkut/learn-java | 72a31e1ecce89bef6d6fd0cea8e7d30183aaca16 | 8a08bb339d12a3b9e325872d29fcedef5c167f5f | refs/heads/master | 2023-03-30T09:00:00.612218 | 2021-03-26T08:55:46 | 2021-03-26T08:55:46 | 281,639,264 | 0 | 0 | null | 2021-03-26T08:55:02 | 2020-07-22T09:52:08 | HTML | UTF-8 | Java | false | false | 422 | java | package com.learn.springbootmockito.service;
import org.springframework.beans.factory.annotation.Autowired;
public class AccountService {
@Autowired
private PaymentService paymentService;
public String buy(int money) {
return this.paymentService.buy(money) > 10 ? "rich" : "poor";
}
public String sell(int money, String name) {
return this.paymentService.sell(money, name);
}
}
| [
"dsorn2@gmail.com"
] | dsorn2@gmail.com |
40b4b68e918d4ecd081d2b22fe68bee0608ea4bf | 5269a957046f496a9f9c7761e3d558f4ea24ed97 | /src/main/java/des/wangku/operate/standard/utls/UtilsReadURL.java | fe8388cecab0c7a9a0e278f8d95929be5308f8f9 | [] | no_license | sluizin/des-wkope-task | d2a9315a2c2eda9428a17f7ea6a1d687e3a2f925 | fc2f859ef693af1a9901110dd9fae6ba87a7d717 | refs/heads/master | 2021-06-12T09:51:26.568064 | 2021-03-25T09:40:05 | 2021-03-25T09:40:05 | 153,067,168 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 48,679 | java | package des.wangku.operate.standard.utls;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.SilentCssErrorHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
/**
* 对URL进行读取操作
* @author Sunjian
* @version 1.0
* @since jdk1.8
*/
public final class UtilsReadURL {
/**
* 参数 - 会员登陆时需要使用的变量,如是否使用会员登陆、登陆界面的一些信息参数
* @author Sunjian
* @version 1.0
* @since jdk1.8
*/
public static final class LoginParameter {
String formID = "";
String inputNamePassword = "";
String inputNameUsername = "";
boolean isUser = false;
String logcheckUrl = "";
String logUrl = "";
String password = "";
String username = "";
/**
* @param isUser boolean
* @param logUrl String
* @param logcheckUrl String
* @param formID String
* @param inputNameUsername String
* @param username String
* @param inputNamePassword String
* @param password String
*/
public LoginParameter(boolean isUser, String logUrl, String logcheckUrl, String formID, String inputNameUsername, String username, String inputNamePassword, String password) {
this.isUser = isUser;
this.logUrl = logUrl;
this.logcheckUrl = logcheckUrl;
this.formID = formID;
this.inputNameUsername = inputNameUsername;
this.username = username;
this.inputNamePassword = inputNamePassword;
this.password = password;
}
}
static final BrowserVersion BrowserVer = BrowserVersion.BEST_SUPPORTED;
static final BrowserVersion BrowserVer2 = BrowserVersion.INTERNET_EXPLORER;
static Map<String, String> datas2 = new HashMap<>();
static Logger logger = LoggerFactory.getLogger(UtilsReadURL.class);
static final NicelyResynchronizingAjaxController nicelyAjax = new NicelyResynchronizingAjaxController();
static final WebClient webClient = new WebClient(BrowserVer);
static {
datas2.put("from", "en");
datas2.put("to", "zh");
datas2.put("query", "jeep");
datas2.put("simple_means_flag", "3");
datas2.put("sign", "14348.318269");
datas2.put("token", "4edbf8229215f26c6b401aaf693466a3");
}
static {
webClient.getOptions().setJavaScriptEnabled(true); //启用JS解释器,默认为true
webClient.getOptions().setCssEnabled(false); //禁用css支持
webClient.getOptions().setThrowExceptionOnScriptError(false); //js运行错误时,是否抛出异常
webClient.getOptions().setTimeout(10000); //设置连接超时时间 ,这里是10S。如果为0,则无限期等待
webClient.waitForBackgroundJavaScript(8000);
webClient.getOptions().setAppletEnabled(true);
webClient.setAjaxController(nicelyAjax);
webClient.setCssErrorHandler(new SilentCssErrorHandler());
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setRedirectEnabled(true);
}
/**
* 下载文件到当地
* @param urlstr String
* @param savePath String
* @return File
*/
public static final File downfile(String urlstr, String savePath) {
if (urlstr == null || savePath == null) return null;
try {
URL url = new URL(urlstr);
String filename = UtilsReadURL.getFileName(url);
return downfile(url, filename, savePath);
} catch (IOException e) {
return null;
}
}
/**
* 下载文件到当地
* @param urlstr String
* @param fileName String
* @param savePath String
* @return File
*/
public static final File downfile(String urlstr, String fileName, String savePath) {
try {
URL url = new URL(urlstr);
return downfile(url, fileName, savePath);
} catch (IOException e) {
return null;
}
}
/**
* 下载文件到当地
* @param urlstr String
* @param fileName String
* @param savePath String
* @return File
*/
public static final synchronized File downfile(URL url, String fileName, String savePath) {
try {
URLConnection con = url.openConnection();
if (fileName == null || fileName.length() == 0) fileName = getFileName(con);
if (fileName == null) return null;
HttpURLConnection conn = (HttpURLConnection) con;
conn.setConnectTimeout(50 * 1000);
conn.setReadTimeout(30*1000);
conn = UtilsConstsRequestHeader.getRndRequestProperty(conn);//得到输入流
InputStream inputStream = conn.getInputStream();//获取自己数组
byte[] getData = UtilsFile.readInputStream(inputStream);//文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) saveDir.mkdir();
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) fos.close();
if (inputStream != null) inputStream.close();
return file;
} catch (IOException e) {
return null;
}
}
/**
* 通过URLConnection得到文件名
* @param url URL
* @return String
*/
public static String getFileName(URL url) {
if (url == null) return null;
String filename = null;
try {
filename = getFileName(url.openConnection());
if (filename != null && filename.length() > 0) return filename;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过URLConnection得到文件名
* @param conn URLConnection
* @return String
*/
public static String getFileName(URLConnection conn) {
if (conn == null) return null;
Map<String, List<String>> hf = conn.getHeaderFields();
if (hf == null) return null;
Set<String> key = hf.keySet();
if (key == null) return null;
try {
for (String skey : key) {
List<String> values = hf.get(skey);
for (String value : values) {
String result = new String(value.getBytes("ISO-8859-1"), "GBK");
int location = result.indexOf("filename");
if (location >= 0) {
result = result.substring(location + "filename".length());
return result.substring(result.indexOf("=") + 1);
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
URL url = conn.getURL();
String urlString = url.toString();
return urlString.substring(urlString.lastIndexOf("/") + 1);
}
public static void getJString(String keyword) {
try {
String href = "https://fanyi.baidu.com/v2transapi";
Connection con = Jsoup.connect(href);
Map<String, String> header_c = new HashMap<>();
//header_c.put("Accept", "*/*");
//header_c.put("Accept-Encoding", "gzip, deflate");
//header_c.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
//header_c.put("Content-Type", "text/*,application/x-www-form-urlencoded; charset=UTF-8");
//header_c.put("Content-Length", "117");
//header_c.put("Origin", "https://fanyi.baidu.com");
//header_c.put("Host", "fanyi.baidu.com");
//header_c.put("Origin", "https://fanyi.baidu.com");
//header_c.put("Referer", "https://fanyi.baidu.com/");
//header_c.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3610.2 Safari/537.36");
//header_c.put("X-Requested-With", "XMLHttpRequest");
//header_c.put("Upgrade-Insecure-Requests", "1");
header_c.put("Cookie",
"BAIDUID=6DC294E63D1D79443EE861C806885497:FG=1; PSTM=1542011390; BIDUPSID=EF309A51D38CDB56B8B7B8F0A9BF85E2; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BDUSS=kdmc2gtVENnZDJkc3Btdko2ZkNveFRsV3Q4MXljMTBnZWttR2xwWkU4YmRXREZjQVFBQUFBJCQAAAAAAAAAAAEAAABtjdJKX7H5t-LHp8TqvP1fAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN3LCVzdywlcY; H_PS_PSSID=1457_21095_28019_22160; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1543971572,1544057384,1544145622,1544403922; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; from_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; to_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; delPer=0; PSINO=1; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; ZD_ENTRY=empty; locale=zh; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1544428883");
con.headers(header_c);
Response login = con.ignoreContentType(true).followRedirects(true).data(datas2).method(Method.GET).execute();
System.out.println("login:" + login.body());
//Document login = con.ignoreContentType(true).followRedirects(true).data(datas2).post();
//System.out.println("login:" + login.body());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到url的更新时间,直接查head,如果错误则返回null
* @param url URL
* @return Date
*/
public static final Date getLastModify(URL url) {
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(30000);
http.setReadTimeout(30000);
http.setRequestMethod("HEAD");
Date lastModify = new Date(http.getLastModified());
return lastModify;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 会员模拟登陆,并得到cookies
* @param para LoginParameter
* @return Map < String, String >
*/
public static Map<String, String> getLoginCookies(LoginParameter para) {
Map<String, String> map = new HashMap<>();
if (para == null || (!para.isUser)) return map;
try {
/*
* 第一次请求
* grab login form page first
* 获取登陆提交的表单信息,及修改其提交data数据(login,password)
*/
Connection con = Jsoup.connect(para.logUrl); // 获取connection
con.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);// 配置模拟浏览器
Response rs = con.execute(); // 获取响应
Document d1 = Jsoup.parse(rs.body()); // 转换为Dom树
/*
* 获取cooking和表单属性
* lets make data map containing all the parameters and its values found in the form
*/
Map<String, String> datas = new HashMap<>();
List<Element> eleLists = d1.getElementById(para.formID).select("input");
for (Element e : eleLists) {
if (e.attr("name").equals(para.inputNameUsername)) e.attr("value", para.username);
if (e.attr("name").equals(para.inputNamePassword)) e.attr("value", para.password);
if (e.attr("name").length() > 0) datas.put(e.attr("name"), e.attr("value"));
}
/*
* 第二次请求,以post方式提交表单数据以及cookie信息
*/
Connection con2 = Jsoup.connect(para.logcheckUrl);
con2.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);
con2.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
// 设置cookie和post上面的map数据
Response login = con2.ignoreContentType(true).followRedirects(true).method(Method.POST).data(datas).cookies(rs.cookies()).execute();
/*
* 打印,登陆成功后的信息
* parse the document from response
* System.out.println(login.body());
* 登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可
*/
map = login.cookies();
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 得到URL真实的url,跟跳转有关的新地址
* @param url URL
* @return URL
*/
public static final URL getReadURL(URL url) {
if (url == null) return null;
try {
String protocol = url.getProtocol().toLowerCase();
if (!"http".equals(protocol)) return url;
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setInstanceFollowRedirects(false);
urlcon.setConnectTimeout(3000);
urlcon.setReadTimeout(3000);
String relocation = urlcon.getHeaderField("Location");
if (relocation == null) return url;
if (relocation.indexOf("http://") > -1 || relocation.indexOf("https://") > -1) return new URL(relocation);
return url;
} catch (IOException e) {
e.printStackTrace();
return url;
}
}
/**
* 调用url,并不进行js运行,得到html
* @param url String
* @return String
*/
public static final String getReadUrlDisJs(String url) {
/** HtmlUnit请求web页面 */
WebClient wc = new WebClient(BrowserVer);
wc.getOptions().setJavaScriptEnabled(false); //启用JS解释器,默认为true
wc.getOptions().setCssEnabled(false); //禁用css支持
wc.getOptions().setThrowExceptionOnScriptError(false); //js运行错误时,是否抛出异常
wc.getOptions().setTimeout(10000); //设置连接超时时间 ,这里是10S。如果为0,则无限期等待
wc.waitForBackgroundJavaScript(10000);
wc.getOptions().setRedirectEnabled(true);
try {
HtmlPage page = wc.getPage(url);
String pageXml = page.asXml(); //以xml的形式获取响应文本
wc.close();
return pageXml;
} catch (Exception e) {
if (wc != null) {
wc.close();
wc = null;
}
e.printStackTrace();
}
return "";
}
/**
* 调用url,并不进行js运行,得到Document
* @param url String
* @return Document
*/
public static final Document getReadUrlDisJsDoc(String url) {
String pageXml2 = UtilsReadURL.getReadUrlDisJs(url);
String baseuri = UtilsReadURL.getUrlDomain(url);
return Jsoup.parse(pageXml2, baseuri);
}
/**
* 从网址中得到classname的text字符串 为null时返回""
* @param url String
* @param classname String
* @param index int
* @return String
*/
public static final String getReadUrlDisJsTextByClass(String url, String classname, int index) {
//logger.debug("url:" + url);
Document doc = getReadUrlDisJsDoc(url);
if (doc == null) return "";
//System.out.println("doc:"+doc.html());
Elements ess = doc.getElementsByClass(classname);
if (ess == null || index >= ess.size()) return "";
Element e = ess.get(index);
if (e == null) return "";
return e.text();
}
/**
* 调用url,并进行js运行,得到html
* @param url String
* @return String
*/
public static final String getReadUrlJs(String url) {
return getReadUrlJs(url, true, false, 20000, 10000);
}
/**
* 调用url,并进行js运行,得到html
* @param url String
* @param jsEnable boolean
* @param cssEnable boolean
* @param timeout int
* @param jsTime long
* @return String
*/
public static final String getReadUrlJs(String url, boolean jsEnable, boolean cssEnable, int timeout, long jsTime) {
WebClient wc = new WebClient(BrowserVer);/* HtmlUnit请求web页面 */
wc.getOptions().setJavaScriptEnabled(jsEnable); //启用JS解释器,默认为true
wc.getOptions().setCssEnabled(cssEnable); //禁用css支持
wc.getOptions().setThrowExceptionOnScriptError(false); //js运行错误时,是否抛出异常
wc.getOptions().setTimeout(timeout); //设置连接超时时间 ,这里是10S。如果为0,则无限期等待
wc.waitForBackgroundJavaScript(jsTime);
wc.getOptions().setRedirectEnabled(true);
try {
HtmlPage page = wc.getPage(url);
String pageXml = page.asXml(); //以xml的形式获取响应文本
wc.close();
return pageXml;
} catch (Exception e) {
if (wc != null) wc.close();
e.printStackTrace();
}
return "";
}
/**
* 调用url,并进行js运行,得到html 后期需要运行js并且验证时再修改此方法
* @param urlString String
* @param cookies Set < Cookie >
* @param code String
* @param refer String
* @return String
*/
@Deprecated
public static final String getReadUrlJs(String urlString, Set<Cookie> cookies, String code, String refer) {
try {
WebRequest request = new WebRequest(new URL(urlString));
request.setCharset(Charset.forName(code));
//request.setProxyHost("120.120.120.x");
//request.setProxyPort(80);
request.setAdditionalHeader("Referer", refer);//设置请求报文头里的refer字段
////设置请求报文头里的User-Agent字段
request.setAdditionalHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
/** HtmlUnit请求web页面 */
WebClient wc = new WebClient(BrowserVer);
wc.getOptions().setJavaScriptEnabled(true); //启用JS解释器,默认为true
wc.getOptions().setCssEnabled(false); //禁用css支持
wc.getOptions().setThrowExceptionOnScriptError(false); //js运行错误时,是否抛出异常
wc.getOptions().setTimeout(20000); //设置连接超时时间 ,这里是10S。如果为0,则无限期等待
wc.getCookieManager().setCookiesEnabled(true);
wc.waitForBackgroundJavaScript(10000);
wc.getOptions().setRedirectEnabled(true);
Iterator<Cookie> iCookies = cookies.iterator();
while (iCookies.hasNext())
wc.getCookieManager().addCookie(iCookies.next());
try {
HtmlPage page = wc.getPage(request);
String pageXml = page.asXml(); //以xml的形式获取响应文本
wc.close();
return pageXml;
} catch (Exception e) {
if (wc != null) wc.close();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 调用url,并进行js运行,得到html
* @param url String
* @return String
*/
public static final String getReadUrlJsDefault(String url) {
try {
HtmlPage page = webClient.getPage(url);
String pageXml = page.asXml(); //以xml的形式获取响应文本
//wc.close();
return pageXml;
} catch (Exception e) {
//if (wc != null) wc.close();
e.printStackTrace();
}
return "";
}
/**
* 调用url,并进行js运行,得到Document
* @param url String
* @return Document
*/
public static final Document getReadUrlJsDocument(String url) {
String pageXml2 = UtilsReadURL.getReadUrlJs(url, true, true, 20000, 20000);
String baseuri = UtilsReadURL.getUrlDomain(url);
return Jsoup.parse(pageXml2, baseuri);
}
/**
* 通过url得到classname的数组
* @param url String
* @param classname String
* @return Elements
*/
public static final Elements getReadUrlJsTextByClassname(String url, String classname) {
Document doc = getReadUrlJsDocument(url);
if (doc == null) return null;
return doc.getElementsByClass(classname);
}
/**
* 从网址中得到classname的text字符串 为null时返回""
* @param url String
* @param classname String
* @param index int
* @return String
*/
public static final String getReadUrlJsTextByClassname(String url, String classname, int index) {
//logger.debug("url:" + url);
Document doc = getReadUrlJsDocument(url);
if (doc == null) return "";
//System.out.println("doc:"+doc.html());
Elements ess = doc.getElementsByClass(classname);
if (ess == null || index >= ess.size()) return "";
Element e = ess.get(index);
if (e == null) return "";
return e.text();
}
/**
* 读取url,以HTTP/1.1格式进行读取,截止到</html>
* @param host String
* @param url String
* @param port int
* @param timeout int
* @param code String
* @return String
*/
public static final String getRealContent(String host, String url, int port, int timeout, String code) {
StringBuilder sb = new StringBuilder();
try (Socket socket = new Socket(host, port);) {
socket.setSoTimeout(timeout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET /" + url + " HTTP/1.1\r\n");
bw.write("Host:" + host + "\r\n");
bw.write("\r\n");
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), code));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
if (line.contains("</html>")) break;
}
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 默认:80端口 30000反应时间
* @param host
* @param url
* @param code
* @return
*/
public static final String getRealContent(String host, String url, String code) {
return getRealContent(host, url, 80, 30000, code);
}
/**
* 80端口 socket
* @param domain String 域名(除去协议)
* @param url String 以/开始的右侧url
* @param code String
* @return Document
*/
public static final Document getRealContentDocument(String domain, String url, String code) {
String content = UtilsReadURL.getRealContent(domain, url, code);
Document doc = Jsoup.parse(content,domain);
return doc;
}
/**
* 得到实际地址
* @param url String
* @return String
*/
public static String getRealLocation(String url) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
HttpGet get = new HttpGet(url);
get.addHeader("Accept", "text/html");
get.addHeader("Accept-Charset", "utf-8");
get.addHeader("Accept-Encoding", "gzip");
get.addHeader("Accept-Language", "en-US,en");
get.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
try {
@SuppressWarnings("unused")
HttpResponse response = httpclient.execute(get, context);
List<URI> redirectLocations = context.getRedirectLocations();
if (redirectLocations == null || redirectLocations.size() == 0) return "";
for (URI ii : redirectLocations) {
return ii.toURL().toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 得到实际地址<br>
* 域名中含有关键字,并排队数组中的含有的关键,如过滤数组中含有关键,则返回
* @param urlString String
* @param key String
* @param filterArr String[]
* @return String
*/
public static final String getRealMultiLocation(final String urlString, String key, String... filterArr) {
if (urlString.indexOf(key) > -1 && (!UtilsArrays.isfilterArr(urlString, filterArr))) return urlString;
String baiduUlr = UtilsReadURL.getRealLocation(urlString);
if (baiduUlr != null && baiduUlr.indexOf(key) > -1 && (!UtilsArrays.isfilterArr(baiduUlr, filterArr))) return baiduUlr;
try {
URL url = new URL(urlString);
URL newurl = UtilsReadURL.getReadURL(url);
if (newurl == null) return "";
String urlStr = newurl.toString();
if (urlStr.indexOf(key) > -1 && (!UtilsArrays.isfilterArr(urlStr, filterArr))) return urlStr;
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
/**
* @param url URL
* @param code String
* @return String
*/
@Deprecated
public static String getSocketContent(URL url, String code) {
if (url == null) return "";
StringBuilder sb = new StringBuilder();
int port = url.getPort();
if (port == -1) port = 80;
String host = url.getHost();
if (host == null) return "";
try (Socket socket = new Socket(host, port);) {
socket.setSoTimeout(30000);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET /" + url.getPath() + " HTTP/1.1\r\n");
bw.write("Host:" + host + "\r\n");
bw.write("\r\n");
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), code));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
if (line.contains("</html>")) break;
}
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
/**
* 只支持http与https协议
* @param url URL
* @param code String
* @param timeout int
* @return String
*/
public static String getSocketContent(URL url, String code, int timeout) {
if (url == null) return "";
StringBuilder sb = new StringBuilder();
String http = url.getProtocol().toLowerCase();
/* 只支持http与https协议 */
if (!UtilsArrays.isExist(http, "http", "https")) return "";
int port = url.getPort();
if ("http".equals(http)) {
if (port == -1) port = 80;
} else {
if (port == -1) port = 443;
}
String host = url.getHost();
if (host == null) return "";
Socket socket = null;
try {
if ("http".equals(http)) {
socket = new Socket(InetAddress.getByName(host), port);
} else {
socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(InetAddress.getByName(host), port);
}
//socket.setKeepAlive(true);
socket.setSoTimeout(timeout);
//socket.setSendBufferSize(200);
if (!socket.isConnected()) {
logger.debug("Socket连接失败:" + url.toString());
return null;
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET /" + url.getPath() + " HTTP/1.1\r\n");
bw.write(UtilsConstsRequestHeader.getRndHeadMapString(host));
/*
* bw.write("Host:" + host + "\r\n");
* bw.write("Content-Type: text/html\r\n");
* bw.write("User-Agent:Mozila/4.0(compatible;MSIE5.01;Window NT5.0)\r\n");
* bw.write("Accept:image/gif.image/jpeg.* /* \r\n");
* bw.write("Accept-Language:zh-cn\r\n");
*/
bw.write("\r\n");
bw.flush();
if (UtilsRnd.getRndBoolean()) try (InputStream is = socket.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is);) {
byte[] buffer = new byte[1024];
int count = 0;
while (true) {
count = bis.read(buffer);
if (count == -1) break;
String line = new String(buffer, 0, count, code);
sb.append(line);
}
} catch (Exception e1) {
e1.printStackTrace();
}
else try (InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) {
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e1) {
e1.printStackTrace();
}
if (bw != null) bw.close();
if (socket != null && !socket.isClosed()) socket.close();
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
return sb.toString();
}
/**
* 得到url状态是200还是404
* @param url URL
* @param code String
* @return int
*/
public static int getSocketContentState(URL url, String code) {
int port = url.getPort();
if (port == -1) port = 80;
String host = url.getHost();
try (Socket socket = new Socket(host, port);) {
socket.setSoTimeout(15000);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET /" + url.getPath() + " HTTP/1.1\r\n");
bw.write("Host:" + host + "\r\n");
bw.write("\r\n");
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), code));
br.close();
bw.close();
} catch (Exception e) {
return 404;
}
return 200;
}
/**
* 通过URL得到文件内容
* @param url String
* @param code String
* @param timeout int
* @return String
*/
public static final String getUrlContent(final String url, final String code, int timeout) {
if (url == null || url.length() == 0) return "";
try {
URL urla = new URL(url);
return getUrlContent(urla, code, timeout);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
/**
* 通过html中的form提交相应表单内容,并返回html结果代码
* @param url String
* @param postUrl String
* @param formID String
* @param method Method
* @param inputMap Map < String,String >
* @return String
*/
public static final String getUrlContent(String url, String postUrl, String formID, Method method, Map<String, String> inputMap) {
try {
/*
* 第一次请求
* grab login form page first
* 获取登陆提交的表单信息,及修改其提交data数据(login,password)
*/
Connection con = Jsoup.connect(url); // 获取connection
con.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);// 配置模拟浏览器
Response rs = con.execute(); // 获取响应
Document d1 = Jsoup.parse(rs.body()); // 转换为Dom树
/*
* 获取cooking和表单属性
* lets make data map containing all the parameters and its values found in the form
*/
Map<String, String> datas = new HashMap<>();
List<Element> eleLists = d1.getElementById(formID).select("input");
for (Element e : eleLists) {
String name = e.attr("name");
if (name == null || name.length() == 0) continue;
String value = e.attr("value");
if (inputMap.containsKey(name)) value = inputMap.get(name);
datas.put(name, value);
}
/* 第二次请求,以post方式提交表单数据以及cookie信息 */
Connection con2 = Jsoup.connect(postUrl);
con2.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);
/* 设置cookie和post上面的map数据 */
Response login = con2.ignoreContentType(true).followRedirects(true).method(method).data(datas).cookies(rs.cookies()).execute();
if (login != null) return login.body();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 通过URL得到文件内容
* @param url URL
* @param code String
* @param timeout int
* @return String
*/
public static final String getUrlContent(final URL url, final String code, int timeout) {
if (url == null) return "";
StringBuilder sb = new StringBuilder(20);
try {
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(timeout);
urlcon.setReadTimeout(timeout);
urlcon.connect();
String returnCode = new Integer(urlcon.getResponseCode()).toString();
if (!returnCode.startsWith("2")) return null;
InputStream is = urlcon.getInputStream();
InputStreamReader isr = new InputStreamReader(is, code);
BufferedReader buffer = new BufferedReader(isr);
String l = null;
while ((l = buffer.readLine()) != null) {
if (l.length() == 0) continue;
sb.append(l);
sb.append('\n');
}
buffer.close();
is.close();
} catch (IOException e) {
}
return sb.toString();
}
/**
* 从地址中提取 http://www.sohu.com
* @param url String
* @return String
*/
public static final String getUrlDomain(String url) {
if (url == null || url.trim().length() == 0) return null;
try {
String newUrl = url.trim().replaceAll("\\\\", "/");
return getUrlDomain(new URL(newUrl));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 得到 http://www.99114.com
* @param url URL
* @return String
*/
public static final String getUrlDomain(URL url) {
if (url == null) return null;
return url.getProtocol() + "://" + url.getHost();
}
/**
* 得到基本网址 http://www.99114.com/
* @param e Element e
* @return String
*/
public static final String getUrlDomain(Element e) {
if (e == null) return null;
return e.ownerDocument().baseUri();
}
/**
* 得到字符串中的域名Host
* @param host String
* @return String
*/
public static String getUrlHost(String host) {
if (host.indexOf("://") > 0) {
try {
URL url = new URL(host);
return getUrlHost(url);
} catch (MalformedURLException e) {
return host;
}
} else {
int index = host.indexOf('/');
if (index > 0) return host.substring(0, index);
}
return host;
}
/**
* 得到字符串中的域名Host
* @param url URL
* @return String
*/
public static String getUrlHost(URL url) {
if (url == null) return null;
return url.getHost();// 获取主机名
}
/**
* 得到URL的特殊关键主目录,如http://www.xxx.com/abc/DEF/123/ 得到 www.xxxx.com/abc/
* @param url URL
* @return String
*/
public static final String getURLMasterKey(URL url) {
if (url == null) return "";
String str = url.toString();
str = str.substring(str.indexOf("//") + 2, str.length());
int index = UtilsString.getStringPosition(str, "/", 1);
if (index == -1) return str;
str = str.substring(0, index + 1);
return str;
}
/**
* 返回url的返回状态值
* @param urlStr String
* @param timeout int
* @return int
*/
public static final int getUrlResponseCode(final String urlStr, int timeout) {
try {
URL url = new URL(urlStr);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(timeout);
urlcon.setReadTimeout(timeout);
urlcon.connect();
return urlcon.getResponseCode();
} catch (Exception e) {
return 0;
}
}
/**
* 返回url的返回ContentLength
* @param urlStr String
* @param timeout int
* @return int
*/
public static final int getUrlResponseContentLength(final String urlStr, int timeout) {
try {
URL url = new URL(urlStr);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(timeout);
urlcon.setReadTimeout(timeout);
urlcon.connect();
return urlcon.getContentLength();
} catch (Exception e) {
return 0;
}
}
/**
* 判断链接是否是死链
* @param urlString String
* @return boolean
*/
public static boolean isConnection(String urlString) {
if (urlString.indexOf("http://") != 0 && urlString.indexOf("https://") != 0) return false;
try {
URL url = new URL(urlString);
return isConnection(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断链接是否是死链
* @param url URL
* @return boolean
*/
public static boolean isConnection(URL url) {
return isConnection(url, 10000);
}
/**
* 判断链接是否是死链
* @param url URL
* @param timeout int
* @return boolean
*/
public static boolean isConnection(URL url, int timeout) {
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setConnectTimeout(timeout);
http.setReadTimeout(timeout);
int result = http.getResponseCode();
return result >= 200 && result < 300;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 从url中判断是否含有关键字数组,在html之间<br>
* 只支持http与https协议
* @param href String
* @param code String
* @param timeout int
* @param arrs String[]
* @return boolean
*/
public static boolean isSocketContainKeywords(String href, String code, int timeout, String... arrs) {
if (href == null || href.length() == 0) return false;
try {
URL url = new URL(href);
return isSocketContainKeywords(url, code, timeout, arrs);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return false;
}
/**
* 从url中判断是否含有关键字数组,在html之间<br>
* 只支持http与https协议
* @param url URL
* @param code String
* @param timeout int
* @param arrs String[]
* @return boolean
*/
public static boolean isSocketContainKeywords(URL url, String code, int timeout, String... arrs) {
if (url == null) return false;
String http = url.getProtocol().toLowerCase();
/* 只支持http与https协议 */
if (!UtilsArrays.isExist(http, "http", "https")) return false;
//int port = url.getPort();
String host = url.getHost();
if (host == null) return false;
try {
Socket socket = null;
if ("http".equals(http)) {
socket = new Socket(InetAddress.getByName(host), 80);
} else {
socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(InetAddress.getByName(host), 443);
}
socket.setSoTimeout(timeout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("GET /" + url.getPath() + " HTTP/1.1\r\n");
bw.write("Host:" + host + "\r\n");
bw.write("Content-Type: text/html\r\n");
bw.write("User-Agent:Mozila/4.0(compatible;MSIE5.01;Window NT5.0)\r\n");
bw.write("Accept:image/gif.image/jpeg.*/*\r\n");
bw.write("Accept-Language:zh-cn\r\n");
bw.write("\r\n");
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), code));
String line = null;
while ((line = br.readLine()) != null) {
if (UtilsString.isContain(line, arrs)) return true;
if (line.contains("</html>")) break;
}
br.close();
bw.close();
if (socket != null && !socket.isClosed()) socket.close();
} catch (Exception e1) {
e1.printStackTrace();
}
return false;
}
public static void main(String[] args) {
String href = "http://www.gazww.com/166/zhangjie124040.shtml";
try {
URL url = new URL(href);
System.out.println("result:" + getSocketContent(url, "utf-8", 5000));
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
public static void main2(String[] args) {
String href = "https://fanyi.baidu.com/#en/zh/success";
try {
URL url = new URL(href);
System.out.println("result:" + getSocketContentState(url, "utf-8"));
/*
* 第一次请求
* grab login form page first
* 获取登陆提交的表单信息,及修改其提交data数据(login,password)
*/
Connection con = Jsoup.connect(href); // 获取connection
con.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);// 配置模拟浏览器
//Response rs = con.execute(); // 获取响应
//Document d1 = Jsoup.parse(rs.body()); // 转换为Dom树
/*
* 获取cooking和表单属性
* lets make data map containing all the parameters and its values found in the form
*/
Map<String, String> datas = new HashMap<>();
Response login = con.ignoreContentType(true).followRedirects(true).method(Method.GET).execute();
/*
* 打印,登陆成功后的信息
* parse the document from response
* System.out.println(login.body());
* 登陆成功后的cookie信息,可以保存到本地,以后登陆时,只需一次登陆即可
*/
//System.out.println(login.body());
String content2 = getUrlContent(new URL("https://fanyi.baidu.com/#en/zh/success"), "utf-8", 20000);
System.out.println(content2);
String content = login.body();
//System.out.println(content);
String lstr = "gtk = '";
int p = content.indexOf(lstr);
if (p > -1) {
int p2 = content.indexOf("'", p + lstr.length());
String keyy = content.substring(p + lstr.length(), p2);
System.out.println(keyy);
}
datas = login.cookies();
for (String key : datas.keySet()) {//keySet获取map集合key的集合 然后在遍历key即可
String value = datas.get(key).toString();//
System.out.println("key:" + key + "\tvalue:" + value);
}
HtmlPage page = webClient.getPage(href);
Set<Cookie> set = webClient.getCookies(new URL(href));
for (Cookie e : set) {
System.out.println(e.getDomain() + "--" + e.getName() + "--" + e.getValue());
}
String pageXml = page.asXml(); //以xml的形式获取响应文本
String newurl = "https://fanyi.baidu.com/v2transapi";
Set<Cookie> setold = new HashSet<>();
setold.add(new Cookie(".fanyi.baidu.com", "from", "en"));
setold.add(new Cookie(".fanyi.baidu.com", "to", "zh"));
setold.add(new Cookie(".fanyi.baidu.com", "query", "soon"));
setold.add(new Cookie(".fanyi.baidu.com", "transtype", "enter"));
setold.add(new Cookie(".fanyi.baidu.com", "simple_means_flag", "3"));
setold.add(new Cookie(".fanyi.baidu.com", "sign", "130710.335271"));
setold.add(new Cookie(".fanyi.baidu.com", "token", "4edbf8229215f26c6b401aaf693466a3"));
Map<String, String> datas2 = new HashMap<>();
datas2.put("from", "en");
datas2.put("to", "zh");
datas2.put("query", "success");
datas2.put("transtype", "enter");
datas2.put("simple_means_flag", "3");
datas2.put("sign", "14348.318269");
datas2.put("token", "4edbf8229215f26c6b401aaf693466a3");
//String content=getReadUrlJs(newurl, setold, "utf-8", "https://fanyi.baidu.com/");
Connection con3 = Jsoup.connect(href); // 获取connection
con3.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);// 配置模拟浏览器
Response rs = con3.execute(); // 获取响应
Document d1 = Jsoup.parse(rs.body()); // 转换为Dom树
Connection con2 = Jsoup.connect(newurl);
con2.headers(UtilsConstsRequestHeader.getRndHeadMap());//UtilsConsts.header_a);
con2.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
// 设置cookie和post上面的map数据
//Map<String, String> cookie=rs.cookies();
//for(String k:cookie.keySet()) {
//System.out.println(k+"=="+cookie.get(k));
//}
/*
* con2.data("from","en");
* con2.data("to","zh");
* con2.data("query","success");
* con2.data("transtype","enter");
* con2.data("simple_means_flag","3");
* con2.data("sign","883095.629414");
* con2.data("token","9b8bb341109338ba7e875bd9a9dd88ba");
*/
Response login2 = con2.ignoreContentType(true).followRedirects(false).referrer("https://fanyi.baidu.com/").data(datas2).method(Method.POST).cookies(rs.cookies()).execute();
System.out.println(login2.body());
//String count=ge;tReadUrlJsDefault(href);
//System.out.println(count);
System.out.println("===============================================");
getJString("jeep");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param url String
* @return Document
*/
public static Document manualRedirectHandler(String url) {
try {
Response response = Jsoup.connect(url).followRedirects(false).execute();
int status = response.statusCode();
System.out.println("Redirect to status:" + status);
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) {
String redirectUrl = response.header("location");
System.out.println("Redirect to:" + redirectUrl);
return manualRedirectHandler(redirectUrl);
}
return Jsoup.parse(response.body());
} catch (Exception e) {
System.out.println("Redirect to Exception:" + e.toString());
return null;
}
}
/**
* 通过URL得到文件内容<br>
* 是否过滤#右侧数据
* @param url URL
* @param isReadUtf8 boolean
* @param enterStr String
* @param delnotes boolean
* @return StringBuilder
*/
public static final StringBuilder readFile(final URL url, final boolean isReadUtf8, String enterStr, boolean delnotes) {
StringBuilder sb = new StringBuilder(20);
if (url == null) return sb;
try {
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(30000);
urlcon.setReadTimeout(30000);
urlcon.connect();
String returnCode = new Integer(urlcon.getResponseCode()).toString();
if (!returnCode.startsWith("2")) return null;
InputStream is = urlcon.getInputStream();
InputStreamReader isr = isReadUtf8 ? new InputStreamReader(is, "utf-8") : new InputStreamReader(is);
BufferedReader buffer = new BufferedReader(isr);
String l = null;
while ((l = buffer.readLine()) != null) {
if (delnotes && l.indexOf('#') >= 0) l = l.substring(0, l.indexOf('#'));
if (l.length() == 0) continue;
sb.append(l);
sb.append(enterStr);
}
buffer.close();
is.close();
return sb;
} catch (IOException e) {
return sb;
}
}
/**
* 读取url,并进行解码
* @param urlString String
* @param encoding String
* @return String
*/
public static String readUrl(String urlString, String encoding) {
InputStream is = null;
ByteArrayOutputStream os = null;
try {
URL url = new URL(urlString);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setConnectTimeout(30000);
uc.setReadTimeout(30000);
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
uc = (HttpURLConnection) reload(uc);
is = uc.getInputStream();
os = new ByteArrayOutputStream(is.available());
int len;
byte[] bytes = new byte[1024 * 8];
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
if (!encoding.equals("auto")) return new String(os.toByteArray(), encoding);
Document document = Jsoup.parseBodyFragment(os.toString());//Jsoup.parse(url, 1000 * 60 * 30);
Elements elements = document.select("meta");
Iterator<Element> i = elements.iterator();
while (i.hasNext()) {
Element element = i.next();
if (element.attr("http-equiv").equals("Content-Type")) {
String content = element.attr("content").trim();
int index = content.indexOf("=");
encoding = content.substring(index + 1);
break;
}
}
if (encoding.equals("auto")) encoding = "gb2312";
return new String(os.toByteArray(), encoding);
} catch (Exception e) {
return "";
} finally {
if (os != null) try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null) try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param uc URLConnection
* @return URLConnection
* @throws Exception
*/
private static URLConnection reload(URLConnection uc) throws Exception {
HttpURLConnection huc = (HttpURLConnection) uc;
if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM)// 302, 301
return reload(new URL(huc.getHeaderField("location")).openConnection());
return uc;
}
/**
* @param url URL
* @return InputStream
*/
public static InputStream returnBitMap(URL url) {
InputStream is = null;
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream(); //得到网络返回的输入流
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
| [
"Administrator@UVMIQYVDHVCM2QN"
] | Administrator@UVMIQYVDHVCM2QN |
4ba838c84bc8082414f09fe01ea93eb5766b71f7 | 1203d0c3975644c1779f69d0677d7206473c0df1 | /src/java/controllers/EstadoCivilController.java | 44acb0eefbe4940a2106e0af5c2ff9fde6a39efb | [] | no_license | ArceusHN/PruebaGIT | adfb24bd447baa714454554e65f834e93d4d9aaa | f56d7873585579e5fab7e289bf2dad99e84de1b2 | refs/heads/master | 2023-04-30T19:35:49.585537 | 2021-04-26T08:28:31 | 2021-04-26T08:28:31 | 361,668,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,020 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controllers;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.EstadosCiviles;
import modelDAO.EstadosCivilesDAO;
/**
*
* @author Omar Fer
*/
@WebServlet(name = "EstadoCivilController", urlPatterns = {"/EstadoCivilController"})
public class EstadoCivilController extends HttpServlet {
String listar = "views/listar.jsp";
String crear = "views/create.jsp";
EstadosCivilesDAO dao = new EstadosCivilesDAO();
EstadosCiviles ec = new EstadosCiviles();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet EstadoCivilController</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet EstadoCivilController at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String acceso = "";
String accion = request.getParameter("accion");
if(accion.equalsIgnoreCase("listar")){
acceso = listar;
}
else if(accion.equalsIgnoreCase("add")){
acceso = crear;
}
else if(accion.equalsIgnoreCase("Agregar")){
String desc = request.getParameter("txtEstadoCivil");
ec.setEsCiv_Descripcion(desc);
dao.add(ec);
acceso = listar;
}
//INVESTIGAR QUE HACE ADEMAS DE REEDIRIGIR
RequestDispatcher vista = request.getRequestDispatcher(acceso);
vista.forward(request, response);
// processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"omaredy09@gmail.com"
] | omaredy09@gmail.com |
aced479e747d00859d9df9d1a8a2ad669c97ac2d | 81283a7b635649ece4704335e96a8f8c03b94529 | /src/java/Jsf/TipopartidacontableController.java | 65e2be4e1a44db04b8edfa4574295733db0500b2 | [] | no_license | navarubio/Inpeca2 | 9741950e5ff6fea518bf4d4e27156b84f4ba9c74 | e82dc9184c622cd4ffe01da07f71e26970306b9c | refs/heads/master | 2021-01-15T15:39:08.217563 | 2016-11-01T19:25:27 | 2016-11-01T19:25:27 | 50,691,810 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,627 | java | package Jsf;
import Modelo.Tipopartidacontable;
import Jsf.util.JsfUtil;
import Jsf.util.JsfUtil.PersistAction;
import Jpa.TipopartidacontableFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@Named("tipopartidacontableController")
@SessionScoped
public class TipopartidacontableController implements Serializable {
@EJB
private Jpa.TipopartidacontableFacade ejbFacade;
private List<Tipopartidacontable> items = null;
private Tipopartidacontable selected;
public TipopartidacontableController() {
}
public Tipopartidacontable getSelected() {
return selected;
}
public void setSelected(Tipopartidacontable selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private TipopartidacontableFacade getFacade() {
return ejbFacade;
}
public Tipopartidacontable prepareCreate() {
selected = new Tipopartidacontable();
initializeEmbeddableKey();
return selected;
}
public void create() {
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("TipopartidacontableCreated"));
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("TipopartidacontableUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("TipopartidacontableDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
}
}
public List<Tipopartidacontable> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Tipopartidacontable getTipopartidacontable(java.lang.Integer id) {
return getFacade().find(id);
}
public List<Tipopartidacontable> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Tipopartidacontable> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
@FacesConverter(forClass = Tipopartidacontable.class)
public static class TipopartidacontableControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
TipopartidacontableController controller = (TipopartidacontableController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "tipopartidacontableController");
return controller.getTipopartidacontable(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Tipopartidacontable) {
Tipopartidacontable o = (Tipopartidacontable) object;
return getStringKey(o.getIdtipopartidacontable());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Tipopartidacontable.class.getName()});
return null;
}
}
}
}
| [
"Inpeca@Inpeca-PC"
] | Inpeca@Inpeca-PC |
dcc6e57ecf2937f02daf25224db721773da1e47e | 615acadfd5c21a78542c5ed1ea16647179fee3a2 | /src/test/java/veb/seminarska/SeminarskaApplicationTests.java | eb3a7f88237a652c5f72c2f581c1c09b652c531e | [] | no_license | martinaradeska/seminarska | 0e54a5e1280ecdfda783dfac151fbc8041c3703c | d8bf25cd9294ebb26730ee9c88c69f7be8a6e068 | refs/heads/master | 2023-04-14T22:53:20.524683 | 2021-04-21T09:17:13 | 2021-04-21T09:17:13 | 360,102,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 219 | java | package veb.seminarska;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SeminarskaApplicationTests {
@Test
void contextLoads() {
}
}
| [
"radeskamartina@outlook.com"
] | radeskamartina@outlook.com |
8aac51e29a5cc6c135b5cbaf337eedb1be3e4e4a | fd83776d7d7b825903af20e33b92dc3d800ec233 | /src/main/java/com/KrupoderovMikhail/github/config/ConfigLoader.java | 713e7b2e6f2aed18986a2aa7c059d5e08ed0e094 | [] | no_license | krupoderovms/JDABot | 260aa774d08029df896b049ebb1319b16ae8d1f9 | 221980176e3b3ec60a2ba8bb028e33e86a5cd388 | refs/heads/master | 2022-11-18T06:48:38.068404 | 2019-08-18T12:19:18 | 2019-08-18T12:19:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 290 | java | package com.KrupoderovMikhail.github.config;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
class ConfigLoader {
String load(File file) throws IOException {
return new String(
Files.readAllBytes(file.toPath())
);
}
}
| [
"mishka.crash@gmail.com"
] | mishka.crash@gmail.com |
b5554bc1379b9588d087a6a79d89ffa2afc7eb9c | b71673707e418dcbf869d0e53ef76f7ec7651ce1 | /core/impl/src/main/java/com/blazebit/persistence/impl/dialect/HSQLDbmsDialect.java | 6c944f17478c5ee933c63156cd64807726ce4a3f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Mobe91/blaze-persistence | bf92028028b241eb6a0a5f13dec323566f5ec9f8 | 8a4c867f07d6d31404d35e4db672b481fc8a2d59 | refs/heads/master | 2023-08-17T05:42:02.526696 | 2020-11-28T20:13:04 | 2020-11-28T20:13:04 | 83,560,399 | 0 | 0 | NOASSERTION | 2020-02-05T21:56:44 | 2017-03-01T13:59:01 | Java | UTF-8 | Java | false | false | 2,835 | java | /*
* Copyright 2014 - 2020 Blazebit.
*
* 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.blazebit.persistence.impl.dialect;
import java.util.Map;
import com.blazebit.persistence.spi.DbmsModificationState;
import com.blazebit.persistence.spi.DbmsStatementType;
import com.blazebit.persistence.spi.DeleteJoinStyle;
import com.blazebit.persistence.spi.LateralStyle;
import com.blazebit.persistence.spi.UpdateJoinStyle;
import com.blazebit.persistence.spi.ValuesStrategy;
/**
* @author Christian Beikov
* @since 1.2.0
*/
public class HSQLDbmsDialect extends DefaultDbmsDialect {
public HSQLDbmsDialect() {
}
public HSQLDbmsDialect(Map<Class<?>, String> childSqlTypes) {
super(childSqlTypes);
}
@Override
public boolean supportsReturningColumns() {
return true;
}
@Override
public boolean supportsWindowFunctions() {
return false;
}
@Override
public ValuesStrategy getValuesStrategy() {
// NOTE: this is only supported in HSQL 2.0+
return ValuesStrategy.VALUES;
}
@Override
public boolean isNullSmallest() {
// Actually, HSQLDB always shows NULL first, regardless of the ordering, but we don't care because it supports null precedence handling
return true;
}
@Override
public LateralStyle getLateralStyle() {
return LateralStyle.NONE;
}
@Override
public DeleteJoinStyle getDeleteJoinStyle() {
return DeleteJoinStyle.MERGE;
}
@Override
public UpdateJoinStyle getUpdateJoinStyle() {
return UpdateJoinStyle.MERGE;
}
@Override
public Map<String, String> appendExtendedSql(StringBuilder sqlSb, DbmsStatementType statementType, boolean isSubquery, boolean isEmbedded, StringBuilder withClause, String limit, String offset, String dmlAffectedTable, String[] returningColumns, Map<DbmsModificationState, String> includedModificationStates) {
if (isSubquery && returningColumns != null) {
throw new IllegalArgumentException("Returning columns in a subquery is not possible for this dbms!");
}
return super.appendExtendedSql(sqlSb, statementType, isSubquery, isEmbedded, withClause, limit, offset, dmlAffectedTable, returningColumns, includedModificationStates);
}
}
| [
"christian.beikov@gmail.com"
] | christian.beikov@gmail.com |
3efe1890fbb72213fb93fd227e2b2313333315ab | e8c246d20733fe8567cb9afe3297034fde05c267 | /demo/app/src/main/java/com/byrcegao/tpdemo/SecondActivity.java | 017612be1c7b5b3ad3d1a3f6934c7724be749f7d | [] | no_license | brycegao/TimePlugin | 1f2cd66e42a0ecfd1e7ff279d7809a33970ad229 | e56227ffd8b38ed984d0748c1c1567feedcd2b82 | refs/heads/master | 2020-03-29T02:08:20.612040 | 2018-09-23T11:53:12 | 2018-09-23T11:53:12 | 149,422,082 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package com.byrcegao.tpdemo;
import android.app.Activity;
import android.os.Bundle;
import com.brycegao.tpannotation.DebugLogger;
public class SecondActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
doSomething(1);
}
@DebugLogger
private void doSomething(int i) {
try {
Thread.sleep(100); //仅仅为了测试
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| [
"gaorui006@ke.com"
] | gaorui006@ke.com |
77b3019024117e999220536cc407afbc2852ccf8 | 894927bf0fc36549955be6fb781974c12bb449eb | /unisa-util/unisa-javaproxies/src/java/Srasa01h/Abean/Srasa01sLstAcademicRecordSunOperation.java | 9797844bc08783d3a4774803cb48642a8807fdd2 | [
"LicenseRef-scancode-generic-cla",
"ECL-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | sadupally/Dev | cd32fa3b753e8d20dd80e794618a8e97d1ff1c79 | ead9de3993b7a805199ac254c6fa99d3dda48adf | refs/heads/master | 2020-03-24T08:15:12.732481 | 2018-07-27T12:54:29 | 2018-07-27T12:54:29 | 142,589,852 | 0 | 0 | ECL-2.0 | 2018-07-27T14:49:51 | 2018-07-27T14:49:50 | null | UTF-8 | Java | false | false | 13,642 | java | package Srasa01h.Abean;
import com.ca.gen80.csu.trace.*;
import com.ca.gen80.csu.exception.*;
import com.ca.gen80.jprt.*;
import com.ca.gen80.odc.*;
import com.ca.gen80.odc.msgobj.*;
import com.ca.gen80.odc.coopflow.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.Serializable;
import java.util.Vector;
import java.beans.*;
import java.util.*;
import java.math.*;
public class Srasa01sLstAcademicRecordSunOperation
implements Serializable
{
String className = "Srasa01sLstAcademicRecordSunOperation";
private Srasa01sLstAcademicRecordSun client;
private TranData tranData = new TranData(
"SRASA01H",
"Srasa01h",
"SRASA01H",
"SRASA01S_LST_ACADEMIC_RECORD_SUN",
"Srasa01sLstAcademicRecordSun",
"SRASA01S",
"DEV SRA STUDENT ACADEMIC REC A",
"SRA_J",
new String [] {"","","","","","","",""},
new String [] {"","","","","","","",""},
"sra_j",
"sra_j",
"",
"",
"sra_j",
"com.ca.gen80.odc.ITPIPTranEntry",
new String [] {"", "0","Y"});
private OutMessage out = new OutMessage();
private InMessage in = new InMessage();
private ITranEntry tran;
public Srasa01sLstAcademicRecordSunOperation(Srasa01sLstAcademicRecordSun client)
{
this.client = client;
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, className, "new Srasa01sLstAcademicRecordSunOperation( client )");
}
}
// -------------------------------------------------------------------
// doSrasa01sLstAcademicRecordSunOperation is called to issue a single request to the
// transaction server.
//
public void doSrasa01sLstAcademicRecordSunOperation()
throws ProxyException, PropertyVetoException
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation", "Entering doSrasa01sLstAcademicRecordSunOperation routine");
}
// Setup the tran entry data
tranData.setIImportView(client.importView);
tranData.setIExportView(client.exportView);
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"About to perform cooperative flow");
}
try {
out.clearMessage();
in.clearMessage();
out.setUserid(client.getClientId());
out.setPassword(client.getClientPassword());
out.setCommand(client.getCommandSent());
out.setDialect(client.getDialect());
out.setNextLocation(client.getNextLocation());
out.setExitStateNum(client.getExitStateSent());
tranData.setFileEncoding(client.getFileEncoding());
tran = tranData.getTranEntry(tran, client.getComCfg(), this.getClass().getClassLoader());
CoopFlow.coopFlow(tran, out, in);
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Successfully performed a cooperative flow, checking results");
}
if (in.errorOccurred() == true)
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Apparently an error occurred, dumping it.");
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Returned error number",
new Integer(in.getError().getNumber()).toString());
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Returned error message",
in.getError().toString());
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperation", in.getError().toString());
}
else
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Apparently no error occurred, retrieving returned data.");
}
client.setCommandReturned(in.getCommand());
client.setExitStateReturned(in.getExitStateNum());
client.setExitStateType(in.getExitStateType());
client.setExitStateMsg(in.getExitStateMessage());
}
}
catch (CSUException e) {
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperation",
"Received CSUException:", e);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperation", e.getClass().getName() + ": " + e.toString());
}
}
// -------------------------------------------------------------------
// doSrasa01sLstAcademicRecordSunOperationAsync is called to begin a single request to the
// server asynchronously.
//
public int doSrasa01sLstAcademicRecordSunOperationAsync(boolean noResponse) throws ProxyException
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationAsync", "Entering doSrasa01sLstAcademicRecordSunOperationAsync routine");
}
int result = -1;
// Setup the tran entry data
tranData.setIImportView(client.importView);
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationAsync",
"About to perform asynchronous cooperative flow");
}
try {
out.clearMessage();
out.setUserid(client.getClientId());
out.setPassword(client.getClientPassword());
out.setCommand(client.getCommandSent());
out.setDialect(client.getDialect());
out.setNextLocation(client.getNextLocation());
out.setExitStateNum(client.getExitStateSent());
tranData.setFileEncoding(client.getFileEncoding());
tran = tranData.getTranEntry(tran, client.getComCfg(), this.getClass().getClassLoader());
result = CoopFlow.coopFlowPollResponse(tran, out, "doSrasa01sLstAcademicRecordSunOperationAsync", noResponse);
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationAsync",
"Successfully started an asynchronous cooperative flow, checking results, id=" + result);
}
return result;
}
catch (CSUException e) {
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationAsync",
"Received CSUException:", e);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationAsync", e.getClass().getName() + ": " + e.toString());
}
}
// -------------------------------------------------------------------
// doSrasa01sLstAcademicRecordSunOperationGetResponse is called to retrieve the results
// of a particular asynchronous cooperative flow.
//
public boolean doSrasa01sLstAcademicRecordSunOperationGetResponse(int id, boolean block)
throws ProxyException, PropertyVetoException
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse", "Entering doSrasa01sLstAcademicRecordSunOperationGetResponse routine, id= " + id);
}
// Setup the tran entry data
tranData.setIExportView(client.exportView);
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"About to retrieve asynchronous results for a cooperative flow");
}
try {
in.clearMessage();
tranData.setFileEncoding(client.getFileEncoding());
tran = tranData.getTranEntry(tran, client.getComCfg(), this.getClass().getClassLoader());
int result = CoopFlow.coopFlowGetResponse(tran, in, id, block);
if (result == CoopFlow.DATA_NOT_READY)
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"GetResponse returned PENDING");
}
return false;
}
if (result == CoopFlow.INVALID_ID)
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
" Illegal identifier given for GetResponse: " + id);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationGetResponse", " Illegal asynchronous id given in get response call: " + id);
}
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Successfully performed a GetResponse on a cooperative flow, checking results");
}
if (in.errorOccurred() == true)
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Apparently an error occurred, dumping it.");
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Returned error number",
new Integer(in.getError().getNumber()).toString());
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Returned error message",
in.getError().toString());
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationGetResponse", in.getError().toString());
}
else
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Apparently no error occurred, retrieving returned data.");
}
client.setCommandReturned(in.getCommand());
client.setExitStateReturned(in.getExitStateNum());
client.setExitStateType(in.getExitStateType());
client.setExitStateMsg(in.getExitStateMessage());
return true;
}
}
catch (CSUException e) {
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationGetResponse",
"Received CSUException:", e);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationGetResponse", e.getClass().getName() + ": " + e.toString());
}
}
// -------------------------------------------------------------------
// doSrasa01sLstAcademicRecordSunOperationCheckResponse is called to inquire about the
// results of an asynchronous cooperative flow.
//
public int doSrasa01sLstAcademicRecordSunOperationCheckResponse(int id) throws ProxyException
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationCheckResponse", "Entering doSrasa01sLstAcademicRecordSunOperationCheckResponse routine, id= " + id);
}
try {
return CoopFlow.coopFlowCheckStatus(id);
}
catch (CSUException e) {
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationCheckResponse",
"Received CSUException:", e);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationCheckResponse", e.getClass().getName() + ": " + e.toString());
}
}
// -------------------------------------------------------------------
// doSrasa01sLstAcademicRecordSunOperationIgnoreResponse is called to inquire that the
// indicated asynchronous request is no longer relevant and the
// results can be ignored.
//
public void doSrasa01sLstAcademicRecordSunOperationIgnoreResponse(int id) throws ProxyException
{
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.record(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationIgnoreResponse", "Entering doSrasa01sLstAcademicRecordSunOperationIgnoreResponse routine, id= " + id);
}
try {
CoopFlow.coopFlowIgnoreResponse(id);
}
catch (CSUException e) {
if (Trace.isTracing(Trace.MASK_APPLICATION))
{
Trace.dump(Trace.MASK_APPLICATION, "doSrasa01sLstAcademicRecordSunOperationIgnoreResponse",
"Received CSUException:", e);
}
throw new ProxyException("doSrasa01sLstAcademicRecordSunOperationIgnoreResponse", e.getClass().getName() + ": " + e.toString());
}
}
}
| [
"UdcsWeb@unisa.ac.za"
] | UdcsWeb@unisa.ac.za |
873b79f1ca45764cc34817f88b72524f2de3d22c | ca4e878a3a778bbe58ae8c86535b0535c404e6f9 | /src/day17_whileLoops/whileLoop_practice3.java | da7a67678c9013af202571524adef6b704330863 | [] | no_license | andipepa/Spring2020Batch18_Java | 20cba349756804a143721beed19bce2794cb9723 | e285261523cb45e1aa22450e5ea01c71b544b8fa | refs/heads/master | 2022-07-31T18:13:46.917465 | 2020-05-22T13:47:56 | 2020-05-22T13:47:56 | 259,497,425 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 511 | java | package day17_whileLoops;
public class whileLoop_practice3 {
public static void main(String[] args) {
// for(int i=1; i<101; i++ if we do with for loop
// System.out.println("*");
int i=1;
while(i<101){
System.out.print("* ");
i++;
}
System.out.println();
int num =3;
System.out.println("*****");
while (num>0){
System.out.println("* *");
num--;
}
System.out.println("*****");
}
}
| [
"andipepa87.ap@gmail.com"
] | andipepa87.ap@gmail.com |
2cbf208267dcc12bfa5cb5ba22efbd2ae9cc8db4 | f45e0a383a6c42619f81b3a7db63729af06009cf | /solutions/code/tutorialquestions/question1aeb/NumberAdder.java | f085592a19c82a172afabe1bbb89c24cd83675ba | [
"Apache-2.0"
] | permissive | xiaoninghe/ProgrammingIITutorialQuestions | 992ce490197c4f9be1226540ff73932eaf9f92be | 16c04e5ca1cb315b050a280b8b6863b395280933 | refs/heads/master | 2023-02-11T19:05:11.347141 | 2021-01-04T08:46:09 | 2021-01-04T08:46:09 | 275,615,426 | 0 | 0 | Apache-2.0 | 2020-06-28T15:39:01 | 2020-06-28T15:39:01 | null | UTF-8 | Java | false | false | 135 | java | package tutorialquestions.question1aeb;
public interface NumberAdder<T extends Number> {
T zero();
T add(T first, T second);
}
| [
"noreply@github.com"
] | noreply@github.com |
2a6ddf89b5e240e68eb1638e73649d1c324b80df | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/13/13_db41f811c70882b84c4ab3ad150393c13db070e1/MapView/13_db41f811c70882b84c4ab3ad150393c13db070e1_MapView_t.java | 69effeda7f367247ca5abaa0862b895a54217339 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 69,999 | java | /*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.map;
import java.awt.AWTKeyStroke;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.dnd.Autoscroll;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.HierarchyBoundsAdapter;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import org.freeplane.core.io.xml.TreeXmlReader;
import org.freeplane.core.resources.IFreeplanePropertyListener;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.ui.IUserInputListenerFactory;
import org.freeplane.core.ui.components.UITools;
import org.freeplane.core.util.ColorUtils;
import org.freeplane.core.util.LogUtils;
import org.freeplane.features.attribute.AttributeController;
import org.freeplane.features.attribute.ModelessAttributeController;
import org.freeplane.features.filter.Filter;
import org.freeplane.features.link.ConnectorModel;
import org.freeplane.features.link.ConnectorModel.Shape;
import org.freeplane.features.link.LinkController;
import org.freeplane.features.link.LinkModel;
import org.freeplane.features.link.NodeLinks;
import org.freeplane.features.map.IMapChangeListener;
import org.freeplane.features.map.IMapSelection;
import org.freeplane.features.map.INodeView;
import org.freeplane.features.map.MapChangeEvent;
import org.freeplane.features.map.MapController;
import org.freeplane.features.map.MapModel;
import org.freeplane.features.map.NodeModel;
import org.freeplane.features.map.SummaryNode;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.mode.ModeController;
import org.freeplane.features.nodestyle.NodeStyleController;
import org.freeplane.features.note.NoteController;
import org.freeplane.features.print.FitMap;
import org.freeplane.features.styles.MapStyle;
import org.freeplane.features.styles.MapStyleModel;
import org.freeplane.features.styles.MapViewLayout;
import org.freeplane.features.text.TextController;
import org.freeplane.features.ui.ViewController;
import org.freeplane.features.url.UrlManager;
import org.freeplane.view.swing.features.filepreview.IViewerFactory;
import org.freeplane.view.swing.features.filepreview.ScalableComponent;
import org.freeplane.view.swing.features.filepreview.ViewerController;
import org.freeplane.view.swing.map.link.ConnectorView;
import org.freeplane.view.swing.map.link.EdgeLinkView;
import org.freeplane.view.swing.map.link.ILinkView;
/**
* This class represents the view of a whole MindMap (in analogy to class
* JTree).
*/
public class MapView extends JPanel implements Printable, Autoscroll, IMapChangeListener, IFreeplanePropertyListener {
private class Resizer extends HierarchyBoundsAdapter {
@Override
public void ancestorResized(HierarchyEvent e) {
if (! isAncorPositionSet()) {
return;
}
if (nodeToBeVisible == null) {
nodeToBeVisible = getSelected();
extraWidth = 0;
}
setViewPositionAfterValidate();
loadBackgroundImageLater();
}
}
private MapViewLayout layoutType;
public MapViewLayout getLayoutType() {
return layoutType;
}
protected void setLayoutType(final MapViewLayout layoutType) {
this.layoutType = layoutType;
}
private boolean showNotes;
boolean showNotes() {
return showNotes;
}
private void setShowNotes() {
final boolean showNotes= NoteController.getController(getModeController()).showNotesInMap(getModel());
if(this.showNotes == showNotes){
return;
}
this.showNotes = showNotes;
getRoot().updateAll();
}
private PaintingMode paintingMode = null;
private class MapSelection implements IMapSelection {
public void centerNode(final NodeModel node) {
final NodeView nodeView = getNodeView(node);
if (nodeView != null) {
MapView.this.centerNode(nodeView, false);
}
}
public NodeModel getSelected() {
final NodeView selected = MapView.this.getSelected();
return selected.getModel();
}
public Set<NodeModel> getSelection() {
return MapView.this.getSelectedNodes();
}
public List<NodeModel> getOrderedSelection() {
return MapView.this.getOrderedSelectedNodes();
}
public List<NodeModel> getSortedSelection(final boolean differentSubtrees) {
return MapView.this.getSelectedNodesSortedByY(differentSubtrees);
}
public boolean isSelected(final NodeModel node) {
final NodeView nodeView = getNodeView(node);
return nodeView != null && MapView.this.isSelected(nodeView);
}
public void keepNodePosition(final NodeModel node, final float horizontalPoint, final float verticalPoint) {
anchorToSelected(node, horizontalPoint, verticalPoint);
}
public void makeTheSelected(final NodeModel node) {
final NodeView nodeView = getNodeView(node);
if (nodeView != null) {
MapView.this.addSelected(nodeView, false);
}
}
public void scrollNodeToVisible(final NodeModel node) {
MapView.this.scrollNodeToVisible(getNodeView(node));
}
public void selectAsTheOnlyOneSelected(final NodeModel node) {
final NodeView nodeView = getNodeView(node);
if (nodeView != null) {
MapView.this.selectAsTheOnlyOneSelected(nodeView);
}
}
public void selectBranch(final NodeModel node, final boolean extend) {
if(! extend)
selectAsTheOnlyOneSelected(node);
MapView.this.addBranchToSelection(getNodeView(node));
}
public void selectContinuous(final NodeModel node) {
MapView.this.selectContinuous(getNodeView(node));
}
public void selectRoot() {
final NodeModel rootNode = getModel().getRootNode();
selectAsTheOnlyOneSelected(rootNode);
centerNode(rootNode);
}
public void setSiblingMaxLevel(final int nodeLevel) {
MapView.this.setSiblingMaxLevel(nodeLevel);
}
public int size() {
return getSelection().size();
}
public void toggleSelected(final NodeModel node) {
MapView.this.toggleSelected(getNodeView(node));
}
public void replaceSelection(NodeModel[] nodes) {
if(nodes.length == 0)
return;
NodeView views[] = new NodeView[nodes.length];
int i = 0;
for(NodeModel node : nodes)
views[i++] = getNodeView(node);
MapView.this.replaceSelection(views);
}
}
private class Selection {
final private Set<NodeView> selectedSet = new LinkedHashSet<NodeView>();
final private List<NodeView> selectedList = new ArrayList<NodeView>();
private NodeView selectedNode = null;
public Selection() {
};
private void select(final NodeView node) {
clear();
selectedSet.add(node);
selectedList.add(node);
selectedNode = node;
addSelectionForHooks(node);
node.repaintSelected();
}
private boolean add(final NodeView node) {
if(selectedNode == null){
select(node);
return true;
}
else{
if(selectedSet.add(node)){
selectedList.add(node);
node.repaintSelected();
return true;
}
return false;
}
}
private void addSelectionForHooks(final NodeView node) {
if(! isSelected())
return;
final ModeController modeController = getModeController();
final MapController mapController = modeController.getMapController();
final NodeModel model = node.getModel();
mapController.onSelect(model);
}
private void clear() {
if (selectedNode != null) {
removeSelectionForHooks(selectedNode);
selectedNode = null;
selectedSet.clear();
selectedList.clear();
}
}
private boolean contains(final NodeView node) {
return selectedSet.contains(node);
}
public Set<NodeView> getSelection() {
return Collections.unmodifiableSet(selectedSet);
}
private boolean deselect(final NodeView node) {
final boolean selectedChanged = selectedNode != null && selectedNode.equals(node);
if (selectedChanged) {
removeSelectionForHooks(node);
}
if (selectedSet.remove(node)){
final int last = selectedList.size() - 1;
if(selectedList.get(last) .equals(node))
selectedList.remove(last);
else
selectedList.remove(node);
node.repaintSelected();
if(selectedChanged) {
if (size() > 0) {
selectedNode = selectedSet.iterator().next();
addSelectionForHooks(selectedNode);
}
else{
selectedNode = null;
}
}
return true;
}
return false;
}
private void removeSelectionForHooks(final NodeView node) {
if (node.getModel() == null || ! isSelected()) {
return;
}
getModeController().getMapController().onDeselect(node.getModel());
}
private int size() {
return selectedSet.size();
}
private void replace(NodeView[] newSelection) {
if(newSelection.length == 0)
return;
final boolean selectedChanges = ! newSelection[0].equals(selectedNode);
if (selectedChanges) {
if(selectedNode != null)
removeSelectionForHooks(selectedNode);
selectedNode = newSelection[0];
}
for(NodeView view : newSelection)
if (!selectedSet.contains(view))
view.repaintSelected();
final NodeView[] oldSelection = selectedSet.toArray(new NodeView[selectedSet.size()]);
selectedSet.clear();
selectedList.clear();
for(NodeView view : newSelection)
if (selectedSet.add(view))
selectedList.add(view);
if (selectedChanges) {
addSelectionForHooks(selectedNode);
}
for(NodeView view : oldSelection)
if (!selectedSet.contains(view))
view.repaintSelected();
}
public NodeView[] toArray() {
return selectedList.toArray(new NodeView[selectedList.size()]);
}
private List<NodeView> getSelectedList() {
return selectedList;
}
private Set<NodeView> getSelectedSet() {
return selectedSet;
}
}
private static final int margin = 20;
static boolean printOnWhiteBackground;
static private IFreeplanePropertyListener propertyChangeListener;
public static final String RESOURCES_SELECTED_NODE_COLOR = "standardselectednodecolor";
public static final String RESOURCES_SELECTED_NODE_RECTANGLE_COLOR = "standardselectednoderectanglecolor";
private static final String PRESENTATION_DIMMER_TRANSPARENCY = "presentation_dimmer_transparency";
private static final String PRESENTATION_MODE_ENABLED = "presentation_mode";
private static final long serialVersionUID = 1L;
static boolean standardDrawRectangleForSelection;
static Color standardSelectColor;
private static Stroke standardSelectionStroke;
static Color standardSelectRectangleColor;
private NodeView anchor;
private Point anchorContentLocation;
/** Used to identify a right click onto a link curve. */
private Vector<ILinkView> arrowLinkViews;
private Color background = null;
private JComponent backgroundComponent;
private Rectangle boundingRectangle = null;
private boolean disableMoveCursor = true;
private int extraWidth;
private FitMap fitMap = FitMap.USER_DEFINED;
private boolean isPreparedForPrinting = false;
private boolean isPrinting = false;
private final ModeController modeController;
final private MapModel model;
private NodeView nodeToBeVisible = null;
private NodeView rootView = null;
private boolean selectedsValid = true;
final private Selection selection = new Selection();
private int siblingMaxLevel;
private float zoom = 1F;
private float anchorHorizontalPoint;
private float anchorVerticalPoint;
private NodeView nodeToBeCentered;
private Font noteFont;
private Font detailFont;
private Color detailForeground;
private Color detailBackground;
private boolean slowScroll;
private static boolean presentationModeEnabled;
private boolean fitToViewport;
private static int transparency;
public MapView(final MapModel model, final ModeController modeController) {
super();
this.model = model;
this.modeController = modeController;
final String name = model.getTitle();
setName(name);
if (MapView.standardSelectColor == null) {
final String stdcolor = ResourceController.getResourceController().getProperty(
MapView.RESOURCES_SELECTED_NODE_COLOR);
MapView.standardSelectColor = ColorUtils.stringToColor(stdcolor);
final String stdtextcolor = ResourceController.getResourceController().getProperty(
MapView.RESOURCES_SELECTED_NODE_RECTANGLE_COLOR);
MapView.standardSelectRectangleColor = ColorUtils.stringToColor(stdtextcolor);
final String drawCircle = ResourceController.getResourceController().getProperty(
ResourceController.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION);
MapView.standardDrawRectangleForSelection = TreeXmlReader.xmlToBoolean(drawCircle);
final String printOnWhite = ResourceController.getResourceController()
.getProperty("printonwhitebackground");
MapView.printOnWhiteBackground = TreeXmlReader.xmlToBoolean(printOnWhite);
MapView.transparency = 255 - ResourceController.getResourceController().getIntProperty(PRESENTATION_DIMMER_TRANSPARENCY, 0x70);
MapView.presentationModeEnabled = ResourceController.getResourceController().getBooleanProperty(PRESENTATION_MODE_ENABLED);
createPropertyChangeListener();
}
this.setAutoscrolls(true);
this.setLayout(new MindMapLayout());
final NoteController noteController = NoteController.getController(getModeController());
showNotes= noteController != null && noteController.showNotesInMap(getModel());
updateContentStyle();
initRoot();
setBackground(requiredBackground());
final MapStyleModel mapStyleModel = MapStyleModel.getExtension(model);
zoom = mapStyleModel.getZoom();
layoutType = mapStyleModel.getMapViewLayout();
final IUserInputListenerFactory userInputListenerFactory = getModeController().getUserInputListenerFactory();
addMouseListener(userInputListenerFactory.getMapMouseListener());
addMouseMotionListener(userInputListenerFactory.getMapMouseListener());
addMouseWheelListener(userInputListenerFactory.getMapMouseWheelListener());
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, emptyNodeViewSet());
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, emptyNodeViewSet());
setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, emptyNodeViewSet());
disableMoveCursor = ResourceController.getResourceController().getBooleanProperty("disable_cursor_move_paper");
addHierarchyBoundsListener(new Resizer());
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
if (fitToViewport) {
adjustBackgroundComponentScale();
repaint();
}
}
});
}
public void replaceSelection(NodeView[] views) {
selection.replace(views);
if(views.length > 0)
views[0].requestFocusInWindow();
}
// generics trickery
private Set<AWTKeyStroke> emptyNodeViewSet() {
return Collections.emptySet();
}
private void anchorToSelected(final NodeModel node, final float horizontalPoint, final float verticalPoint) {
final NodeView view = getNodeView(node);
anchorToSelected(view, horizontalPoint, verticalPoint);
}
void anchorToSelected(final NodeView view, final float horizontalPoint, final float verticalPoint) {
if (view != null && view.getMainView() != null) {
anchor = view;
anchorHorizontalPoint = horizontalPoint;
anchorVerticalPoint = verticalPoint;
anchorContentLocation = getAnchorCenterPoint();
if (nodeToBeVisible == null) {
nodeToBeVisible = anchor;
extraWidth = 0;
}
}
}
/*
* (non-Javadoc)
* @see java.awt.dnd.Autoscroll#autoscroll(java.awt.Point)
*/
public void autoscroll(final Point cursorLocn) {
final Rectangle r = new Rectangle((int) cursorLocn.getX() - MapView.margin, (int) cursorLocn.getY()
- MapView.margin, 1 + 2 * MapView.margin, 1 + 2 * MapView.margin);
scrollRectToVisible(r);
}
public void centerNode(final NodeView node, boolean slowScroll) {
if (node != null) {
this.slowScroll = slowScroll;
nodeToBeVisible = null;
if (!isShowing()) {
centerNodeAfterMapIsDisplayed(node);
}
else {
nodeToBeCentered = node;
if (!isLayoutCompleted()) {
centerNodeLater();
}
else {
centerNodeNow(slowScroll);
}
}
}
}
private void centerNodeLater() {
EventQueue.invokeLater(new Runnable() {
public void run() {
centerNode(nodeToBeCentered, MapView.this.slowScroll);
}
});
}
private void centerNodeNow(boolean slowScroll) {
final JViewport viewPort = (JViewport) getParent();
if(slowScroll)
viewPort.putClientProperty(ViewController.SLOW_SCROLLING, Boolean.TRUE);
final Dimension d = viewPort.getExtentSize();
final JComponent content = nodeToBeCentered.getContent();
final Rectangle rect = new Rectangle(content.getWidth() / 2 - d.width / 2, content.getHeight() / 2 - d.height
/ 2, d.width, d.height);
final Point oldAnchorContentLocation = anchorContentLocation;
anchorContentLocation = new Point();
final Point oldViewPosition = viewPort.getViewPosition();
content.scrollRectToVisible(rect);
final Point newViewPosition = viewPort.getViewPosition();
if (oldViewPosition.equals(newViewPosition)) {
anchorContentLocation = oldAnchorContentLocation;
}
nodeToBeCentered = null;
this.slowScroll = false;
}
private void centerNodeAfterMapIsDisplayed(final NodeView node) {
boolean isRetryEventListenerAlreadySet = null != nodeToBeCentered;
if (!isRetryEventListenerAlreadySet) {
HierarchyListener retryEventListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
if (isShowing()) {
removeHierarchyListener(this);
loadBackgroundImageLater();
if (nodeToBeCentered != null)
centerNode(nodeToBeCentered, MapView.this.slowScroll);
}
}
};
addHierarchyListener(retryEventListener);
}
nodeToBeCentered = node;
}
boolean isLayoutCompleted() {
final JViewport viewPort = (JViewport) getParent();
final Dimension visibleDimension = viewPort.getExtentSize();
return visibleDimension.width > 0;
}
static private void createPropertyChangeListener() {
MapView.propertyChangeListener = new IFreeplanePropertyListener() {
public void propertyChanged(final String propertyName, final String newValue, final String oldValue) {
final Component mapView = Controller.getCurrentController().getMapViewManager().getMapViewComponent();
if (!(mapView instanceof MapView)) {
return;
}
if (propertyName.equals(RESOURCES_SELECTED_NODE_COLOR)) {
MapView.standardSelectColor = ColorUtils.stringToColor(newValue);
((MapView) mapView).repaintSelecteds();
return;
}
if (propertyName.equals(RESOURCES_SELECTED_NODE_RECTANGLE_COLOR)) {
MapView.standardSelectRectangleColor = ColorUtils.stringToColor(newValue);
((MapView) mapView).repaintSelecteds();
return;
}
if (propertyName.equals(ResourceController.RESOURCE_DRAW_RECTANGLE_FOR_SELECTION)) {
MapView.standardDrawRectangleForSelection = TreeXmlReader.xmlToBoolean(newValue);
((MapView) mapView).repaintSelecteds();
return;
}
if (propertyName.equals("printonwhitebackground")) {
MapView.printOnWhiteBackground = TreeXmlReader.xmlToBoolean(newValue);
return;
}
if (propertyName.equals(PRESENTATION_DIMMER_TRANSPARENCY)) {
MapView.transparency = 255 - ResourceController.getResourceController().getIntProperty(PRESENTATION_DIMMER_TRANSPARENCY, 0x70);
((MapView) mapView).repaint();
return;
}
if (propertyName.equals(PRESENTATION_MODE_ENABLED)) {
MapView.presentationModeEnabled = ResourceController.getResourceController().getBooleanProperty(PRESENTATION_MODE_ENABLED);
((MapView) mapView).repaint();
return;
}
}
};
ResourceController.getResourceController().addPropertyChangeListener(MapView.propertyChangeListener);
}
public void deselect(final NodeView newSelected) {
if (selection.contains(newSelected) && selection.deselect(newSelected)) {
newSelected.repaintSelected();
}
}
public Object detectCollision(final Point p) {
if (arrowLinkViews == null) {
return null;
}
for (int i = 0; i < arrowLinkViews.size(); ++i) {
final ILinkView arrowView = arrowLinkViews.get(i);
if (arrowView.detectCollision(p, true)) {
return arrowView.getModel();
}
}
for (int i = 0; i < arrowLinkViews.size(); ++i) {
final ILinkView arrowView = arrowLinkViews.get(i);
if (arrowView.detectCollision(p, false)) {
return arrowView.getModel();
}
}
return null;
}
/**
* Call preparePrinting() before printing and endPrinting() after printing
* to minimize calculation efforts
*/
public void endPrinting() {
if (!isPreparedForPrinting)
return;
isPreparedForPrinting = false;
isPrinting = false;
if (zoom == 1f) {
getRoot().updateAll();
synchronized (getTreeLock()) {
validateTree();
}
}
if (MapView.printOnWhiteBackground) {
setBackground(background);
}
}
private Point getAnchorCenterPoint() {
final MainView mainView = anchor.getMainView();
final Point anchorCenterPoint = new Point((int) (mainView.getWidth() * anchorHorizontalPoint), (int) (mainView
.getHeight() * anchorVerticalPoint));
final JViewport parent = (JViewport) getParent();
if (parent == null) {
return new Point();
}
try {
UITools.convertPointToAncestor(mainView, anchorCenterPoint, parent);
}
catch (final NullPointerException e) {
return new Point();
}
final Point viewPosition = parent.getViewPosition();
anchorCenterPoint.x += viewPosition.x - parent.getWidth() / 2;
anchorCenterPoint.y += viewPosition.y - parent.getHeight() / 2;
return anchorCenterPoint;
}
/*
* (non-Javadoc)
* @see java.awt.dnd.Autoscroll#getAutoscrollInsets()
*/
public Insets getAutoscrollInsets() {
final Container parent = getParent();
if (parent == null) {
return new Insets(0, 0, 0, 0);
}
final Rectangle outer = getBounds();
final Rectangle inner = parent.getBounds();
return new Insets(inner.y - outer.y + MapView.margin, inner.x - outer.x + MapView.margin, outer.height
- inner.height - inner.y + outer.y + MapView.margin, outer.width - inner.width - inner.x + outer.x
+ MapView.margin);
}
public Rectangle getInnerBounds() {
final Rectangle innerBounds = rootView.getBounds();
final Rectangle maxBounds = new Rectangle(0, 0, getWidth(), getHeight());
for (int i = 0; i < arrowLinkViews.size(); ++i) {
final ILinkView arrowView = arrowLinkViews.get(i);
arrowView.increaseBounds(innerBounds);
}
return innerBounds.intersection(maxBounds);
}
public IMapSelection getMapSelection() {
return new MapSelection();
}
public ModeController getModeController() {
return modeController;
}
public MapModel getModel() {
return model;
}
public Point getNodeContentLocation(final NodeView nodeView) {
final Point contentXY = new Point(0, 0);
UITools.convertPointToAncestor(nodeView.getContent(), contentXY, this);
return contentXY;
}
private NodeView getNodeView(Object o) {
if(! (o instanceof NodeModel))
return null;
final NodeView nodeView = getNodeView((NodeModel)o);
return nodeView;
}
public NodeView getNodeView(final NodeModel node) {
if (node == null) {
return null;
}
for (INodeView iNodeView : node.getViewers()) {
if(! (iNodeView instanceof NodeView)){
continue;
}
final NodeView candidateView = (NodeView) iNodeView;
if (candidateView.getMap() == this) {
return candidateView;
}
}
NodeView root = getRoot();
if(root.getModel().equals(node))
return root;
else
return null;
}
/*
* (non-Javadoc)
* @see javax.swing.JComponent#getPreferredSize()
*/
@Override
public Dimension getPreferredSize() {
if (!getParent().isValid()) {
final Dimension preferredLayoutSize = getLayout().preferredLayoutSize(this);
return preferredLayoutSize;
}
return super.getPreferredSize();
}
public NodeView getRoot() {
return rootView;
}
public NodeView getSelected() {
if(! selectedsValid) {
NodeView node = selection.selectedNode;
if (node == null || ! SwingUtilities.isDescendingFrom(node, this))
validateSelecteds();
else {
final JComponent content = node.getContent();
if (content == null || ! content.isVisible())
validateSelecteds();
}
}
return selection.selectedNode;
}
public Set<NodeModel> getSelectedNodes() {
validateSelecteds();
return new AbstractSet<NodeModel>() {
@Override
public int size() {
return selection.size();
}
@Override
public boolean contains(Object o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.contains(nodeView);
}
@Override
public boolean add(NodeModel o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.add(nodeView);
}
@Override
public boolean remove(Object o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.deselect(nodeView);
}
@Override
public Iterator<NodeModel> iterator() {
return new Iterator<NodeModel>() {
final Iterator<NodeView> i = selection.getSelectedSet().iterator();
public boolean hasNext() {
return i.hasNext();
}
public NodeModel next() {
return i.next().getModel();
}
public void remove() {
i.remove();
}
};
}
};
}
public List<NodeModel> getOrderedSelectedNodes() {
validateSelecteds();
return new AbstractList<NodeModel>(){
@Override
public boolean add(NodeModel o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.add(nodeView);
}
@Override
public boolean contains(Object o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.contains(nodeView);
}
@Override
public boolean remove(Object o) {
final NodeView nodeView = getNodeView(o);
if(nodeView == null)
return false;
return selection.deselect(nodeView);
}
@Override
public NodeModel get(int index) {
return selection.getSelectedList().get(index).getModel();
}
@Override
public int size() {
return selection.size();
}
};
}
/**
* @param differentSubtrees
* @return an ArrayList of MindMapNode objects. If both ancestor and
* descandant node are selected, only the ancestor ist returned
*/
ArrayList<NodeModel> getSelectedNodesSortedByY(final boolean differentSubtrees) {
validateSelecteds();
final TreeMap<Integer, LinkedList<NodeModel>> sortedNodes = new TreeMap<Integer, LinkedList<NodeModel>>();
iteration: for (final NodeView view : selection.getSelectedSet()) {
if (differentSubtrees) {
for (Component parent = view.getParent(); parent != null; parent = parent.getParent()) {
if (selection.getSelectedSet().contains(parent)) {
continue iteration;
}
}
}
final Point point = new Point();
UITools.convertPointToAncestor(view.getParent(), point, this);
final NodeModel node = view.getModel();
if(node.getParentNode() != null){
point.y += node.getParentNode().getIndex(node);
}
LinkedList<NodeModel> nodeList = sortedNodes.get(point.y);
if (nodeList == null) {
nodeList = new LinkedList<NodeModel>();
sortedNodes.put(point.y, nodeList);
}
nodeList.add(node);
}
final ArrayList<NodeModel> selectedNodes = new ArrayList<NodeModel>();
for (final LinkedList<NodeModel> nodeList : sortedNodes.values()) {
for (final NodeModel nodeModel : nodeList) {
selectedNodes.add(nodeModel);
}
}
return selectedNodes;
}
/**
* @return
*/
public Collection<NodeView> getSelection() {
validateSelecteds();
return selection.getSelection();
}
public int getSiblingMaxLevel() {
return siblingMaxLevel;
}
/**
* Returns the size of the visible part of the view in view coordinates.
*/
public Dimension getViewportSize() {
final JViewport mapViewport = (JViewport) getParent();
return mapViewport == null ? null : mapViewport.getSize();
}
private NodeView getVisibleLeft(final NodeView oldSelected) {
NodeView newSelected = oldSelected;
final NodeModel oldModel = oldSelected.getModel();
if (oldModel.isRoot()) {
newSelected = oldSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), true);
}
else if (!oldSelected.isLeft()) {
newSelected = oldSelected.getVisibleParentView();
}
else {
if (getModeController().getMapController().isFolded(oldModel)) {
getModeController().getMapController().setFolded(oldModel, false);
return oldSelected;
}
newSelected = oldSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), true);
while (newSelected != null && !newSelected.isContentVisible()) {
newSelected = newSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), true);
}
if(newSelected == null)
newSelected = getVisibleSummaryView(oldSelected);
}
return newSelected;
}
private NodeView getVisibleSummaryView(NodeView node) {
if(node.isRoot())
return null;
final int currentSummaryLevel = SummaryNode.getSummaryLevel(node.getModel());
int level = currentSummaryLevel;
final int requiredSummaryLevel = level + 1;
final NodeView parent = node.getParentView();
for (int i = 1 + getIndex(node);i < parent.getComponentCount();i++){
final Component component = parent.getComponent(i);
if(! (component instanceof NodeView))
break;
NodeView next = (NodeView) component;
if(next.isLeft() != node.isLeft())
continue;
if(next.isSummary())
level++;
else
level = 0;
if(level == requiredSummaryLevel){
if(next.getModel().isVisible())
return next;
break;
}
if(level == currentSummaryLevel && SummaryNode.isFirstGroupNode(next.getModel()))
break;
}
return getVisibleSummaryView(parent);
}
int getIndex(NodeView node) {
final NodeView parent = node.getParentView();
for(int i = 0; i < parent.getComponentCount(); i++){
if(parent.getComponent(i).equals(node))
return i;
}
return -1;
}
private NodeView getVisibleRight(final NodeView oldSelected) {
NodeView newSelected = oldSelected;
final NodeModel oldModel = oldSelected.getModel();
if (oldModel.isRoot()) {
newSelected = oldSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), false);
}
else if (oldSelected.isLeft()) {
newSelected = oldSelected.getVisibleParentView();
}
else {
if (getModeController().getMapController().isFolded(oldModel)) {
getModeController().getMapController().setFolded(oldModel, false);
return oldSelected;
}
newSelected = oldSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), false);
while (newSelected != null && !newSelected.isContentVisible()) {
newSelected = newSelected.getPreferredVisibleChild(layoutType.equals(MapViewLayout.OUTLINE), false);
}
if(newSelected == null)
newSelected = getVisibleSummaryView(oldSelected);
}
return newSelected;
}
public float getZoom() {
return zoom;
}
public int getZoomed(final int number) {
return (int) Math.ceil(number * zoom);
}
private void initRoot() {
anchorContentLocation = new Point();
rootView = NodeViewFactory.getInstance().newNodeView(getModel().getRootNode(), this, this, 0);
anchor = rootView;
}
private void loadBackgroundImageLater() {
final String fitToViewportAsString = MapStyle.getController(modeController).getPropertySetDefault(model,
MapStyle.FIT_TO_VIEWPORT);
fitToViewport = Boolean.parseBoolean(fitToViewportAsString);
EventQueue.invokeLater(new Runnable() {
public void run() {
loadBackgroundImage();
}
});
}
public boolean isPrinting() {
return isPrinting;
}
public boolean isSelected(final NodeView n) {
if(isPrinting || (! selectedsValid &&
(selection.selectedNode == null || ! SwingUtilities.isDescendingFrom(selection.selectedNode, this) || ! selection.selectedNode.getContent().isVisible())))
return false;
return selection.contains(n);
}
/**
* Add the node to the selection if it is not yet there, making it the
* focused selected node.
*/
void addSelected(final NodeView newSelected, boolean scroll) {
selection.add(newSelected);
if(scroll)
scrollNodeToVisible(newSelected);
}
public void mapChanged(final MapChangeEvent event) {
final Object property = event.getProperty();
if (property.equals(MapStyle.RESOURCES_BACKGROUND_COLOR)) {
setBackground(requiredBackground());
return;
}
if (property.equals(MapStyle.MAP_STYLES)){
// set default font for notes:
updateContentStyle();
}
if (property.equals(MapStyle.MAP_STYLES) && event.getMap().equals(model)
|| property.equals(ModelessAttributeController.ATTRIBUTE_VIEW_TYPE)
|| property.equals(Filter.class)
|| property.equals(UrlManager.MAP_URL)) {
setBackground(requiredBackground());
getRoot().updateAll();
return;
}
if(property.equals(AttributeController.SHOW_ICON_FOR_ATTRIBUTES)
||property.equals(NoteController.SHOW_NOTE_ICONS))
updateStateIconsRecursively(getRoot());
if(property.equals(NoteController.SHOW_NOTES_IN_MAP))
setShowNotes();
if (property.equals(MapStyle.RESOURCES_BACKGROUND_IMAGE)) {
final String fitToViewportAsString = MapStyle.getController(modeController).getPropertySetDefault(model,
MapStyle.FIT_TO_VIEWPORT);
fitToViewport = Boolean.parseBoolean(fitToViewportAsString);
loadBackgroundImage();
}
if (property.equals(MapStyle.FIT_TO_VIEWPORT)) {
final String fitToViewportAsString = MapStyle.getController(modeController).getPropertySetDefault(model,
MapStyle.FIT_TO_VIEWPORT);
fitToViewport = Boolean.parseBoolean(fitToViewportAsString);
adjustBackgroundComponentScale();
repaint();
}
}
private void loadBackgroundImage() {
final MapStyle mapStyle = getModeController().getExtension(MapStyle.class);
final String uriString = mapStyle.getProperty(model, MapStyle.RESOURCES_BACKGROUND_IMAGE);
if (uriString == null) {
backgroundComponent = null;
return;
}
URI uri = assignAbsoluteURI(uriString);
final ViewerController vc = getModeController().getExtension(ViewerController.class);
final IViewerFactory factory = vc.getCombiFactory();
if (uri != null) {
assignViewerToBackgroundComponent(factory, uri);
((ScalableComponent) backgroundComponent).setCenter(true);
}
repaint();
}
private URI assignAbsoluteURI(final String uriString) {
final UrlManager urlManager = getModeController().getExtension(UrlManager.class);
URI uri = null;
try {
uri = urlManager.getAbsoluteUri(model, new URI(uriString));
}
catch (final URISyntaxException e) {
LogUtils.severe(e);
}
catch (MalformedURLException e) {
LogUtils.severe(e);
}
return uri;
}
private void assignViewerToBackgroundComponent(final IViewerFactory factory, final URI uri) {
try {
if (fitToViewport) {
final JViewport vp = (JViewport) getParent();
final Dimension viewPortSize = vp.getVisibleRect().getSize();
backgroundComponent = (JComponent) factory.createViewer(uri, viewPortSize);
}
else {
backgroundComponent = (JComponent) factory.createViewer(uri, zoom);
}
}
catch (final MalformedURLException e1) {
LogUtils.severe(e1);
}
catch (final IOException e1) {
LogUtils.severe(e1);
}
}
private void updateStateIconsRecursively(NodeView node) {
final MainView mainView = node.getMainView();
if(mainView == null)
return;
mainView.updateIcons(node);
for(int i = 0; i < node.getComponentCount(); i++){
final Component component = node.getComponent(i);
if(component instanceof NodeView)
updateStateIconsRecursively((NodeView) component);
}
}
private void updateContentStyle() {
final NodeStyleController style = Controller.getCurrentModeController().getExtension(NodeStyleController.class);
MapModel map = getModel();
noteFont = UITools.scale(style.getDefaultFont(map, MapStyleModel.NOTE_STYLE));
final MapStyleModel model = MapStyleModel.getExtension(map);
final NodeModel detailStyleNode = model.getStyleNodeSafe(MapStyleModel.DETAILS_STYLE);
detailFont = UITools.scale(style.getFont(detailStyleNode));
detailBackground = style.getBackgroundColor(detailStyleNode);
detailForeground = style.getColor(detailStyleNode);
}
public boolean selectLeft(boolean continious) {
NodeView selected = getSelected();
NodeView newSelected = getVisibleLeft(selected);
return selectRightOrLeft(newSelected, continious);
}
private boolean selectRightOrLeft(NodeView newSelected, boolean continious) {
if (newSelected == null) {
return false;
}
if(continious){
if(newSelected.isParentOf(getSelected())){
selectAsTheOnlyOneSelected(newSelected);
addBranchToSelection(newSelected);
}
else{
addBranchToSelection(getSelected());
}
}
else
selectAsTheOnlyOneSelected(newSelected);
return true;
}
public boolean selectRight(boolean continious) {
NodeView selected = getSelected();
NodeView newSelected = getVisibleRight(selected);
return selectRightOrLeft(newSelected, continious);
}
public boolean selectUp(boolean continious) {
return selectSibling(continious, false, false);
}
private boolean selectSibling(boolean continious, boolean page, boolean down) {
NodeView nextSelected = getSelected();
do {
final NodeView nextVisibleSibling = getNextVisibleSibling(nextSelected, down);
if(nextSelected == null || nextSelected == nextVisibleSibling)
return false;
nextSelected = nextVisibleSibling;
} while (nextSelected.isSelected());
if(page){
NodeView sibling = nextSelected;
for(;;) {
sibling = getNextVisibleSibling(sibling, down);
if(sibling == nextSelected || sibling.getParentView() != nextSelected.getParentView())
break;
nextSelected = sibling;
}
}
if(continious){
selectAsTheOnlyOneSelected(getSelected());
NodeView node = getSelected();
do{
node = getNextVisibleSibling(node, down);
addSelected(node, false);
}while(node != nextSelected);
scrollNodeToVisible(nextSelected);
}
else
selectAsTheOnlyOneSelected(nextSelected);
return true;
}
public NodeView getNextVisibleSibling(NodeView node, boolean down) {
return down ? node.getNextVisibleSibling() : node.getPreviousVisibleSibling();
}
public boolean selectDown(boolean continious) {
return selectSibling(continious, false, true);
}
public boolean selectPageDown(boolean continious) {
return selectSibling(continious, true, true);
}
public boolean selectPageUp(boolean continious) {
return selectSibling(continious, true, false);
}
public void onNodeDeleted(final NodeModel parent, final NodeModel child, final int index) {
}
public void onNodeInserted(final NodeModel parent, final NodeModel child, final int newIndex) {
}
public void onNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
public void onPreNodeDelete(final NodeModel oldParent, final NodeModel selectedNode, final int index) {
}
/*****************************************************************
** P A I N T I N G **
*****************************************************************/
/*
* (non-Javadoc)
* @see javax.swing.JComponent#paint(java.awt.Graphics)
*/
@Override
public void paint(final Graphics g) {
if (!isPrinting && isPreparedForPrinting){
isPreparedForPrinting = false;
EventQueue.invokeLater(new Runnable() {
public void run() {
endPrinting();
repaint();
}
});
return;
}
if (isValid()) {
anchorContentLocation = getAnchorCenterPoint();
}
final Graphics2D g2 = (Graphics2D) g.create();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
Controller.getCurrentController().getMapViewManager().setTextRenderingHint(g2);
super.paint(g2);
}
finally {
this.paintingMode = null;
g2.dispose();
}
}
@Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
if (backgroundComponent != null) {
setAndPaintBackgroundComponent(g);
}
}
private void setAndPaintBackgroundComponent(final Graphics g) {
Graphics backgroundGraphics = g.create();
try {
setBackgroundComponentLocation(backgroundGraphics);
backgroundComponent.paint(backgroundGraphics);
repaint();
}
finally {
backgroundGraphics.dispose();
}
}
private void setBackgroundComponentLocation(Graphics g) {
if (fitToViewport) {
final JViewport vp = (JViewport) getParent();
final Point viewPosition = vp.getViewPosition();
g.translate(viewPosition.x, viewPosition.y);
}
else {
final Point centerPoint = getRootCenterPoint();
final Point backgroundImageTopLeft = getBackgroundImageTopLeft(centerPoint);
g.translate(backgroundImageTopLeft.x, backgroundImageTopLeft.y);
}
}
private Point getRootCenterPoint() {
final Point centerPoint = new Point(getRoot().getMainView().getWidth() / 2,
getRoot().getMainView().getHeight() / 2);
UITools.convertPointToAncestor(getRoot().getMainView(), centerPoint, this);
return centerPoint;
}
private Point getBackgroundImageTopLeft(Point centerPoint) {
int x = centerPoint.x - (backgroundComponent.getWidth() / 2);
int y = centerPoint.y - (backgroundComponent.getHeight() / 2);
return new Point(x, y);
}
@Override
protected void paintChildren(final Graphics g) {
final boolean paintLinksBehind = ResourceController.getResourceController().getBooleanProperty(
"paint_connectors_behind");
final PaintingMode paintModes[];
if(paintLinksBehind)
paintModes = new PaintingMode[]{
PaintingMode.CLOUDS,
PaintingMode.LINKS, PaintingMode.NODES, PaintingMode.SELECTED_NODES
};
else
paintModes = new PaintingMode[]{
PaintingMode.CLOUDS,
PaintingMode.NODES, PaintingMode.SELECTED_NODES, PaintingMode.LINKS
};
Graphics2D g2 = (Graphics2D) g;
paintChildren(g2, paintModes);
if(presentationModeEnabled)
paintDimmer(g2, paintModes);
paintSelecteds(g2);
highlightEditor(g2);
}
private void paintChildren(Graphics2D g2, final PaintingMode[] paintModes) {
for(PaintingMode paintingMode : paintModes){
this.paintingMode = paintingMode;
switch(paintingMode){
case LINKS:
paintLinks(g2);
break;
default:
super.paintChildren(g2);
}
}
};
private void paintDimmer(Graphics2D g2, PaintingMode[] paintModes) {
final Color color = g2.getColor();
try{
Color dimmer = new Color(0, 0, 0, transparency);
g2.setColor(dimmer);
g2.fillRect(0, 0, getWidth(), getHeight());
}
finally{
g2.setColor(color);
}
for (final NodeView selected : getSelection()) {
highlightSelected(g2, selected, paintModes);
}
}
private void highlightEditor(Graphics2D g2) {
final Component editor = getComponent(0);
if(editor instanceof NodeView)
return;
final java.awt.Shape oldClip = g2.getClip();
try{
g2.setClip(editor.getX(), editor.getY(), editor.getWidth(), editor.getHeight());
super.paintChildren(g2);
}
finally{
g2.setClip(oldClip);
}
}
protected PaintingMode getPaintingMode() {
return paintingMode;
}
private void paintLinks(final Collection<LinkModel> links, final Graphics2D graphics,
final HashSet<ConnectorModel> alreadyPaintedLinks) {
final Font font = graphics.getFont();
try {
final Iterator<LinkModel> linkIterator = links.iterator();
while (linkIterator.hasNext()) {
final LinkModel next = linkIterator.next();
if (!(next instanceof ConnectorModel)) {
continue;
}
final ConnectorModel ref = (ConnectorModel) next;
if (alreadyPaintedLinks.add(ref)) {
final NodeModel target = ref.getTarget();
if (target == null) {
continue;
}
final NodeModel source = ref.getSource();
final NodeView sourceView = getNodeView(source);
final NodeView targetView = getNodeView(target);
final ILinkView arrowLink;
if (sourceView != null && targetView != null
&& (Shape.EDGE_LIKE.equals(ref.getShape()) || sourceView.getMap().getLayoutType() == MapViewLayout.OUTLINE)
&& source.isVisible() && target.isVisible()) {
arrowLink = new EdgeLinkView(ref, getModeController(), sourceView, targetView);
}
else {
arrowLink = new ConnectorView(ref, sourceView, targetView, getBackground());
}
arrowLink.paint(graphics);
arrowLinkViews.add(arrowLink);
}
}
}
finally {
graphics.setFont(font);
}
}
private void paintLinks(final Graphics2D graphics) {
arrowLinkViews = new Vector<ILinkView>();
final Object renderingHint = getModeController().getController().getMapViewManager().setEdgesRenderingHint(
graphics);
paintLinks(rootView, graphics, new HashSet<ConnectorModel>());
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint);
}
private void paintLinks(final NodeView source, final Graphics2D graphics,
final HashSet<ConnectorModel> alreadyPaintedLinks) {
final NodeModel node = source.getModel();
final Collection<LinkModel> outLinks = NodeLinks.getLinks(node);
paintLinks(outLinks, graphics, alreadyPaintedLinks);
final Collection<LinkModel> inLinks = LinkController.getController(getModeController()).getLinksTo(node);
paintLinks(inLinks, graphics, alreadyPaintedLinks);
final int nodeViewCount = source.getComponentCount();
for (int i = 0; i < nodeViewCount; i++) {
final Component component = source.getComponent(i);
if (!(component instanceof NodeView)) {
continue;
}
final NodeView child = (NodeView) component;
if (!isPrinting) {
final Rectangle bounds = SwingUtilities.convertRectangle(source, child.getBounds(), this);
final JViewport vp = (JViewport) getParent();
final Rectangle viewRect = vp.getViewRect();
viewRect.x -= viewRect.width;
viewRect.y -= viewRect.height;
viewRect.width *= 3;
viewRect.height *= 3;
if (!viewRect.intersects(bounds)) {
continue;
}
}
paintLinks(child, graphics, alreadyPaintedLinks);
}
}
private void paintSelecteds(final Graphics2D g) {
if (!MapView.standardDrawRectangleForSelection || isPrinting()) {
return;
}
final Color c = g.getColor();
final Stroke s = g.getStroke();
g.setColor(MapView.standardSelectRectangleColor);
final Stroke standardSelectionStroke = getStandardSelectionStroke();
g.setStroke(standardSelectionStroke);
final Object renderingHint = getModeController().getController().getMapViewManager().setEdgesRenderingHint(g);
for (final NodeView selected : getSelection()) {
paintSelectionRectangle(g, selected);
}
g.setColor(c);
g.setStroke(s);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, renderingHint);
}
private RoundRectangle2D.Float getRoundRectangleAround(NodeView selected, int gap, int arcw) {
final JComponent content = selected.getContent();
final Point contentLocation = new Point();
UITools.convertPointToAncestor(content, contentLocation, this);
gap -= 1;
final RoundRectangle2D.Float roundRectClip = new RoundRectangle2D.Float(
contentLocation.x - gap, contentLocation.y - gap,
content.getWidth() + 2 * gap, content.getHeight() + 2 * gap, arcw, arcw);
return roundRectClip;
}
private void paintSelectionRectangle(final Graphics2D g, final NodeView selected) {
if (selected.getMainView().isEdited()) {
return;
}
final RoundRectangle2D.Float roundRectClip = getRoundRectangleAround(selected, 4, 15);
g.draw(roundRectClip);
}
private void highlightSelected(Graphics2D g, NodeView selected, PaintingMode[] paintedModes) {
final java.awt.Shape highlightClip;
if (MapView.standardDrawRectangleForSelection)
highlightClip = getRoundRectangleAround(selected, 4, 15);
else
highlightClip = getRoundRectangleAround(selected, 4, 2);
final java.awt.Shape oldClip = g.getClip();
final Rectangle oldClipBounds = g.getClipBounds();
try{
g.setClip(highlightClip);
if(oldClipBounds != null)
g.clipRect(oldClipBounds.x, oldClipBounds.y, oldClipBounds.width, oldClipBounds.height);
final Rectangle clipBounds = highlightClip.getBounds();
final Color color = g.getColor();
g.setColor(getBackground());
g.fillRect(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height);
g.setColor(color);
paintChildren(g, paintedModes);
}
finally{
g.setClip(oldClip);
}
}
Stroke getStandardSelectionStroke() {
if (MapView.standardSelectionStroke == null) {
MapView.standardSelectionStroke = new BasicStroke(2.0f);
}
final Stroke standardSelectionStroke = MapView.standardSelectionStroke;
return standardSelectionStroke;
}
/**
* Call preparePrinting() before printing and endPrinting() after printing
* to minimize calculation efforts
*/
public void preparePrinting() {
isPrinting = true;
if (!isPreparedForPrinting) {
if (zoom == 1f) {
getRoot().updateAll();
synchronized (getTreeLock()) {
validateTree();
}
}
if (MapView.printOnWhiteBackground) {
background = getBackground();
setBackground(Color.WHITE);
}
fitMap = FitMap.valueOf();
if (backgroundComponent != null && fitMap == FitMap.BACKGROUND) {
boundingRectangle = getBackgroundImageInnerBounds();
}
else {
boundingRectangle = getInnerBounds();
}
isPreparedForPrinting = true;
}
}
private Rectangle getBackgroundImageInnerBounds() {
final Point centerPoint = getRootCenterPoint();
final Point backgroundImageTopLeft = getBackgroundImageTopLeft(centerPoint);
backgroundComponent.setLocation(backgroundImageTopLeft);
return backgroundComponent.getBounds();
}
@Override
public void print(final Graphics g) {
try {
preparePrinting();
super.print(g);
}
finally {
isPrinting = false;
}
}
public void render(Graphics g1, final Rectangle source, final Rectangle target) {
Graphics2D g = (Graphics2D) g1;
AffineTransform old = g.getTransform();
final double scaleX = (0.0 + target.width) / source.width;
final double scaleY = (0.0 + target.height) / source.height;
final double zoom;
if(scaleX < scaleY){
zoom = scaleX;
}
else{
zoom = scaleY;
}
AffineTransform tr2 = new AffineTransform(old);
tr2.translate(target.getWidth() / 2, target.getHeight() / 2);
tr2.scale(zoom, zoom);
tr2.translate(-source.getX()- (source.getWidth() ) / 2, -source.getY()- (source.getHeight()) / 2);
g.setTransform(tr2);
final Rectangle clipBounds = g1.getClipBounds();
g1.clipRect(source.x, source.y, source.width, source.height);
print(g1);
g.setTransform(old);
g1.setClip(clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height);
}
public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) {
double userZoomFactor = ResourceController.getResourceController().getDoubleProperty("user_zoom", 1);
userZoomFactor = Math.max(0, userZoomFactor);
userZoomFactor = Math.min(2, userZoomFactor);
if ((fitMap == FitMap.PAGE || fitMap == FitMap.BACKGROUND) && pageIndex > 0) {
return Printable.NO_SUCH_PAGE;
}
final Graphics2D g2 = (Graphics2D) graphics.create();
preparePrinting();
final double zoomFactor;
final double imageableX = pageFormat.getImageableX();
final double imageableY = pageFormat.getImageableY();
final double imageableWidth = pageFormat.getImageableWidth();
final double imageableHeight = pageFormat.getImageableHeight();
g2.clipRect((int)imageableX, (int)imageableY, (int)imageableWidth, (int)imageableHeight);
final double mapWidth = boundingRectangle.getWidth();
final double mapHeight = boundingRectangle.getHeight();
if (fitMap == FitMap.PAGE || fitMap == FitMap.BACKGROUND) {
final double zoomFactorX = imageableWidth / mapWidth;
final double zoomFactorY = imageableHeight / mapHeight;
zoomFactor = Math.min(zoomFactorX, zoomFactorY) * 0.99;
}
else {
if (fitMap == FitMap.WIDTH) {
zoomFactor = imageableWidth / mapWidth * 0.99;
}
else if (fitMap == FitMap.HEIGHT) {
zoomFactor = imageableHeight / mapHeight * 0.99;
}
else {
zoomFactor = userZoomFactor / UITools.FONT_SCALE_FACTOR;
}
final int nrPagesInWidth = (int) Math.ceil(zoomFactor * mapWidth
/ imageableWidth);
final int nrPagesInHeight = (int) Math.ceil(zoomFactor * mapHeight
/ imageableHeight);
if (pageIndex >= nrPagesInWidth * nrPagesInHeight) {
return Printable.NO_SUCH_PAGE;
}
final int yPageCoord = (int) Math.floor(pageIndex / nrPagesInWidth);
final int xPageCoord = pageIndex - yPageCoord * nrPagesInWidth;
g2.translate(-imageableWidth * xPageCoord, -imageableHeight * yPageCoord);
}
g2.translate(imageableX, imageableY);
g2.scale(zoomFactor, zoomFactor);
final double mapX = boundingRectangle.getX();
final double mapY = boundingRectangle.getY();
g2.translate(-mapX, -mapY);
print(g2);
g2.dispose();
return Printable.PAGE_EXISTS;
}
private void repaintSelecteds() {
for (final NodeView selected : getSelection()) {
selected.repaintSelected();
}
}
private Color requiredBackground() {
final MapStyle mapStyle = getModeController().getExtension(MapStyle.class);
final Color mapBackground = mapStyle.getBackground(model);
return mapBackground;
}
void revalidateSelecteds() {
selectedsValid = false;
}
/**
* Scroll the viewport of the map to the south-west, i.e. scroll the map
* itself to the north-east.
*/
public void scrollBy(final int x, final int y) {
final JViewport mapViewport = (JViewport) getParent();
if (mapViewport != null) {
final Point currentPoint = mapViewport.getViewPosition();
currentPoint.translate(x, y);
if (currentPoint.getX() < 0) {
currentPoint.setLocation(0, currentPoint.getY());
}
if (currentPoint.getY() < 0) {
currentPoint.setLocation(currentPoint.getX(), 0);
}
final double maxX = getSize().getWidth() - mapViewport.getExtentSize().getWidth();
final double maxY = getSize().getHeight() - mapViewport.getExtentSize().getHeight();
if (currentPoint.getX() > maxX) {
currentPoint.setLocation(maxX, currentPoint.getY());
}
if (currentPoint.getY() > maxY) {
currentPoint.setLocation(currentPoint.getX(), maxY);
}
mapViewport.setViewPosition(currentPoint);
}
}
public void scrollNodeToVisible(final NodeView node) {
scrollNodeToVisible(node, 0);
}
public void scrollNodeToVisible(final NodeView node, final int extraWidth) {
if (nodeToBeCentered != null) {
if (node != nodeToBeCentered) {
centerNode(node, false);
}
return;
}
if (!isValid()) {
nodeToBeVisible = node;
this.extraWidth = extraWidth;
return;
}
final int HORIZ_SPACE = 10;
final int HORIZ_SPACE2 = 20;
final int VERT_SPACE = 5;
final int VERT_SPACE2 = 10;
final JComponent nodeContent = node.getContent();
int width = nodeContent.getWidth();
if (extraWidth < 0) {
width -= extraWidth;
nodeContent.scrollRectToVisible(new Rectangle(-HORIZ_SPACE + extraWidth, -VERT_SPACE, width + HORIZ_SPACE2,
nodeContent.getHeight() + VERT_SPACE2));
}
else {
width += extraWidth;
nodeContent.scrollRectToVisible(new Rectangle(-HORIZ_SPACE, -VERT_SPACE, width + HORIZ_SPACE2, nodeContent
.getHeight()
+ VERT_SPACE2));
}
}
/**
* Select the node, resulting in only that one being selected.
*/
public void selectAsTheOnlyOneSelected(final NodeView newSelected) {
if(! newSelected.getModel().isVisible())
throw new AssertionError("select invisible node");
if (ResourceController.getResourceController().getBooleanProperty("center_selected_node")) {
centerNode(newSelected, true);
}
else {
scrollNodeToVisible(newSelected);
}
selectAsTheOnlyOneSelected(newSelected, true);
setSiblingMaxLevel(newSelected.getModel().getNodeLevel(false));
}
public void selectAsTheOnlyOneSelected(final NodeView newSelected, final boolean requestFocus) {
if (requestFocus) {
newSelected.requestFocusInWindow();
}
scrollNodeToVisible(newSelected);
if(selection.size() == 1 && getSelected().equals(newSelected)){
return;
}
final NodeView[] oldSelecteds = selection.toArray();
selection.select(newSelected);
if (newSelected.getModel().getParentNode() != null) {
((NodeView) newSelected.getParent()).setPreferredChild(newSelected);
}
newSelected.repaintSelected();
for (final NodeView oldSelected : oldSelecteds) {
if (oldSelected != null) {
oldSelected.repaintSelected();
}
}
}
/**
* Select the node and his descendants. On extend = false clear up the
* previous selection. if extend is false, the past selection will be empty.
* if yes, the selection will extended with this node and its children
*/
private void addBranchToSelection(final NodeView newlySelectedNodeView) {
if (newlySelectedNodeView.isContentVisible()) {
addSelected(newlySelectedNodeView, false);
}
for (final NodeView target : newlySelectedNodeView.getChildrenViews()) {
addBranchToSelection(target);
}
}
void selectContinuous(final NodeView newSelected) {
if(newSelected.isRoot()){
selection.add(newSelected);
scrollNodeToVisible(newSelected);
return;
}
final NodeView parentView = newSelected.getParentView();
final boolean isLeft = newSelected.isLeft();
final NodeModel parent = parentView.getModel();
final int newIndex = parent.getIndex(newSelected.getModel());
int indexGapAbove = Integer.MAX_VALUE;
int indexGapBelow = Integer.MIN_VALUE;
final LinkedList<NodeView> childrenViews = parentView.getChildrenViews();
for(NodeView sibling : childrenViews){
if(newSelected == sibling || sibling.isLeft() != isLeft || ! sibling.isSelected())
continue;
final int index2 = parent.getIndex(sibling.getModel());
final int indexGap = newIndex - index2;
if(indexGap > 0){
if(indexGap < indexGapAbove){
indexGapAbove = indexGap;
}
}
else if(indexGapAbove == Integer.MAX_VALUE){
if(indexGap > indexGapBelow){
indexGapBelow = indexGap;
}
}
}
if(indexGapAbove == Integer.MAX_VALUE && indexGapBelow == Integer.MIN_VALUE){
selection.add(newSelected);
scrollNodeToVisible(newSelected);
return;
}
NodeView lastSelected = newSelected;
for(NodeView sibling : childrenViews){
if(sibling.isLeft() != isLeft)
continue;
final int index2 = parent.getIndex(sibling.getModel());
final int indexGap = newIndex - index2;
if(indexGap >= 0 && indexGapAbove < Integer.MAX_VALUE && indexGap < indexGapAbove
|| indexGap <= 0 && indexGapAbove == Integer.MAX_VALUE && indexGapBelow > Integer.MIN_VALUE && indexGap > indexGapBelow){
selection.add(sibling);
lastSelected = sibling;
}
}
scrollNodeToVisible(lastSelected);
}
public void setMoveCursor(final boolean isHand) {
final int requiredCursor = (isHand && !disableMoveCursor) ? Cursor.MOVE_CURSOR : Cursor.DEFAULT_CURSOR;
if (getCursor().getType() != requiredCursor) {
setCursor(requiredCursor != Cursor.DEFAULT_CURSOR ? new Cursor(requiredCursor) : null);
}
}
void setSiblingMaxLevel(final int level) {
siblingMaxLevel = level;
}
private void setViewPositionAfterValidate() {
if(nodeToBeCentered != null){
centerNode(nodeToBeCentered, slowScroll);
return;
}
if (anchorContentLocation.getX() == 0 && anchorContentLocation.getY() == 0) {
return;
}
final JViewport vp = (JViewport) getParent();
final Point viewPosition = vp.getViewPosition();
final Point oldAnchorContentLocation = anchorContentLocation;
final Point newAnchorContentLocation = getAnchorCenterPoint();
if (anchor != getRoot()) {
anchor = getRoot();
anchorContentLocation = getAnchorCenterPoint();
}
else {
anchorContentLocation = newAnchorContentLocation;
}
final int deltaX = newAnchorContentLocation.x - oldAnchorContentLocation.x;
final int deltaY = newAnchorContentLocation.y - oldAnchorContentLocation.y;
if (deltaX != 0 || deltaY != 0) {
viewPosition.x += deltaX;
viewPosition.y += deltaY;
final int scrollMode = vp.getScrollMode();
vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
vp.setViewPosition(viewPosition);
vp.setScrollMode(scrollMode);
}
else {
repaintVisible();
}
if (nodeToBeVisible != null) {
final int scrollMode = vp.getScrollMode();
vp.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
scrollNodeToVisible(nodeToBeVisible, extraWidth);
vp.setScrollMode(scrollMode);
nodeToBeVisible = null;
}
}
public void setZoom(final float zoom) {
this.zoom = zoom;
anchorToSelected(getSelected(), CENTER_ALIGNMENT, CENTER_ALIGNMENT);
getRoot().updateAll();
adjustBackgroundComponentScale();
}
private void adjustBackgroundComponentScale() {
if (backgroundComponent != null) {
if (fitToViewport) {
final JViewport vp = (JViewport) getParent();
final Dimension viewPortSize = vp.getVisibleRect().getSize();
((ScalableComponent) backgroundComponent).setFinalViewerSize(viewPortSize);
}
else {
((ScalableComponent) backgroundComponent).setMaximumComponentSize(getPreferredSize());
((ScalableComponent) backgroundComponent).setFinalViewerSize(zoom);
}
}
}
/**
* Add the node to the selection if it is not yet there, remove it
* otherwise.
* @param requestFocus
*/
private void toggleSelected(final NodeView nodeView) {
if (isSelected(nodeView)) {
if(selection.size() > 1)
selection.deselect(nodeView);
}
else {
selection.add(nodeView);
scrollNodeToVisible(nodeView);
}
}
private void validateSelecteds() {
if (selectedsValid) {
return;
}
selectedsValid = true;
final NodeView selectedView = getSelected();
if(selectedView == null){
final NodeView root = getRoot();
selectAsTheOnlyOneSelected(root);
centerNode(root, false);
return;
}
final NodeModel selectedNode = selectedView.getModel();
final ArrayList<NodeView> selectedNodes = new ArrayList<NodeView>(getSelection().size());
for (final NodeView nodeView : getSelection()) {
if (nodeView != null) {
selectedNodes.add(nodeView);
}
}
selection.clear();
for (final NodeView nodeView : selectedNodes) {
if (nodeView.isContentVisible()) {
selection.add(nodeView);
}
}
if (getSelected() != null) {
return;
}
for(NodeModel node = selectedNode.getParentNode(); node != null; node = node.getParentNode()){
final NodeView newNodeView = getNodeView(node);
if(newNodeView != null && newNodeView.isContentVisible() ){
selectAsTheOnlyOneSelected(newNodeView);
return;
}
}
selectAsTheOnlyOneSelected(getRoot());
}
/*
* (non-Javadoc)
* @see java.awt.Container#validateTree()
*/
@Override
protected void validateTree() {
validateSelecteds();
getRoot().validateTree();
super.validateTree();
setViewPositionAfterValidate();
}
public void onPreNodeMoved(final NodeModel oldParent, final int oldIndex, final NodeModel newParent,
final NodeModel child, final int newIndex) {
}
public void repaintVisible() {
final JViewport vp = (JViewport) getParent();
repaint(vp.getViewRect());
}
public void propertyChanged(String propertyName, String newValue, String oldValue) {
if(propertyName.equals(TextController.MARK_TRANSFORMED_TEXT))
UITools.repaintAll(getRoot());
}
public void selectVisibleAncestorOrSelf(NodeView preferred) {
while(! preferred.getModel().isVisible())
preferred = preferred.getParentView();
selectAsTheOnlyOneSelected(preferred);
}
public Font getDefaultNoteFont() {
return noteFont;
}
public Font getDetailFont() {
return detailFont;
}
public Color getDetailForeground() {
return detailForeground;
}
public Color getDetailBackground() {
return detailBackground;
}
private boolean isSelected() {
return Controller.getCurrentController().getMapViewManager().getMapViewComponent() == MapView.this;
}
void selectIfSelectionIsEmpty(NodeView nodeView) {
if(selection.selectedNode == null)
selectAsTheOnlyOneSelected(nodeView);
}
private boolean isAncorPositionSet() {
return anchorContentLocation.getX() != 0 || anchorContentLocation.getY() != 0;
}
public static MapView getMapView(final Component component) {
if(component instanceof MapView)
return (MapView) component;
return (MapView) SwingUtilities.getAncestorOfClass(MapView.class, component);
}
public void select() {
getModeController().getController().getMapViewManager().changeToMapView(this);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
628f7c2e3e1da6fa332105f2354c2fd46490cd64 | 35edc1b0607a23c198237bd32959d61b333c4569 | /part09-Part09_04.DifferentKindsOfBoxes/src/main/java/OneItemBox.java | d693399232eb63784dea4f3b7f4c2a1834640bf6 | [
"MIT"
] | permissive | boardinary/JavaMooc2 | 5160df9391329c7b7d9e8d233809d576d62dbc73 | 9f55a98c2c1ee969e2bed55814065356d876bb0a | refs/heads/main | 2022-12-30T06:41:27.466046 | 2020-10-24T11:44:07 | 2020-10-24T11:44:07 | 306,867,952 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java |
import java.util.HashSet;
public class OneItemBox extends Box {
private HashSet<Item> item;
public OneItemBox() {
this.item = new HashSet<>();
}
public void add(Item item) {
if (this.item.isEmpty()) {
this.item.add(item);
}
}
public boolean isInBox(Item item) {
return this.item.contains(item);
}
}
| [
"boardinary@gmail.com"
] | boardinary@gmail.com |
30b979cb5cbe1b39c6c3c52f0111e3f1a2a75509 | 0645367d52746a07dd92f370da09e69b388dee02 | /src/main/java/com/gwangple/matwiki/login/controller/LoginController.java | 379fea00994275f303b8a08f7782cfa6b8bd7e10 | [] | no_license | pakooon/MatWiki | 88a73a55bbe97741133a86699b5e72dc3bbea42d | ecde43dc2ae4abb69e9a95c37132175f1fae46ec | refs/heads/master | 2021-01-18T15:41:03.691671 | 2017-08-15T10:53:48 | 2017-08-15T10:53:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,921 | java | package com.gwangple.matwiki.login.controller;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gwangple.matwiki.common.service.CommService;
import com.gwangple.matwiki.common.utils.CommonUtils;
import com.gwangple.matwiki.login.dto.JoinMembershipDTO;
import com.gwangple.matwiki.login.dto.LoginDto;
import com.gwangple.matwiki.login.service.LoginService;
@Controller
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Resource(name="loginService")
private LoginService loginService;
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
@Resource(name="commService")
private CommService commService;
public void setCommService(CommService commService) {
this.commService = commService;
}
//회원가입
@RequestMapping(value = "/joinMembership", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> joinMembership(Locale locale, @Valid JoinMembershipDTO joinMembershipDTO, BindingResult bindingResult, HttpSession sess) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String responseType = "";
//파라미터:: 회원아이디(이메일주소), 비밀번호, 비밀번호 확인, 회원 ip 주소
//1. 비밀번호 및 비밀번호 확인 암호화
//2. 암호화된 비밀번호 비교
//3. 아이디, 비밀번호IP저장
responseType = loginService.getJoinValidationCheck(joinMembershipDTO);
if( "0000".equals(responseType) ){
//회원가입
//loginService.insJoinMembership(joinMembershipDTO);
}
map.put("responseType", responseType);
return map;
}
/**
* 로그인 실행
* @param locale
* @param loginDto
* @param bindingResult
* @return
* @throws SQLException
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> login(Locale locale, @Valid LoginDto loginDto, BindingResult bindingResult, HttpSession sess) throws SQLException {
String sessStr = (String)sess.getAttribute("ss");
/*
* 테스트 코드 start ========================================================================
*/
logger.info("세션값1::[{}]"+sessStr);
if(sessStr == null){
sess.setAttribute("ss", "sessSuccess!!");
sessStr = (String)sess.getAttribute("ss");
}
logger.info("세션값2::[{}]"+sessStr);
String seqTest = commService.getSeqGenerator("SEQ_NON_USER_INFO");
logger.info("시퀀스번호::[{}]",seqTest);
Map<String, Object> map = new HashMap<String, Object>();
map.put("seq", seqTest);
/*
* 테스트 코드 end ========================================================================
*/
//파라미터 validation check
if(bindingResult.hasErrors()){
logger.info("필수파라미터 오류!!");
return null;
}
////아이디 패스워드 확인
int loginResult = loginService.loginCheck(loginDto);
if( loginResult == 0 ){
//아이디가 없거나 패스워드가 틀립니다
return null;
}else if( loginResult == 1 ){
//로그인 성공
//세션 설정
//userDto로 만들어서 관리
return null;
}else if( loginResult <= -1 ){
//오류
return null;
}
return map;
}
//로그인 확인
//자동로그인 기능
//페이스북 로그인(보류)
//아이디 찾기
//비밀번호 찾기
}
| [
"rapbby@naver.com"
] | rapbby@naver.com |
b63a70fd03ca2150668559b61c85e8f4920b294e | addf69d2fb04007b7bef0f281763459e68481ad5 | /leave_managment_system/Android-SmartWebView-master/Signup_form/app/src/test/java/com/example/signup_form/ExampleUnitTest.java | 886ff97ad4e7dfd056cd0966746a08a7ee33bbf0 | [] | no_license | moinsahab/leave_managment_system | 2131ec1fd3a68c0eff2e8deac320b4f172f23c1c | c81f71124f4302b31d0ab2798f552f95d29e64ac | refs/heads/master | 2023-04-23T14:22:29.862209 | 2021-05-04T12:50:54 | 2021-05-04T12:50:54 | 364,251,269 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 384 | java | package com.example.signup_form;
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);
}
} | [
"ammartanweer7370@gmail.com"
] | ammartanweer7370@gmail.com |
3a80196bf183e8a9acb9a0abab09b6764db34dac | 2b1743259fa0c2696d0d5929de361594f5aa3174 | /CafeManage/src/main/java/local/CafeDeleted.java | 89562e8ae8d9c55a8d18043e0bbea649f81b2e79 | [] | no_license | rlatjdwo555/SKtarbucks | 2d6e82df96f60350aed1ba946ad1b729262ab800 | f0f8aea6b0159e288e60401e9e475f5f67c58ba1 | refs/heads/main | 2023-06-19T08:40:27.489826 | 2021-07-20T02:45:06 | 2021-07-20T02:45:06 | 385,084,187 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 695 | java |
package local;
public class CafeDeleted extends AbstractEvent {
private Long id;
private String cafeNm;
private Long pCnt;
private String chkDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCafeNm() {
return cafeNm;
}
public void setCafeNm(String cafeNm) {
this.cafeNm = cafeNm;
}
public Long getPCnt() {
return pCnt;
}
public void setPCnt(Long pCnt) {
this.pCnt = pCnt;
}
public String getChkDate() {
return chkDate;
}
public void setChkDate(String chkDate) {
this.chkDate = chkDate;
}
}
| [
"ksj0495@naver.com"
] | ksj0495@naver.com |
287104aaec82b6f9f5929261bd1201513969c3bd | 04ee30d21ca63bd81fa321529f789686bc281970 | /第6章/src/exercise/Quiz6_1_1.java | a680a3dbd70d7e998913d90e707111cda0b51f3f | [] | no_license | yuta-pharmacy2359/Java_Object | f594416ea2a84c9c4c292dd10fa605831ac4bc3d | 3fe2a55bc86857f11f7c8615993e988b404f6e4c | refs/heads/master | 2023-08-20T13:03:31.771546 | 2021-10-16T11:18:23 | 2021-10-16T11:18:23 | 410,186,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 376 | java | package exercise;
public class Quiz6_1_1 {
/*
A ← B ← C
A ← B ← D ← E
間違っているもの
(1) CはAのサブクラスである → x
(2) CはEのスーパークラスである → ◯
(3) EはAのサブクラスである → x
(4) BはEのスーパークラスである → x
(5) AはDのスーパークラスである → x
*/
} | [
"yuta.shogai@gmail.com"
] | yuta.shogai@gmail.com |
0f8ea50d975a41af0a3878aa9ac8dafe5e7a5fe7 | 6f3b475dfa253ab9e9533428088790ef5c6898b2 | /Annotations/src/autowire/model/Address.java | 85429d99137768e537332bb820e179a384e65795 | [] | no_license | yusufsevinc/springLearnExamples | 710bf2f2d4380e3250a976f7e70e6f8607581f5d | 2fc8caa5a13e97557297d8d9e273888a7287111b | refs/heads/master | 2023-07-09T13:05:10.085534 | 2021-08-05T13:59:56 | 2021-08-18T14:59:12 | 381,757,686 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 439 | java | package autowire.model;
public class Address {
private String city;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "Address [city=" + city + ", country=" + country + "]";
}
}
| [
"1yusufsevinc@gmail.com"
] | 1yusufsevinc@gmail.com |
28291ad2a6b0ac6021077c4daae25cad9bdd9333 | 63e36d35f51bea83017ec712179302a62608333e | /OnePlusCamera/android/support/v4/util/TimeUtils.java | 9255be44ee25c9fbcf1928d3dff76165138e6fcf | [] | no_license | hiepgaf/oneplus_blobs_decompiled | 672aa002fa670bdcba8fdf34113bc4b8e85f8294 | e1ab1f2dd111f905ff1eee18b6a072606c01c518 | refs/heads/master | 2021-06-26T11:24:21.954070 | 2017-08-26T12:45:56 | 2017-08-26T12:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,639 | java | package android.support.v4.util;
import java.io.PrintWriter;
public class TimeUtils
{
public static final int HUNDRED_DAY_FIELD_LEN = 19;
private static final int SECONDS_PER_DAY = 86400;
private static final int SECONDS_PER_HOUR = 3600;
private static final int SECONDS_PER_MINUTE = 60;
private static char[] sFormatStr = new char[24];
private static final Object sFormatSync = new Object();
private static int accumField(int paramInt1, int paramInt2, boolean paramBoolean, int paramInt3)
{
if (paramInt1 > 99) {
return paramInt2 + 3;
}
if (!paramBoolean) {}
for (;;)
{
if (paramInt1 <= 9) {
break label32;
}
return paramInt2 + 2;
if (paramInt3 >= 3) {
break;
}
}
label32:
if (!paramBoolean) {
label36:
if (!paramBoolean) {
break label52;
}
}
label52:
while (paramInt1 > 0)
{
return paramInt2 + 1;
if (paramInt3 >= 2) {
break;
}
break label36;
}
return 0;
}
public static void formatDuration(long paramLong1, long paramLong2, PrintWriter paramPrintWriter)
{
if (paramLong1 == 0L)
{
paramPrintWriter.print("--");
return;
}
formatDuration(paramLong1 - paramLong2, paramPrintWriter, 0);
}
public static void formatDuration(long paramLong, PrintWriter paramPrintWriter)
{
formatDuration(paramLong, paramPrintWriter, 0);
}
public static void formatDuration(long paramLong, PrintWriter paramPrintWriter, int paramInt)
{
synchronized (sFormatSync)
{
paramInt = formatDurationLocked(paramLong, paramInt);
paramPrintWriter.print(new String(sFormatStr, 0, paramInt));
return;
}
}
public static void formatDuration(long paramLong, StringBuilder paramStringBuilder)
{
synchronized (sFormatSync)
{
int i = formatDurationLocked(paramLong, 0);
paramStringBuilder.append(sFormatStr, 0, i);
return;
}
}
private static int formatDurationLocked(long paramLong, int paramInt)
{
char[] arrayOfChar;
if (sFormatStr.length >= paramInt)
{
arrayOfChar = sFormatStr;
if (paramLong != 0L) {}
}
else
{
for (;;)
{
if (paramInt - 1 <= 0)
{
arrayOfChar[0] = '0';
return 1;
sFormatStr = new char[paramInt];
break;
}
arrayOfChar[0] = ' ';
}
}
int i;
int m;
label67:
int i4;
int j;
label95:
int n;
label105:
int i1;
int k;
label117:
int i3;
label144:
boolean bool;
if (paramLong <= 0L)
{
i = 1;
if (i != 0) {
break label288;
}
m = 43;
i4 = (int)(paramLong % 1000L);
i = (int)Math.floor(paramLong / 1000L);
j = 0;
if (i > 86400) {
break label298;
}
if (i > 3600) {
break label315;
}
n = 0;
if (i > 60) {
break label338;
}
i1 = 0;
k = i;
if (paramInt != 0) {
break label360;
}
i3 = 0;
arrayOfChar[i3] = ((char)m);
m = i3 + 1;
if (paramInt != 0) {
break label506;
}
paramInt = 0;
j = printField(arrayOfChar, j, 'd', m, false, 0);
if (j != m) {
break label511;
}
bool = false;
label169:
if (paramInt != 0) {
break label517;
}
i = 0;
label175:
j = printField(arrayOfChar, n, 'h', j, bool, i);
if (j != m) {
break label522;
}
bool = false;
label201:
if (paramInt != 0) {
break label528;
}
i = 0;
label207:
j = printField(arrayOfChar, i1, 'm', j, bool, i);
if (j != m) {
break label533;
}
bool = false;
label233:
if (paramInt != 0) {
break label539;
}
i = 0;
label239:
i = printField(arrayOfChar, k, 's', j, bool, i);
if (paramInt != 0) {
break label544;
}
}
label258:
for (paramInt = 0;; paramInt = 3)
{
paramInt = printField(arrayOfChar, i4, 'm', i, true, paramInt);
arrayOfChar[paramInt] = 's';
return paramInt + 1;
i = 0;
break;
label288:
paramLong = -paramLong;
m = 45;
break label67;
label298:
j = i / 86400;
i -= 86400 * j;
break label95;
label315:
k = i / 3600;
n = k;
i -= k * 3600;
break label105;
label338:
k = i / 60;
i1 = k;
k = i - k * 60;
break label117;
label360:
i = accumField(j, 1, false, 0);
label376:
label395:
label414:
int i2;
if (i <= 0)
{
bool = false;
i += accumField(n, 1, bool, 2);
if (i > 0) {
break label489;
}
bool = false;
i += accumField(i1, 1, bool, 2);
if (i > 0) {
break label495;
}
bool = false;
i2 = i + accumField(k, 1, bool, 2);
if (i2 > 0) {
break label501;
}
}
label489:
label495:
label501:
for (i = 0;; i = 3)
{
i3 = accumField(i4, 2, true, i);
i = 0;
i2 = i3 + 1 + i2;
for (;;)
{
i3 = i;
if (i2 >= paramInt) {
break;
}
arrayOfChar[i] = ' ';
i2 += 1;
i += 1;
}
bool = true;
break label376;
bool = true;
break label395;
bool = true;
break label414;
}
label506:
paramInt = 1;
break label144;
label511:
bool = true;
break label169;
label517:
i = 2;
break label175;
label522:
bool = true;
break label201;
label528:
i = 2;
break label207;
label533:
bool = true;
break label233;
label539:
i = 2;
break label239;
label544:
if (i == m) {
break label258;
}
}
}
private static int printField(char[] paramArrayOfChar, int paramInt1, char paramChar, int paramInt2, boolean paramBoolean, int paramInt3)
{
label10:
int i;
if (paramBoolean)
{
if (paramBoolean) {
break label88;
}
if (paramInt1 > 99) {
break label94;
}
i = paramInt2;
label19:
if (paramBoolean) {
break label126;
}
label24:
if (paramInt1 <= 9) {
break label135;
}
label30:
paramInt2 = paramInt1 / 10;
paramArrayOfChar[i] = ((char)(char)(paramInt2 + 48));
i += 1;
paramInt1 -= paramInt2 * 10;
}
for (;;)
{
paramArrayOfChar[i] = ((char)(char)(paramInt1 + 48));
paramInt1 = i + 1;
paramArrayOfChar[paramInt1] = ((char)paramChar);
return paramInt1 + 1;
if (paramInt1 > 0) {
break;
}
return paramInt2;
label88:
if (paramInt3 < 3) {
break label10;
}
label94:
int j = paramInt1 / 100;
paramArrayOfChar[paramInt2] = ((char)(char)(j + 48));
i = paramInt2 + 1;
paramInt1 -= j * 100;
break label19;
label126:
if (paramInt3 < 2) {
break label24;
}
break label30;
label135:
if (paramInt2 != i) {
break label30;
}
}
}
}
/* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/android/support/v4/util/TimeUtils.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"joshuous@gmail.com"
] | joshuous@gmail.com |
e6a7847971c7d51ef22ffb902e66a9e984f9dcff | 93f3578669fb0d0030a550316aebe0d7b4221631 | /rpc-supplychain/src/main/java/cn/com/glsx/supplychain/kafka/OperatorExportKafkaMessage.java | 20754f8fe3ee253ec5c6cdc388cdf9959c67d8e6 | [] | no_license | shanghaif/supplychain | 4d7de62809b6c88ac5080a85a77fc4bf3d856db8 | c36c771b0304c5739de98bdfc322c0082a9e523d | refs/heads/master | 2023-02-09T19:01:35.562699 | 2021-01-05T09:39:11 | 2021-01-05T09:39:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 684 | java | package cn.com.glsx.supplychain.kafka;
public class OperatorExportKafkaMessage {
private Integer taskCfgId;
private String userName;
private ExportMerchantOrder merchantOrderExport;
public Integer getTaskCfgId() {
return taskCfgId;
}
public void setTaskCfgId(Integer taskCfgId) {
this.taskCfgId = taskCfgId;
}
public ExportMerchantOrder getMerchantOrderExport() {
return merchantOrderExport;
}
public void setMerchantOrderExport(ExportMerchantOrder merchantOrderExport) {
this.merchantOrderExport = merchantOrderExport;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
| [
"3064741443@qq.com"
] | 3064741443@qq.com |
46c91f66c3df1cede9837297ae7a91a9d962d8ad | d8782a3691b0f90e5f447b4422f52a60b50eef59 | /src/com/oca/loop/eleven/Test.java | 6757aa6b4738faaa3785ef33952adb268b76af3b | [] | no_license | Mehran-at/OCA-JavaSE8 | aebf50eb0485dad9bbf2eb23b588bc8607e9eb13 | 8254b936396038a9d049cc4bfe6399021c7934b2 | refs/heads/master | 2023-04-17T09:10:55.252715 | 2021-05-02T20:48:05 | 2021-05-02T20:48:05 | 362,449,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 379 | java | package com.oca.loop.eleven;
class Test {
public static void main(String[] args) {
int x = 1;
while (checkAndIncrement(x)) {
System.out.println(x);
}
}
private static boolean checkAndIncrement(int x) {
if (x < 5) {
x++;
return true;
} else {
return false;
}
}
}
| [
"mehran.hosseini@ebcont.com"
] | mehran.hosseini@ebcont.com |
eacb5e880b22a1b7166f3bc7d38bce4dca3d4193 | 336392d8707252fcff26fcf2c8a8c852ecb6a7ed | /achartengine/demo/org/achartengine/chartdemo/demo/chart/WeightDialChart.java | 0d3f8c3e2f8863c719fe45277c4d3af1fb0e057e | [] | no_license | hackugyo/AChartEngine | 3e9a30061bdfe47b407f8c5e320f87784063b210 | 2289cd7670697f7bbde6479df794dd492e5d4ba0 | refs/heads/master | 2020-12-24T22:20:40.920447 | 2012-09-03T07:28:52 | 2012-09-03T07:28:52 | 5,625,137 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,687 | java | /**
* Copyright (C) 2009, 2010 SC 4ViewSoft SRL
*
* 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.achartengine.chartdemo.demo.chart;
import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DialRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.DialRenderer.Type;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
/**
* Budget demo pie chart.
*/
public class WeightDialChart extends AbstractDemoChart {
/**
* Returns the chart name.
* @return the chart name
*/
public String getName() {
return "Weight chart";
}
/**
* Returns the chart description.
* @return the chart description
*/
public String getDesc() {
return "The weight indicator (dial chart)";
}
/**
* Executes the chart demo.
* @param context the context
* @return the built intent
*/
public Intent execute(Context context) {
CategorySeries category = new CategorySeries("Weight indic");
category.add("Current", 75);
category.add("Minimum", 65);
category.add("Maximum", 90);
DialRenderer renderer = new DialRenderer();
renderer.setChartTitleTextSize(20);
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
renderer.setMargins(new int[] {20, 30, 15, 0});
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(Color.BLUE);
renderer.addSeriesRenderer(r);
r = new SimpleSeriesRenderer();
r.setColor(Color.rgb(0, 150, 0));
renderer.addSeriesRenderer(r);
r = new SimpleSeriesRenderer();
r.setColor(Color.GREEN);
renderer.addSeriesRenderer(r);
renderer.setLabelsTextSize(10);
renderer.setLabelsColor(Color.WHITE);
renderer.setShowLabels(true);
renderer.setVisualTypes(new DialRenderer.Type[] {Type.ARROW, Type.NEEDLE, Type.NEEDLE});
renderer.setMinValue(0);
renderer.setMaxValue(150);
return ChartFactory.getDialChartIntent(context, category, renderer, "Weight indicator");
}
}
| [
"moskvin@netcook.org"
] | moskvin@netcook.org |
1e308fd497aaadb6403eb65678b249a1da36354e | eb295bff5cf78317400eded03d3397a519f3d5ab | /src/main/java/com/adMaroc/Tecdoc/BackOffice/Models/TecdocData/AllocationOfGenArtToSearchStructure.java | 1946697beca3c5fdf2a57c773312f23019c77a47 | [] | no_license | papsukis/Tecdoc-BE | 9aeaa917f5443d542491586495ef1dcb1fbad13c | ca01c97586c84084e39ed39365c649c89493ec59 | refs/heads/master | 2023-06-08T10:41:50.425469 | 2021-06-22T15:56:53 | 2021-06-22T15:56:53 | 331,469,230 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,436 | java | package com.adMaroc.Tecdoc.BackOffice.Models.TecdocData;
;
import com.adMaroc.Tecdoc.BackOffice.Models.TecdocData.compositeKeys.AllocationOfGenArtToSearchStructureId;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name="t_302_allocation_of_genart_to_search_structure")
public class AllocationOfGenArtToSearchStructure {
@EmbeddedId
AllocationOfGenArtToSearchStructureId id;
long dLNr;
long sA;
long sortNr;
long loschFlag;
@MapsId("nodeId")
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "nodeId",
referencedColumnName = "nodeId")
private TecdocSearchStructure tecdocSearchStructure;
@MapsId("genArtNr")
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "genArtNr",
referencedColumnName = "genArtNr")
private GenericArticles genericArticles;
public AllocationOfGenArtToSearchStructure(Map<String,String> datas) {
this.id = id;
this.dLNr = dLNr;
this.sA = sA;
this.sortNr = sortNr;
this.loschFlag = loschFlag;
}
public AllocationOfGenArtToSearchStructureId getId() {
return id;
}
public void setId(AllocationOfGenArtToSearchStructureId id) {
this.id = id;
}
public long getdLNr() {
return dLNr;
}
public void setdLNr(long dLNr) {
this.dLNr = dLNr;
}
public long getsA() {
return sA;
}
public void setsA(long sA) {
this.sA = sA;
}
public long getSortNr() {
return sortNr;
}
public void setSortNr(long sortNr) {
this.sortNr = sortNr;
}
public long getLoschFlag() {
return loschFlag;
}
public void setLoschFlag(long loschFlag) {
this.loschFlag = loschFlag;
}
public TecdocSearchStructure getTecdocSearchStructure() {
return tecdocSearchStructure;
}
public void setTecdocSearchStructure(TecdocSearchStructure tecdocSearchStructure) {
this.tecdocSearchStructure = tecdocSearchStructure;
}
public GenericArticles getGenericArticles() {
return genericArticles;
}
public void setGenericArticles(GenericArticles genericArticles) {
this.genericArticles = genericArticles;
}
}
| [
"ali.belemlih@gmail.com"
] | ali.belemlih@gmail.com |
9505224004f0738b6c6901b00910ec0cf37b0f85 | a1b8a83d2c7360284072548e5d0e3e16d79a6b58 | /wyait-manage/src/main/java/com/wyait/manage/utils/ShiroFilterUtils.java | 7a4026c01e3db870d6f634c239b24377dd333c61 | [] | no_license | adolphs/system | 443822789243c4590456e24dd5294430336f49cf | 9a391d5249ac44b498b2e628dec5945a3acebf3c | refs/heads/main | 2023-02-27T02:07:43.527298 | 2021-02-08T09:55:44 | 2021-02-08T09:55:44 | 305,930,810 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,227 | java | package com.wyait.manage.utils;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wyait.manage.entity.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @项目名称:wyait-manager
* @类名称:ShiroFilterUtils
* @类描述:shiro工具类
* @创建人:wyait
* @创建时间:2018年4月24日 下午5:12:04
* @version:
*/
public class ShiroFilterUtils {
private static final Logger logger = LoggerFactory
.getLogger(ShiroFilterUtils.class);
private final static ObjectMapper objectMapper = new ObjectMapper();
/**
*
* @描述:判断请求是否是ajax
* @创建人:wyait
* @创建时间:2018年4月24日 下午5:00:22
* @param request
* @return
*/
public static boolean isAjax(ServletRequest request){
String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
if("XMLHttpRequest".equalsIgnoreCase(header)){
logger.debug("shiro工具类【wyait-manager-->ShiroFilterUtils.isAjax】当前请求,为Ajax请求");
return Boolean.TRUE;
}
logger.debug("shiro工具类【wyait-manager-->ShiroFilterUtils.isAjax】当前请求,非Ajax请求");
return Boolean.FALSE;
}
/**
*
* @描述:response输出json
* @创建人:wyait
* @创建时间:2018年4月24日 下午5:14:22
* @param response
* @param result
*/
public static void out(HttpServletResponse response, ResponseResult result){
PrintWriter out = null;
try {
response.setCharacterEncoding("UTF-8");//设置编码
response.setContentType("application/json");//设置返回类型
out = response.getWriter();
out.println(objectMapper.writeValueAsString(result));//输出
logger.error("用户在线数量限制【wyait-manage-->ShiroFilterUtils.out】响应json信息成功");
} catch (Exception e) {
logger.error("用户在线数量限制【wyait-manage-->ShiroFilterUtils.out】响应json信息出错", e);
}finally{
if(null != out){
out.flush();
out.close();
}
}
}
}
| [
"asa_don@163.com"
] | asa_don@163.com |
a6efafc757dcc59307953fdeeb21f5fad5d41d86 | 58a2b991afab5db26a9ad5a27714764dfc7eef8f | /spring-core-own-collection-type-injection/src/main/java/com/raghu/bean/College.java | 60a1085dd6a42212a79c55036d78a165c86a0160 | [] | no_license | raghupulishetti/spring | 09bae32783007b5d4a269cd2f324d7ac79f30654 | 7b5b3d93fea6b8a5b0c755759cfdf0afdb2a6161 | refs/heads/master | 2022-12-21T13:23:05.263278 | 2019-11-07T03:18:59 | 2019-11-07T03:18:59 | 210,146,536 | 0 | 0 | null | 2022-12-16T10:37:06 | 2019-09-22T12:49:53 | Java | UTF-8 | Java | false | false | 708 | java | package com.raghu.bean;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class College {
private List<String> coursesList;
private Set<String> coursesSet;
private Map<String, String> coursesMap;
public List<String> getCoursesList() {
return coursesList;
}
public void setCoursesList(List<String> coursesList) {
this.coursesList = coursesList;
}
public Set<String> getCoursesSet() {
return coursesSet;
}
public void setCoursesSet(Set<String> coursesSet) {
this.coursesSet = coursesSet;
}
public Map<String, String> getCoursesMap() {
return coursesMap;
}
public void setCoursesMap(Map<String, String> coursesMap) {
this.coursesMap = coursesMap;
}
}
| [
"raghupulishetti@gmail.com"
] | raghupulishetti@gmail.com |
6beb20232c72153de3686e49f6224816ae31a294 | 4db09952d8db66be55a149230f94539782fd3773 | /app/src/main/java/com/ayush/moviefinder/activity/MainActivity.java | 7eb29fccabc1b6629e8a2a7e7122868cd506547c | [] | no_license | ricots/movie-finder | c1d9625870be0129e34649274563740c06905f7c | d297079dea614db49f0d8a79ae8c54c0183f5068 | refs/heads/master | 2021-01-17T06:54:58.675658 | 2016-05-23T12:28:29 | 2016-05-23T12:28:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,929 | java | package com.ayush.moviefinder.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TextView;
import com.ayush.moviefinder.R;
import com.ayush.moviefinder.view.AppConstant;
public class MainActivity extends Activity implements OnItemSelectedListener {
private Spinner spinner;
private EditText searchEditText;
private EditText yearEditText;
private String searchText;
private String yearText;
private String movieType;
private TextView footer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
/* Spinner to select movie type */
spinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.type_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
spinner.setAdapter(adapter);
footer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchText = searchEditText.getText().toString().trim();
yearText = yearEditText.getText().toString().trim();
Intent i = new Intent(MainActivity.this, MoviesListActivity.class);
i.putExtra(AppConstant.intentExtras.SEARCH_TEXT, searchText);
i.putExtra(AppConstant.intentExtras.YEAR_TEXT, yearText);
i.putExtra(AppConstant.intentExtras.MOVIE_TYPE, movieType);
MainActivity.this.startActivity(i);
overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
}
});
}
/* Initialising the UI components */
private void initUI() {
searchEditText = (EditText) findViewById(R.id.et_search);
yearEditText = (EditText) findViewById(R.id.et_year_of_release);
spinner = (Spinner) findViewById(R.id.selection_spinner);
footer = (TextView) findViewById(R.id.footer_search);
}
/**
* Getting the movie type that is selected by the user.
* If the user selects "All" then sending empty type to the server so that we will get the complete list
*/
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
movieType = parent.getItemAtPosition(position).toString();
if (movieType.equalsIgnoreCase("All"))
movieType = "";
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| [
"ayush.kedia@nearbuy.com"
] | ayush.kedia@nearbuy.com |
20a546d7031add572219c57ef0ef9403a511a797 | f071803da7cc1c2174fbe4f7daf34c423fc51feb | /src/org/task/It16.java | 0e89ffa88e1c9950ab7bed796e7286d5e4b00ee6 | [] | no_license | Charanbuddy/Iteration-Programs | fd88a26ffa1958d90475f8d925b2efd0136dca98 | 999c1764e75fa437f1115a436906942f4fab07bd | refs/heads/master | 2023-02-21T02:08:59.103742 | 2021-01-27T16:38:44 | 2021-01-27T16:38:44 | 333,156,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 500 | java | package org.task;
import java.util.Scanner;
public class It16 {
public static void main(String[] args) {
// To reverse a string using type conversion(String to Integer Conversion)
Scanner sc = new Scanner(System.in);
System.out.println("Type a string:" + sc);
String n = sc.next();
String name = String.valueOf(n);
String reverse = "";
for (int i = name.length() - 1; i >= 0; i--) {
char c = name.charAt(i);
reverse = reverse + c;
}
System.out.println(reverse);
}
}
| [
"charanbuddy@gmail.com"
] | charanbuddy@gmail.com |
cae101b9e8dfa42bd2c315a2c822476cb1eb6be7 | 425ac2b3d2ba036202c1dc72c561d3a904df33ad | /support/cas-server-support-throttle-couchdb/src/main/java/org/apereo/cas/web/support/CouchDbThrottledSubmissionHandlerInterceptorAdapter.java | ff0e932416dbdfb79c1c9ecbc32e2f668e90746e | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | fogbeam/cas_mirror | fee69b4b1a7bf5cac87da75b209edc3cc3c1d5d6 | b7daea814f1238e95a6674663b2553555a5b2eed | refs/heads/master | 2023-01-07T08:34:26.200966 | 2021-08-12T19:14:41 | 2021-08-12T19:14:41 | 41,710,765 | 1 | 2 | Apache-2.0 | 2022-12-27T15:39:03 | 2015-09-01T01:53:24 | Java | UTF-8 | Java | false | false | 1,864 | java | package org.apereo.cas.web.support;
import org.apereo.cas.couchdb.audit.AuditActionContextCouchDbRepository;
import lombok.val;
import org.apereo.inspektr.audit.AuditActionContext;
import org.apereo.inspektr.common.web.ClientInfoHolder;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.stream.Collectors;
/**
* This is {@link CouchDbThrottledSubmissionHandlerInterceptorAdapter}.
*
* @author Timur Duehr
* @since 6.0.0
*/
public class CouchDbThrottledSubmissionHandlerInterceptorAdapter extends AbstractInspektrAuditHandlerInterceptorAdapter {
private static final String NAME = "CouchDbThrottle";
private final AuditActionContextCouchDbRepository repository;
public CouchDbThrottledSubmissionHandlerInterceptorAdapter(final ThrottledSubmissionHandlerConfigurationContext configurationContext,
final AuditActionContextCouchDbRepository repository) {
super(configurationContext);
this.repository = repository;
}
@Override
public boolean exceedsThreshold(final HttpServletRequest request) {
val clientInfo = ClientInfoHolder.getClientInfo();
val remoteAddress = clientInfo.getClientIpAddress();
val failures = repository.findByThrottleParams(remoteAddress,
getUsernameParameterFromRequest(request),
getConfigurationContext().getAuthenticationFailureCode(),
getConfigurationContext().getApplicationCode(),
LocalDateTime.now(ZoneOffset.UTC).minusSeconds(getConfigurationContext().getFailureRangeInSeconds()))
.stream().map(AuditActionContext::getWhenActionWasPerformed).collect(Collectors.toList());
return calculateFailureThresholdRateAndCompare(failures);
}
@Override
public String getName() {
return NAME;
}
}
| [
"mm1844@gmail.com"
] | mm1844@gmail.com |
56f697b284bba9e969f34ed98cfe344eddfd707d | 0c6429ba16d93c6d0f94c881d74b9f5b233e5120 | /Exam1/src/main/java/com/hand/api/service/impl/FilmService.java | fce50a842826c58c72b627e18b515598c748107c | [] | no_license | phr27/JavaTest5 | dcd82a0d02c4c2b51113ecd0aa237a7c2edc5223 | d45471452bd2da550ffa01e51d729be08caf2e2b | refs/heads/master | 2020-03-26T05:03:05.684704 | 2018-08-13T10:32:50 | 2018-08-13T10:32:50 | 144,536,076 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 760 | java | package com.hand.api.service.impl;
import com.github.pagehelper.PageHelper;
import com.hand.api.service.IFilmService;
import com.hand.domain.entity.Film;
import com.hand.domain.entity.Page;
import com.hand.infra.mapper.FilmMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FilmService implements IFilmService {
@Autowired
private FilmMapper filmMapper;
public List<Film> selectFilmsByPage(Page page) {
return filmMapper.selectByPage(page);
}
public List<Film> selectFilmsWithPageHelper(Integer page, Integer pageSize) {
PageHelper.startPage(page, pageSize);
return filmMapper.selectAll();
}
}
| [
"phr27@163.com"
] | phr27@163.com |
b0e0216b36316a47828de5ad58e2fe382e5a477d | a82d8e866f993cf843f9e8f4e900b7db20dbb396 | /tr/org/lyk2016/todo/Todo.java | f375b5151de772e21a62db24a6db422edfc3f5e8 | [] | no_license | cankayaozan/producer-consumer | 01ecb779c5617858779f4c78bd33867163b52eb7 | 28876449791287d2f48807fbedd29d7640b67dfc | refs/heads/master | 2020-09-26T20:52:58.538724 | 2016-08-18T14:29:10 | 2016-08-18T14:29:10 | 66,003,796 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 519 | java | package tr.org.lyk2016.todo;
public class Todo {
private String description;
private boolean done;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Todo(String description) {
super();
this.description = description;
}
public String getCheckbox() {
return done ? "☑" : "�";
}
}
| [
"ozan"
] | ozan |
1d4daa5de0e4414e45b95ea6ca7672fa590d34e9 | aedd4a32c28a1ee1fcaa644bde2f01b66de5560f | /spring-test/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatchersIntegrationTests.java | fff82c63274408f9e66ac4e6507543aa566e3b7f | [
"Apache-2.0"
] | permissive | jmgx001/spring-framework-4.3.x | 262bc09fe914f2df7d75bd376aa46cb326d0abe0 | 5051c9f0d1de5c5ce962e55e3259cc5e1116e9d6 | refs/heads/master | 2023-07-13T11:18:35.673302 | 2021-08-12T15:59:07 | 2021-08-12T15:59:07 | 395,353,329 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,398 | java | /*
* Copyright 2002-2016 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.test.web.client.samples.matchers;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import org.junit.After;
import org.junit.Test;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
/**
* Examples of defining expectations on JSON request content with
* <a href="https://github.com/jayway/JsonPath">JsonPath</a> expressions.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @see org.springframework.test.web.client.match.JsonPathRequestMatchers
* @see org.springframework.test.web.client.match.JsonPathRequestMatchersTests
*/
public class JsonPathRequestMatchersIntegrationTests {
private static final MultiValueMap<String, Person> people = new LinkedMultiValueMap<>();
static {
people.add("composers", new Person("Johann Sebastian Bach"));
people.add("composers", new Person("Johannes Brahms"));
people.add("composers", new Person("Edvard Grieg"));
people.add("composers", new Person("Robert Schumann"));
people.add("performers", new Person("Vladimir Ashkenazy"));
people.add("performers", new Person("Yehudi Menuhin"));
}
private final RestTemplate restTemplate =
new RestTemplate(Collections.singletonList(new MappingJackson2HttpMessageConverter()));
private final MockRestServiceServer mockServer = MockRestServiceServer.createServer(this.restTemplate);
@Test
public void exists() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0]").exists())
.andExpect(jsonPath("$.composers[1]").exists())
.andExpect(jsonPath("$.composers[2]").exists())
.andExpect(jsonPath("$.composers[3]").exists())
.andRespond(withSuccess());
}
@Test
public void doesNotExist() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[?(@.name == 'Edvard Grieeeeeeg')]").doesNotExist())
.andExpect(jsonPath("$.composers[?(@.name == 'Robert Schuuuuuuman')]").doesNotExist())
.andExpect(jsonPath("$.composers[4]").doesNotExist())
.andRespond(withSuccess());
}
@Test
public void value() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach"))
.andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin"))
.andRespond(withSuccess());
}
@Test
public void hamcrestMatchers() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach")))
.andExpect(jsonPath("$.performers[1].name").value(equalTo("Yehudi Menuhin")))
.andExpect(jsonPath("$.composers[0].name", startsWith("Johann")))
.andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy")))
.andExpect(jsonPath("$.performers[1].name", containsString("di Me")))
.andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))
.andExpect(jsonPath("$.composers[:3].name", hasItem("Johannes Brahms")))
.andRespond(withSuccess());
}
@Test
public void hamcrestMatchersWithParameterizedJsonPaths() throws Exception {
String composerName = "$.composers[%s].name";
String performerName = "$.performers[%s].name";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath(composerName, 0).value(startsWith("Johann")))
.andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy")))
.andExpect(jsonPath(performerName, 1).value(containsString("di Me")))
.andExpect(jsonPath(composerName, 1).value(isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))
.andRespond(withSuccess());
}
@Test
public void isArray() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers").isArray())
.andRespond(withSuccess());
}
@Test
public void isString() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].name").isString())
.andRespond(withSuccess());
}
@Test
public void isNumber() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].someDouble").isNumber())
.andRespond(withSuccess());
}
@Test
public void isBoolean() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].someBoolean").isBoolean())
.andRespond(withSuccess());
}
@After
public void performRequestAndVerify() throws URISyntaxException {
this.restTemplate.put(new URI("/composers"), people);
this.mockServer.verify();
}
}
| [
"1119459519@qq.com"
] | 1119459519@qq.com |
1e5adf4a51bd6cb9fd8f50d2d3185957ef1114e6 | 361a8ea9d1080a9ffe76e7e9d9e39c7ec0fc9fb1 | /exam-model/src/main/java/com/exam/pojo/PaperExample.java | e36607822a98f1b8ab80fe1303cc673414521e3c | [] | no_license | DreamXuan/-mqx | 1b8bf3cb1435d56eba8384020de5f25615b8bf5b | 95da046a11cd5f88bf10cc110fb65519ccdb8ebc | refs/heads/master | 2022-12-22T18:47:48.731751 | 2019-09-10T02:01:04 | 2019-09-10T02:01:04 | 207,274,406 | 0 | 0 | null | 2019-09-10T02:03:14 | 2019-09-09T09:34:40 | CSS | UTF-8 | Java | false | false | 11,140 | java | package com.exam.pojo;
import java.util.ArrayList;
import java.util.List;
public class PaperExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public PaperExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andPidIsNull() {
addCriterion("pid is null");
return (Criteria) this;
}
public Criteria andPidIsNotNull() {
addCriterion("pid is not null");
return (Criteria) this;
}
public Criteria andPidEqualTo(Integer value) {
addCriterion("pid =", value, "pid");
return (Criteria) this;
}
public Criteria andPidNotEqualTo(Integer value) {
addCriterion("pid <>", value, "pid");
return (Criteria) this;
}
public Criteria andPidGreaterThan(Integer value) {
addCriterion("pid >", value, "pid");
return (Criteria) this;
}
public Criteria andPidGreaterThanOrEqualTo(Integer value) {
addCriterion("pid >=", value, "pid");
return (Criteria) this;
}
public Criteria andPidLessThan(Integer value) {
addCriterion("pid <", value, "pid");
return (Criteria) this;
}
public Criteria andPidLessThanOrEqualTo(Integer value) {
addCriterion("pid <=", value, "pid");
return (Criteria) this;
}
public Criteria andPidIn(List<Integer> values) {
addCriterion("pid in", values, "pid");
return (Criteria) this;
}
public Criteria andPidNotIn(List<Integer> values) {
addCriterion("pid not in", values, "pid");
return (Criteria) this;
}
public Criteria andPidBetween(Integer value1, Integer value2) {
addCriterion("pid between", value1, value2, "pid");
return (Criteria) this;
}
public Criteria andPidNotBetween(Integer value1, Integer value2) {
addCriterion("pid not between", value1, value2, "pid");
return (Criteria) this;
}
public Criteria andPnameIsNull() {
addCriterion("pname is null");
return (Criteria) this;
}
public Criteria andPnameIsNotNull() {
addCriterion("pname is not null");
return (Criteria) this;
}
public Criteria andPnameEqualTo(String value) {
addCriterion("pname =", value, "pname");
return (Criteria) this;
}
public Criteria andPnameNotEqualTo(String value) {
addCriterion("pname <>", value, "pname");
return (Criteria) this;
}
public Criteria andPnameGreaterThan(String value) {
addCriterion("pname >", value, "pname");
return (Criteria) this;
}
public Criteria andPnameGreaterThanOrEqualTo(String value) {
addCriterion("pname >=", value, "pname");
return (Criteria) this;
}
public Criteria andPnameLessThan(String value) {
addCriterion("pname <", value, "pname");
return (Criteria) this;
}
public Criteria andPnameLessThanOrEqualTo(String value) {
addCriterion("pname <=", value, "pname");
return (Criteria) this;
}
public Criteria andPnameLike(String value) {
addCriterion("pname like", value, "pname");
return (Criteria) this;
}
public Criteria andPnameNotLike(String value) {
addCriterion("pname not like", value, "pname");
return (Criteria) this;
}
public Criteria andPnameIn(List<String> values) {
addCriterion("pname in", values, "pname");
return (Criteria) this;
}
public Criteria andPnameNotIn(List<String> values) {
addCriterion("pname not in", values, "pname");
return (Criteria) this;
}
public Criteria andPnameBetween(String value1, String value2) {
addCriterion("pname between", value1, value2, "pname");
return (Criteria) this;
}
public Criteria andPnameNotBetween(String value1, String value2) {
addCriterion("pname not between", value1, value2, "pname");
return (Criteria) this;
}
public Criteria andSidIsNull() {
addCriterion("sid is null");
return (Criteria) this;
}
public Criteria andSidIsNotNull() {
addCriterion("sid is not null");
return (Criteria) this;
}
public Criteria andSidEqualTo(Integer value) {
addCriterion("sid =", value, "sid");
return (Criteria) this;
}
public Criteria andSidNotEqualTo(Integer value) {
addCriterion("sid <>", value, "sid");
return (Criteria) this;
}
public Criteria andSidGreaterThan(Integer value) {
addCriterion("sid >", value, "sid");
return (Criteria) this;
}
public Criteria andSidGreaterThanOrEqualTo(Integer value) {
addCriterion("sid >=", value, "sid");
return (Criteria) this;
}
public Criteria andSidLessThan(Integer value) {
addCriterion("sid <", value, "sid");
return (Criteria) this;
}
public Criteria andSidLessThanOrEqualTo(Integer value) {
addCriterion("sid <=", value, "sid");
return (Criteria) this;
}
public Criteria andSidIn(List<Integer> values) {
addCriterion("sid in", values, "sid");
return (Criteria) this;
}
public Criteria andSidNotIn(List<Integer> values) {
addCriterion("sid not in", values, "sid");
return (Criteria) this;
}
public Criteria andSidBetween(Integer value1, Integer value2) {
addCriterion("sid between", value1, value2, "sid");
return (Criteria) this;
}
public Criteria andSidNotBetween(Integer value1, Integer value2) {
addCriterion("sid not between", value1, value2, "sid");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | [
"2628451573@qq.com"
] | 2628451573@qq.com |
e1140fdae4963d497a1c77d72059162dbda7843c | ca6f18eef7d7c2498a997e0ac094f740ee731849 | /src/HashMap/Anagrams.java | 13643b0ce0e56ba1a83ae320612cc69c8a4d2b14 | [] | no_license | cindywmiao/LeetCodeSolution | d08bf95e7a09d1fe54690a033d9a6629ab2e99b3 | dba65db3fa4322c7492135b254b983d54978c0df | refs/heads/master | 2020-03-23T16:45:50.733603 | 2018-08-13T02:43:12 | 2018-08-13T02:43:12 | 141,826,573 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,658 | java | package HashMap;
import java.util.*;
public class Anagrams {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Character> set1 = new HashSet<Character>();
set1.add('a');
HashSet<Character> set2 = new HashSet<Character>();
set2.add('a');
HashMap<HashSet<Character>, Integer> map = new HashMap<HashSet<Character>, Integer>();
map.put(set1,1);
System.out.println(map.containsKey(set2));
String[] strs = {"abc","abcc","bbb", "abcb", "cba"};
List<String> result = anagrams(strs);
for(String s : result){
System.out.println(s);
}
}
public static List<String> anagrams(String[] strs) {
ArrayList<String> ret = new ArrayList<String>();
HashMap<String, ArrayList<String>> ht = new HashMap<String, ArrayList<String>>();
for(int i=0; i<strs.length; i++){
String sorted = sorted(strs[i]);
ArrayList<String> val = ht.get(sorted);
if(val != null){
val.add(strs[i]);
}else{
val = new ArrayList<String>();
val.add(strs[i]);
ht.put(sorted, val);
}
}
Set<String> set = ht.keySet();
for(String s : set){
ArrayList<String> val = ht.get(s);
if(val.size() > 1){
ret.addAll(val);
}
}
return ret;
}
public static String sorted(String a){
char[] achar = a.toCharArray();
Arrays.sort(achar);
return new String(achar);
}
}
| [
"cindywmiao@gmail.com"
] | cindywmiao@gmail.com |
3da92487dec42bba5ae7c69b99223984f0f45e15 | 31171546ba1f130067eb90f381f081833e357767 | /1112/src/com/example/libs/ZipSearch.java | 2f1d50640b964b3f8c688fedc10d3ec5cf138000 | [] | no_license | alrha486/SIST-JSP-Programming | d28aa621e07ea75fefe4833b85465975e212f518 | b73e1357f3084e3e733f407b17909148dbe276e9 | refs/heads/master | 2020-04-03T08:29:25.343262 | 2018-11-27T00:19:26 | 2018-11-27T00:19:26 | 155,134,866 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,967 | java | package com.example.libs;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.example.libs.model.DBClose;
import com.example.libs.model.DBConnection;
public class ZipSearch extends SimpleTagSupport{
private String keyword;
public void setKeyword(String keyword) {
this.keyword = keyword;
}
@Override
public void doTag() throws JspException, IOException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
JspContext ctx = this.getJspContext();
JspWriter out = ctx.getOut();
try {
conn = DBConnection.getConnection();
String sql = "SELECT zipcode, sido, gugun, dong, bunji FROM zipcode " +
"WHERE dong LIKE '%" + this.keyword + "%' ";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
out.println("<table border='1'>");
out.println("<thead><tr><th>우편번호</th><th>시도</th>");
out.println("<th>시/군/구</th><th>읍/면/동</th><th>번지</th></tr></thead>");
out.println("<tbody>");
if(!rs.next()) {
out.println("<tr>");
out.println("<td colspan='5'>찾고자 하시는 읍/면/동이 없습니다.</td></tr>");
}else {
do {
out.println("<tr>");
out.print("<td>" + rs.getString("zipcode") + "</td>");
out.print("<td>" + rs.getString("sido") + "</td>");
out.print("<td>" + rs.getString("gugun") + "</td>");
out.print("<td>" + rs.getString("dong") + "</td>");
out.print("<td>" + rs.getString("bunji") + "</td>");
out.println("</tr>");
}while(rs.next());
}
if(rs != null) rs.close(); if(pstmt != null) pstmt.close();
}catch(SQLException ex) {
System.out.println(ex);
}finally {
DBClose.close(conn);
}
}
}
| [
"alrha486@naver.com"
] | alrha486@naver.com |
5b6c809a0efbb743d4620b50ead11cfefa44fdf0 | cc7f391d1a325c6e4d65bc819d33c222379ecf1a | /app/src/main/java/com/example/jturco/trabajopracticoturco/TurcoTp/Login/IIngresar.java | 3d2d58d6c8e30dd3491d60318b5efb1438896072 | [] | no_license | turcojuan/TpAndroid | 0b42f9288d2ddd49edc042e94ed697cd5a46bb93 | 83f3dae4c50615f5f176b198b7b06176db34c7b6 | refs/heads/master | 2021-01-20T09:38:06.961436 | 2017-06-22T18:24:12 | 2017-06-22T18:24:12 | 90,275,533 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 220 | java | package com.example.jturco.trabajopracticoturco.TurcoTp.Login;
/**
* Created by jturco on 04/05/2017.
*/
public interface IIngresar {
public void ingresarDatosLogin();
public void irPantallaRegistar();
}
| [
"jturco@tmoviles.com.ar"
] | jturco@tmoviles.com.ar |
f9e4c1f1e59d9f4a5b458234a5cdcf26456066e1 | 48a2135f2f05fc09c1bc367ef594ee9f704a4289 | /ovh-java-sdk-ipLoadbalancing/src/main/java/net/minidev/ovh/api/iploadbalancing/status/OvhService.java | 28d1e873ad88e2ecdad470a3c5e775fc14cb8d5a | [
"BSD-3-Clause"
] | permissive | UrielCh/ovh-java-sdk | 913c1fbd4d3ea1ff91de8e1c2671835af67a8134 | e41af6a75f508a065a6177ccde9c2491d072c117 | refs/heads/master | 2022-09-27T11:15:23.115006 | 2022-09-02T04:41:33 | 2022-09-02T04:41:33 | 87,030,166 | 13 | 4 | BSD-3-Clause | 2022-09-02T04:41:34 | 2017-04-03T01:59:23 | Java | UTF-8 | Java | false | false | 234 | java | package net.minidev.ovh.api.iploadbalancing.status;
/**
* The status of a Load Balancer service
*/
public class OvhService {
/**
* The status of your Load Balancer billing domain
*
* canBeNull
*/
public OvhEnum status;
}
| [
"uriel.chemouni@gmail.com"
] | uriel.chemouni@gmail.com |
a42893187b09bdde18888b34f18a28306a28b5f0 | 62accff45f74eda60411d0c5b79480788981d413 | /src/test/java/com/lsj/springboot/SpringbootApplicationTestsAdapter.java | 4c6c5f2a8a80b0d4445a76c37a906d098e4dcf31 | [] | no_license | yuanshuaif/SpringBoot | d1f05b461dd32a564063917f7166f803e0e42ff4 | 082861e06f8a3cbf53bf461a3f0d836decf2c2e9 | refs/heads/master | 2022-07-20T07:50:58.380072 | 2022-07-17T05:29:46 | 2022-07-17T05:29:46 | 243,789,945 | 1 | 1 | null | 2021-01-13T08:11:57 | 2020-02-28T15:10:39 | Java | UTF-8 | Java | false | false | 836 | java | package com.lsj.springboot;
import com.lsj.springboot.designMode.structural.adapter.classAdapter.TargetInterface;
import com.lsj.springboot.designMode.structural.adapter.objectAdapter.TargetInterface1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 适配器模式测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTestsAdapter {
@Autowired
private TargetInterface target;
@Autowired
private TargetInterface1 target1;
@Test
public void testAdatper() {
target.targetMethod();
}
@Test
public void testAdatper1() {
target1.targetMethod();
}
}
| [
"yuanshuaif@yonyou.com"
] | yuanshuaif@yonyou.com |
030385ed07ac08b4bb3ca5d4bec33939ea204fd7 | bf26b2216850d96fcd923044a68f7a58934db6f7 | /src/main/java/com/desafio/assembleia/repository/VotoRepository.java | 5e3304c752abcffcb1e93ae87044cf1e1d557a18 | [] | no_license | adr90dev/APIAssembleia | 0d71276bed04560a4f84442a8bc3fc3bfc3deaf4 | 89f5f41387f9158788aa5aa2dac3e2ff4df98167 | refs/heads/main | 2023-05-02T16:08:01.151461 | 2021-05-24T22:31:24 | 2021-05-24T22:31:24 | 370,396,634 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 282 | java | package com.desafio.assembleia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.desafio.assembleia.model.Voto;
@Repository
public interface VotoRepository extends JpaRepository<Voto, Long>{
}
| [
"adriano.rocha.oliveira@hotmail.com"
] | adriano.rocha.oliveira@hotmail.com |
f42e094640264144a31e8d6e71fc57d26d1bd67b | d4d25a1399d0d7b2b6b4bbf75bae4f0e8319c26b | /src/main/java/dao/Sql2oEndangeredAnimalDao.java | e27913871900aab072c1c8a8247524a60eb4c161 | [
"MIT"
] | permissive | maghanga/wildlife_tracker | dfefb6f56f50b3aa8e51bee0c96a70edd37371ee | 7d387609e863533979d95e9dcbea6e7b1e8eade3 | refs/heads/master | 2022-04-05T03:44:19.737084 | 2020-01-21T11:49:10 | 2020-01-21T11:49:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 923 | java | package dao;
import models.EndangeredAnimal;
import org.sql2o.*;
import java.util.List;
public class Sql2oEndangeredAnimalDao implements EndangeredAnimalDao{
private final Sql2o sql2o;
public Sql2oEndangeredAnimalDao(Sql2o sql2o) { this.sql2o = sql2o; }
@Override
public List<EndangeredAnimal> getAll() {
try (Connection con = sql2o.open()) {
return con.createQuery("SELECT * FROM endangered_animals")
.throwOnMappingFailure(false).executeAndFetch(EndangeredAnimal.class);
}
}
@Override
public EndangeredAnimal findById(int id) {
try (Connection con = sql2o.open()) {
return con.createQuery("SELECT * FROM endangered_animals WHERE id = :id")
.addParameter("id", id)
.throwOnMappingFailure(false)
.executeAndFetchFirst(EndangeredAnimal.class);
}
}
} | [
"wavyylikethesea@gmail.com"
] | wavyylikethesea@gmail.com |
03ca98ac4735669595b328983c57933974b514d8 | 2627cdc69b7ee68fb50a0a7f8464d0d0543cdd95 | /src/gcconverter/util/HTMLReader.java | b2ef763da4476eed704ae4a0d554183f4c15aeb4 | [
"Apache-2.0"
] | permissive | stuchl4n3k/GCConverter | 9d64981ac0be783739b966887025065e60992c3b | f39ac3fffa39b2606013f617b9b61f30e54b9943 | refs/heads/master | 2016-09-06T16:11:54.621371 | 2012-06-06T12:57:50 | 2012-06-06T12:57:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,314 | java | package gcconverter.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author stuchlanek
*/
public class HTMLReader {
public static final int MAX_FILE_SIZE = 100000;
public static String getHTML(URL url) {
if (url == null) {
return null;
}
String content = null;
try {
System.out.println("Now connecting to: "+url);
URLConnection conn = url.openConnection();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
if (content == null) {
content = line + "\n";
} else {
content += line + "\n";
}
if (content.length() > MAX_FILE_SIZE) {
break;
}
}
}
} catch (IOException ex) {
Logger.getLogger(HTMLReader.class.getName()).log(Level.SEVERE, null, ex);
}
return content;
}
}
| [
"stuchl4n3k@gmail.com"
] | stuchl4n3k@gmail.com |
033182551240ebf35de1825a4e66587f345486d5 | 9278e8dd9198731fd7d269a835b71fbeb596fd03 | /java/book-manage-system/src/main/java/com/jimo/util/Result.java | 92ffee3b4e2087b7f740f2745c66b6be5cd1bd61 | [] | no_license | mycodefarm/old-memory-code | 7f5c6246141e8e79f5021e32f1e4163ae3bbd0db | 1e167b01ce93c089cc3768de0793b61b832b3652 | refs/heads/master | 2021-08-30T19:39:57.069096 | 2017-12-19T06:58:52 | 2017-12-19T06:58:52 | 114,587,693 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 463 | java | package com.jimo.util;
public class Result {
private Integer code;
private String msg;
private Object data;
public Object getData() {
return data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public void setData(Object data) {
this.data = data;
}
public Result() {
super();
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| [
"15982406684@163.com"
] | 15982406684@163.com |
d26932a6fa5ff12a82ef408abe4230d7829079ae | b1d2c1f7494a83b9a02635e3490603ceb388b7a2 | /YSZGRDGL/src/main/java/com/wzj/dao/PbtSampleItemMapper.java | ed7dd45178685771f860efbb1399445d41b4b192 | [] | no_license | wzhjmail/YSZGRDGL | d31f6f3d1b5cdf2d596c14e091bb3ee4c02d9cf5 | 4ea916d548ac701fbf4fa163bde4b7bc03da35b7 | refs/heads/master | 2022-12-21T06:48:34.927370 | 2021-05-08T06:07:51 | 2021-05-08T06:07:51 | 139,333,432 | 0 | 0 | null | 2022-12-16T03:25:37 | 2018-07-01T13:56:06 | JavaScript | UTF-8 | Java | false | false | 429 | java | package com.wzj.dao;
import org.apache.ibatis.annotations.Select;
import com.wzj.pojo.PbtSampleItem;
public interface PbtSampleItemMapper {
public int delete(String f_sample_key);
public int insert(PbtSampleItem pbt);
public int update(PbtSampleItem pbt);
@Select({"select * from PBT_SAMPLE_ITEM where F_SAMPLE_KEY = #{f_sample_key,jdbcType=VARCHAR}"})
public PbtSampleItem findBySampleKey(String f_sample_key);
} | [
"wzhj_mail@qq.com"
] | wzhj_mail@qq.com |
3171496e935521ce029aedf87bbac4e348c977be | 68feeb501a9a159b67412151c07ddb9a45b7c304 | /1_Project/src/Mario/BasicEnemyItemBlockInfo.java | 2993b43dda93134a02b4c23c4854988f987d16c3 | [] | no_license | hiro727/mario-engine | d3f8e8c453ac4d694192d8d4ebff33ebfa4ed92a | f47ba30a6d6aac2669d8f96a2d34b6be9c799dfe | refs/heads/master | 2021-05-30T07:01:32.666068 | 2015-09-25T17:46:09 | 2015-09-25T17:46:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,486 | java | package Mario;
import java.io.*;
public class BasicEnemyItemBlockInfo {
static int [] itemNum, minI, maxI, eachsizeI;
static double[] speedI, dxI, dyI;
static int[][] xI, yI, conditionI;
static int [] eneNum, minE, maxE, eachsizeE;
static double[] speedE, dxE;
static int[][] xE, yE;
static int [] blkNum = new int[4];
static int[][] xB = new int[4][], yB = new int[4][], itemB = new int[4][];
public BasicEnemyItemBlockInfo(Pictures p, Ground g) {
// BASIC ITEM INFO
System.out.println("Initializing field items");
itemNum = new int[Pictures.maxI];
minI = new int[Pictures.maxI];
maxI = new int[Pictures.maxI];
eachsizeI = new int[Pictures.maxI];
speedI = new double[Pictures.maxI];
dxI = new double[Pictures.maxI];
dyI = new double[Pictures.maxI];
xI = new int[Pictures.maxI][];
yI = new int[Pictures.maxI][];
conditionI = new int[Pictures.maxI][];
try {
//BufferedReader ri = new BufferedReader(new FileReader(Frames.fullPath+"info/items.txt"));
BufferedReader ri = new BufferedReader(new FileReader("info/items.txt"));
for(int i=0;i<Pictures.maxI;i++){
//System.out.println("Initializing field items "+i);
ri.readLine(); //... info
minI[i] = Integer.parseInt(ri.readLine());
maxI[i] = Integer.parseInt(ri.readLine());
eachsizeI[i] = Integer.parseInt(ri.readLine());
speedI[i] = Double.parseDouble(ri.readLine());
dxI[i] = Double.parseDouble(ri.readLine());
dyI[i] = Double.parseDouble(ri.readLine());
ri.readLine();
itemNum[i] = Integer.parseInt(ri.readLine());
xI[i] = new int[itemNum[i]];
yI[i] = new int[itemNum[i]];
conditionI[i] = new int[itemNum[i]];
for(int j=0;j<itemNum[i];j++){//System.out.println(i+" : "+j);
xI[i][j] = (Integer.parseInt(ri.readLine())-1)*20;
yI[i][j] = Integer.parseInt(ri.readLine());
conditionI[i][j] = Integer.parseInt(ri.readLine());
}
}
ri.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Initializing field enemies");
eneNum = new int[Pictures.maxE];
minE = new int[Pictures.maxE];
maxE = new int[Pictures.maxE];
eachsizeE = new int[Pictures.maxE];
speedE = new double[Pictures.maxE];
dxE = new double[Pictures.maxE];
xE = new int[Pictures.maxE][];
yE = new int[Pictures.maxE][];
try{
//BufferedReader re = new BufferedReader(new FileReader(Frames.fullPath+"info/enemies/"+Frames.names[Frames.worldcounter]+".txt"));
BufferedReader re = new BufferedReader(new FileReader("info/enemies/"+Frames.names[Frames.worldcounter]+".txt"));
for(int i=0;i<Pictures.maxE;i++){
//System.out.println("Initializing field enemies "+i);
re.readLine(); //... info
minE[i] = Integer.parseInt(re.readLine());//System.out.println(minE[i]);
maxE[i] = Integer.parseInt(re.readLine());//System.out.println(maxE[i]);
eachsizeE[i] = Integer.parseInt(re.readLine());//System.out.println(eachsizeE[i]);
speedE[i] = Double.parseDouble(re.readLine());//System.out.println(speedE[i]);
dxE[i] = Double.parseDouble(re.readLine());//System.out.println(dxE[i]);
re.readLine();
eneNum[i] = Integer.parseInt(re.readLine());
xE[i] = new int[eneNum[i]];
yE[i] = new int[eneNum[i]];
for(int j=0;j<eneNum[i];j++){//System.out.println(i+" : "+j);
xE[i][j] = (Integer.parseInt(re.readLine())-1)*20;
if(i==2)xE[i][j] += 10;
yE[i][j] = Integer.parseInt(re.readLine());
}
}
re.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//BufferedReader rb = new BufferedReader(new FileReader(Frames.fullPath+"info/blocks/"+Frames.names[Frames.worldcounter]+".txt"));
BufferedReader rb = new BufferedReader(new FileReader("info/blocks/"+Frames.names[Frames.worldcounter]+".txt"));
rb.readLine(); //get rid of item info
for(int i=0;i<4;i++){
rb.readLine(); //get rid of inst
blkNum[i] = Integer.parseInt(rb.readLine());
xB[i] = new int[blkNum[i]];
yB[i] = new int[blkNum[i]];
if(i!=0){
itemB[i] = new int[blkNum[i]];
for(int j=0;j<blkNum[i];j++){//System.out.println(i+" "+j);
xB[i][j] = (Integer.parseInt(rb.readLine())-1)*20;
yB[i][j] = g.normal-Integer.parseInt(rb.readLine())*20;
itemB[i][j] = Integer.parseInt(rb.readLine());
//System.out.println(i+" "+j+" at "+xB[i][j]+" with "+yB[i][j]);
}
}else{
for(int j=0;j<blkNum[i];j++){
xB[i][j] = (Integer.parseInt(rb.readLine())-1)*20;
yB[i][j] = g.normal-Integer.parseInt(rb.readLine())*20;
//System.out.println(i+" "+j+" at "+xB[i][j]+" with "+yB[i][j]);
}
}
}
rb.close();
//int[] y = new int[g.width];
int i=0, j=0;
boolean finish = false;
while(!finish){
for(int x=xB[i][j];x<xB[i][j]+20;x++){
Ground.thereisblock[x] = true;
//System.out.println(x+" : "+Ground.thereisblock[x]);
}
if(j<blkNum[i]-1) j++;
else if(i<3){ i++; j=0;}
else if(i==3&&j==blkNum[i]-1)finish=true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getX(int i, int j){
return xI[i][j];
}
}
| [
"lazysealion1995@gmail.com"
] | lazysealion1995@gmail.com |
461973f8b72dea79a025768c85e4df0537d83c51 | f3baf6ada6be799230294497cfd995f291bec58b | /src/test/java/es/padis/course/config/WebConfigurerTestController.java | 09e436b56e50da6cd39a0566a64761878c332d2c | [] | no_license | padis/course-application | 5277f2447881e170d41b751c6aa168f0e986e5d6 | 50412dd47e410bd5956f2622df6c7f7277bb394c | refs/heads/master | 2022-06-05T04:35:08.667154 | 2022-05-18T19:08:05 | 2022-05-18T19:08:05 | 181,922,167 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 378 | java | package es.padis.course.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebConfigurerTestController {
@GetMapping("/api/test-cors")
public void testCorsOnApiPath() {
}
@GetMapping("/test/test-cors")
public void testCorsOnOtherPath() {
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
5dbde1132aae6ad5e708253c5e48d1fa925a1102 | 066e16b3867b416652f96168ef60d0372fd38f5c | /Controle/classes/conta/Conta.java | ed7cb3ed0c7a31886270622e7408e39fc483f74e | [] | no_license | emersonlara/Controle-Notas | f1c3d7d2cd311c8df9316fb182e6c0a5f10f8700 | b4e00a213b9c9119933cacc40ddcec6afff5ac8b | refs/heads/master | 2023-07-09T11:36:05.372581 | 2021-08-16T13:58:05 | 2021-08-16T13:58:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,007 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package classes.conta;
/**
*
* @author guilherme.machado
*/
public class Conta {
private int id, nivel;
private String nome = "", login = "", categoria = "", senha = "", email = "";
private boolean block, compra, almoxarife, administracao, engenharia, financeiro, gerencia, logado;
private long ultimoLogin, expira;
public Conta() {
this(-1, 0, "", "", "", "", "", true, false, false, false, false, false, false, true, 0, 0);
}
public Conta(int id, int nivel, String nome, String login, String categoria, String senha, String email, boolean block, boolean compra, boolean almoxarife, boolean administracao, boolean engenharia, boolean financeiro, boolean gerencia, boolean logado, long ultimoLogin, long expira) {
this.id = id;
this.nivel = nivel;
this.nome = nome;
this.login = login;
this.categoria = categoria;
this.senha = senha;
this.email = email;
this.block = block;
this.compra = compra;
this.almoxarife = almoxarife;
this.administracao = administracao;
this.engenharia = engenharia;
this.financeiro = financeiro;
this.gerencia = gerencia;
this.logado = logado;
this.ultimoLogin = ultimoLogin;
this.expira = expira;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNivel() {
return nivel;
}
public void setNivel(int nivel) {
this.nivel = nivel;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isBlock() {
return block;
}
public void setBlock(boolean block) {
this.block = block;
}
public boolean isCompra() {
return compra;
}
public void setCompra(boolean compra) {
this.compra = compra;
}
public boolean isAlmoxarife() {
return almoxarife;
}
public void setAlmoxarife(boolean almoxarife) {
this.almoxarife = almoxarife;
}
public boolean isAdministracao() {
return administracao;
}
public void setAdministracao(boolean administracao) {
this.administracao = administracao;
}
public boolean isEngenharia() {
return engenharia;
}
public void setEngenharia(boolean engenharia) {
this.engenharia = engenharia;
}
public boolean isFinanceiro() {
return financeiro;
}
public void setFinanceiro(boolean financeiro) {
this.financeiro = financeiro;
}
public boolean isGerencia() {
return gerencia;
}
public void setGerencia(boolean gerencia) {
this.gerencia = gerencia;
}
public boolean isLogado() {
return logado;
}
public void setLogado(boolean logado) {
this.logado = logado;
}
public long getUltimoLogin() {
return ultimoLogin;
}
public void setUltimoLogin(long ultimoLogin) {
this.ultimoLogin = ultimoLogin;
}
public long getExpira() {
return expira;
}
public void setExpira(long expira) {
this.expira = expira;
}
}
| [
"59860892+ghpm99@users.noreply.github.com"
] | 59860892+ghpm99@users.noreply.github.com |
97d195f3c26c419355e6fa4ccb5cb9f5d467adc5 | 2106da21ed50fabce32f8bb4b57cd49966da7d75 | /src/service/impl/StudentDAOimpl.java | e037953284d347bc052d4670fc80a696b49502e7 | [] | no_license | jinshuai8899/Instructional-Management-system | 42c44178876e887d61e1e2880068a0d87d440ea8 | e8d51aa1be24002005e633500a9a244ccaedd6ad | refs/heads/master | 2023-03-21T14:50:11.709172 | 2019-10-12T07:58:46 | 2019-10-12T07:58:46 | null | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,025 | java | package service.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;
import entity.CourseInfo;
import entity.ScoreInfo;
import entity.StuInfo;
import entity.TeacherInfo;
import service.StudentDAO;
@Transactional
public class StudentDAOimpl implements StudentDAO{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory=sessionFactory;
}
@Override
public StuInfo queryStudentsByid(String sid) {
System.out.println("queryStudentsByid调用");
Session session=sessionFactory.getCurrentSession();
StuInfo s =(StuInfo)session.get(StuInfo.class,sid);
return s;
}
@Override
public List<ScoreInfo> queryScoreByid(StuInfo s) {
System.out.println("queryScoreByid调用");
Session session=sessionFactory.getCurrentSession();
String hql="select sco from ScoreInfo sco where stuInfo=:s";
Query query=session.createQuery(hql);
query.setParameter("s",s);
List<ScoreInfo> list =query.list();
return list;
}
@Override
public CourseInfo queryCourseByid(String cid) {
System.out.println("queryCourseByid调用");
Session session=sessionFactory.getCurrentSession();
CourseInfo c =(CourseInfo)session.get(CourseInfo.class,cid);
return c;
}
@Override
public TeacherInfo queryTeacherByid(String tid) {
Session session=sessionFactory.getCurrentSession();
TeacherInfo t =(TeacherInfo)session.get(TeacherInfo.class,tid);
return t;
}
@Override
public boolean addScore(ScoreInfo s) {
System.out.println("addScore 被调用..................");
Session session=sessionFactory.getCurrentSession();
session.save(s);
return true;
}
@Override
public boolean deletScore(ScoreInfo s) {
System.out.println("deletScore 被调用..................");
Session session=sessionFactory.getCurrentSession();
session.delete(s);
return true;
}
}
| [
"1012568337@qq,com"
] | 1012568337@qq,com |
12063c1819446c9d3a619025e8c1219955422262 | cb8c6117569c65cd72b950defe9a8051f46e9e0f | /cloudalibaba-config-nacos-client337/src/main/java/com/cgs/springcloud/controller/NacosConfigController.java | af922e12eb5c5c3b7978e8bd45436c300a921a83 | [] | no_license | ChenGuoSong/cloud2020 | aba613b7e883f190b86050643f01ba5458085d80 | cb32bc49e7dee99d363a8cbb9e981a3e788327f3 | refs/heads/master | 2022-07-15T02:10:29.959896 | 2020-04-10T10:01:33 | 2020-04-10T10:01:33 | 252,679,728 | 1 | 0 | null | 2022-06-21T03:07:52 | 2020-04-03T08:50:42 | Java | UTF-8 | Java | false | false | 558 | java | package com.cgs.springcloud.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope //开启nacos自动刷新
public class NacosConfigController {
@Value("${config.info}")
private String info;
@GetMapping(value = "/config/getInfo")
public String getNacosCongfigInfo(){
return info;
}
}
| [
"522860353@qq.com"
] | 522860353@qq.com |
3cfacf3c70f4ab4316e0ddbadeff5adc16901b21 | 7466200443b0dd60c956a1f03a5524fa9cc4f350 | /pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/LLCRealtimeClusterSplitCommitIntegrationTest.java | fca5d99cc2febbf44e8858e31d54c944a7682d49 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"CC-PDDC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"CPL-1.0",
"CDDL-1.1",
"EPL-1.0",
"BSD-2-Clause",
"EPL-2.0",
... | permissive | winedepot/pinot | 9d445e4c9230700e4cfd9dbe4ae85c32f43a1353 | 2dd03f5feb5bfa960a533c1a80a3aaf493d82607 | refs/heads/develop | 2020-05-01T01:50:48.249209 | 2019-07-01T23:20:53 | 2019-07-01T23:20:53 | 177,204,268 | 2 | 0 | Apache-2.0 | 2021-06-26T22:40:27 | 2019-03-22T20:20:47 | Java | UTF-8 | Java | false | false | 1,668 | java | /**
* 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.pinot.integration.tests;
import org.apache.commons.configuration.Configuration;
import org.apache.pinot.common.utils.CommonConstants;
import org.apache.pinot.controller.ControllerConf;
/**
* Integration test that extends LLCRealtimeClusterIntegrationTest but with split commit enabled.
*/
public class LLCRealtimeClusterSplitCommitIntegrationTest extends LLCRealtimeClusterIntegrationTest {
@Override
public void startController() {
ControllerConf controllerConfig = getDefaultControllerConfiguration();
controllerConfig.setSplitCommit(true);
startController(controllerConfig);
}
@Override
public void startServer() {
Configuration serverConfig = getDefaultServerConfiguration();
serverConfig.setProperty(CommonConstants.Server.CONFIG_OF_ENABLE_SPLIT_COMMIT, true);
startServer(serverConfig);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fb83fd8df9e91efb717c8d032fd4a795f0da9eb3 | ef8a143893beaaa90f9287133880e90ea7d2aaaa | /Perestroika-Problem/src/main/java/cz/cuni/mff/perestroika/perestroika_problem_15_3_0_1_0_5_4/Goal.java | 099c800205c41258e3bb2fba30eba9a5ce8b3e6a | [
"MIT"
] | permissive | martinpilat/jPDDL | fb976ae66b248eaa021b8662f300829ef9bdb198 | c5e8389cccc9707b387de41298ae51983908a3f6 | refs/heads/master | 2021-06-13T18:41:14.994546 | 2021-03-26T15:55:23 | 2021-03-26T15:55:23 | 155,592,082 | 0 | 0 | MIT | 2018-10-31T16:46:57 | 2018-10-31T16:46:57 | null | UTF-8 | Java | false | false | 3,800 | java | package cz.cuni.mff.perestroika.perestroika_problem_15_3_0_1_0_5_4;
import cz.cuni.mff.jpddl.PDDLGoal;
import cz.cuni.mff.jpddl.PDDLState;
import cz.cuni.mff.perestroika.domain.State;
public class Goal extends PDDLGoal {
@Override
public String toPDDL() {
return "(:goal (and (alive)\n"
+ " (taken r1)\n"
+ " (taken r2)\n"
+ " (taken r3)\n"
+ " (taken r4)\n"
+ " (taken r5)\n"
+ " (taken r6)\n"
+ " (taken r7)\n"
+ " (taken r8)\n"
+ " (taken r9)\n"
+ " )\n"
+ ")";
}
/**
* Whether the goal has been achieved in 'state'.
*
* GOAL
*
* :goal (and (alive r1)
* (taken r1)
* (taken r2)
* (taken r3)
* (taken r4)
* )
*
* @param state
* @return
*/
public boolean isAchieved(State state) {
return state.p_Alive.isSet()
&& state.p_Taken.isSet(E_Resources.r1)
&& state.p_Taken.isSet(E_Resources.r2)
&& state.p_Taken.isSet(E_Resources.r3)
&& state.p_Taken.isSet(E_Resources.r4)
&& state.p_Taken.isSet(E_Resources.r5)
&& state.p_Taken.isSet(E_Resources.r6)
&& state.p_Taken.isSet(E_Resources.r7)
&& state.p_Taken.isSet(E_Resources.r8)
&& state.p_Taken.isSet(E_Resources.r9);
}
public boolean isAchievedAll(State... states) {
for (State state : states) {
if (!isAchieved(state)) return false;
}
return true;
}
public boolean isAchievedUnion(State... states) {
boolean achieved;
achieved = false;
for (State state : states) {
if (achieved = state.p_Alive.isSet()) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r1)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r2)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r3)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r4)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r5)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r6)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r7)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r8)) break;
}
if (!achieved) return false;
achieved = false;
for (State state : states) {
if (achieved = state.p_Taken.isSet(E_Resources.r9)) break;
}
if (!achieved) return false;
return true;
}
public boolean isAchievedAny(State... states) {
for (State state : states) {
if (isAchieved(state)) return true;
}
return false;
}
// ========================
// PDDLGoal Generic Methods
// ========================
@Override
public boolean isAchieved(PDDLState state) {
return isAchieved((State)state);
}
@Override
public boolean isAchievedAll(PDDLState... states) {
return isAchievedAll((State[])states);
}
@Override
public boolean isAchievedUnion(PDDLState... states) {
return isAchievedUnion((State[])states);
}
@Override
public boolean isAchievedAny(PDDLState... states) {
return isAchievedAny((State[])states);
}
} | [
"martin.pilat@gmail.com"
] | martin.pilat@gmail.com |
878258fd65fca19ccb0158b2604cf542b232b0c5 | fb4d9beea2df2eb18c24127ad1b77171d6ee3995 | /src/test/java/it/maraschi/testapp/config/WebConfigurerTest.java | 9e94178fa8ea5458434d6ff234dfdde7def29b52 | [] | no_license | dandymi/jhtestapp | c0e56329c8d741d9e6b1a3b8930157a86c44d1e4 | 5e9ea6f16444badf56ac2b9a5f74a0a4b0b5fbec | refs/heads/master | 2020-05-21T06:24:11.753982 | 2019-05-10T08:16:34 | 2019-05-10T08:16:34 | 185,943,368 | 0 | 0 | null | 2019-05-10T08:16:35 | 2019-05-10T07:47:28 | Java | UTF-8 | Java | false | false | 7,177 | java | package it.maraschi.testapp.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.web.filter.CachingHttpHeadersFilter;
import org.h2.server.web.WebServlet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.servlet.*;
import java.io.File;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Unit tests for the {@link WebConfigurer} class.
*/
public class WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class))
.when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class))
.when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDocumentRoot() != null) {
assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/"));
}
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
options("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
1acaa886b0a79b3ae5ccf41bee3f11ed46f1298a | b4f6ef593d37f49b0bd80c50ef9293f51871336c | /app/src/androidTest/java/com/project/csci3130/dalrs/AddDropTest.java | 549f4267db0ab952a17fd78b49cf528543b14821 | [] | no_license | DanielZhang17/3130Project | a0660d27ba3a5034e7c35c6e1fb2f5fe4e1de8cc | fc3d2e84c1ae613e0c7b7703b76153c528168b8e | refs/heads/master | 2020-04-17T19:51:22.611175 | 2018-08-04T21:14:36 | 2018-08-04T21:14:36 | 137,971,331 | 0 | 0 | null | 2018-06-20T02:45:04 | 2018-06-20T02:45:03 | null | UTF-8 | Java | false | false | 7,834 | java | package com.project.csci3130.dalrs;
import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class AddDropTest {
@Rule
public ActivityTestRule<LoginActivity> mActivityTestRule = new ActivityTestRule<>(LoginActivity.class);
@Test
public void addDropTest() {
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatAutoCompleteTextView = onView(
allOf(withId(R.id.email),
childAtPosition(
childAtPosition(
withClassName(is("android.support.design.widget.TextInputLayout")),
0),
0)));
appCompatAutoCompleteTextView.perform(scrollTo(), replaceText("sh908427@dal.ca"), closeSoftKeyboard());
ViewInteraction appCompatEditText = onView(
allOf(withId(R.id.password),
childAtPosition(
childAtPosition(
withClassName(is("android.support.design.widget.TextInputLayout")),
0),
0)));
appCompatEditText.perform(scrollTo(), replaceText("987654321"), closeSoftKeyboard());
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.email_sign_in_button), withText("Login"),
childAtPosition(
allOf(withId(R.id.email_login_form),
childAtPosition(
withId(R.id.login_form),
0)),
3)));
appCompatButton.perform(scrollTo(), click());
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatImageButton = onView(
allOf(withContentDescription("Open navigation drawer"),
childAtPosition(
allOf(withId(R.id.toolbar),
childAtPosition(
withClassName(is("android.support.design.widget.AppBarLayout")),
0)),
1),
isDisplayed()));
appCompatImageButton.perform(click());
ViewInteraction navigationMenuItemView = onView(
allOf(childAtPosition(
allOf(withId(R.id.design_navigation_view),
childAtPosition(
withId(R.id.nav_view),
0)),
1),
isDisplayed()));
navigationMenuItemView.perform(click());
ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.changeTerm), withText("Submit"),
childAtPosition(
childAtPosition(
withId(R.id.content_login_interface),
0),
2),
isDisplayed()));
appCompatButton2.perform(click());
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ViewInteraction appCompatEditText2 = onView(
allOf(withId(R.id.editText),
childAtPosition(
childAtPosition(
withId(android.R.id.content),
0),
0),
isDisplayed()));
appCompatEditText2.perform(replaceText("10002"), closeSoftKeyboard());
ViewInteraction appCompatButton3 = onView(
allOf(withId(R.id.button1), withText("Add"),
childAtPosition(
childAtPosition(
withId(android.R.id.content),
0),
1),
isDisplayed()));
appCompatButton3.perform(click());
ViewInteraction appCompatButton4 = onView(
allOf(withId(R.id.button2), withText("Drop"),
childAtPosition(
childAtPosition(
withId(android.R.id.content),
0),
2),
isDisplayed()));
appCompatButton4.perform(click());
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4838db9219eb0e8af7e6a7df4b0d5b49b246a9be | 8061a8a4e6bf119f1c8bbfb624956aaa781528a7 | /src/kr/capa/acip/vo/board/EventVO.java | 87b5b7f39c65d5e1b0afffd862d76e43df489c08 | [] | no_license | guntae/skuniv | 58d022c2df3d6ad63e921f98031d99ccef9040a0 | 525365aeff88aee149e8c88f6d21115dab65b5b8 | refs/heads/master | 2020-04-09T14:18:07.815080 | 2016-09-12T10:22:15 | 2016-09-12T10:22:15 | 67,997,104 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 950 | java | package kr.capa.acip.vo.board;
public class EventVO {
private String evnum;
private String evtitle;
private String evpic;
private String evregdate;
private String lnum;
public String getEvnum() {
return evnum;
}
public void setEvnum(String evnum) {
this.evnum = evnum;
}
public String getEvtitle() {
return evtitle;
}
public void setEvtitle(String evtitle) {
this.evtitle = evtitle;
}
public String getEvpic() {
return evpic;
}
public void setEvpic(String evpic) {
this.evpic = evpic;
}
public String getEvregdate() {
return evregdate;
}
public void setEvregdate(String evregdate) {
this.evregdate = evregdate;
}
public String getLnum() {
return lnum;
}
public void setLnum(String lnum) {
this.lnum = lnum;
}
@Override
public String toString() {
return "EventVO [evnum=" + evnum + ", evtitle=" + evtitle + ", evpic=" + evpic + ", evregdate=" + evregdate
+ ", lnum=" + lnum + "]";
}
}
| [
"w_parisen@naver.com"
] | w_parisen@naver.com |
f3939fcc06d93be2d79f7380f7c0e7d5d3ee1151 | f1ccae53ae3c48bf076b987def32eff80fffe7de | /loveattention/LoveAttention/src/com/zykj/loveattention/utils/CharacterParser.java | 32398c1fe1d2cf7fc3bc2df4985bdc59213f6495 | [] | no_license | lss5415/LoveAttention | 284dd0d23bb36b89a320ff2758e3247fc8bece5e | fa2307e62bb5c261fc02b576f2691849444f14a7 | refs/heads/master | 2021-01-18T23:08:21.567488 | 2016-03-25T02:51:25 | 2016-03-25T02:51:25 | 40,869,399 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,267 | java | package com.zykj.loveattention.utils;
/**
* @author lss 2015年7月7日 Java汉字转换为拼音
*
*/
public class CharacterParser {
private static int[] pyvalue = new int[] {-20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032,
-20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728,
-19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261,
-19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961,
-18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490,
-18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988,
-17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692,
-17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733,
-16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419,
-16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959,
-15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631,
-15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180,
-15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941,
-14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857,
-14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353,
-14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094,
-14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831,
-13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329,
-13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860,
-12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300,
-12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358,
-11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014,
-10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309,
-10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254};
public static String[] pystr = new String[] {"a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian",
"biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", "chao", "che",
"chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", "cou", "cu", "cuan",
"cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du",
"duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang",
"gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang",
"hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian",
"jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken",
"keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng",
"li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai",
"man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai",
"nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan",
"nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu",
"qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re",
"ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha",
"shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun",
"shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao",
"tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi",
"xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi",
"yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha",
"zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui",
"zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"};
private StringBuilder buffer;
private String resource;
private static CharacterParser characterParser = new CharacterParser();
public static CharacterParser getInstance() {
return characterParser;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
/** * 汉字转成ASCII码 * * @param chs * @return */
private int getChsAscii(String chs) {
int asc = 0;
try {
byte[] bytes = chs.getBytes("gb2312");
if (bytes == null || bytes.length > 2 || bytes.length <= 0) {
throw new RuntimeException("illegal resource string");
}
if (bytes.length == 1) {
asc = bytes[0];
}
if (bytes.length == 2) {
int hightByte = 256 + bytes[0];
int lowByte = 256 + bytes[1];
asc = (256 * hightByte + lowByte) - 256 * 256;
}
} catch (Exception e) {
System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
}
return asc;
}
/** * 单字解析 * * @param str * @return */
public String convert(String str) {
String result = null;
int ascii = getChsAscii(str);
if (ascii > 0 && ascii < 160) {
result = String.valueOf((char) ascii);
} else {
for (int i = (pyvalue.length - 1); i >= 0; i--) {
if (pyvalue[i] <= ascii) {
result = pystr[i];
break;
}
}
}
return result;
}
/** * 词组解析 * * @param chs * @return */
public String getSelling(String chs) {
String key, value;
buffer = new StringBuilder();
for (int i = 0; i < chs.length(); i++) {
key = chs.substring(i, i + 1);
if (key.getBytes().length >= 2) {
value = (String) convert(key);
if (value == null) {
value = "unknown";
}
} else {
value = key;
}
buffer.append(value);
}
return buffer.toString();
}
public String getSpelling() {
return this.getSelling(this.getResource());
}
}
| [
"541531745@qq.com"
] | 541531745@qq.com |
5a62cd7eb9657420547ecc45dde45a759a110475 | 6ec37b1b15c82ee63c5a3f5f3c777d9195bcf673 | /ModuloGeneral/src/main/java/bamas/espe/ec/interfaces/InterfaceRem.java | 8c55db7492b9fa5334ea28da631b6c10c6ad5bdc | [] | no_license | JannethOlivarez/bamas_back | 135d98b1cf4e7de8f0f51c6cae7c4a8496bbd90c | 2fb6988e957ebb09af2e7eca05a3918bef0e6da3 | refs/heads/master | 2020-04-04T12:06:52.262695 | 2018-11-02T19:55:50 | 2018-11-02T19:55:50 | 155,914,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 199 | java | package bamas.espe.ec.interfaces;
import org.springframework.data.jpa.repository.JpaRepository;
import bamas.espe.ec.modelos.Rem;
public interface InterfaceRem extends JpaRepository<Rem,Long> {
}
| [
"jannetholivarez@gmail.com"
] | jannetholivarez@gmail.com |
22237f6c70d21d658fd93aab8c3ca45a39b979ce | 0c45b2012ee2715b0b725e764fbfc9bc40109936 | /src/br/inf/portalfiscal/nfe/canc/eventocancnfe/TEvento.java | d44269d990558cdfcfb088d1d0d6d6ea15ff3e8e | [] | no_license | roneison85/NFeLib4.00 | 9d5c50bd0011a624dff1279e15cc4d31257ade0e | d8bcb84aaca63c428cc8ca175330e77809b7f2c7 | refs/heads/master | 2021-12-10T07:18:43.952886 | 2021-12-01T10:44:19 | 2021-12-01T10:44:19 | 203,785,144 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,516 | java | //
// Este arquivo foi gerado pela Arquitetura JavaTM para Implementa��o de Refer�ncia (JAXB) de Bind XML, v2.2.8-b130911.1802
// Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas as modifica��es neste arquivo ser�o perdidas ap�s a recompila��o do esquema de origem.
// Gerado em: 2017.07.13 �s 10:08:44 AM BRT
//
package br.inf.portalfiscal.nfe.canc.eventocancnfe;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Tipo Evento
*
* <p>Classe Java de TEvento complex type.
*
* <p>O seguinte fragmento do esquema especifica o conte�do esperado contido dentro desta classe.
*
* <pre>
* <complexType name="TEvento">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="infEvento">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/>
* <element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/>
* <choice>
* <element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/>
* <element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/>
* </choice>
* <element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/>
* <element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/>
* <element name="tpEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <pattern value="[0-9]{6}"/>
* <enumeration value="110111"/>
* </restriction>
* </simpleType>
* </element>
* <element name="nSeqEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <pattern value="[1-9]|[1][0-9]{0,1}|20"/>
* </restriction>
* </simpleType>
* </element>
* <element name="verEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="1.00"/>
* </restriction>
* </simpleType>
* </element>
* <element name="detEvento">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="descEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="Cancelamento"/>
* </restriction>
* </simpleType>
* </element>
* <element name="nProt" type="{http://www.portalfiscal.inf.br/nfe}TProt"/>
* <element name="xJust" type="{http://www.portalfiscal.inf.br/nfe}TJust"/>
* </sequence>
* <attribute name="versao" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="1.00"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="Id" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}ID">
* <pattern value="ID[0-9]{52}"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element ref="{http://www.w3.org/2000/09/xmldsig#}Signature"/>
* </sequence>
* <attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEvento" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = {
"infEvento",
"signature"
})
public class TEvento {
@XmlElement(required = true)
protected TEvento.InfEvento infEvento;
@XmlElement(name = "Signature", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true)
protected SignatureType signature;
@XmlAttribute(name = "versao", required = true)
protected String versao;
/**
* Obt�m o valor da propriedade infEvento.
*
* @return
* possible object is
* {@link TEvento.InfEvento }
*
*/
public TEvento.InfEvento getInfEvento() {
return infEvento;
}
/**
* Define o valor da propriedade infEvento.
*
* @param value
* allowed object is
* {@link TEvento.InfEvento }
*
*/
public void setInfEvento(TEvento.InfEvento value) {
this.infEvento = value;
}
/**
* Obt�m o valor da propriedade signature.
*
* @return
* possible object is
* {@link SignatureType }
*
*/
public SignatureType getSignature() {
return signature;
}
/**
* Define o valor da propriedade signature.
*
* @param value
* allowed object is
* {@link SignatureType }
*
*/
public void setSignature(SignatureType value) {
this.signature = value;
}
/**
* Obt�m o valor da propriedade versao.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersao() {
return versao;
}
/**
* Define o valor da propriedade versao.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersao(String value) {
this.versao = value;
}
/**
* <p>Classe Java de anonymous complex type.
*
* <p>O seguinte fragmento do esquema especifica o conte�do esperado contido dentro desta classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cOrgao" type="{http://www.portalfiscal.inf.br/nfe}TCOrgaoIBGE"/>
* <element name="tpAmb" type="{http://www.portalfiscal.inf.br/nfe}TAmb"/>
* <choice>
* <element name="CNPJ" type="{http://www.portalfiscal.inf.br/nfe}TCnpjOpc"/>
* <element name="CPF" type="{http://www.portalfiscal.inf.br/nfe}TCpf"/>
* </choice>
* <element name="chNFe" type="{http://www.portalfiscal.inf.br/nfe}TChNFe"/>
* <element name="dhEvento" type="{http://www.portalfiscal.inf.br/nfe}TDateTimeUTC"/>
* <element name="tpEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <pattern value="[0-9]{6}"/>
* <enumeration value="110111"/>
* </restriction>
* </simpleType>
* </element>
* <element name="nSeqEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <pattern value="[1-9]|[1][0-9]{0,1}|20"/>
* </restriction>
* </simpleType>
* </element>
* <element name="verEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="1.00"/>
* </restriction>
* </simpleType>
* </element>
* <element name="detEvento">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="descEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="Cancelamento"/>
* </restriction>
* </simpleType>
* </element>
* <element name="nProt" type="{http://www.portalfiscal.inf.br/nfe}TProt"/>
* <element name="xJust" type="{http://www.portalfiscal.inf.br/nfe}TJust"/>
* </sequence>
* <attribute name="versao" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="1.00"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="Id" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}ID">
* <pattern value="ID[0-9]{52}"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cOrgao",
"tpAmb",
"cnpj",
"cpf",
"chNFe",
"dhEvento",
"tpEvento",
"nSeqEvento",
"verEvento",
"detEvento"
})
public static class InfEvento {
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String cOrgao;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String tpAmb;
@XmlElement(name = "CNPJ", namespace = "http://www.portalfiscal.inf.br/nfe")
protected String cnpj;
@XmlElement(name = "CPF", namespace = "http://www.portalfiscal.inf.br/nfe")
protected String cpf;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String chNFe;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String dhEvento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String tpEvento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String nSeqEvento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String verEvento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected TEvento.InfEvento.DetEvento detEvento;
@XmlAttribute(name = "Id", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
/**
* Obt�m o valor da propriedade cOrgao.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCOrgao() {
return cOrgao;
}
/**
* Define o valor da propriedade cOrgao.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOrgao(String value) {
this.cOrgao = value;
}
/**
* Obt�m o valor da propriedade tpAmb.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTpAmb() {
return tpAmb;
}
/**
* Define o valor da propriedade tpAmb.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTpAmb(String value) {
this.tpAmb = value;
}
/**
* Obt�m o valor da propriedade cnpj.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCNPJ() {
return cnpj;
}
/**
* Define o valor da propriedade cnpj.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCNPJ(String value) {
this.cnpj = value;
}
/**
* Obt�m o valor da propriedade cpf.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCPF() {
return cpf;
}
/**
* Define o valor da propriedade cpf.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCPF(String value) {
this.cpf = value;
}
/**
* Obt�m o valor da propriedade chNFe.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChNFe() {
return chNFe;
}
/**
* Define o valor da propriedade chNFe.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChNFe(String value) {
this.chNFe = value;
}
/**
* Obt�m o valor da propriedade dhEvento.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDhEvento() {
return dhEvento;
}
/**
* Define o valor da propriedade dhEvento.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDhEvento(String value) {
this.dhEvento = value;
}
/**
* Obt�m o valor da propriedade tpEvento.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTpEvento() {
return tpEvento;
}
/**
* Define o valor da propriedade tpEvento.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTpEvento(String value) {
this.tpEvento = value;
}
/**
* Obt�m o valor da propriedade nSeqEvento.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNSeqEvento() {
return nSeqEvento;
}
/**
* Define o valor da propriedade nSeqEvento.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNSeqEvento(String value) {
this.nSeqEvento = value;
}
/**
* Obt�m o valor da propriedade verEvento.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVerEvento() {
return verEvento;
}
/**
* Define o valor da propriedade verEvento.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVerEvento(String value) {
this.verEvento = value;
}
/**
* Obt�m o valor da propriedade detEvento.
*
* @return
* possible object is
* {@link TEvento.InfEvento.DetEvento }
*
*/
public TEvento.InfEvento.DetEvento getDetEvento() {
return detEvento;
}
/**
* Define o valor da propriedade detEvento.
*
* @param value
* allowed object is
* {@link TEvento.InfEvento.DetEvento }
*
*/
public void setDetEvento(TEvento.InfEvento.DetEvento value) {
this.detEvento = value;
}
/**
* Obt�m o valor da propriedade id.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Define o valor da propriedade id.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* <p>Classe Java de anonymous complex type.
*
* <p>O seguinte fragmento do esquema especifica o conte�do esperado contido dentro desta classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="descEvento">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="Cancelamento"/>
* </restriction>
* </simpleType>
* </element>
* <element name="nProt" type="{http://www.portalfiscal.inf.br/nfe}TProt"/>
* <element name="xJust" type="{http://www.portalfiscal.inf.br/nfe}TJust"/>
* </sequence>
* <attribute name="versao" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <enumeration value="1.00"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"descEvento",
"nProt",
"xJust"
})
public static class DetEvento {
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String descEvento;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String nProt;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String xJust;
@XmlAttribute(name = "versao", required = true)
protected String versao;
/**
* Obt�m o valor da propriedade descEvento.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescEvento() {
return descEvento;
}
/**
* Define o valor da propriedade descEvento.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescEvento(String value) {
this.descEvento = value;
}
/**
* Obt�m o valor da propriedade nProt.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNProt() {
return nProt;
}
/**
* Define o valor da propriedade nProt.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNProt(String value) {
this.nProt = value;
}
/**
* Obt�m o valor da propriedade xJust.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXJust() {
return xJust;
}
/**
* Define o valor da propriedade xJust.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXJust(String value) {
this.xJust = value;
}
/**
* Obt�m o valor da propriedade versao.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersao() {
return versao;
}
/**
* Define o valor da propriedade versao.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersao(String value) {
this.versao = value;
}
}
}
}
| [
"roneison.machado@gmail.com"
] | roneison.machado@gmail.com |
efb6b8f3a30ffd39d3c7406470ad3d7a8cb969fc | 597ea280b433dff12feb85feebe6b99c7534c9ac | /core-java-volume/src/main/java/com/builderPattern/player/StreamlinedModePlayerBuilder.java | 1497927732a305796d67d6ad931a2e24aee6a3e5 | [] | no_license | GoldBladeAncestor/java-volume | 80f97b2a1ecd38a3fb3a7c9ec56897ddfbae04ca | c357b5d6fdc5c5e57c2843e3d550fee28128c3ce | refs/heads/master | 2022-12-21T11:27:38.398065 | 2019-06-04T03:23:08 | 2019-06-04T03:23:08 | 189,962,375 | 0 | 0 | null | 2022-12-16T05:00:39 | 2019-06-03T08:08:53 | Java | UTF-8 | Java | false | false | 506 | java | package com.builderPattern.player;
/**
* @Description:
* @Author:Antonio
* @Date:Created in 15:20 2019/5/17
*/
public class StreamlinedModePlayerBuilder extends PlayerBuilder {
@Override
public void buildMenu() {
}
@Override
public void buildList() {
}
@Override
public void buildWindow() {
player.setWindow(true);
}
@Override
public void buildBar() {
player.setBar(true);
}
@Override
public void buildCollect() {
}
}
| [
"34149712+GoldBladeAncestor@users.noreply.github.com"
] | 34149712+GoldBladeAncestor@users.noreply.github.com |
27411386143ec5567094eb8aac09c4d75aeabab5 | ce91c9153d02b25268660238a1df77af3fca418e | /src/app/riskapp/entity/BrMst.java | 6e68f1c072ca43784f2438fea3fe3e0e260d6e17 | [] | no_license | mygithut/mytest | 3605ea7b2a7e88c4024d028be05e6c0cb42f1905 | 44dd7df1d299e25b16188400a6cb05b4bc46812a | refs/heads/master | 2020-05-02T02:38:06.552117 | 2019-03-26T03:58:33 | 2019-03-26T03:58:33 | 177,699,322 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,293 | java | package app.riskapp.entity;
/**
* BrMst entity. @author MyEclipse Persistence Tools
*/
public class BrMst implements java.io.Serializable {
// Fields
private String brNo;
private String brName;
private String chargePersonName;
private String manageLvl;
private String fbrCode;
private String legalPersonFlag;
private String conPersonName;
private String conPhone;
private String conAddr;
private String postNo;
private String brClFlag;
private String superBrNo;
private String fax;
private String brf;
// Constructors
/** default constructor */
public BrMst() {
}
/** minimal constructor */
public BrMst(String brNo) {
this.brNo = brNo;
}
/** full constructor */
public BrMst(String brNo, String brName, String chargePersonName,
String manageLvl, String fbrCode, String legalPersonFlag,
String conPersonName, String conPhone, String conAddr,
String postNo, String brClFlag, String superBrNo, String fax,
String brf) {
this.brNo = brNo;
this.brName = brName;
this.chargePersonName = chargePersonName;
this.manageLvl = manageLvl;
this.fbrCode = fbrCode;
this.legalPersonFlag = legalPersonFlag;
this.conPersonName = conPersonName;
this.conPhone = conPhone;
this.conAddr = conAddr;
this.postNo = postNo;
this.brClFlag = brClFlag;
this.superBrNo = superBrNo;
this.fax = fax;
this.brf = brf;
}
// Property accessors
public String getBrNo() {
return this.brNo;
}
public void setBrNo(String brNo) {
this.brNo = brNo;
}
public String getBrName() {
return this.brName;
}
public void setBrName(String brName) {
this.brName = brName;
}
public String getChargePersonName() {
return this.chargePersonName;
}
public void setChargePersonName(String chargePersonName) {
this.chargePersonName = chargePersonName;
}
public String getManageLvl() {
return this.manageLvl;
}
public void setManageLvl(String manageLvl) {
this.manageLvl = manageLvl;
}
public String getFbrCode() {
return this.fbrCode;
}
public void setFbrCode(String fbrCode) {
this.fbrCode = fbrCode;
}
public String getLegalPersonFlag() {
return this.legalPersonFlag;
}
public void setLegalPersonFlag(String legalPersonFlag) {
this.legalPersonFlag = legalPersonFlag;
}
public String getConPersonName() {
return this.conPersonName;
}
public void setConPersonName(String conPersonName) {
this.conPersonName = conPersonName;
}
public String getConPhone() {
return this.conPhone;
}
public void setConPhone(String conPhone) {
this.conPhone = conPhone;
}
public String getConAddr() {
return this.conAddr;
}
public void setConAddr(String conAddr) {
this.conAddr = conAddr;
}
public String getPostNo() {
return this.postNo;
}
public void setPostNo(String postNo) {
this.postNo = postNo;
}
public String getBrClFlag() {
return this.brClFlag;
}
public void setBrClFlag(String brClFlag) {
this.brClFlag = brClFlag;
}
public String getSuperBrNo() {
return this.superBrNo;
}
public void setSuperBrNo(String superBrNo) {
this.superBrNo = superBrNo;
}
public String getFax() {
return this.fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getBrf() {
return this.brf;
}
public void setBrf(String brf) {
this.brf = brf;
}
} | [
"lifeisshort888@gmail.com"
] | lifeisshort888@gmail.com |
b0b3234578808edcc2635640acb95c1b9159ace1 | 78f284cd59ae5795f0717173f50e0ebe96228e96 | /factura-negocio/src/cl/stotomas/factura/negocio/training_2/copy3/copy2/TestingFinal.java | 14c7e9c59956f9fa78bb7d498552748dd8b5113a | [] | no_license | Pattricio/Factura | ebb394e525dfebc97ee2225ffc5fca10962ff477 | eae66593ac653f85d05071b6ccb97fb1e058502d | refs/heads/master | 2020-03-16T03:08:45.822070 | 2018-05-07T15:29:25 | 2018-05-07T15:29:25 | 132,481,305 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,699 | java | package cl.stotomas.factura.negocio.training_2.copy3.copy2;
import java.applet.Applet;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class TestingFinal {
public static String decryptMessage(final byte[] message, byte[] secretKey)
{
try {
// CÓDIGO VULNERABLE
final SecretKeySpec KeySpec = new SecretKeySpec(secretKey, "DES");
final Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, KeySpec);
// RECOMENDACIÓN VERACODE
// final Cipher cipher = Cipher.getInstance("DES...");
// cipher.init(Cipher.DECRYPT_MODE, KeySpec);
return new String(cipher.doFinal(message));
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
class Echo {
// Control de Proceso
// Posible reemplazo de librería por una maliciosa
// Donde además se nos muestra el nombre explícito de esta.
public native void runEcho();
{
System.loadLibrary("echo"); // Se carga librería
}
public void main(String[] args)
{
new Echo().runEcho();
}
public final class TestApplet extends Applet {
private static final long serialVersionUID = 1L;
}
//Comparación de referencias de objeto en lugar de contenido de objeto
// El if dentro de este código no se ejecutará.
// porque se prioriza el String a mostrar.
public final class compareStrings{
public String str1;
public String str2;
public void comparar()
{
if (str1 == str2)
{
System.out.println("str1 == str2");
}
}
}
}
}
| [
"Adriana Molano@DESKTOP-GQ96FK8"
] | Adriana Molano@DESKTOP-GQ96FK8 |
b69b0d15944feeb19381cd2b51e419fde7d94ce3 | d9fe1c9f3df50a0c288bc76d9b691a5286f15fcf | /lang-base/src/main/java/cn/soft1010/lang/CharacterTest.java | 9187668685c346dfe07e1c77ba3089112b8434b6 | [] | no_license | nine-free/Base-Java-lang | 6d2836a352d001a24ac0be93f08b20866cd50102 | c834db8a4471f65320327460690b61e3cc1bbb6e | refs/heads/master | 2021-01-18T18:59:43.921764 | 2017-04-13T05:58:39 | 2017-04-13T05:58:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 231 | java | package cn.soft1010.lang;
/**
* Created by zhangjifu on 2017/3/31.
*/
public class CharacterTest {
public static void main(String[] args) {
System.out.println(Character.isSpaceChar("\n".toCharArray()[0]));
}
}
| [
"zhangjifu@vipkid.com.cn"
] | zhangjifu@vipkid.com.cn |
45ddd8bbd889a3e9704c3f98c42f49c87e57b70f | 354596386e28bd189f4c9a83d149ad185ebc1df5 | /TefServices/gen/com/example/tefservices/BuildConfig.java | 789b8fde2e582eebc072d2dc6c69c7bf7bb9562c | [
"MIT"
] | permissive | stephaneAG/Android_tests | fe904b22dae0f3de254d9a3cf5572498daa2ab65 | 0cb64cf24a4b00eadc3448e965a51a349584a221 | refs/heads/master | 2021-01-17T17:07:17.702149 | 2015-06-14T04:58:47 | 2015-06-14T04:58:47 | 37,399,684 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 165 | java | /** Automatically generated file. DO NOT MODIFY */
package com.example.tefservices;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | [
"seedsodesign@gmail.com"
] | seedsodesign@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.