hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
922e712e4aef5dbbb4587d422739431ba13054e1
1,640
java
Java
swim-system-java/swim-core-java/swim.http/src/test/java/swim/http/header/ContentEncodingSpec.java
DeepInThought/swim
4738619aa4a1c99cafe36c542fc5ae847a9ed27d
[ "Apache-2.0" ]
null
null
null
swim-system-java/swim-core-java/swim.http/src/test/java/swim/http/header/ContentEncodingSpec.java
DeepInThought/swim
4738619aa4a1c99cafe36c542fc5ae847a9ed27d
[ "Apache-2.0" ]
null
null
null
swim-system-java/swim-core-java/swim.http/src/test/java/swim/http/header/ContentEncodingSpec.java
DeepInThought/swim
4738619aa4a1c99cafe36c542fc5ae847a9ed27d
[ "Apache-2.0" ]
1
2020-06-10T09:05:13.000Z
2020-06-10T09:05:13.000Z
37.272727
96
0.748171
994,747
// Copyright 2015-2020 SWIM.AI inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package swim.http.header; import org.testng.annotations.Test; import swim.http.Http; import swim.http.HttpAssertions; import swim.http.HttpHeader; import static swim.http.HttpAssertions.assertWrites; public class ContentEncodingSpec { public void assertParses(String string, HttpHeader header) { HttpAssertions.assertParses(Http.standardParser().headerParser(), string, header); } @Test public void parseContentEncodingHeaders() { assertParses("Content-Encoding: gzip", ContentEncoding.from("gzip")); assertParses("Content-Encoding: identity,gzip", ContentEncoding.from("identity", "gzip")); assertParses("Content-Encoding: identity, gzip", ContentEncoding.from("identity", "gzip")); assertParses("Content-Encoding: identity , gzip", ContentEncoding.from("identity", "gzip")); } @Test public void writeContentEncodingHeaders() { assertWrites(ContentEncoding.from("gzip"), "Content-Encoding: gzip"); assertWrites(ContentEncoding.from("identity", "gzip"), "Content-Encoding: identity, gzip"); } }
922e7186bf0e1c7b6255d8f4a1be78c4bce6472b
5,041
java
Java
jOOQ-test/examples/org/jooq/examples/mysql/sakila/tables/records/SakilaCityRecord.java
cybernetics/jOOQ
ab29b4a73f5bbe027eeff352be5a75e70db9760a
[ "Apache-2.0" ]
1
2019-04-22T08:49:14.000Z
2019-04-22T08:49:14.000Z
jOOQ-test/examples/org/jooq/examples/mysql/sakila/tables/records/SakilaCityRecord.java
cybernetics/jOOQ
ab29b4a73f5bbe027eeff352be5a75e70db9760a
[ "Apache-2.0" ]
null
null
null
jOOQ-test/examples/org/jooq/examples/mysql/sakila/tables/records/SakilaCityRecord.java
cybernetics/jOOQ
ab29b4a73f5bbe027eeff352be5a75e70db9760a
[ "Apache-2.0" ]
null
null
null
21.635193
237
0.61337
994,748
/** * This class is generated by jOOQ */ package org.jooq.examples.mysql.sakila.tables.records; /** * This class is generated by jOOQ. */ @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class SakilaCityRecord extends org.jooq.impl.UpdatableRecordImpl<org.jooq.examples.mysql.sakila.tables.records.SakilaCityRecord> implements org.jooq.Record4<java.lang.Short, java.lang.String, java.lang.Short, java.sql.Timestamp> { private static final long serialVersionUID = -644711027; /** * Setter for <code>sakila.city.city_id</code>. */ public void setCityId(java.lang.Short value) { setValue(0, value); } /** * Getter for <code>sakila.city.city_id</code>. */ public java.lang.Short getCityId() { return (java.lang.Short) getValue(0); } /** * Setter for <code>sakila.city.city</code>. */ public void setCity(java.lang.String value) { setValue(1, value); } /** * Getter for <code>sakila.city.city</code>. */ public java.lang.String getCity() { return (java.lang.String) getValue(1); } /** * Setter for <code>sakila.city.country_id</code>. */ public void setCountryId(java.lang.Short value) { setValue(2, value); } /** * Getter for <code>sakila.city.country_id</code>. */ public java.lang.Short getCountryId() { return (java.lang.Short) getValue(2); } /** * Setter for <code>sakila.city.last_update</code>. */ public void setLastUpdate(java.sql.Timestamp value) { setValue(3, value); } /** * Getter for <code>sakila.city.last_update</code>. */ public java.sql.Timestamp getLastUpdate() { return (java.sql.Timestamp) getValue(3); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Record1<java.lang.Short> key() { return (org.jooq.Record1) super.key(); } // ------------------------------------------------------------------------- // Record4 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Row4<java.lang.Short, java.lang.String, java.lang.Short, java.sql.Timestamp> fieldsRow() { return (org.jooq.Row4) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Row4<java.lang.Short, java.lang.String, java.lang.Short, java.sql.Timestamp> valuesRow() { return (org.jooq.Row4) super.valuesRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field1() { return org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY.CITY_ID; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field2() { return org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY.CITY_; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.Short> field3() { return org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY.COUNTRY_ID; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.sql.Timestamp> field4() { return org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY.LAST_UPDATE; } /** * {@inheritDoc} */ @Override public java.lang.Short value1() { return getCityId(); } /** * {@inheritDoc} */ @Override public java.lang.String value2() { return getCity(); } /** * {@inheritDoc} */ @Override public java.lang.Short value3() { return getCountryId(); } /** * {@inheritDoc} */ @Override public java.sql.Timestamp value4() { return getLastUpdate(); } /** * {@inheritDoc} */ @Override public SakilaCityRecord value1(java.lang.Short value) { setCityId(value); return this; } /** * {@inheritDoc} */ @Override public SakilaCityRecord value2(java.lang.String value) { setCity(value); return this; } /** * {@inheritDoc} */ @Override public SakilaCityRecord value3(java.lang.Short value) { setCountryId(value); return this; } /** * {@inheritDoc} */ @Override public SakilaCityRecord value4(java.sql.Timestamp value) { setLastUpdate(value); return this; } /** * {@inheritDoc} */ @Override public SakilaCityRecord values(java.lang.Short value1, java.lang.String value2, java.lang.Short value3, java.sql.Timestamp value4) { return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached SakilaCityRecord */ public SakilaCityRecord() { super(org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY); } /** * Create a detached, initialised SakilaCityRecord */ public SakilaCityRecord(java.lang.Short cityId, java.lang.String city, java.lang.Short countryId, java.sql.Timestamp lastUpdate) { super(org.jooq.examples.mysql.sakila.tables.SakilaCity.CITY); setValue(0, cityId); setValue(1, city); setValue(2, countryId); setValue(3, lastUpdate); } }
922e71937ab1e52da5e2d2ba5440b10ed72c08c4
310
java
Java
study-try-finally/src/com/example/PreciousResource.java
deepcloudlabs/dcl204-2021-dec-14
2fed9042830ebee84c74da10bdd46923af47c6a3
[ "MIT" ]
1
2022-01-14T08:31:44.000Z
2022-01-14T08:31:44.000Z
study-try-finally/src/com/example/PreciousResource.java
deepcloudlabs/dcl204-2021-dec-14
2fed9042830ebee84c74da10bdd46923af47c6a3
[ "MIT" ]
null
null
null
study-try-finally/src/com/example/PreciousResource.java
deepcloudlabs/dcl204-2021-dec-14
2fed9042830ebee84c74da10bdd46923af47c6a3
[ "MIT" ]
null
null
null
18.235294
60
0.725806
994,749
package com.example; public class PreciousResource implements AutoCloseable { private int id; public PreciousResource(int id) { this.id = id; } @Override public void close() throws Exception { System.err.println("Closing the precious resource " + id); throw new RuntimeException("Ooops!"); } }
922e71d8fa6c479ac98be6b96f5f73aafeebf051
4,016
java
Java
fluent/src/main/java/io/kubernetes/client/openapi/models/V1LoadBalancerStatusFluent.java
luke-zhang580/java
edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b
[ "Apache-2.0" ]
2,389
2017-05-13T16:11:07.000Z
2022-03-31T07:06:17.000Z
fluent/src/main/java/io/kubernetes/client/openapi/models/V1LoadBalancerStatusFluent.java
luke-zhang580/java
edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b
[ "Apache-2.0" ]
2,128
2017-05-10T17:53:06.000Z
2022-03-30T22:21:15.000Z
fluent/src/main/java/io/kubernetes/client/openapi/models/V1LoadBalancerStatusFluent.java
luke-zhang580/java
edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b
[ "Apache-2.0" ]
1,112
2017-05-10T03:45:57.000Z
2022-03-31T10:02:03.000Z
70.45614
227
0.833665
994,750
package io.kubernetes.client.openapi.models; import io.kubernetes.client.fluent.VisitableBuilder; import com.google.gson.annotations.SerializedName; import io.kubernetes.client.fluent.Fluent; import io.kubernetes.client.fluent.Nested; import java.util.ArrayList; import java.lang.String; import java.util.function.Predicate; import java.lang.Integer; import java.lang.Deprecated; import java.util.Iterator; import java.util.Collection; import java.util.List; import java.lang.Boolean; /** * Generated */ public interface V1LoadBalancerStatusFluent<A extends io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent<A>> extends io.kubernetes.client.fluent.Fluent<A>{ public A addToIngress(java.lang.Integer index,io.kubernetes.client.openapi.models.V1LoadBalancerIngress item); public A setToIngress(java.lang.Integer index,io.kubernetes.client.openapi.models.V1LoadBalancerIngress item); public A addToIngress(io.kubernetes.client.openapi.models.V1LoadBalancerIngress... items); public A addAllToIngress(java.util.Collection<io.kubernetes.client.openapi.models.V1LoadBalancerIngress> items); public A removeFromIngress(io.kubernetes.client.openapi.models.V1LoadBalancerIngress... items); public A removeAllFromIngress(java.util.Collection<io.kubernetes.client.openapi.models.V1LoadBalancerIngress> items); public A removeMatchingFromIngress(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1LoadBalancerIngressBuilder> predicate); /** * This method has been deprecated, please use method buildIngress instead. * @return The buildable object. */ @java.lang.Deprecated public java.util.List<io.kubernetes.client.openapi.models.V1LoadBalancerIngress> getIngress(); public java.util.List<io.kubernetes.client.openapi.models.V1LoadBalancerIngress> buildIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerIngress buildIngress(java.lang.Integer index); public io.kubernetes.client.openapi.models.V1LoadBalancerIngress buildFirstIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerIngress buildLastIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerIngress buildMatchingIngress(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1LoadBalancerIngressBuilder> predicate); public java.lang.Boolean hasMatchingIngress(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1LoadBalancerIngressBuilder> predicate); public A withIngress(java.util.List<io.kubernetes.client.openapi.models.V1LoadBalancerIngress> ingress); public A withIngress(io.kubernetes.client.openapi.models.V1LoadBalancerIngress... ingress); public java.lang.Boolean hasIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> addNewIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> addNewIngressLike(io.kubernetes.client.openapi.models.V1LoadBalancerIngress item); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> setNewIngressLike(java.lang.Integer index,io.kubernetes.client.openapi.models.V1LoadBalancerIngress item); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> editIngress(java.lang.Integer index); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> editFirstIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> editLastIngress(); public io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<A> editMatchingIngress(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1LoadBalancerIngressBuilder> predicate); public interface IngressNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1LoadBalancerIngressFluent<io.kubernetes.client.openapi.models.V1LoadBalancerStatusFluent.IngressNested<N>>{ public N and(); public N endIngress(); } }
922e746d4abee87637cc9a0fde60017f12ac0173
2,004
java
Java
ForgeBackend/src/main/java/com/forge/PortfolioReviewService/models/PortfolioItems.java
tech-david/deployforge
96791e6f96ba44eba17011cf38e8309859b1a3c3
[ "MIT" ]
null
null
null
ForgeBackend/src/main/java/com/forge/PortfolioReviewService/models/PortfolioItems.java
tech-david/deployforge
96791e6f96ba44eba17011cf38e8309859b1a3c3
[ "MIT" ]
null
null
null
ForgeBackend/src/main/java/com/forge/PortfolioReviewService/models/PortfolioItems.java
tech-david/deployforge
96791e6f96ba44eba17011cf38e8309859b1a3c3
[ "MIT" ]
null
null
null
26.368421
110
0.778942
994,751
package com.forge.PortfolioReviewService.models; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Generated; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity() @Table(name = "portfolio_items") @EqualsAndHashCode() @Generated() /* Wrapper class for potfolio section bean that includes some extra metadata * such as the title of the section, it's priority in the portfolio * and loosely coupling the individuals beans from the portfolio instance * */ public class PortfolioItems{ @JsonIgnore @Transient private static final String SIMPLE_NAME = PortfolioItems.class.getSimpleName(); @Id @Column(name = "portfolio_items_id") @GeneratedValue(strategy = GenerationType.AUTO) private int portfolioItemId; @ManyToOne(targetEntity = Portfolio.class, cascade = CascadeType.ALL) @JoinColumn(name="portfolio_id", nullable = false) private int portfolioId; @Column(name = "priority") private int priority; //to implement custom section titles in future sprints //set default database value to class name instead of default bean field @Column(name = "title", nullable = false) private String title = SIMPLE_NAME; @OneToMany(targetEntity=PortfolioItems.class, mappedBy="portfolioItemId") public List<?> items; @Override public String toString() { return "PortfolioItems [portfolioItemId=" + portfolioItemId + ", portfolioId=" + portfolioId + ", priority=" + priority + ", title=" + title + "]"; } }
922e74f082825916812108bce814d197db02e5f6
884
java
Java
src/main/java/com/petsvalley/service/PhysicalService.java
guancgsuccess/petsvalley
82c9e39f271bd18c2bd6aee654bca0dc11773c6a
[ "Apache-2.0" ]
1
2021-06-17T02:57:17.000Z
2021-06-17T02:57:17.000Z
src/main/java/com/petsvalley/service/PhysicalService.java
guancgsuccess/petsvalley
82c9e39f271bd18c2bd6aee654bca0dc11773c6a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/petsvalley/service/PhysicalService.java
guancgsuccess/petsvalley
82c9e39f271bd18c2bd6aee654bca0dc11773c6a
[ "Apache-2.0" ]
1
2021-06-17T02:57:18.000Z
2021-06-17T02:57:18.000Z
28.516129
113
0.763575
994,752
package com.petsvalley.service; import com.petsvalley.entity.Apply; import com.petsvalley.entity.Physicals; import com.petsvalley.util.PageModel; import java.util.Date; public interface PhysicalService { PageModel<Physicals> getPhysicalByPage( PageModel<Physicals> page, Integer userId ); Integer getCount( Integer userId ); Integer deleteById( Integer msgid ); Integer getCountByDate( Integer userId, Date to, Date from1 ); PageModel<Physicals> getPhysicalByPageDate( PageModel<Physicals> page, Integer userId, Date to, Date from1 ); int insert( Physicals physicals ); Integer getCountManage( ); PageModel<Physicals> getPhysicalsByPageManage( PageModel<Physicals> page ); Integer getCountByDateManage( Date to2, Date from2 ); PageModel<Physicals> getPhysicalsByPageDateManage( PageModel<Physicals> page, Date to2, Date from2 ); }
922e751b17d7e3849d2d0882c897c5089173c9be
2,154
java
Java
habitaciones-01-logic/src/main/java/co/edu/uniandes/csw/habitaciones/ejbs/MultaLogic.java
Uniandes-isis2603/habitaciones_01
ad035f03509588bcafcba71dc6cb3fa03348a905
[ "MIT" ]
null
null
null
habitaciones-01-logic/src/main/java/co/edu/uniandes/csw/habitaciones/ejbs/MultaLogic.java
Uniandes-isis2603/habitaciones_01
ad035f03509588bcafcba71dc6cb3fa03348a905
[ "MIT" ]
null
null
null
habitaciones-01-logic/src/main/java/co/edu/uniandes/csw/habitaciones/ejbs/MultaLogic.java
Uniandes-isis2603/habitaciones_01
ad035f03509588bcafcba71dc6cb3fa03348a905
[ "MIT" ]
null
null
null
33.65625
93
0.692201
994,753
/* * Copyright (C) 2017 c.penaloza. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package co.edu.uniandes.csw.habitaciones.ejbs; import co.edu.uniandes.csw.habitaciones.entities.MultaEntity; import co.edu.uniandes.csw.habitaciones.exceptions.BusinessLogicException; import co.edu.uniandes.csw.habitaciones.persistence.MultaPersistence; import javax.ejb.Stateless; import javax.inject.Inject; import org.springframework.util.Assert; @Stateless public class MultaLogic { public MultaLogic(){ } private static final long serialVersionUID = 1L; @Inject public MultaLogic (MultaPersistence persistence) { Assert.notNull(persistence, "My persistence must be not null"); this.persistence = persistence; } private MultaPersistence persistence; public MultaEntity getMulta(Long codigo){ return persistence.find(codigo); } public MultaEntity createMulta(MultaEntity entity) throws BusinessLogicException{ if( persistence.find(entity.getReserva().getCodigoReserva()) == null) { throw new BusinessLogicException("Ya existe una multa asociada a esa reserva."); } persistence.create(entity); return entity; } public MultaEntity updateMulta(MultaEntity entity){ return persistence.update(entity); } }
922e754f44d4c053087d768dc0289ac23c15d0db
5,140
java
Java
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/com/facebook/drawee/backends/pipeline/R.java
Fausts-Alptraum/518120910046AndroidHW6
186a0ff130d3e7d274ec29c6899fe1a62f2e6451
[ "Apache-2.0" ]
6
2021-03-04T16:31:57.000Z
2021-06-09T16:07:47.000Z
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/com/facebook/drawee/backends/pipeline/R.java
Fausts-Alptraum/518120910046AndroidHW6
186a0ff130d3e7d274ec29c6899fe1a62f2e6451
[ "Apache-2.0" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/com/facebook/drawee/backends/pipeline/R.java
Fausts-Alptraum/518120910046AndroidHW6
186a0ff130d3e7d274ec29c6899fe1a62f2e6451
[ "Apache-2.0" ]
null
null
null
58.409091
362
0.745136
994,754
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.facebook.drawee.backends.pipeline; public final class R { private R() {} public static final class attr { private attr() {} public static final int actualImageScaleType = 0x7f020022; public static final int actualImageUri = 0x7f020023; public static final int backgroundImage = 0x7f020034; public static final int fadeDuration = 0x7f02007c; public static final int failureImage = 0x7f02007d; public static final int failureImageScaleType = 0x7f02007e; public static final int overlayImage = 0x7f0200eb; public static final int placeholderImage = 0x7f0200f3; public static final int placeholderImageScaleType = 0x7f0200f4; public static final int pressedStateOverlayImage = 0x7f0200f9; public static final int progressBarAutoRotateInterval = 0x7f0200fa; public static final int progressBarImage = 0x7f0200fb; public static final int progressBarImageScaleType = 0x7f0200fc; public static final int retryImage = 0x7f020105; public static final int retryImageScaleType = 0x7f020106; public static final int roundAsCircle = 0x7f020107; public static final int roundBottomLeft = 0x7f020108; public static final int roundBottomRight = 0x7f020109; public static final int roundTopLeft = 0x7f02010a; public static final int roundTopRight = 0x7f02010b; public static final int roundWithOverlayColor = 0x7f02010c; public static final int roundedCornerRadius = 0x7f02010d; public static final int roundingBorderColor = 0x7f02010e; public static final int roundingBorderPadding = 0x7f02010f; public static final int roundingBorderWidth = 0x7f020110; public static final int viewAspectRatio = 0x7f020156; } public static final class id { private id() {} public static final int center = 0x7f07002d; public static final int centerCrop = 0x7f07002e; public static final int centerInside = 0x7f07002f; public static final int fitCenter = 0x7f070049; public static final int fitEnd = 0x7f07004a; public static final int fitStart = 0x7f07004b; public static final int fitXY = 0x7f07004c; public static final int focusCrop = 0x7f07004d; public static final int none = 0x7f07006e; } public static final class styleable { private styleable() {} public static final int[] GenericDraweeHierarchy = { 0x7f020022, 0x7f020034, 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f0200eb, 0x7f0200f3, 0x7f0200f4, 0x7f0200f9, 0x7f0200fa, 0x7f0200fb, 0x7f0200fc, 0x7f020105, 0x7f020106, 0x7f020107, 0x7f020108, 0x7f020109, 0x7f02010a, 0x7f02010b, 0x7f02010c, 0x7f02010d, 0x7f02010e, 0x7f02010f, 0x7f020110, 0x7f020156 }; public static final int GenericDraweeHierarchy_actualImageScaleType = 0; public static final int GenericDraweeHierarchy_backgroundImage = 1; public static final int GenericDraweeHierarchy_fadeDuration = 2; public static final int GenericDraweeHierarchy_failureImage = 3; public static final int GenericDraweeHierarchy_failureImageScaleType = 4; public static final int GenericDraweeHierarchy_overlayImage = 5; public static final int GenericDraweeHierarchy_placeholderImage = 6; public static final int GenericDraweeHierarchy_placeholderImageScaleType = 7; public static final int GenericDraweeHierarchy_pressedStateOverlayImage = 8; public static final int GenericDraweeHierarchy_progressBarAutoRotateInterval = 9; public static final int GenericDraweeHierarchy_progressBarImage = 10; public static final int GenericDraweeHierarchy_progressBarImageScaleType = 11; public static final int GenericDraweeHierarchy_retryImage = 12; public static final int GenericDraweeHierarchy_retryImageScaleType = 13; public static final int GenericDraweeHierarchy_roundAsCircle = 14; public static final int GenericDraweeHierarchy_roundBottomLeft = 15; public static final int GenericDraweeHierarchy_roundBottomRight = 16; public static final int GenericDraweeHierarchy_roundTopLeft = 17; public static final int GenericDraweeHierarchy_roundTopRight = 18; public static final int GenericDraweeHierarchy_roundWithOverlayColor = 19; public static final int GenericDraweeHierarchy_roundedCornerRadius = 20; public static final int GenericDraweeHierarchy_roundingBorderColor = 21; public static final int GenericDraweeHierarchy_roundingBorderPadding = 22; public static final int GenericDraweeHierarchy_roundingBorderWidth = 23; public static final int GenericDraweeHierarchy_viewAspectRatio = 24; public static final int[] SimpleDraweeView = { 0x7f020023 }; public static final int SimpleDraweeView_actualImageUri = 0; } }
922e760c04891ca1691cfb6da56b3c415b94408a
37,426
java
Java
sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/FlatteningSerializerTests.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/FlatteningSerializerTests.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/core/azure-core/src/test/java/com/azure/core/implementation/jackson/FlatteningSerializerTests.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
49.115486
252
0.688292
994,755
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.implementation.jackson; import com.azure.core.implementation.TypeUtil; import com.azure.core.implementation.models.jsonflatten.ClassWithFlattenedProperties; import com.azure.core.implementation.models.jsonflatten.FlattenedProduct; import com.azure.core.implementation.models.jsonflatten.FlattenedPropertiesAndJsonAnyGetter; import com.azure.core.implementation.models.jsonflatten.JsonFlattenNestedInner; import com.azure.core.implementation.models.jsonflatten.JsonFlattenOnArrayType; import com.azure.core.implementation.models.jsonflatten.JsonFlattenOnCollectionType; import com.azure.core.implementation.models.jsonflatten.JsonFlattenOnJsonIgnoredProperty; import com.azure.core.implementation.models.jsonflatten.JsonFlattenOnPrimitiveType; import com.azure.core.implementation.models.jsonflatten.JsonFlattenWithJsonInfoDiscriminator; import com.azure.core.implementation.models.jsonflatten.SampleResource; import com.azure.core.implementation.models.jsonflatten.School; import com.azure.core.implementation.models.jsonflatten.Student; import com.azure.core.implementation.models.jsonflatten.Teacher; import com.azure.core.implementation.models.jsonflatten.VirtualMachineIdentity; import com.azure.core.implementation.models.jsonflatten.VirtualMachineScaleSet; import com.azure.core.implementation.models.jsonflatten.VirtualMachineScaleSetNetworkConfiguration; import com.azure.core.implementation.models.jsonflatten.VirtualMachineScaleSetNetworkProfile; import com.azure.core.implementation.models.jsonflatten.VirtualMachineScaleSetVMProfile; import com.azure.core.util.serializer.JacksonAdapter; import com.azure.core.util.serializer.SerializerEncoding; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import wiremock.com.google.common.collect.ImmutableList; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class FlatteningSerializerTests { private static final JacksonAdapter ADAPTER = new JacksonAdapter(); @Test public void canFlatten() { Foo foo = new Foo(); foo.bar("hello.world"); // List<String> baz = Arrays.asList("hello", "hello.world"); foo.baz(baz); HashMap<String, String> qux = new HashMap<>(); qux.put("hello", "world"); qux.put("a.b", "c.d"); qux.put("bar.a", "ttyy"); qux.put("bar.b", "uuzz"); foo.qux(qux); // serialization String serialized = serialize(foo); assertEquals("{\"$type\":\"foo\",\"properties\":{\"bar\":\"hello.world\",\"props\":{\"baz\":[\"hello\",\"hello.world\"],\"q\":{\"qux\":{\"hello\":\"world\",\"a.b\":\"c.d\",\"bar.b\":\"uuzz\",\"bar.a\":\"ttyy\"}}}}}", serialized); // deserialization Foo deserialized = deserialize(serialized, Foo.class); assertEquals("hello.world", deserialized.bar()); Assertions.assertArrayEquals(new String[]{"hello", "hello.world"}, deserialized.baz().toArray()); assertNotNull(deserialized.qux()); assertEquals("world", deserialized.qux().get("hello")); assertEquals("c.d", deserialized.qux().get("a.b")); assertEquals("ttyy", deserialized.qux().get("bar.a")); assertEquals("uuzz", deserialized.qux().get("bar.b")); } @Test public void canSerializeMapKeysWithDotAndSlash() { String serialized = serialize(prepareSchoolModel()); assertEquals("{\"teacher\":{\"students\":{\"af.B/D\":{},\"af.B/C\":{}}},\"tags\":{\"foo.aa\":\"bar\",\"x.y\":\"zz\"},\"properties\":{\"name\":\"school1\"}}", serialized); } /** * Validates decoding and encoding of a type with type id containing dot and no additional properties For decoding * and encoding base type will be used. */ @Test public void canHandleTypeWithTypeIdContainingDotAndNoProperties() { String rabbitSerialized = "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}"; String shelterSerialized = "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}},{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}}]}}"; AnimalWithTypeIdContainingDot rabbitDeserialized = deserialize(rabbitSerialized, AnimalWithTypeIdContainingDot.class); assertTrue(rabbitDeserialized instanceof RabbitWithTypeIdContainingDot); assertNotNull(rabbitDeserialized); AnimalShelter shelterDeserialized = deserialize(shelterSerialized, AnimalShelter.class); assertNotNull(shelterDeserialized); assertEquals(2, shelterDeserialized.animalsInfo().size()); for (FlattenableAnimalInfo animalInfo : shelterDeserialized.animalsInfo()) { assertTrue(animalInfo.animal() instanceof RabbitWithTypeIdContainingDot); assertNotNull(animalInfo.animal()); } } /** * Validates that decoding and encoding of a type with type id containing dot and can be done. For decoding and * encoding base type will be used. */ @Test public void canHandleTypeWithTypeIdContainingDot0() { List<String> meals = Arrays.asList("carrot", "apple"); // AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals); String serialized = serialize(animalToSerialize); // String[] results = { "{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}", "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}" }; assertTrue(Arrays.asList(results).contains(serialized)); // De-Serialize // AnimalWithTypeIdContainingDot animalDeserialized = deserialize(serialized, AnimalWithTypeIdContainingDot.class); assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot); RabbitWithTypeIdContainingDot rabbit = (RabbitWithTypeIdContainingDot) animalDeserialized; assertNotNull(rabbit.meals()); assertEquals(rabbit.meals().size(), 2); } /** * Validates that decoding and encoding of a type with type id containing dot and can be done. For decoding and * encoding concrete type will be used. */ @Test public void canHandleTypeWithTypeIdContainingDot1() { List<String> meals = Arrays.asList("carrot", "apple"); // RabbitWithTypeIdContainingDot rabbitToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals); String serialized = serialize(rabbitToSerialize); // String[] results = { "{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}", "{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}" }; assertTrue(Arrays.asList(results).contains(serialized)); // De-Serialize // RabbitWithTypeIdContainingDot rabbitDeserialized = deserialize(serialized, RabbitWithTypeIdContainingDot.class); assertNotNull(rabbitDeserialized); assertNotNull(rabbitDeserialized.meals()); assertEquals(rabbitDeserialized.meals().size(), 2); } /** * Validates that decoding and encoding of a type with flattenable property and type id containing dot and can be * done. For decoding and encoding base type will be used. */ @Test public void canHandleTypeWithFlattenablePropertyAndTypeIdContainingDot0() { AnimalWithTypeIdContainingDot animalToSerialize = new DogWithTypeIdContainingDot() .withBreed("AKITA") .withCuteLevel(10); // serialization String serialized = serialize(animalToSerialize); String[] results = { "{\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10}}", "{\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}", "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10}}", "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\"}", "{\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\"}", "{\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}", }; assertTrue(Arrays.asList(results).contains(serialized)); // de-serialization AnimalWithTypeIdContainingDot animalDeserialized = deserialize(serialized, AnimalWithTypeIdContainingDot.class); assertTrue(animalDeserialized instanceof DogWithTypeIdContainingDot); DogWithTypeIdContainingDot dogDeserialized = (DogWithTypeIdContainingDot) animalDeserialized; assertNotNull(dogDeserialized); assertEquals(dogDeserialized.breed(), "AKITA"); assertEquals(dogDeserialized.cuteLevel(), (Integer) 10); } /** * Validates that decoding and encoding of a type with flattenable property and type id containing dot and can be * done. For decoding and encoding concrete type will be used. */ @Test public void canHandleTypeWithFlattenablePropertyAndTypeIdContainingDot1() { DogWithTypeIdContainingDot dogToSerialize = new DogWithTypeIdContainingDot().withBreed("AKITA").withCuteLevel(10); // serialization String serialized = serialize(dogToSerialize); String[] results = { "{\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10}}", "{\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}", "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\",\"properties\":{\"cuteLevel\":10}}", "{\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\"}", "{\"properties\":{\"cuteLevel\":10},\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\",\"breed\":\"AKITA\"}", "{\"properties\":{\"cuteLevel\":10},\"breed\":\"AKITA\",\"@odata.type\":\"#Favourite.Pet.DogWithTypeIdContainingDot\"}", }; assertTrue(Arrays.asList(results).contains(serialized)); // de-serialization DogWithTypeIdContainingDot dogDeserialized = deserialize(serialized, DogWithTypeIdContainingDot.class); assertNotNull(dogDeserialized); assertEquals(dogDeserialized.breed(), "AKITA"); assertEquals(dogDeserialized.cuteLevel(), (Integer) 10); } /** * Validates that decoding and encoding of a array of type with type id containing dot and can be done. For decoding * and encoding base type will be used. */ @Test public void canHandleArrayOfTypeWithTypeIdContainingDot0() { List<String> meals = Arrays.asList("carrot", "apple"); // AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals); List<AnimalWithTypeIdContainingDot> animalsToSerialize = new ArrayList<>(); animalsToSerialize.add(animalToSerialize); String serialized = serialize(animalsToSerialize); String[] results = { "[{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}]", "[{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}]", }; assertTrue(Arrays.asList(results).contains(serialized)); // De-serialize // List<AnimalWithTypeIdContainingDot> animalsDeserialized = deserialize(serialized, TypeUtil.createParameterizedType(List.class, AnimalWithTypeIdContainingDot.class)); assertNotNull(animalsDeserialized); assertEquals(1, animalsDeserialized.size()); AnimalWithTypeIdContainingDot animalDeserialized = animalsDeserialized.get(0); assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot); RabbitWithTypeIdContainingDot rabbitDeserialized = (RabbitWithTypeIdContainingDot) animalDeserialized; assertNotNull(rabbitDeserialized.meals()); assertEquals(rabbitDeserialized.meals().size(), 2); } /** * Validates that decoding and encoding of a array of type with type id containing dot and can be done. For decoding * and encoding concrete type will be used. */ @Test public void canHandleArrayOfTypeWithTypeIdContainingDot1() { List<String> meals = Arrays.asList("carrot", "apple"); // RabbitWithTypeIdContainingDot rabbitToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals); List<RabbitWithTypeIdContainingDot> rabbitsToSerialize = new ArrayList<>(); rabbitsToSerialize.add(rabbitToSerialize); String serialized = serialize(rabbitsToSerialize); String[] results = { "[{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}]", "[{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}]", }; assertTrue(Arrays.asList(results).contains(serialized)); // De-serialize // List<RabbitWithTypeIdContainingDot> rabbitsDeserialized = deserialize(serialized, TypeUtil.createParameterizedType(List.class, RabbitWithTypeIdContainingDot.class)); assertNotNull(rabbitsDeserialized); assertEquals(1, rabbitsDeserialized.size()); RabbitWithTypeIdContainingDot rabbitDeserialized = rabbitsDeserialized.get(0); assertNotNull(rabbitDeserialized.meals()); assertEquals(rabbitDeserialized.meals().size(), 2); } /** * Validates that decoding and encoding of a composed type with type id containing dot and can be done. */ @Test public void canHandleComposedTypeWithTypeIdContainingDot0() { List<String> meals = Arrays.asList("carrot", "apple"); AnimalWithTypeIdContainingDot animalToSerialize = new RabbitWithTypeIdContainingDot().withMeals(meals); FlattenableAnimalInfo animalInfoToSerialize = new FlattenableAnimalInfo().withAnimal(animalToSerialize); List<FlattenableAnimalInfo> animalsInfoSerialized = ImmutableList.of(animalInfoToSerialize); AnimalShelter animalShelterToSerialize = new AnimalShelter().withAnimalsInfo(animalsInfoSerialized); String serialized = serialize(animalShelterToSerialize); String[] results = { "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"meals\":[\"carrot\",\"apple\"],\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\"}}]}}", "{\"properties\":{\"animalsInfo\":[{\"animal\":{\"@odata.type\":\"#Favourite.Pet.RabbitWithTypeIdContainingDot\",\"meals\":[\"carrot\",\"apple\"]}}]}}", }; assertTrue(Arrays.asList(results).contains(serialized)); // de-serialization // AnimalShelter shelterDeserialized = deserialize(serialized, AnimalShelter.class); assertNotNull(shelterDeserialized.animalsInfo()); assertEquals(shelterDeserialized.animalsInfo().size(), 1); FlattenableAnimalInfo animalsInfoDeserialized = shelterDeserialized.animalsInfo().get(0); assertTrue(animalsInfoDeserialized.animal() instanceof RabbitWithTypeIdContainingDot); AnimalWithTypeIdContainingDot animalDeserialized = animalsInfoDeserialized.animal(); assertTrue(animalDeserialized instanceof RabbitWithTypeIdContainingDot); RabbitWithTypeIdContainingDot rabbitDeserialized = (RabbitWithTypeIdContainingDot) animalDeserialized; assertNotNull(rabbitDeserialized); assertNotNull(rabbitDeserialized.meals()); assertEquals(rabbitDeserialized.meals().size(), 2); } @Test public void canHandleComposedSpecificPolymorphicTypeWithTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet1()); assertEquals(2, composedTurtleDeserialized.turtlesSet1().size()); // serialize(composedTurtleDeserialized); // // -- Validate scalar property // String serializedScalarWithTypeId = "{\"turtlesSet1Lead\":{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}}"; // de-serialization // composedTurtleDeserialized = deserialize(serializedScalarWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet1Lead()); assertEquals(10, (long) composedTurtleDeserialized.turtlesSet1Lead().size()); assertEquals(100, (long) composedTurtleDeserialized.turtlesSet1Lead().age()); // serialize(composedTurtleDeserialized); } @Test public void canHandleComposedSpecificPolymorphicTypeWithoutTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10 },{\"age\":200,\"size\":20 }]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet1()); assertEquals(2, composedTurtleDeserialized.turtlesSet1().size()); // serialize(composedTurtleDeserialized); // // -- Validate scalar property // String serializedScalarWithTypeId = "{\"turtlesSet1Lead\":{\"age\":100,\"size\":10 }}"; // de-serialization // composedTurtleDeserialized = deserialize(serializedScalarWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet1Lead()); assertEquals(100, (long) composedTurtleDeserialized.turtlesSet1Lead().age()); // serialize(composedTurtleDeserialized); } @Test public void canHandleComposedSpecificPolymorphicTypeWithAndWithoutTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet1\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20 }]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet1()); assertEquals(2, composedTurtleDeserialized.turtlesSet1().size()); // serialize(composedTurtleDeserialized); } @Test public void canHandleComposedGenericPolymorphicTypeWithTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet2()); assertEquals(2, composedTurtleDeserialized.turtlesSet2().size()); // assertTrue(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot); assertTrue(composedTurtleDeserialized.turtlesSet2().get(1) instanceof TurtleWithTypeIdContainingDot); // serialize(composedTurtleDeserialized); // // -- Validate scalar property // String serializedScalarWithTypeId = "{\"turtlesSet2Lead\":{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"}}"; // de-serialization // composedTurtleDeserialized = deserialize(serializedScalarWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet2Lead()); assertTrue(composedTurtleDeserialized.turtlesSet2Lead() instanceof TurtleWithTypeIdContainingDot); assertEquals(10, (long) ((TurtleWithTypeIdContainingDot) composedTurtleDeserialized.turtlesSet2Lead()).size()); assertEquals(100, (long) composedTurtleDeserialized.turtlesSet2Lead().age()); // serialize(composedTurtleDeserialized); } @Test public void canHandleComposedGenericPolymorphicTypeWithoutTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10 },{\"age\":200,\"size\":20 }]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet2()); assertEquals(2, composedTurtleDeserialized.turtlesSet2().size()); // Assertions.assertFalse(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot); Assertions.assertFalse(composedTurtleDeserialized.turtlesSet2().get(1) instanceof TurtleWithTypeIdContainingDot); // // -- Validate scalar property // serialize(composedTurtleDeserialized); // String serializedScalarWithTypeId = "{\"turtlesSet2Lead\":{\"age\":100,\"size\":10 }}"; // de-serialization // composedTurtleDeserialized = deserialize(serializedScalarWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet2Lead()); // serialize(composedTurtleDeserialized); } @Test public void canHandleComposedGenericPolymorphicTypeWithAndWithoutTypeId() { // // -- Validate vector property // String serializedCollectionWithTypeId = "{\"turtlesSet2\":[{\"age\":100,\"size\":10,\"@odata.type\":\"#Favourite.Pet.TurtleWithTypeIdContainingDot\"},{\"age\":200,\"size\":20 }]}"; // de-serialization // ComposeTurtles composedTurtleDeserialized = deserialize(serializedCollectionWithTypeId, ComposeTurtles.class); assertNotNull(composedTurtleDeserialized); assertNotNull(composedTurtleDeserialized.turtlesSet2()); assertEquals(2, composedTurtleDeserialized.turtlesSet2().size()); // assertTrue(composedTurtleDeserialized.turtlesSet2().get(0) instanceof TurtleWithTypeIdContainingDot); assertNotNull(composedTurtleDeserialized.turtlesSet2().get(1)); // serialize(composedTurtleDeserialized); } @Test public void canHandleEscapedProperties() { FlattenedProduct productToSerialize = new FlattenedProduct() .setProductName("drink") .setProductType("chai"); // serialization // String serialized = serialize(productToSerialize); String[] results = { "{\"properties\":{\"p.name\":\"drink\",\"type\":\"chai\"}}", "{\"properties\":{\"type\":\"chai\",\"p.name\":\"drink\"}}", }; assertTrue(Arrays.asList(results).contains(serialized)); // de-serialization // FlattenedProduct productDeserialized = deserialize(serialized, FlattenedProduct.class); assertNotNull(productDeserialized); assertEquals(productDeserialized.getProductName(), "drink"); assertEquals(productDeserialized.getProductType(), "chai"); } @Test public void canHandleSinglePropertyBeingFlattened() { ClassWithFlattenedProperties classWithFlattenedProperties = new ClassWithFlattenedProperties("random", "E24JJxztP"); String serialized = serialize(classWithFlattenedProperties); String[] results = { "{\"@odata\":{\"type\":\"random\"},\"@odata.etag\":\"E24JJxztP\"}", "{\"@odata.etag\":\"E24JJxztP\",\"@odata\":{\"type\":\"random\"}}" }; assertTrue(Arrays.asList(results).contains(serialized)); ClassWithFlattenedProperties deserialized = deserialize(serialized, ClassWithFlattenedProperties.class); assertNotNull(deserialized); assertEquals(classWithFlattenedProperties.getOdataType(), deserialized.getOdataType()); assertEquals(classWithFlattenedProperties.getOdataETag(), deserialized.getOdataETag()); } @Test public void canHandleMultiLevelPropertyFlattening() { VirtualMachineScaleSet virtualMachineScaleSet = new VirtualMachineScaleSet() .setVirtualMachineProfile(new VirtualMachineScaleSetVMProfile() .setNetworkProfile(new VirtualMachineScaleSetNetworkProfile() .setNetworkInterfaceConfigurations(Collections.singletonList( new VirtualMachineScaleSetNetworkConfiguration().setName("name").setPrimary(true))))); String serialized = serialize(virtualMachineScaleSet); String expected = "{\"properties\":{\"virtualMachineProfile\":{\"networkProfile\":{\"networkInterfaceConfigurations\":[{\"name\":\"name\",\"properties\":{\"primary\":true}}]}}}}"; assertEquals(expected, serialized); VirtualMachineScaleSet deserialized = deserialize(serialized, VirtualMachineScaleSet.class); assertNotNull(deserialized); VirtualMachineScaleSetNetworkConfiguration expectedConfig = virtualMachineScaleSet.getVirtualMachineProfile() .getNetworkProfile() .getNetworkInterfaceConfigurations() .get(0); VirtualMachineScaleSetNetworkConfiguration actualConfig = deserialized.getVirtualMachineProfile() .getNetworkProfile() .getNetworkInterfaceConfigurations() .get(0); assertEquals(expectedConfig.getName(), actualConfig.getName()); assertEquals(expectedConfig.getPrimary(), actualConfig.getPrimary()); } @Test public void jsonFlattenOnArrayType() { JsonFlattenOnArrayType expected = new JsonFlattenOnArrayType() .setJsonFlattenArray(new String[]{"hello", "goodbye", null}); String expectedSerialization = "{\"jsonflatten\":{\"array\":[\"hello\",\"goodbye\",null]}}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); JsonFlattenOnArrayType deserialized = deserialize(actualSerialization, JsonFlattenOnArrayType.class); assertArrayEquals(expected.getJsonFlattenArray(), deserialized.getJsonFlattenArray()); } @Test public void jsonFlattenOnCollectionTypeList() { final List<String> listCollection = Arrays.asList("hello", "goodbye", null); JsonFlattenOnCollectionType expected = new JsonFlattenOnCollectionType() .setJsonFlattenCollection(Collections.unmodifiableList(listCollection)); String expectedSerialization = "{\"jsonflatten\":{\"collection\":[\"hello\",\"goodbye\",null]}}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); JsonFlattenOnCollectionType deserialized = deserialize(actualSerialization, JsonFlattenOnCollectionType.class); assertEquals(expected.getJsonFlattenCollection().size(), deserialized.getJsonFlattenCollection().size()); for (int i = 0; i < expected.getJsonFlattenCollection().size(); i++) { assertEquals(expected.getJsonFlattenCollection().get(i), deserialized.getJsonFlattenCollection().get(i)); } } @Test public void jsonFlattenOnJsonIgnoredProperty() { JsonFlattenOnJsonIgnoredProperty expected = new JsonFlattenOnJsonIgnoredProperty() .setName("name") .setIgnored("ignored"); String expectedSerialization = "{\"name\":\"name\"}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); JsonFlattenOnJsonIgnoredProperty deserialized = deserialize(actualSerialization, JsonFlattenOnJsonIgnoredProperty.class); assertEquals(expected.getName(), deserialized.getName()); assertNull(deserialized.getIgnored()); } @Test public void jsonFlattenOnPrimitiveType() { JsonFlattenOnPrimitiveType expected = new JsonFlattenOnPrimitiveType() .setJsonFlattenBoolean(true) .setJsonFlattenDecimal(1.25D) .setJsonFlattenNumber(2) .setJsonFlattenString("string"); String expectedSerialization = "{\"jsonflatten\":{\"boolean\":true,\"decimal\":1.25,\"number\":2,\"string\":\"string\"}}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); JsonFlattenOnPrimitiveType deserialized = deserialize(actualSerialization, JsonFlattenOnPrimitiveType.class); assertEquals(expected.isJsonFlattenBoolean(), deserialized.isJsonFlattenBoolean()); assertEquals(expected.getJsonFlattenDecimal(), deserialized.getJsonFlattenDecimal()); assertEquals(expected.getJsonFlattenNumber(), deserialized.getJsonFlattenNumber()); assertEquals(expected.getJsonFlattenString(), deserialized.getJsonFlattenString()); } @Test public void jsonFlattenWithJsonInfoDiscriminator() { JsonFlattenWithJsonInfoDiscriminator expected = new JsonFlattenWithJsonInfoDiscriminator() .setJsonFlattenDiscriminator("discriminator"); String expectedSerialization = "{\"type\":\"JsonFlattenWithJsonInfoDiscriminator\",\"jsonflatten\":{\"discriminator\":\"discriminator\"}}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); JsonFlattenWithJsonInfoDiscriminator deserialized = deserialize(actualSerialization, JsonFlattenWithJsonInfoDiscriminator.class); assertEquals(expected.getJsonFlattenDiscriminator(), deserialized.getJsonFlattenDiscriminator()); } @Test public void flattenedPropertiesAndJsonAnyGetter() { FlattenedPropertiesAndJsonAnyGetter expected = new FlattenedPropertiesAndJsonAnyGetter() .setString("string") .addAdditionalProperty("key1", "value1") .addAdditionalProperty("key2", "value2"); String expectedSerialization = "{\"flattened\":{\"string\":\"string\"},\"key1\":\"value1\",\"key2\":\"value2\"}"; String actualSerialization = serialize(expected); assertEquals(expectedSerialization, actualSerialization); FlattenedPropertiesAndJsonAnyGetter deserialized = deserialize(actualSerialization, FlattenedPropertiesAndJsonAnyGetter.class); assertEquals(expected.getString(), deserialized.getString()); assertEquals(expected.additionalProperties().size(), deserialized.additionalProperties().size()); for (String key : expected.additionalProperties().keySet()) { assertEquals(expected.additionalProperties().get(key), deserialized.additionalProperties().get(key)); } } @Test public void jsonFlattenFinalMap() { final HashMap<String, String> mapProperties = new HashMap<String, String>() {{ put("/subscriptions/0-0-0-0-0/resourcegroups/0/providers/Microsoft.ManagedIdentity/0", "value"); }}; School school = new School().setTags(mapProperties); String actualSerialization = serialize(school); String expectedSerialization = "{\"tags\":{\"/subscriptions/0-0-0-0-0/resourcegroups" + "/0/providers/Microsoft.ManagedIdentity/0\":\"value\"}}"; Assertions.assertEquals(expectedSerialization, actualSerialization); } @Test public void jsonFlattenNestedInner() { JsonFlattenNestedInner expected = new JsonFlattenNestedInner(); VirtualMachineIdentity identity = new VirtualMachineIdentity(); final Map<String, Object> map = new HashMap<>(); map.put("/subscriptions/0-0-0-0-0/resourcegroups/0/providers/Microsoft.ManagedIdentity/userAssignedIdentities/0", new Object()); identity.setType(Arrays.asList("SystemAssigned, UserAssigned")); identity.setUserAssignedIdentities(map); expected.setIdentity(identity); String expectedSerialization = "{\"identity\":{\"type\":[\"SystemAssigned, UserAssigned\"]," + "\"userAssignedIdentities\":{\"/subscriptions/0-0-0-0-0/resourcegroups/0/providers/" + "Microsoft.ManagedIdentity/userAssignedIdentities/0\":{}}}}"; String actualSerialization = serialize(expected); Assertions.assertEquals(expectedSerialization, actualSerialization); } @Test public void jsonFlattenRepeatedPropertyNameDeserialize() throws IOException { SampleResource deserialized = JacksonAdapter.createDefaultSerializerAdapter().deserialize( "{\"name\":\"...-01\",\"properties\":{\"registrationTtl\":\"10675199.02:48:05.4775807\",\"authorizationRules\":[]}}", SampleResource.class, SerializerEncoding.JSON ); assertEquals("10675199.02:48:05.4775807", deserialized.getRegistrationTtl()); assertNull(deserialized.getNamePropertiesName()); } @ParameterizedTest @MethodSource("emptyDanglingNodeJsonSupplier") public void jsonFlattenEmptyDanglingNodesDeserialize(String json, Object expected) throws IOException { // test to verify null dangling nodes are still retained and set to null FlattenDangling deserialized = JacksonAdapter.createDefaultSerializerAdapter().deserialize( json, FlattenDangling.class, SerializerEncoding.JSON ); assertEquals(expected, deserialized.getFlattenedProperty()); } private static String serialize(Object object) { try { return ADAPTER.serialize(object, SerializerEncoding.JSON); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static <T> T deserialize(String json, Type type) { try { return ADAPTER.deserialize(json, type, SerializerEncoding.JSON); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private static Stream<Arguments> emptyDanglingNodeJsonSupplier() { return Stream.of( Arguments.of("{\"a\":{}}", null), Arguments.of("{\"a\":{\"flattened\": {}}}", null), Arguments.of("{\"a\":{\"flattened\": {\"property\": null}}}", null), Arguments.of("{\"a\":{\"flattened\": {\"property\": \"value\"}}}", "value") ); } private School prepareSchoolModel() { Teacher teacher = new Teacher(); Map<String, Student> students = new HashMap<>(); students.put("af.B/C", new Student()); students.put("af.B/D", new Student()); teacher.setStudents(students); School school = new School().setName("school1"); school.setTeacher(teacher); Map<String, String> schoolTags = new HashMap<>(); schoolTags.put("foo.aa", "bar"); schoolTags.put("x.y", "zz"); school.setTags(schoolTags); return school; } }
922e77844efb00acf3c012449dfdd9a4242616cd
623
java
Java
product/src/main/java/io/github/thesixonenine/product/service/SkuInfoService.java
thesixonenine/619
f8b9d44f77a2eb81bd1fec6d747d8860433b0d2c
[ "MIT" ]
1
2020-06-30T01:22:08.000Z
2020-06-30T01:22:08.000Z
product/src/main/java/io/github/thesixonenine/product/service/SkuInfoService.java
thesixonenine/619
f8b9d44f77a2eb81bd1fec6d747d8860433b0d2c
[ "MIT" ]
null
null
null
product/src/main/java/io/github/thesixonenine/product/service/SkuInfoService.java
thesixonenine/619
f8b9d44f77a2eb81bd1fec6d747d8860433b0d2c
[ "MIT" ]
null
null
null
25.958333
76
0.796148
994,756
package io.github.thesixonenine.product.service; import com.baomidou.mybatisplus.extension.service.IService; import io.github.thesixonenine.common.utils.PageUtils; import io.github.thesixonenine.product.entity.SkuInfoEntity; import io.github.thesixonenine.product.vo.ItemVO; import java.util.Map; import java.util.concurrent.ExecutionException; /** * sku信息 * * @author thesixonenine * @date 2020-06-06 00:59:35 */ public interface SkuInfoService extends IService<SkuInfoEntity> { PageUtils queryPage(Map<String, Object> params); ItemVO item(Long skuId) throws ExecutionException, InterruptedException; }
922e78973e7ea0df78491083bc3991f18ea11343
83
java
Java
evl-examples/src/main/java/eu/daproject/evl/tomultimethods/part3/D.java
ylegoc/evl
d436edf01d01d8fdb61114d9e046f3993b5e3a68
[ "Apache-2.0" ]
1
2020-04-28T20:37:16.000Z
2020-04-28T20:37:16.000Z
evl-examples/src/main/java/eu/daproject/evl/tomultimethods/part3/D.java
ylegoc/evl
d436edf01d01d8fdb61114d9e046f3993b5e3a68
[ "Apache-2.0" ]
null
null
null
evl-examples/src/main/java/eu/daproject/evl/tomultimethods/part3/D.java
ylegoc/evl
d436edf01d01d8fdb61114d9e046f3993b5e3a68
[ "Apache-2.0" ]
null
null
null
13.833333
47
0.722892
994,757
package eu.daproject.evl.tomultimethods.part3; public class D extends A { }
922e78f960303fed1c8e653731094e50e1fddaf7
713
java
Java
interpreter/bytecode/BranchCode.java
ichaudry/interpreter
a13b9f069952649efa1d5aad1fe6713a5e2732a5
[ "MIT" ]
null
null
null
interpreter/bytecode/BranchCode.java
ichaudry/interpreter
a13b9f069952649efa1d5aad1fe6713a5e2732a5
[ "MIT" ]
null
null
null
interpreter/bytecode/BranchCode.java
ichaudry/interpreter
a13b9f069952649efa1d5aad1fe6713a5e2732a5
[ "MIT" ]
null
null
null
28.52
103
0.720898
994,758
package interpreter.bytecode; /** * This abstract class is extended by all instances of branch codes * e.g FalseBranch, Call, Goto * The two variables 'label' and 'address' are important in resolving addresses and making jump calls. */ public abstract class BranchCode extends ByteCode { //Label to branch to private String label; //Address of label. Set by resolve address function in 'program' class private int Address; //Getter functions public String getLabel(){ return label;} public int getAddress(){return Address;} //Setter functions public void setLabel(String label){this.label=label;} public void setAddress(int Address){ this.Address = Address; } }
922e7a0b6b69bb46eaf76e969f04ee27d7c11bc0
391
java
Java
src/main/java/com/may14spring/May14springController.java
ipcrmdemo/may14spring
711b515b18c901010912c35ddcddc51acac09536
[ "Apache-2.0" ]
null
null
null
src/main/java/com/may14spring/May14springController.java
ipcrmdemo/may14spring
711b515b18c901010912c35ddcddc51acac09536
[ "Apache-2.0" ]
null
null
null
src/main/java/com/may14spring/May14springController.java
ipcrmdemo/may14spring
711b515b18c901010912c35ddcddc51acac09536
[ "Apache-2.0" ]
null
null
null
24.4375
62
0.751918
994,759
package com.may14spring; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.GetMapping; @RestController class May14springController { @GetMapping("/hello/{name}") public String person(@PathVariable String name) { return "Hello " + name + "!"; } }
922e7ab02d147255ed4bc9e5f67ee34ebde70ea0
103
java
Java
src/main/java/com/kazale/pontointeligente/api/enums/PerfilEnum.java
fbentodsca/ApiPonto
9990d2ab01d58d497f992d43f7f1c9900dc26712
[ "MIT" ]
null
null
null
src/main/java/com/kazale/pontointeligente/api/enums/PerfilEnum.java
fbentodsca/ApiPonto
9990d2ab01d58d497f992d43f7f1c9900dc26712
[ "MIT" ]
null
null
null
src/main/java/com/kazale/pontointeligente/api/enums/PerfilEnum.java
fbentodsca/ApiPonto
9990d2ab01d58d497f992d43f7f1c9900dc26712
[ "MIT" ]
null
null
null
14.714286
46
0.796117
994,760
package com.kazale.pontointeligente.api.enums; public enum PerfilEnum { ROLE_Admin, Role_Usuario; }
922e7ac98f1b5dcff77fa5e88c03bd5a5d4a8ed3
624
java
Java
src/main/java/com/xyf/blog/web/ArchiveShowController.java
xuyafei9303/blog
ff0153120a6aeea2a407c5d3626189638ee32950
[ "Apache-2.0" ]
1
2020-01-05T05:43:29.000Z
2020-01-05T05:43:29.000Z
src/main/java/com/xyf/blog/web/ArchiveShowController.java
xuyafei9303/blog
ff0153120a6aeea2a407c5d3626189638ee32950
[ "Apache-2.0" ]
null
null
null
src/main/java/com/xyf/blog/web/ArchiveShowController.java
xuyafei9303/blog
ff0153120a6aeea2a407c5d3626189638ee32950
[ "Apache-2.0" ]
null
null
null
27.130435
68
0.758013
994,761
package com.xyf.blog.web; import com.xyf.blog.service.IBlogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ArchiveShowController { @Autowired private IBlogService blogService; @GetMapping("/archives") public String archive(Model model) { model.addAttribute("archiveMap", blogService.archiveBlog()); model.addAttribute("blogCount", blogService.countBlog()); return "archives"; } }
922e7d26e5d17be8e67e1d1e4213083f45798019
85,606
java
Java
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/export/JRXlsMetadataExporter.java
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/export/JRXlsMetadataExporter.java
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
src/visao/jasperreports-6.15.0/src/net/sf/jasperreports/engine/export/JRXlsMetadataExporter.java
EuKaique/Projeto-Diagnostico-Medico
cf7cc535ff31992b7568dba777c8faafafa6920c
[ "MIT" ]
null
null
null
32.493738
238
0.705925
994,762
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2019 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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 3 of the License, or * (at your option) any later version. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ /* * Contributor: Manuel Paul <ychag@example.com>, * Rat & Tat Beratungsgesellschaft mbH, * Muehlenkamp 6c, * 22303 Hamburg, * Germany. */ package net.sf.jasperreports.engine.export; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.font.TextAttribute; import java.awt.geom.Dimension2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.AttributedCharacterIterator; import java.text.AttributedCharacterIterator.Attribute; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.collections4.map.ReferenceMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFFooter; import org.apache.poi.hssf.usermodel.HSSFHeader; import org.apache.poi.hssf.usermodel.HSSFName; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFPrintSetup; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HeaderFooter; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellReference; import net.sf.jasperreports.engine.DefaultJasperReportsContext; import net.sf.jasperreports.engine.JRBoxContainer; import net.sf.jasperreports.engine.JRCommonGraphicElement; import net.sf.jasperreports.engine.JRCommonText; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRFont; import net.sf.jasperreports.engine.JRGenericElementType; import net.sf.jasperreports.engine.JRGenericPrintElement; import net.sf.jasperreports.engine.JRLineBox; import net.sf.jasperreports.engine.JRPen; import net.sf.jasperreports.engine.JRPrintElement; import net.sf.jasperreports.engine.JRPrintEllipse; import net.sf.jasperreports.engine.JRPrintFrame; import net.sf.jasperreports.engine.JRPrintGraphicElement; import net.sf.jasperreports.engine.JRPrintHyperlink; import net.sf.jasperreports.engine.JRPrintImage; import net.sf.jasperreports.engine.JRPrintLine; import net.sf.jasperreports.engine.JRPrintRectangle; import net.sf.jasperreports.engine.JRPrintText; import net.sf.jasperreports.engine.JRPropertiesUtil; import net.sf.jasperreports.engine.JRRuntimeException; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.base.JRBaseFont; import net.sf.jasperreports.engine.export.data.BooleanTextValue; import net.sf.jasperreports.engine.export.data.DateTextValue; import net.sf.jasperreports.engine.export.data.NumberTextValue; import net.sf.jasperreports.engine.export.data.StringTextValue; import net.sf.jasperreports.engine.export.data.TextValue; import net.sf.jasperreports.engine.export.data.TextValueHandler; import net.sf.jasperreports.engine.export.type.ImageAnchorTypeEnum; import net.sf.jasperreports.engine.type.ImageTypeEnum; import net.sf.jasperreports.engine.type.LineDirectionEnum; import net.sf.jasperreports.engine.type.ModeEnum; import net.sf.jasperreports.engine.type.OrientationEnum; import net.sf.jasperreports.engine.type.RotationEnum; import net.sf.jasperreports.engine.type.RunDirectionEnum; import net.sf.jasperreports.engine.util.DefaultFormatFactory; import net.sf.jasperreports.engine.util.ImageUtil; import net.sf.jasperreports.engine.util.JRDataUtils; import net.sf.jasperreports.engine.util.JRImageLoader; import net.sf.jasperreports.engine.util.JRStyledText; import net.sf.jasperreports.export.XlsExporterConfiguration; import net.sf.jasperreports.export.XlsMetadataExporterConfiguration; import net.sf.jasperreports.export.XlsMetadataReportConfiguration; import net.sf.jasperreports.export.XlsReportConfiguration; import net.sf.jasperreports.renderers.DataRenderable; import net.sf.jasperreports.renderers.DimensionRenderable; import net.sf.jasperreports.renderers.Graphics2DRenderable; import net.sf.jasperreports.renderers.Renderable; import net.sf.jasperreports.renderers.RenderersCache; import net.sf.jasperreports.renderers.ResourceRenderer; /** * @author Sanda Zaharia (lyhxr@example.com) */ public class JRXlsMetadataExporter extends JRXlsAbstractMetadataExporter<XlsMetadataReportConfiguration, XlsMetadataExporterConfiguration, JRXlsExporterContext> { private static final Log log = LogFactory.getLog(JRXlsMetadataExporter.class); /** * The exporter key, as used in * {@link GenericElementHandlerEnviroment#getElementHandler(JRGenericElementType, String)}. */ public static final String XLS_EXPORTER_KEY = JRPropertiesUtil.PROPERTY_PREFIX + "xls"; public static short MAX_COLOR_INDEX = 56; public static short MIN_COLOR_INDEX = 10; /* Indexes from 0 to 9 are reserved */ public static String CURRENT_ROW_HEIGHT = "CURRENT_ROW_HEIGHT"; private static Map<Color,HSSFColor> hssfColorsCache = new ReferenceMap<Color,HSSFColor>(); protected final DateFormat isoDateFormat = JRDataUtils.getIsoDateFormat(); protected Map<StyleInfo,HSSFCellStyle> loadedCellStyles = new HashMap<StyleInfo,HSSFCellStyle>(); protected Map<String,List<Hyperlink>> anchorLinks = new HashMap<String,List<Hyperlink>>(); protected Map<Integer,List<Hyperlink>> pageLinks = new HashMap<Integer,List<Hyperlink>>(); protected Map<String,HSSFName> anchorNames = new HashMap<String,HSSFName>(); protected HSSFWorkbook workbook; protected HSSFSheet sheet; protected HSSFRow row; protected HSSFCell cell; protected HSSFCellStyle emptyCellStyle; protected CreationHelper createHelper; private HSSFPalette palette = null; protected Map<String, HSSFCellStyle> columnStylesMap; protected Map<String, Integer> columnWidths; protected Map<String, Float> columnWidthRatios; protected Map<HSSFCell, String> formulaCellsMap; /** * */ protected short whiteIndex = HSSFColor.HSSFColorPredefined.WHITE.getIndex(); protected short blackIndex = HSSFColor.HSSFColorPredefined.BLACK.getIndex(); protected short customColorIndex = MIN_COLOR_INDEX; protected FillPatternType backgroundMode = FillPatternType.SOLID_FOREGROUND; protected HSSFDataFormat dataFormat; protected HSSFPatriarch patriarch; protected static final String EMPTY_SHEET_NAME = "Sheet1"; protected class ExporterContext extends BaseExporterContext implements JRXlsExporterContext { } /** * @see #JRXlsMetadataExporter(JasperReportsContext) */ public JRXlsMetadataExporter(){ this(DefaultJasperReportsContext.getInstance()); } /** * */ public JRXlsMetadataExporter(JasperReportsContext jasperReportsContext) { super(jasperReportsContext); exporterContext = new ExporterContext(); } @Override protected Class<XlsMetadataExporterConfiguration> getConfigurationInterface() { return XlsMetadataExporterConfiguration.class; } @Override protected Class<XlsMetadataReportConfiguration> getItemConfigurationInterface() { return XlsMetadataReportConfiguration.class; } @Override protected void initExport() { super.initExport(); sheet = null; } @Override protected void initReport() { super.initReport(); XlsReportConfiguration configuration = getCurrentItemConfiguration(); if (!configuration.isWhitePageBackground()) { backgroundMode = FillPatternType.NO_FILL; } nature = new JRXlsMetadataExporterNature( jasperReportsContext, filter, configuration.isIgnoreGraphics(), configuration.isIgnorePageMargins() ); } @Override protected void openWorkbook(OutputStream os) throws JRException { XlsMetadataExporterConfiguration configuration = getCurrentConfiguration(); String lcWorkbookTemplate = workbookTemplate == null ? configuration.getWorkbookTemplate() : workbookTemplate; if (lcWorkbookTemplate == null) { workbook = new HSSFWorkbook(); } else { InputStream templateIs = null; try { templateIs = getRepository().getInputStreamFromLocation(lcWorkbookTemplate); if (templateIs == null) { throw new JRRuntimeException( EXCEPTION_MESSAGE_KEY_TEMPLATE_NOT_FOUND, new Object[]{lcWorkbookTemplate} ); } else { workbook = new HSSFWorkbook(new POIFSFileSystem(templateIs)); boolean keepSheets = keepTemplateSheets == null ? configuration.isKeepWorkbookTemplateSheets() : keepTemplateSheets; if (keepSheets) { sheetIndex += workbook.getNumberOfSheets(); } else { for(int i = 0; i < workbook.getNumberOfSheets(); i++) { workbook.removeSheetAt(i); } } } } catch (JRException e) { throw new JRRuntimeException(e); } catch (IOException e) { throw new JRRuntimeException(e); } finally { if (templateIs != null) { try { templateIs.close(); } catch (IOException e) { } } } } emptyCellStyle = workbook.createCellStyle(); emptyCellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex()); emptyCellStyle.setFillPattern(backgroundMode); dataFormat = workbook.createDataFormat(); createHelper = workbook.getCreationHelper(); firstPageNotSet = true; palette = workbook.getCustomPalette(); customColorIndex = MIN_COLOR_INDEX; columnWidths = new HashMap<String, Integer>(); columnWidthRatios = new HashMap<String, Float>(); formulaCellsMap = new HashMap<HSSFCell,String>(); } @Override protected void createSheet(SheetInfo sheetInfo) { this.sheetInfo = sheetInfo; sheet = workbook.createSheet(sheetInfo.sheetName); patriarch = sheet.createDrawingPatriarch(); HSSFPrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(pageFormat.getOrientation() == OrientationEnum.LANDSCAPE); short paperSize = getSuitablePaperSize(); XlsReportConfiguration configuration = getCurrentItemConfiguration(); if(paperSize != -1) { printSetup.setPaperSize(paperSize); } String password = configuration.getPassword(); if(password != null) { sheet.protectSheet(password); } sheet.setMargin(Sheet.LeftMargin, LengthUtil.inch(configuration.getPrintPageLeftMargin())); sheet.setMargin(Sheet.RightMargin, LengthUtil.inch(configuration.getPrintPageRightMargin())); sheet.setMargin(Sheet.TopMargin, LengthUtil.inch(configuration.getPrintPageTopMargin())); sheet.setMargin(Sheet.BottomMargin, LengthUtil.inch(configuration.getPrintPageBottomMargin())); if(configuration.getSheetHeaderLeft() != null) { sheet.getHeader().setLeft(configuration.getSheetHeaderLeft()); } if(configuration.getSheetHeaderCenter() != null) { sheet.getHeader().setCenter(configuration.getSheetHeaderCenter()); } if(configuration.getSheetHeaderRight() != null) { sheet.getHeader().setRight(configuration.getSheetHeaderRight()); } if(configuration.getSheetFooterLeft() != null) { sheet.getFooter().setLeft(configuration.getSheetFooterLeft()); } if(configuration.getSheetFooterCenter() != null) { sheet.getFooter().setCenter(configuration.getSheetFooterCenter()); } if(configuration.getSheetFooterRight() != null) { sheet.getFooter().setRight(configuration.getSheetFooterRight()); } printSetup.setHeaderMargin(LengthUtil.inch(configuration.getPrintHeaderMargin())); printSetup.setFooterMargin(LengthUtil.inch(configuration.getPrintFooterMargin())); RunDirectionEnum sheetDirection = configuration.getSheetDirection(); if(sheetDirection != null) { printSetup.setLeftToRight(sheetDirection == RunDirectionEnum.LTR); sheet.setRightToLeft(sheetDirection == RunDirectionEnum.RTL); } if(sheetInfo.sheetFirstPageNumber != null && sheetInfo.sheetFirstPageNumber > 0) { printSetup.setPageStart((short)sheetInfo.sheetFirstPageNumber.intValue()); printSetup.setUsePage(true); firstPageNotSet = false; } else { Integer documentFirstPageNumber = configuration.getFirstPageNumber(); if(documentFirstPageNumber != null && documentFirstPageNumber > 0 && firstPageNotSet) { printSetup.setPageStart((short)documentFirstPageNumber.intValue()); printSetup.setUsePage(true); firstPageNotSet = false; } } if(!firstPageNotSet && (sheet.getFooter().getCenter() == null || sheet.getFooter().getCenter().length() == 0)) { sheet.getFooter().setCenter("Page " + HeaderFooter.page()); } boolean showGridlines = true; if (sheetInfo.sheetShowGridlines == null) { Boolean documentShowGridlines = configuration.isShowGridLines(); if (documentShowGridlines != null) { showGridlines = documentShowGridlines; } } else { showGridlines = sheetInfo.sheetShowGridlines; } sheet.setDisplayGridlines(showGridlines); backgroundMode = Boolean.TRUE.equals(sheetInfo.whitePageBackground) ? FillPatternType.SOLID_FOREGROUND : FillPatternType.NO_FILL; // maxRowFreezeIndex = 0; // maxColumnFreezeIndex = 0; onePagePerSheetMap.put(sheetIndex, configuration.isOnePagePerSheet()); sheetsBeforeCurrentReportMap.put(sheetIndex, sheetsBeforeCurrentReport); } @Override protected void closeSheet() { if (sheet == null) { return; } HSSFPrintSetup printSetup = sheet.getPrintSetup(); if (isValidScale(sheetInfo.sheetPageScale)) { printSetup.setScale((short)sheetInfo.sheetPageScale.intValue()); } else { XlsReportConfiguration configuration = getCurrentItemConfiguration(); Integer fitWidth = configuration.getFitWidth(); if (fitWidth != null) { printSetup.setFitWidth(fitWidth.shortValue()); sheet.setAutobreaks(true); } Integer fitHeight = configuration.getFitHeight(); fitHeight = fitHeight == null ? (Boolean.TRUE == configuration.isAutoFitPageHeight() ? (pageIndex - sheetInfo.sheetFirstPageIndex) : null) : fitHeight; if (fitHeight != null) { printSetup.setFitHeight(fitHeight.shortValue()); sheet.setAutobreaks(true); } } } @Override protected void closeWorkbook(OutputStream os) throws JRException { try { for (Object anchorName : anchorNames.keySet()) { HSSFName anchor = anchorNames.get(anchorName); List<Hyperlink> linkList = anchorLinks.get(anchorName); anchor.setRefersToFormula("'" + workbook.getSheetName(anchor.getSheetIndex()) + "'!"+ anchor.getRefersToFormula()); if(linkList != null && !linkList.isEmpty()) { for(Hyperlink link : linkList) { link.setAddress(anchor.getRefersToFormula()); } } } if(!definedNamesMap.isEmpty()) { for(Map.Entry<NameScope, String> entry : definedNamesMap.entrySet()) { HSSFName name = workbook.createName(); NameScope nameScope = entry.getKey(); name.setNameName(nameScope.getName()); name.setRefersToFormula(entry.getValue()); int scopeIndex = workbook.getSheetIndex(nameScope.getScope()); // name and name scope are ignoring case in Excel if(nameScope.getScope() != null && !DEFAULT_DEFINED_NAME_SCOPE.equalsIgnoreCase(nameScope.getScope()) && scopeIndex >= 0) { name.setSheetIndex(scopeIndex); } } } // applying formulas if(formulaCellsMap != null && !formulaCellsMap.isEmpty()) { for(Map.Entry<HSSFCell, String> formulaCell: formulaCellsMap.entrySet()) { try { formulaCell.getKey().setCellFormula(formulaCell.getValue()); } catch(Exception e) { // usually an org.apache.poi.ss.formula.FormulaParseException // or a java.lang.IllegalArgumentException // or a java.lang.IllegalStateException if(log.isWarnEnabled()) { log.warn(e.getMessage()); } throw new JRException(e); } } } int index = 0; for (Integer linkPage : pageLinks.keySet()) { List<Hyperlink> linkList = pageLinks.get(linkPage); if(linkList != null && !linkList.isEmpty()) { for(Hyperlink link : linkList) { index = onePagePerSheetMap.get(linkPage-1)!= null ? (onePagePerSheetMap.get(linkPage-1) ? Math.max(0, linkPage - 1) : Math.max(0, sheetsBeforeCurrentReportMap.get(linkPage))) : 0; link.setAddress("'" + workbook.getSheetName(index)+ "'!$A$1"); } } } for(int i=0; i < workbook.getNumberOfSheets(); i++) { HSSFSheet currentSheet = workbook.getSheetAt(i); currentSheet.setForceFormulaRecalculation(true); for(String columnName : columnNames) { Integer columnWidth = columnWidths.get(columnName); Float columnWidthRatio = columnWidthRatios.get(columnName); if (columnWidth != null && columnWidth < Integer.MAX_VALUE) { if(columnWidthRatio != null && columnWidthRatio > 1f) { columnWidth = Math.round(43 * columnWidth * columnWidthRatio); } else { columnWidth = 43 * columnWidth; } currentSheet.setColumnWidth(columnNamesMap.get(columnName), Math.min(columnWidth, 256*255)); } else { currentSheet.autoSizeColumn(columnNamesMap.get(columnName), false); } } } workbook.write(os); } catch (IOException e) { throw new JRException( EXCEPTION_MESSAGE_KEY_REPORT_GENERATION_ERROR, new Object[]{jasperPrint.getName()}, e); } } @Override protected void setColumnWidth(int col, int width) { } protected void setRowHeight(HSSFRow row) { Integer rowHeight = (Integer)currentRow.get(CURRENT_ROW_HEIGHT); if (row != null && rowHeight != null && rowHeight < Integer.MAX_VALUE) { row.setHeightInPoints((Integer)currentRow.get(CURRENT_ROW_HEIGHT)); } } protected void adjustRowHeight(int rowHeight, Boolean isAutofit) { if(isAutofit != null && isAutofit) { currentRow.put(CURRENT_ROW_HEIGHT, Integer.MAX_VALUE); } else if(!currentRow.containsKey(CURRENT_ROW_HEIGHT) || (Integer)currentRow.get(CURRENT_ROW_HEIGHT) < rowHeight) { currentRow.put(CURRENT_ROW_HEIGHT, rowHeight); } } protected void adjustColumnWidth(String columnName, int columnWidth, Boolean isAutofit) { if(isAutofit != null && isAutofit) { columnWidths.put(columnName, Integer.MAX_VALUE); } else { if(!columnWidths.containsKey(columnName) || columnWidths.get(columnName) < columnWidth) { columnWidths.put(columnName, columnWidth); } if(!columnWidthRatios.containsKey(columnName) && sheetInfo.columnWidthRatio != null) { columnWidthRatios.put(columnName, sheetInfo.columnWidthRatio); } } } protected void addBlankCell(HSSFCellStyle cellStyle, Map<String, Object> cellValueMap, String currentColumnName) throws JRException { HSSFCellStyle currentStyle = cellStyle != null ? cellStyle : (columnStylesMap.get(currentColumnName) != null ? columnStylesMap.get(currentColumnName) : emptyCellStyle); cellValueMap.put(currentColumnName, new CellSettings(currentStyle)); } @Override protected void writeCurrentRow(Map<String, Object> currentRow, Map<String, Object> repeatedValues) throws JRException { row = sheet.createRow(sheet.getPhysicalNumberOfRows()); setRowHeight(row); for(int i = 0; i< columnNames.size(); i++) { String columnName = columnNames.get(i); CellSettings cellSettings = (CellSettings)currentRow.get(columnName) == null ? (repeatedValues.get(columnName) != null ? (CellSettings)repeatedValues.get(columnName) : null) : (CellSettings)currentRow.get(columnName); cell = row.createCell(i); if(cellSettings != null) { CellType type = cellSettings.getCellType(); cell.setCellType(type); Object cellValue = cellSettings.getCellValue(); if(cellValue != null) { if(cellValue instanceof RichTextString) { cell.setCellValue((RichTextString)cellSettings.getCellValue()); } else if (cellValue instanceof Number) { cell.setCellValue(((Number)cellSettings.getCellValue()).doubleValue()); } else if (cellValue instanceof Date) { cell.setCellValue((Date)cellSettings.getCellValue()); } else if(cellValue instanceof Boolean) { cell.setCellValue((Boolean)cellSettings.getCellValue()); }else if(cellValue instanceof ImageSettings){ ImageSettings imageSettings = (ImageSettings)cellValue; try { HSSFClientAnchor anchor = new HSSFClientAnchor( 0, 0, 0, 0, (short)(i), rowIndex, (short)(i + 1), rowIndex+1 ); anchor.setAnchorType(imageSettings.getAnchorType()); patriarch.createPicture(anchor, imageSettings.getIndex()); } catch (Exception ex) { throw new JRException( EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, null, ex); } catch (Error err) { throw new JRException( EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, null, err); } } } if(cellSettings.getCellStyle() != null) { cell.setCellStyle(cellSettings.getCellStyle()); } if(cellSettings.getFormula() != null) { // the formula text will be stored in formulaCellsMap in order to be applied only after // all defined names are created and available in the workbook (see #closeWorkbook()) formulaCellsMap.put(cell, cellSettings.getFormula()); } if(cellSettings.getLink() != null) { cell.setHyperlink(cellSettings.getLink()); } } } ++rowIndex; } @Override protected void exportLine(JRPrintLine line) throws JRException { String currentColumnName = line.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_COLUMN_NAME); if (currentColumnName != null && currentColumnName.length() > 0) { boolean repeatValue = getPropertiesUtil().getBooleanProperty(line, JRXlsAbstractMetadataExporter.PROPERTY_REPEAT_VALUE, false); setColumnName(currentColumnName); adjustColumnWidth(currentColumnName, line.getWidth(), ((JRXlsExporterNature)nature).getColumnAutoFit(line)); adjustRowHeight(line.getHeight(), ((JRXlsExporterNature)nature).getRowAutoFit(line)); short forecolor = getWorkbookColor(line.getLinePen().getLineColor()).getIndex(); int side = BoxStyle.TOP; float ratio = line.getWidth() / line.getHeight(); if (ratio > 1) { if (line.getDirectionValue() == LineDirectionEnum.TOP_DOWN) { side = BoxStyle.TOP; } else { side = BoxStyle.BOTTOM; } } else { if (line.getDirectionValue() == LineDirectionEnum.TOP_DOWN) { side = BoxStyle.LEFT; } else { side = BoxStyle.RIGHT; } } BoxStyle boxStyle = new BoxStyle(side, line.getLinePen()); FillPatternType mode = backgroundMode; short backcolor = whiteIndex; if (!Boolean.TRUE.equals(sheetInfo.ignoreCellBackground) && line.getBackcolor() != null) { mode = FillPatternType.SOLID_FOREGROUND; backcolor = getWorkbookColor(line.getBackcolor()).getIndex(); } HSSFCellStyle cellStyle = getLoadedCellStyle( mode, backcolor, HorizontalAlignment.LEFT, VerticalAlignment.TOP, (short)0, getLoadedFont(getDefaultFont(), forecolor, null, getLocale()), boxStyle, isCellLocked(line), isCellHidden(line), isShrinkToFit(line) ); addBlankElement(cellStyle, repeatValue, currentColumnName); } } @Override protected void exportRectangle(JRPrintGraphicElement element) throws JRException { String currentColumnName = element.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_COLUMN_NAME); if (currentColumnName != null && currentColumnName.length() > 0) { boolean repeatValue = getPropertiesUtil().getBooleanProperty(element, JRXlsAbstractMetadataExporter.PROPERTY_REPEAT_VALUE, false); setColumnName(currentColumnName); adjustColumnWidth(currentColumnName, element.getWidth(), ((JRXlsExporterNature)nature).getColumnAutoFit(element)); adjustRowHeight(element.getHeight(), ((JRXlsExporterNature)nature).getRowAutoFit(element)); short forecolor = getWorkbookColor(element.getLinePen().getLineColor()).getIndex(); FillPatternType mode = backgroundMode; short backcolor = whiteIndex; if (!Boolean.TRUE.equals(sheetInfo.ignoreCellBackground) && element.getBackcolor() != null) { mode = FillPatternType.SOLID_FOREGROUND; backcolor = getWorkbookColor(element.getBackcolor()).getIndex(); } HSSFCellStyle cellStyle = getLoadedCellStyle( mode, backcolor, HorizontalAlignment.LEFT, VerticalAlignment.TOP, (short)0, getLoadedFont(getDefaultFont(), forecolor, null, getLocale()), new BoxStyle(element), isCellLocked(element), isCellHidden(element), isShrinkToFit(element) ); addBlankElement(cellStyle, repeatValue, currentColumnName); } } @Override protected void exportText(final JRPrintText textElement) throws JRException { String currentColumnName = textElement.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_COLUMN_NAME); if (currentColumnName != null && currentColumnName.length() > 0) { final boolean hasCurrentColumnData = textElement.getPropertiesMap().containsProperty(JRXlsAbstractMetadataExporter.PROPERTY_DATA); String currentColumnData = textElement.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_DATA); boolean repeatValue = getPropertiesUtil().getBooleanProperty(textElement, JRXlsAbstractMetadataExporter.PROPERTY_REPEAT_VALUE, false); setColumnName(currentColumnName); adjustColumnWidth(currentColumnName, textElement.getWidth(), ((JRXlsExporterNature)nature).getColumnAutoFit(textElement)); adjustRowHeight(textElement.getHeight(), isWrapText(textElement) || Boolean.TRUE.equals(((JRXlsExporterNature)nature).getRowAutoFit(textElement))); final short forecolor = getWorkbookColor(textElement.getForecolor()).getIndex(); TextAlignHolder textAlignHolder = getTextAlignHolder(textElement); HorizontalAlignment horizontalAlignment = getHorizontalAlignment(textAlignHolder); VerticalAlignment verticalAlignment = getVerticalAlignment(textAlignHolder); short rotation = getRotation(textAlignHolder); XlsReportConfiguration configuration = getCurrentItemConfiguration(); FillPatternType mode = backgroundMode; short backcolor = whiteIndex; if (!Boolean.TRUE.equals(sheetInfo.ignoreCellBackground) && textElement.getBackcolor() != null) { mode = FillPatternType.SOLID_FOREGROUND; backcolor = getWorkbookColor(textElement.getBackcolor()).getIndex(); } final StyleInfo baseStyle = isIgnoreTextFormatting(textElement) ? new StyleInfo( mode, whiteIndex, horizontalAlignment, verticalAlignment, (short)0, null, (BoxStyle)null, isWrapText(textElement) || Boolean.TRUE.equals(((JRXlsExporterNature)nature).getColumnAutoFit(textElement)), isCellLocked(textElement), isCellHidden(textElement), isShrinkToFit(textElement) ) : new StyleInfo( mode, backcolor, horizontalAlignment, verticalAlignment, rotation, getLoadedFont(textElement, forecolor, null, getTextLocale(textElement)), new BoxStyle(textElement), isWrapText(textElement) || Boolean.TRUE.equals(((JRXlsExporterNature)nature).getColumnAutoFit(textElement)), isCellLocked(textElement), isCellHidden(textElement), isShrinkToFit(textElement) ); final JRStyledText styledText; final String textStr; final String formula; final CellSettings cellSettings = new CellSettings(); if (hasCurrentColumnData) { styledText = new JRStyledText(); if (currentColumnData != null) { styledText.append(currentColumnData); } textStr = currentColumnData; formula = null; } else { styledText = getStyledText(textElement); if (styledText != null) { textStr = styledText.getText(); } else { textStr = null; } formula = getFormula(textElement); } TextValue value = null; String pattern = null; if ( formula != null || configuration.isDetectCellType() ) { value = getTextValue(textElement, textStr); if (value instanceof NumberTextValue) { pattern = ((NumberTextValue)value).getPattern(); } else if (value instanceof DateTextValue) { pattern = ((DateTextValue)value).getPattern(); } } String convertedPattern = getConvertedPattern(textElement, pattern); if (convertedPattern != null) { baseStyle.setDataFormat(dataFormat.getFormat(convertedPattern)); } if (formula != null) { cellSettings.importValues(CellType.FORMULA, getLoadedCellStyle(baseStyle), null, formula); } else if (configuration.isDetectCellType()) { value.handle(new TextValueHandler() { @Override public void handle(StringTextValue textValue) { if (JRCommonText.MARKUP_NONE.equals(textElement.getMarkup()) || isIgnoreTextFormatting(textElement)) { cellSettings.importValues(CellType.STRING, getLoadedCellStyle(baseStyle), new HSSFRichTextString(textValue.getText())); } else { cellSettings.importValues(CellType.STRING, getLoadedCellStyle(baseStyle), getRichTextString(styledText, forecolor, textElement, getTextLocale(textElement))); } } @Override public void handle(NumberTextValue textValue) { Number value = null; if (hasCurrentColumnData) { if (textStr != null) { try { value = Double.parseDouble(textStr); } catch (NumberFormatException nfe) { throw new JRRuntimeException(nfe); } } } else { value = textValue.getValue(); } if ( value != null && DefaultFormatFactory.STANDARD_NUMBER_FORMAT_DURATION.equals(convertedPattern) ) { value = value.doubleValue() / 86400; } cellSettings.importValues(CellType.NUMERIC, getLoadedCellStyle(baseStyle), value); } @Override public void handle(DateTextValue textValue) { Date value = null; if (hasCurrentColumnData) { if (textStr != null) { try { value = new Date(Long.parseLong(textStr)); } catch (NumberFormatException nfe) { try { value = isoDateFormat.parse(textStr); } catch (ParseException pe) { throw new JRRuntimeException(pe); } } } } else { value = textValue.getValue() == null ? null : translateDateValue(textElement, textValue.getValue()); } cellSettings.importValues(CellType.NUMERIC, getLoadedCellStyle(baseStyle), value); } @Override public void handle(BooleanTextValue textValue) { Boolean value = hasCurrentColumnData ? Boolean.valueOf(textStr) : textValue.getValue(); cellSettings.importValues(CellType.BOOLEAN, getLoadedCellStyle(baseStyle), value); } }); } else { if (JRCommonText.MARKUP_NONE.equals(textElement.getMarkup()) || isIgnoreTextFormatting(textElement)) { cellSettings.importValues(CellType.STRING, getLoadedCellStyle(baseStyle), new HSSFRichTextString(textStr)); } else { cellSettings.importValues(CellType.STRING, getLoadedCellStyle(baseStyle), getRichTextString(styledText, forecolor, textElement, getTextLocale(textElement))); } } if(!configuration.isIgnoreAnchors()) { String anchorName = textElement.getAnchorName(); if(anchorName != null) { HSSFName aName = workbook.createName(); aName.setNameName(toExcelName(anchorName)); aName.setSheetIndex(workbook.getSheetIndex(sheet)); CellReference cRef = new CellReference(rowIndex, columnNamesMap.get(currentColumnName), true, true); aName.setRefersToFormula(cRef.formatAsString()); anchorNames.put(anchorName, aName); } } setHyperlinkCell(textElement, cellSettings); addTextElement(cellSettings, textStr, repeatValue, currentColumnName); } } protected void setHyperlinkCell(JRPrintHyperlink hyperlink, CellSettings cellSettings) { Hyperlink link = null; Boolean ignoreHyperlink = HyperlinkUtil.getIgnoreHyperlink(XlsReportConfiguration.PROPERTY_IGNORE_HYPERLINK, hyperlink); if (ignoreHyperlink == null) { ignoreHyperlink = getCurrentItemConfiguration().isIgnoreHyperlink(); } if (!ignoreHyperlink) { JRHyperlinkProducer customHandler = getHyperlinkProducer(hyperlink); if (customHandler == null) { switch (hyperlink.getHyperlinkTypeValue()) { case REFERENCE: { String href = hyperlink.getHyperlinkReference(); if (href != null) { link = createHelper.createHyperlink(HyperlinkType.URL); link.setAddress(href); } break; } case LOCAL_ANCHOR : { if(!getCurrentItemConfiguration().isIgnoreAnchors()) { String href = hyperlink.getHyperlinkAnchor(); if (href != null) { link = createHelper.createHyperlink(HyperlinkType.DOCUMENT); if(anchorLinks.containsKey(href)) { (anchorLinks.get(href)).add(link); } else { List<Hyperlink> hrefList = new ArrayList<Hyperlink>(); hrefList.add(link); anchorLinks.put(href, hrefList); } } } break; } case LOCAL_PAGE : { Integer hrefPage = (getCurrentItemConfiguration().isOnePagePerSheet() ? hyperlink.getHyperlinkPage() : 0); if (hrefPage != null) { link = createHelper.createHyperlink(HyperlinkType.DOCUMENT); if(pageLinks.containsKey(sheetsBeforeCurrentReport+hrefPage)) { pageLinks.get(sheetsBeforeCurrentReport + hrefPage).add(link); } else { List<Hyperlink> hrefList = new ArrayList<Hyperlink>(); hrefList.add(link); pageLinks.put(sheetsBeforeCurrentReport + hrefPage, hrefList); } } break; } case REMOTE_ANCHOR : { String href = hyperlink.getHyperlinkReference(); if (href != null && hyperlink.getHyperlinkAnchor() != null) { href = href + "#" + hyperlink.getHyperlinkAnchor(); link = createHelper.createHyperlink(HyperlinkType.FILE); link.setAddress(href); } break; } case REMOTE_PAGE : { String href = hyperlink.getHyperlinkReference(); if (href != null && hyperlink.getHyperlinkPage() != null) { href = href + "#JR_PAGE_ANCHOR_0_" + hyperlink.getHyperlinkPage().toString(); link = createHelper.createHyperlink(HyperlinkType.FILE); link.setAddress(href); } break; } case NONE: default: { } } } else { String href = customHandler.getHyperlink(hyperlink); if (href != null) { link = createHelper.createHyperlink(HyperlinkType.URL); link.setAddress(href); } } if(link != null) { //TODO: make tooltips functional // if(hyperlink.getHyperlinkTooltip() != null) // { // link.setLabel(hyperlink.getHyperlinkTooltip()); // } cellSettings.setLink(link); } } } protected void addTextElement(CellSettings cellSettings, String textStr, boolean repeatValue, String currentColumnName) throws JRException { if (columnNames.size() > 0) { if (columnNames.contains(currentColumnName) && !currentRow.containsKey(currentColumnName) && isColumnReadOnTime(currentRow, currentColumnName)) { // the column is for export but was not read yet and comes in the expected order addCell(cellSettings, currentRow, currentColumnName); } else if ( (columnNames.contains(currentColumnName) && !currentRow.containsKey(currentColumnName) && !isColumnReadOnTime(currentRow, currentColumnName)) // the column is for export, was not read yet, but it is read after it should be || (columnNames.contains(currentColumnName) && currentRow.containsKey(currentColumnName)) ) { // the column is for export and was already read if(rowIndex == 1 && getCurrentItemConfiguration().isWriteHeader()) { writeReportHeader(); } writeCurrentRow(currentRow, repeatedValues); currentRow.clear(); addCell(cellSettings, currentRow, currentColumnName); } // set auto fill columns if(repeatValue) { if ( currentColumnName != null && currentColumnName.length() > 0 && textStr.length() > 0) { addCell(cellSettings, repeatedValues, currentColumnName); } } else { repeatedValues.remove(currentColumnName); } } } protected void addBlankElement(HSSFCellStyle cellStyle, boolean repeatValue, String currentColumnName) throws JRException { if (columnNames.size() > 0) { if (columnNames.contains(currentColumnName) && !currentRow.containsKey(currentColumnName) && isColumnReadOnTime(currentRow, currentColumnName)) { // the column is for export but was not read yet and comes in the expected order addBlankCell(cellStyle, currentRow, currentColumnName); } else if ( (columnNames.contains(currentColumnName) && !currentRow.containsKey(currentColumnName) && !isColumnReadOnTime(currentRow, currentColumnName)) // the column is for export, was not read yet, but it is read after it should be || (columnNames.contains(currentColumnName) && currentRow.containsKey(currentColumnName)) ) { // the column is for export and was already read if(rowIndex == 1 && getCurrentItemConfiguration().isWriteHeader()) { writeReportHeader(); } writeCurrentRow(currentRow, repeatedValues); currentRow.clear(); addBlankCell(cellStyle, currentRow, currentColumnName); } // set auto fill columns if(repeatValue) { if (repeatValue && currentColumnName != null && currentColumnName.length() > 0 && cellStyle != null) { addBlankCell(cellStyle, repeatedValues, currentColumnName); } } else { repeatedValues.remove(currentColumnName); } } } protected void addCell(CellSettings cellSettings, Map<String, Object> cellValueMap, String currentColumnName) throws JRException { cellValueMap.put(currentColumnName, cellSettings); } protected HSSFRichTextString getRichTextString(JRStyledText styledText, short forecolor, JRFont defaultFont, Locale locale) { String text = styledText.getText(); HSSFRichTextString richTextStr = new HSSFRichTextString(text); int runLimit = 0; AttributedCharacterIterator iterator = styledText.getAttributedString().getIterator(); while(runLimit < styledText.length() && (runLimit = iterator.getRunLimit()) <= styledText.length()) { Map<Attribute,Object> attributes = iterator.getAttributes(); JRFont runFont = attributes.isEmpty()? defaultFont : new JRBaseFont(attributes); short runForecolor = attributes.get(TextAttribute.FOREGROUND) != null ? getWorkbookColor((Color)attributes.get(TextAttribute.FOREGROUND)).getIndex() : forecolor; HSSFFont font = getLoadedFont(runFont, runForecolor, attributes, locale); richTextStr.applyFont(iterator.getIndex(), runLimit, font); iterator.setIndex(runLimit); } return richTextStr; } @Override public void exportImage(JRPrintImage element) throws JRException { String currentColumnName = element.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_COLUMN_NAME); if (currentColumnName != null && currentColumnName.length() > 0) { boolean repeatValue = getPropertiesUtil().getBooleanProperty(element, JRXlsAbstractMetadataExporter.PROPERTY_REPEAT_VALUE, false); setColumnName(currentColumnName); adjustColumnWidth(currentColumnName, element.getWidth(), ((JRXlsExporterNature)nature).getColumnAutoFit(element)); adjustRowHeight(element.getHeight(), Boolean.TRUE.equals(((JRXlsExporterNature)nature).getRowAutoFit(element))); int topPadding = Math.max(element.getLineBox().getTopPadding(), getImageBorderCorrection(element.getLineBox().getTopPen())); int leftPadding = Math.max(element.getLineBox().getLeftPadding(), getImageBorderCorrection(element.getLineBox().getLeftPen())); int bottomPadding = Math.max(element.getLineBox().getBottomPadding(), getImageBorderCorrection(element.getLineBox().getBottomPen())); int rightPadding = Math.max(element.getLineBox().getRightPadding(), getImageBorderCorrection(element.getLineBox().getRightPen())); int tmpAvailableImageWidth = element.getWidth() - leftPadding - rightPadding; int availableImageWidth = tmpAvailableImageWidth < 0 ? 0 : tmpAvailableImageWidth; int tmpAvailableImageHeight = element.getHeight() - topPadding - bottomPadding; int availableImageHeight = tmpAvailableImageHeight < 0 ? 0 : tmpAvailableImageHeight; InternalImageProcessor imageProcessor = new InternalImageProcessor( element, availableImageWidth, availableImageHeight ); Renderable renderer = element.getRenderer(); if ( renderer != null && imageProcessor.availableImageWidth > 0 && imageProcessor.availableImageHeight > 0 ) { InternalImageProcessorResult imageProcessorResult = null; try { imageProcessorResult = imageProcessor.process(renderer); } catch (Exception e) { Renderable onErrorRenderer = getRendererUtil().handleImageError(e, element.getOnErrorTypeValue()); if (onErrorRenderer != null) { imageProcessorResult = imageProcessor.process(onErrorRenderer); } } if (imageProcessorResult != null)//FIXMEXLS background for null images like the other exporters { XlsMetadataReportConfiguration configuration = getCurrentItemConfiguration(); FillPatternType mode = backgroundMode; short backcolor = whiteIndex; if (!Boolean.TRUE.equals(sheetInfo.ignoreCellBackground) && element.getBackcolor() != null) { mode = FillPatternType.SOLID_FOREGROUND; backcolor = getWorkbookColor(element.getBackcolor()).getIndex(); } short forecolor = getWorkbookColor(element.getLineBox().getPen().getLineColor()).getIndex(); if(element.getModeValue() == ModeEnum.OPAQUE ) { backcolor = getWorkbookColor(element.getBackcolor()).getIndex(); } HSSFCellStyle cellStyle = getLoadedCellStyle( mode, backcolor, HorizontalAlignment.LEFT, VerticalAlignment.TOP, (short)0, getLoadedFont(getDefaultFont(), forecolor, null, getLocale()), new BoxStyle(element), isCellLocked(element), isCellHidden(element), isShrinkToFit(element) ); addBlankElement(cellStyle, false, currentColumnName); int colIndex = columnNamesMap.get(currentColumnName); try { HSSFClientAnchor anchor = new HSSFClientAnchor( 0, //paddings and offsets, although calculated, are deliberately ignored 0, 0, 0, (short)(colIndex), rowIndex, (short)(colIndex + 1), rowIndex+1 ); ImageAnchorTypeEnum imageAnchorType = ImageAnchorTypeEnum.getByName( JRPropertiesUtil.getOwnProperty(element, XlsReportConfiguration.PROPERTY_IMAGE_ANCHOR_TYPE) ); if (imageAnchorType == null) { imageAnchorType = configuration.getImageAnchorType(); if (imageAnchorType == null) { imageAnchorType = ImageAnchorTypeEnum.MOVE_NO_SIZE; } } anchor.setAnchorType(JRXlsExporter.getAnchorType(imageAnchorType)); //pngEncoder.setImage(bi); //int imgIndex = workbook.addPicture(pngEncoder.pngEncode(), HSSFWorkbook.PICTURE_TYPE_PNG); int imgIndex = workbook.addPicture(imageProcessorResult.imageData, HSSFWorkbook.PICTURE_TYPE_PNG); patriarch.createPicture(anchor, imgIndex).setRotationDegree(imageProcessorResult.angle); // set auto fill columns if(repeatValue) { CellSettings cellSettings = new CellSettings(cellStyle); cellSettings.setCellValue(new ImageSettings(imgIndex, anchor.getAnchorType())); addCell(cellSettings, repeatedValues, currentColumnName); } else { repeatedValues.remove(currentColumnName); } // setHyperlinkCell(element); } catch (Exception ex) { throw new JRException( EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, null, ex); } catch (Error err) { throw new JRException( EXCEPTION_MESSAGE_KEY_CANNOT_ADD_CELL, null, err); } } } } } private class InternalImageProcessor { private final JRPrintImage imageElement; private final RenderersCache imageRenderersCache; private final int availableImageWidth; private final int availableImageHeight; protected InternalImageProcessor( JRPrintImage imageElement, int availableImageWidth, int availableImageHeight ) { this.imageElement = imageElement; this.imageRenderersCache = imageElement.isUsingCache() ? renderersCache : new RenderersCache(getJasperReportsContext()); this.availableImageWidth = availableImageWidth; this.availableImageHeight = availableImageHeight; } private InternalImageProcessorResult process(Renderable renderer) throws JRException { InternalImageProcessorResult imageProcessorResult = null; if (renderer instanceof ResourceRenderer) { renderer = imageRenderersCache.getLoadedRenderer((ResourceRenderer)renderer); } switch (imageElement.getScaleImageValue()) { case CLIP: { imageProcessorResult = processImageClip( imageRenderersCache.getGraphics2DRenderable(renderer) ); break; } case FILL_FRAME: { Dimension dimension = null; if ( imageElement.getRotation() == RotationEnum.LEFT || imageElement.getRotation() == RotationEnum.RIGHT ) { dimension = new Dimension(availableImageHeight, availableImageWidth); } else { dimension = new Dimension(availableImageWidth, availableImageHeight); } imageProcessorResult = processImageFillFrame( getRendererUtil().getImageDataRenderable( imageRenderersCache, renderer, dimension, ModeEnum.OPAQUE == imageElement.getModeValue() ? imageElement.getBackcolor() : null ) ); break; } case RETAIN_SHAPE: default: { Dimension dimension = null; if ( imageElement.getRotation() == RotationEnum.LEFT || imageElement.getRotation() == RotationEnum.RIGHT ) { dimension = new Dimension(availableImageHeight, availableImageWidth); } else { dimension = new Dimension(availableImageWidth, availableImageHeight); } imageProcessorResult = processImageRetainShape( getRendererUtil().getImageDataRenderable( imageRenderersCache, renderer, dimension, ModeEnum.OPAQUE == imageElement.getModeValue() ? imageElement.getBackcolor() : null ) ); break; } } return imageProcessorResult; } private InternalImageProcessorResult processImageClip(Graphics2DRenderable renderer) throws JRException { int normalWidth = availableImageWidth; int normalHeight = availableImageHeight; DimensionRenderable dimensionRenderer = imageRenderersCache.getDimensionRenderable((Renderable)renderer); Dimension2D dimension = dimensionRenderer == null ? null : dimensionRenderer.getDimension(jasperReportsContext); if (dimension != null) { normalWidth = (int) dimension.getWidth(); normalHeight = (int) dimension.getHeight(); } int minWidth = 0; int minHeight = 0; int topOffset = 0; int leftOffset = 0; int bottomOffset = 0; int rightOffset = 0; int translateX = 0; int translateY = 0; short angle = 0; switch (imageElement.getRotation()) { case LEFT : if (dimension == null) { normalWidth = availableImageHeight; normalHeight = availableImageWidth; } minWidth = Math.min(normalWidth, availableImageHeight); minHeight = Math.min(normalHeight, availableImageWidth); topOffset = (int)((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageHeight - normalWidth)); leftOffset = (int)(ImageUtil.getYAlignFactor(imageElement) * (availableImageWidth - normalHeight)); bottomOffset = (int)(ImageUtil.getXAlignFactor(imageElement) * (availableImageHeight - normalWidth)); rightOffset = (int)((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageWidth - normalHeight)); translateX = bottomOffset; translateY = leftOffset; angle = -90; break; case RIGHT : if (dimension == null) { normalWidth = availableImageHeight; normalHeight = availableImageWidth; } minWidth = Math.min(normalWidth, availableImageHeight); minHeight = Math.min(normalHeight, availableImageWidth); topOffset = (int)(ImageUtil.getXAlignFactor(imageElement) * (availableImageHeight - normalWidth)); leftOffset = (int)((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageWidth - normalHeight)); bottomOffset = (int)((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageHeight - normalWidth)); rightOffset = (int)(ImageUtil.getYAlignFactor(imageElement) * (availableImageWidth - normalHeight)); translateX = topOffset; translateY = rightOffset; angle = 90; break; case UPSIDE_DOWN : minWidth = Math.min(normalWidth, availableImageWidth); minHeight = Math.min(normalHeight, availableImageHeight); topOffset = (int)((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageHeight - normalHeight)); leftOffset = (int)((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageWidth - normalWidth)); bottomOffset = (int)(ImageUtil.getYAlignFactor(imageElement) * (availableImageHeight - normalHeight)); rightOffset = (int)(ImageUtil.getXAlignFactor(imageElement) * (availableImageWidth - normalWidth)); translateX = rightOffset; translateY = bottomOffset; angle = 180; break; case NONE : default : minWidth = Math.min(normalWidth, availableImageWidth); minHeight = Math.min(normalHeight, availableImageHeight); topOffset = (int)(ImageUtil.getYAlignFactor(imageElement) * (availableImageHeight - normalHeight)); leftOffset = (int)(ImageUtil.getXAlignFactor(imageElement) * (availableImageWidth - normalWidth)); bottomOffset = (int)((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageHeight - normalHeight)); rightOffset = (int)((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageWidth - normalWidth)); translateX = leftOffset; translateY = topOffset; angle = 0; break; } int dpi = getPropertiesUtil().getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72); double scale = dpi/72d; BufferedImage bi = new BufferedImage( (int)(scale * minWidth), (int)(scale * minHeight), BufferedImage.TYPE_INT_ARGB ); Graphics2D grx = bi.createGraphics(); try { grx.scale(scale, scale); grx.clip( new Rectangle( 0, 0, minWidth, minHeight ) ); renderer.render( jasperReportsContext, grx, new Rectangle( translateX > 0 ? 0 : translateX, translateY > 0 ? 0 : translateY, normalWidth, normalHeight ) ); } finally { grx.dispose(); } return new InternalImageProcessorResult( JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi, ImageTypeEnum.PNG), topOffset < 0 ? 0 : topOffset, leftOffset < 0 ? 0 : leftOffset, bottomOffset < 0 ? 0 : bottomOffset, rightOffset < 0 ? 0 : rightOffset, angle ); } private InternalImageProcessorResult processImageFillFrame(DataRenderable renderer) throws JRException { short angle = 0; switch (imageElement.getRotation()) { case LEFT: angle = -90; break; case RIGHT: angle = 90; break; case UPSIDE_DOWN: angle = 180; break; case NONE: default: angle = 0; break; } return new InternalImageProcessorResult( renderer.getData(jasperReportsContext), 0, 0, 0, 0, angle ); } private InternalImageProcessorResult processImageRetainShape(DataRenderable renderer) throws JRException { float normalWidth = availableImageWidth; float normalHeight = availableImageHeight; DimensionRenderable dimensionRenderer = imageRenderersCache.getDimensionRenderable((Renderable)renderer); Dimension2D dimension = dimensionRenderer == null ? null : dimensionRenderer.getDimension(jasperReportsContext); if (dimension != null) { normalWidth = (int) dimension.getWidth(); normalHeight = (int) dimension.getHeight(); } float ratioX = 1f; float ratioY = 1f; int imageWidth = 0; int imageHeight = 0; int topOffset = 0; int leftOffset = 0; int bottomOffset = 0; int rightOffset = 0; short angle = 0; switch (imageElement.getRotation()) { case LEFT: ratioX = availableImageWidth / normalHeight; ratioY = availableImageHeight / normalWidth; ratioX = ratioX < ratioY ? ratioX : ratioY; ratioY = ratioX; imageWidth = (int)(normalHeight * ratioX); imageHeight = (int)(normalWidth * ratioY); topOffset = (int) ((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageHeight - imageHeight)); leftOffset = (int) (ImageUtil.getYAlignFactor(imageElement) * (availableImageWidth - imageWidth)); bottomOffset = (int) (ImageUtil.getXAlignFactor(imageElement) * (availableImageHeight - imageHeight)); rightOffset = (int) ((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageWidth - imageWidth)); angle = -90; break; case RIGHT: ratioX = availableImageWidth / normalHeight; ratioY = availableImageHeight / normalWidth; ratioX = ratioX < ratioY ? ratioX : ratioY; ratioY = ratioX; imageWidth = (int)(normalHeight * ratioX); imageHeight = (int)(normalWidth * ratioY); topOffset = (int) (ImageUtil.getXAlignFactor(imageElement) * (availableImageHeight - imageHeight)); leftOffset = (int) ((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageWidth - imageWidth)); bottomOffset = (int) ((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageHeight - imageHeight)); rightOffset = (int) (ImageUtil.getYAlignFactor(imageElement) * (availableImageWidth - imageWidth)); angle = 90; break; case UPSIDE_DOWN: ratioX = availableImageWidth / normalWidth; ratioY = availableImageHeight / normalHeight; ratioX = ratioX < ratioY ? ratioX : ratioY; ratioY = ratioX; imageWidth = (int)(normalWidth * ratioX); imageHeight = (int)(normalHeight * ratioY); topOffset = (int) ((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageHeight - imageHeight)); leftOffset = (int) ((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageWidth - imageWidth)); bottomOffset = (int) (ImageUtil.getYAlignFactor(imageElement) * (availableImageHeight - imageHeight)); rightOffset = (int) (ImageUtil.getXAlignFactor(imageElement) * (availableImageWidth - imageWidth)); angle = 180; break; case NONE: default: ratioX = availableImageWidth / normalWidth; ratioY = availableImageHeight / normalHeight; ratioX = ratioX < ratioY ? ratioX : ratioY; ratioY = ratioX; imageWidth = (int)(normalWidth * ratioX); imageHeight = (int)(normalHeight * ratioY); topOffset = (int) (ImageUtil.getYAlignFactor(imageElement) * (availableImageHeight - imageHeight)); leftOffset = (int) (ImageUtil.getXAlignFactor(imageElement) * (availableImageWidth - imageWidth)); bottomOffset = (int) ((1f - ImageUtil.getYAlignFactor(imageElement)) * (availableImageHeight - imageHeight)); rightOffset = (int) ((1f - ImageUtil.getXAlignFactor(imageElement)) * (availableImageWidth - imageWidth)); angle = 0; break; } return new InternalImageProcessorResult( renderer.getData(jasperReportsContext), topOffset, leftOffset, bottomOffset, rightOffset, angle ); } } private class InternalImageProcessorResult { private final byte[] imageData; // private final int topOffset; // private final int leftOffset; // private final int bottomOffset; // private final int rightOffset; private final short angle; protected InternalImageProcessorResult( byte[] imageData, int topOffset, int leftOffset, int bottomOffset, int rightOffset, short angle ) { this.imageData = imageData; // this.topOffset = topOffset; // this.leftOffset = leftOffset; // this.bottomOffset = bottomOffset; // this.rightOffset = rightOffset; this.angle = angle; } } protected HSSFCellStyle getLoadedCellStyle(StyleInfo style) { HSSFCellStyle cellStyle = loadedCellStyles.get(style); if (cellStyle == null) { cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor(style.backcolor); cellStyle.setFillPattern(style.mode); cellStyle.setAlignment(style.horizontalAlignment); cellStyle.setVerticalAlignment(style.verticalAlignment); cellStyle.setRotation(style.rotation); if(style.font != null) { cellStyle.setFont(style.font); } cellStyle.setWrapText(style.lcWrapText); cellStyle.setLocked(style.lcCellLocked); cellStyle.setHidden(style.lcCellHidden); cellStyle.setShrinkToFit(style.lcShrinkToFit); if (style.hasDataFormat()) { cellStyle.setDataFormat(style.getDataFormat()); } if (!Boolean.TRUE.equals(sheetInfo.ignoreCellBorder) && style.box != null) { BoxStyle box = style.box; if (box.borderStyle[BoxStyle.TOP] != null) cellStyle.setBorderTop(box.borderStyle[BoxStyle.TOP]); cellStyle.setTopBorderColor(box.borderColour[BoxStyle.TOP]); if (box.borderStyle[BoxStyle.LEFT] != null) cellStyle.setBorderLeft(box.borderStyle[BoxStyle.LEFT]); cellStyle.setLeftBorderColor(box.borderColour[BoxStyle.LEFT]); if (box.borderStyle[BoxStyle.BOTTOM] != null) cellStyle.setBorderBottom(box.borderStyle[BoxStyle.BOTTOM]); cellStyle.setBottomBorderColor(box.borderColour[BoxStyle.BOTTOM]); if (box.borderStyle[BoxStyle.RIGHT] != null) cellStyle.setBorderRight(box.borderStyle[BoxStyle.RIGHT]); cellStyle.setRightBorderColor(box.borderColour[BoxStyle.RIGHT]); } loadedCellStyles.put(style, cellStyle); } return cellStyle; } protected HSSFCellStyle getLoadedCellStyle( FillPatternType mode, short backcolor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, short rotation, HSSFFont font, BoxStyle box, boolean isCellLocked, boolean isCellHidden, boolean isShrinkToFit ) { return getLoadedCellStyle(new StyleInfo(mode, backcolor, horizontalAlignment, verticalAlignment, rotation, font, box, true, isCellLocked, isCellHidden, isShrinkToFit)); } /** * */ protected static BorderStyle getBorderStyle(JRPen pen) { float lineWidth = pen.getLineWidth(); if (lineWidth > 0f) { switch (pen.getLineStyleValue()) { case DOUBLE : { return BorderStyle.DOUBLE; } case DOTTED : { return BorderStyle.DOTTED; } case DASHED : { if (lineWidth >= 1f) { return BorderStyle.MEDIUM_DASHED; } return BorderStyle.DASHED; } case SOLID : default : { if (lineWidth >= 2f) { return BorderStyle.THICK; } else if (lineWidth >= 1f) { return BorderStyle.MEDIUM; } else if (lineWidth >= 0.5f) { return BorderStyle.THIN; } return BorderStyle.HAIR; } } } return BorderStyle.NONE; } @Override protected void exportFrame(JRPrintFrame frame) throws JRException { for (Object element : frame.getElements()) { if (element instanceof JRPrintLine) { exportLine((JRPrintLine)element); } else if (element instanceof JRPrintRectangle) { exportRectangle((JRPrintRectangle)element); } else if (element instanceof JRPrintEllipse) { exportRectangle((JRPrintEllipse)element); } else if (element instanceof JRPrintImage) { exportImage((JRPrintImage) element); } else if (element instanceof JRPrintText) { exportText((JRPrintText)element); } else if (element instanceof JRPrintFrame) { exportFrame((JRPrintFrame) element); } else if (element instanceof JRGenericPrintElement) { exportGenericElement((JRGenericPrintElement) element); } } } @Override protected void exportGenericElement(JRGenericPrintElement element) throws JRException { String currentColumnName = element.getPropertiesMap().getProperty(JRXlsAbstractMetadataExporter.PROPERTY_COLUMN_NAME); if(currentColumnName != null && currentColumnName.length() > 0) { boolean repeatValue = getPropertiesUtil().getBooleanProperty(element, JRXlsAbstractMetadataExporter.PROPERTY_REPEAT_VALUE, false); int colIndex = columnNamesMap.get(currentColumnName); setColumnName(currentColumnName); adjustColumnWidth(currentColumnName, element.getWidth(), ((JRXlsExporterNature)nature).getColumnAutoFit(element)); adjustRowHeight(element.getHeight(), Boolean.TRUE.equals(((JRXlsExporterNature)nature).getRowAutoFit(element))); GenericElementXlsMetadataHandler handler = (GenericElementXlsMetadataHandler)GenericElementHandlerEnviroment.getInstance(getJasperReportsContext()).getElementHandler( element.getGenericType(), XLS_EXPORTER_KEY); if (handler != null) { rowIndex = handler.exportElement( exporterContext, element, currentRow, repeatedValues, columnNames, columnNamesMap, currentColumnName, colIndex, rowIndex, repeatValue ); } else { if (log.isDebugEnabled()) { log.debug("No XLS Metadata generic element handler for " + element.getGenericType()); } } } } @Override protected ExporterNature getNature() { return nature; } @Override public String getExporterKey() { return XLS_EXPORTER_KEY; } @Override public String getExporterPropertiesPrefix() { return XLS_EXPORTER_PROPERTIES_PREFIX; } protected void setColumnName(String currentColumnName) { // when no columns are provided, build the column names list as they are retrieved from the report element property if (!hasDefinedColumns) { if (currentColumnName != null && currentColumnName.length() > 0 && !columnNames.contains(currentColumnName)) { columnNamesMap.put( currentColumnName, columnNames.size()); columnNames.add(currentColumnName); } } } /** * Writes the header column names */ @Override protected void writeReportHeader() throws JRException { row = sheet.createRow(0); for(int i = 0; i< columnNames.size(); i++) { String columnName = columnNames.get(i); cell = row.createCell(i); cell.setCellType(CellType.STRING); cell.setCellValue(new HSSFRichTextString(columnName)); } } @Override protected void setSheetName(String sheetName) { workbook.setSheetName(workbook.getSheetIndex(sheet) , sheetName); } @Override protected void setFreezePane(int rowIndex, int colIndex) { if(rowIndex > 0 || colIndex > 0) { sheet.createFreezePane(Math.max(0, colIndex), Math.max(0, rowIndex)); } } @Override protected void setAutoFilter(String autoFilterRange) { //TODO: recalculate autoFilterRange depending on exported columns // sheet.setAutoFilter(CellRangeAddress.valueOf(autoFilterRange)); } @Override protected void setRowLevels(XlsRowLevelInfo levelInfo, String level) { //TODO: recalculate row levels depending on exported columns // if(levelInfo != null) { // Map<String, Integer> levelMap = levelInfo.getLevelMap(); // if(levelMap != null && levelMap.size() > 0) { // for(String l : levelMap.keySet()) { // if (level == null || l.compareTo(level) >= 0) { // Integer startIndex = levelMap.get(l); // if(levelInfo.getEndIndex() >= startIndex) { // sheet.groupRow(startIndex, levelInfo.getEndIndex()); // } // } // } // sheet.setRowSumsBelow(false); // } // } } private final short getSuitablePaperSize() { if (pageFormat == null) { return -1; } long width = 0; long height = 0; short ps = -1; if ((pageFormat.getPageWidth() != 0) && (pageFormat.getPageHeight() != 0)) { double dWidth = (pageFormat.getPageWidth() / 72.0); double dHeight = (pageFormat.getPageHeight() / 72.0); height = Math.round(dHeight * 25.4); width = Math.round(dWidth * 25.4); // Compare to ISO 216 A-Series (A3-A5). All other ISO 216 formats // not supported by POI Api yet. // A3 papersize also not supported by POI Api yet. for (int i = 4; i < 6; i++) { int w = calculateWidthForDinAN(i); int h = calculateHeightForDinAN(i); if (((w == width) && (h == height)) || ((h == width) && (w == height))) { if (i == 4) { ps = HSSFPrintSetup.A4_PAPERSIZE; } else if (i == 5) { ps = HSSFPrintSetup.A5_PAPERSIZE; } break; } } //envelope sizes if (ps == -1) { // ISO 269 sizes - "Envelope DL" (110 x 220 mm) if (((width == 110) && (height == 220)) || ((width == 220) && (height == 110))) { ps = HSSFPrintSetup.ENVELOPE_DL_PAPERSIZE; } } // Compare to common North American Paper Sizes (ANSI X3.151-1987). if (ps == -1) { // ANSI X3.151-1987 - "Letter" (216 x 279 mm) if (((width == 216) && (height == 279)) || ((width == 279) && (height == 216))) { ps = HSSFPrintSetup.LETTER_PAPERSIZE; } // ANSI X3.151-1987 - "Legal" (216 x 356 mm) if (((width == 216) && (height == 356)) || ((width == 356) && (height == 216))) { ps = HSSFPrintSetup.LEGAL_PAPERSIZE; } // ANSI X3.151-1987 - "Executive" (190 x 254 mm) else if (((width == 190) && (height == 254)) || ((width == 254) && (height == 190))) { ps = HSSFPrintSetup.EXECUTIVE_PAPERSIZE; } // ANSI X3.151-1987 - "Ledger/Tabloid" (279 x 432 mm) // Not supported by POI Api yet. } } return ps; } private HorizontalAlignment getHorizontalAlignment(TextAlignHolder alignment) { switch (alignment.horizontalAlignment) { case RIGHT: return HorizontalAlignment.RIGHT; case CENTER: return HorizontalAlignment.CENTER; case JUSTIFIED: return HorizontalAlignment.JUSTIFY; case LEFT: default: return HorizontalAlignment.LEFT; } } private VerticalAlignment getVerticalAlignment(TextAlignHolder alignment) { switch (alignment.verticalAlignment) { case BOTTOM: return VerticalAlignment.BOTTOM; case MIDDLE: return VerticalAlignment.CENTER; case JUSTIFIED: return VerticalAlignment.JUSTIFY; case TOP: default: return VerticalAlignment.TOP; } } private short getRotation(TextAlignHolder alignment) { switch (alignment.rotation) { case LEFT: return 90; case RIGHT: return -90; case UPSIDE_DOWN: case NONE: default: return 0; } } /** * */ protected HSSFColor getWorkbookColor(Color awtColor) { HSSFColor color = null; if(awtColor != null) { byte red = (byte)awtColor.getRed(); byte green = (byte)awtColor.getGreen(); byte blue = (byte)awtColor.getBlue(); XlsExporterConfiguration configuration = getCurrentConfiguration(); if (configuration.isCreateCustomPalette()) { try { color = palette.findColor(red,green, blue) != null ? palette.findColor(red,green, blue) : palette.addColor(red,green, blue); } catch(Exception e) { if(customColorIndex < MAX_COLOR_INDEX) { palette.setColorAtIndex(customColorIndex, red, green, blue); color = palette.getColor(customColorIndex++); } else { color = palette.findSimilarColor(red, green, blue); } } } } return color == null ? getNearestColor(awtColor) : color; } /** * */ protected static HSSFColor getNearestColor(Color awtColor) { HSSFColor color = hssfColorsCache.get(awtColor); if (color == null) { Map<?,?> triplets = HSSFColor.getTripletHash(); if (triplets != null) { Collection<?> keys = triplets.keySet(); if (keys != null && keys.size() > 0) { Object key = null; HSSFColor crtColor = null; short[] rgb = null; int diff = 0; int minDiff = 999; for (Iterator<?> it = keys.iterator(); it.hasNext();) { key = it.next(); crtColor = (HSSFColor) triplets.get(key); rgb = crtColor.getTriplet(); diff = Math.abs(rgb[0] - awtColor.getRed()) + Math.abs(rgb[1] - awtColor.getGreen()) + Math.abs(rgb[2] - awtColor.getBlue()); if (diff < minDiff) { minDiff = diff; color = crtColor; } } } } hssfColorsCache.put(awtColor, color); } return color; } /** * */ protected HSSFFont getLoadedFont(JRFont font, short forecolor, Map<Attribute,Object> attributes, Locale locale) { HSSFFont cellFont = null; String fontName = fontUtil.getExportFontFamily(font.getFontName(), locale, getExporterKey()); boolean isFontSizeFixEnabled = getCurrentItemConfiguration().isFontSizeFixEnabled(); short superscriptType = HSSFFont.SS_NONE; if( attributes != null && attributes.get(TextAttribute.SUPERSCRIPT) != null) { Object value = attributes.get(TextAttribute.SUPERSCRIPT); if(TextAttribute.SUPERSCRIPT_SUPER.equals(value)) { superscriptType = HSSFFont.SS_SUPER; } else if(TextAttribute.SUPERSCRIPT_SUB.equals(value)) { superscriptType = HSSFFont.SS_SUB; } } for (int i = 0; i < loadedFonts.size(); i++) { HSSFFont cf = (HSSFFont)loadedFonts.get(i); short fontSize = (short)font.getFontsize(); if (isFontSizeFixEnabled) { fontSize -= 1; } if ( cf.getFontName().equals(fontName) && (cf.getColor() == forecolor) && (cf.getFontHeightInPoints() == fontSize) && ((cf.getUnderline() == HSSFFont.U_SINGLE)?(font.isUnderline()):(!font.isUnderline())) && (cf.getStrikeout() == font.isStrikeThrough()) && (cf.getBold() == font.isBold()) && (cf.getItalic() == font.isItalic()) && (cf.getTypeOffset() == superscriptType) ) { cellFont = cf; break; } } if (cellFont == null) { cellFont = workbook.createFont(); cellFont.setFontName(fontName); cellFont.setColor(forecolor); short fontSize = (short)font.getFontsize(); if (isFontSizeFixEnabled) { fontSize -= 1; } cellFont.setFontHeightInPoints(fontSize); if (font.isUnderline()) { cellFont.setUnderline(HSSFFont.U_SINGLE); } if (font.isStrikeThrough()) { cellFont.setStrikeout(true); } if (font.isBold()) { cellFont.setBold(true); } if (font.isItalic()) { cellFont.setItalic(true); } cellFont.setTypeOffset(superscriptType); loadedFonts.add(cellFont); } return cellFont; } @Override protected void createSheet(CutsInfo xCuts, SheetInfo sheetInfo) { } @Override protected void setRowHeight(int rowIndex, int lastRowHeight, Cut yCut, XlsRowLevelInfo levelInfo) throws JRException { } @Override protected void addRowBreak(int rowIndex) { sheet.setRowBreak(rowIndex); } @Override protected void setColumnWidth(int col, int width, boolean autoFit) { } @Override protected void updateSheet(JRPrintElement element) { JRXlsMetadataExporterNature xlsNature = (JRXlsMetadataExporterNature)nature; configureDefinedNames(xlsNature, element); updatePageMargin(xlsNature.getPrintPageTopMargin(element), Sheet.TopMargin); updatePageMargin(xlsNature.getPrintPageLeftMargin(element), Sheet.LeftMargin); updatePageMargin(xlsNature.getPrintPageBottomMargin(element), Sheet.BottomMargin); updatePageMargin(xlsNature.getPrintPageRightMargin(element), Sheet.RightMargin); updateHeaderFooterMargin(xlsNature.getPrintHeaderMargin(element), true); updateHeaderFooterMargin(xlsNature.getPrintFooterMargin(element), false); HSSFHeader header = sheet.getHeader(); String sheetHeaderLeft = xlsNature.getSheetHeaderLeft(element); if(sheetHeaderLeft != null) { header.setLeft(sheetHeaderLeft); } String sheetHeaderCenter = xlsNature.getSheetHeaderCenter(element); if(sheetHeaderCenter != null) { header.setCenter(sheetHeaderCenter); } String sheetHeaderRight = xlsNature.getSheetHeaderRight(element); if(sheetHeaderRight != null) { header.setRight(sheetHeaderRight); } HSSFFooter footer = sheet.getFooter(); String sheetFooterLeft = xlsNature.getSheetFooterLeft(element); if(sheetFooterLeft != null) { footer.setLeft(sheetFooterLeft); } String sheetFooterCenter = xlsNature.getSheetFooterCenter(element); if(sheetFooterCenter != null) { footer.setCenter(sheetFooterCenter); } String sheetFooterRight = xlsNature.getSheetFooterRight(element); if(sheetFooterRight != null) { footer.setRight(sheetFooterRight); } } private void updatePageMargin(Integer marginValue, short marginType) { if(marginValue != null) { double margin = LengthUtil.inch(marginValue); if(margin > sheet.getMargin(marginType)) { sheet.setMargin(marginType, margin); } } } private void updateHeaderFooterMargin(Integer marginValue, boolean isHeaderMargin) { if(marginValue != null) { HSSFPrintSetup printSetup = sheet.getPrintSetup(); double margin = LengthUtil.inch(marginValue); if(isHeaderMargin) { if(margin > printSetup.getHeaderMargin()) { printSetup.setHeaderMargin(margin); } } else { if(margin > printSetup.getFooterMargin()) { printSetup.setFooterMargin(margin); } } } } /** * */ protected class BoxStyle { protected static final int TOP = 0; protected static final int LEFT = 1; protected static final int BOTTOM = 2; protected static final int RIGHT = 3; protected BorderStyle[] borderStyle = new BorderStyle[] {BorderStyle.NONE, BorderStyle.NONE, BorderStyle.NONE, BorderStyle.NONE}; protected short[] borderColour = new short[4]; private int hash; public BoxStyle(int side, JRPen pen) { borderStyle[side] = JRXlsMetadataExporter.getBorderStyle(pen); borderColour[side] = JRXlsMetadataExporter.this.getWorkbookColor(pen.getLineColor()).getIndex(); hash = computeHash(); } public BoxStyle(JRPrintElement element) { if(element != null) { if (element instanceof JRBoxContainer) { setBox(((JRBoxContainer)element).getLineBox()); } if (element instanceof JRCommonGraphicElement) { setPen(((JRCommonGraphicElement)element).getLinePen()); } } } public void setBox(JRLineBox box) { borderStyle[TOP] = JRXlsMetadataExporter.getBorderStyle(box.getTopPen()); borderColour[TOP] = JRXlsMetadataExporter.this.getWorkbookColor(box.getTopPen().getLineColor()).getIndex(); borderStyle[BOTTOM] = JRXlsMetadataExporter.getBorderStyle(box.getBottomPen()); borderColour[BOTTOM] = JRXlsMetadataExporter.this.getWorkbookColor(box.getBottomPen().getLineColor()).getIndex(); borderStyle[LEFT] = JRXlsMetadataExporter.getBorderStyle(box.getLeftPen()); borderColour[LEFT] = JRXlsMetadataExporter.this.getWorkbookColor(box.getLeftPen().getLineColor()).getIndex(); borderStyle[RIGHT] = JRXlsMetadataExporter.getBorderStyle(box.getRightPen()); borderColour[RIGHT] = JRXlsMetadataExporter.this.getWorkbookColor(box.getRightPen().getLineColor()).getIndex(); hash = computeHash(); } public void setPen(JRPen pen) { if ( borderStyle[TOP] == BorderStyle.NONE && borderStyle[LEFT] == BorderStyle.NONE && borderStyle[BOTTOM] == BorderStyle.NONE && borderStyle[RIGHT] == BorderStyle.NONE ) { BorderStyle style = JRXlsMetadataExporter.getBorderStyle(pen); short colour = JRXlsMetadataExporter.this.getWorkbookColor(pen.getLineColor()).getIndex(); borderStyle[TOP] = style; borderStyle[BOTTOM] = style; borderStyle[LEFT] = style; borderStyle[RIGHT] = style; borderColour[TOP] = colour; borderColour[BOTTOM] = colour; borderColour[LEFT] = colour; borderColour[RIGHT] = colour; } hash = computeHash(); } private int computeHash() { int hashCode = (borderStyle[TOP] == null ? 0 : borderStyle[TOP].hashCode()); hashCode = 31*hashCode + borderColour[TOP]; hashCode = 31*hashCode + (borderStyle[BOTTOM] == null ? 0 : borderStyle[BOTTOM].hashCode()); hashCode = 31*hashCode + borderColour[BOTTOM]; hashCode = 31*hashCode + (borderStyle[LEFT] == null ? 0 : borderStyle[LEFT].hashCode()); hashCode = 31*hashCode + borderColour[LEFT]; hashCode = 31*hashCode + (borderStyle[RIGHT] == null ? 0 : borderStyle[RIGHT].hashCode()); hashCode = 31*hashCode + borderColour[RIGHT]; return hashCode; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object o) { BoxStyle b = (BoxStyle) o; return b.borderStyle[TOP] == borderStyle[TOP] && b.borderColour[TOP] == borderColour[TOP] && b.borderStyle[BOTTOM] == borderStyle[BOTTOM] && b.borderColour[BOTTOM] == borderColour[BOTTOM] && b.borderStyle[LEFT] == borderStyle[LEFT] && b.borderColour[LEFT] == borderColour[LEFT] && b.borderStyle[RIGHT] == borderStyle[RIGHT] && b.borderColour[RIGHT] == borderColour[RIGHT]; } @Override public String toString() { return "(" + borderStyle[TOP] + "/" + borderColour[TOP] + "," + borderStyle[BOTTOM] + "/" + borderColour[BOTTOM] + "," + borderStyle[LEFT] + "/" + borderColour[LEFT] + "," + borderStyle[RIGHT] + "/" + borderColour[RIGHT] + ")"; } } /** * */ protected class StyleInfo { protected final FillPatternType mode; protected final short backcolor; protected final HorizontalAlignment horizontalAlignment; protected final VerticalAlignment verticalAlignment; protected final short rotation; protected final HSSFFont font; protected final BoxStyle box; protected final boolean lcWrapText; protected final boolean lcCellLocked; protected final boolean lcCellHidden; protected final boolean lcShrinkToFit; private short lcDataFormat = -1; private int hashCode; public StyleInfo( FillPatternType mode, short backcolor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, short rotation, HSSFFont font, BoxStyle box, boolean wrapText, boolean cellLocked, boolean cellHidden, boolean shrinkToFit ) { this.mode = mode; this.backcolor = backcolor; this.horizontalAlignment = horizontalAlignment; this.verticalAlignment = verticalAlignment; this.rotation = rotation; this.font = font; this.box = box; this.lcWrapText = shrinkToFit ? false : wrapText; this.lcCellLocked = cellLocked; this.lcCellHidden = cellHidden; this.lcShrinkToFit = shrinkToFit; hashCode = computeHash(); } protected int computeHash() { int hash = mode.hashCode(); hash = 31*hash + backcolor; hash = 31*hash + horizontalAlignment.hashCode(); hash = 31*hash + verticalAlignment.hashCode(); hash = 31*hash + rotation; hash = 31*hash + (font == null ? 0 : font.getIndex()); hash = 31*hash + (box == null ? 0 : box.hashCode()); hash = 31*hash + lcDataFormat; hash = 31*hash + (lcWrapText ? 0 : 1); hash = 31*hash + (lcCellLocked ? 0 : 1); hash = 31*hash + (lcCellHidden ? 0 : 1); hash = 31*hash + (lcShrinkToFit ? 0 : 1); return hash; } public void setDataFormat(short dataFormat) { this.lcDataFormat = dataFormat; hashCode = computeHash(); } public boolean hasDataFormat() { return lcDataFormat != -1; } public short getDataFormat() { return lcDataFormat; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object o) { StyleInfo s = (StyleInfo) o; return s.mode == mode && s.backcolor == backcolor && s.horizontalAlignment == horizontalAlignment && s.verticalAlignment == verticalAlignment && s.rotation == rotation && (s.font == null ? font == null : (font != null && s.font.getIndex() == font.getIndex())) && (s.box == null ? box == null : (box != null && s.box.equals(box))) && s.rotation == rotation && s.lcWrapText == lcWrapText && s.lcCellLocked == lcCellLocked && s.lcCellHidden == lcCellHidden && s.lcShrinkToFit == lcShrinkToFit; //FIXME should dataformat be part of equals? it is part of toString()... } @Override public String toString() { return "(" + mode + "," + backcolor + "," + horizontalAlignment + "," + verticalAlignment + "," + rotation + "," + font + "," + box + "," + lcDataFormat + "," + lcWrapText + "," + lcCellLocked + "," + lcCellHidden + "," + lcShrinkToFit + ")"; } } protected class CellSettings { private CellType cellType; private HSSFCellStyle cellStyle; private Object cellValue; private String formula; private Hyperlink link; public CellSettings() { } public CellSettings(HSSFCellStyle cellStyle) { this(CellType.BLANK, cellStyle, null); } public CellSettings( CellType cellType, HSSFCellStyle cellStyle, Object cellValue ) { this(cellType, cellStyle, cellValue, null); } public CellSettings( CellType cellType, HSSFCellStyle cellStyle, Object cellValue, String formula ) { this(cellType, cellStyle, cellValue, formula, null); } public CellSettings( CellType cellType, HSSFCellStyle cellStyle, Object cellValue, String formula, Hyperlink link ) { this.cellType = cellType; this.cellStyle = cellStyle; this.cellValue = cellValue; this.formula = formula; this.link = link; } public HSSFCellStyle getCellStyle() { return cellStyle; } public void setCellStyle(HSSFCellStyle cellStyle) { this.cellStyle = cellStyle; } public CellType getCellType() { return cellType; } public void setCellType(CellType cellType) { this.cellType = cellType; } public Object getCellValue() { return cellValue; } public void setCellValue(Object cellValue) { this.cellValue = cellValue; } public String getFormula() { return formula; } public void setFormula(String formula) { this.formula = formula; } public Hyperlink getLink() { return link; } public void setLink(Hyperlink link) { this.link = link; } public void importValues( CellType cellType, HSSFCellStyle cellStyle, Object cellValue ) { this.importValues(cellType, cellStyle, cellValue, null); } public void importValues( CellType cellType, HSSFCellStyle cellStyle, Object cellValue, String formula ) { this.importValues(cellType, cellStyle, cellValue, formula, null); } public void importValues( CellType cellType, HSSFCellStyle cellStyle, Object cellValue, String formula, Hyperlink link ) { if(!CellType.FORMULA.equals(cellType)) { this.cellType = cellType; } this.cellStyle = cellStyle; this.cellValue = cellValue; this.formula = formula; this.link = link; } } } class ImageSettings { private int index; private ClientAnchor.AnchorType anchorType; public ImageSettings() { } public ImageSettings(int index, ClientAnchor.AnchorType anchorType) { this.index = index; this.anchorType = anchorType; } public int getIndex() { return index; } public ClientAnchor.AnchorType getAnchorType() { return anchorType; } }
922e7d4fe5bdb5a05992e3bc91372d3db345dc5b
1,896
java
Java
HesaplamaOrnegi/app/src/main/java/com/serifgungor/hesaplamaornegi/MainActivity.java
harunlakodla/Temel-Kullanimlar-Android
84702b49dff2a2aa882ac382e935b2d5c24b5987
[ "Apache-2.0" ]
2
2020-11-16T03:41:51.000Z
2020-11-16T03:41:55.000Z
HesaplamaOrnegi/app/src/main/java/com/serifgungor/hesaplamaornegi/MainActivity.java
harunlakodla/Temel-Kullanimlar-Android
84702b49dff2a2aa882ac382e935b2d5c24b5987
[ "Apache-2.0" ]
null
null
null
HesaplamaOrnegi/app/src/main/java/com/serifgungor/hesaplamaornegi/MainActivity.java
harunlakodla/Temel-Kullanimlar-Android
84702b49dff2a2aa882ac382e935b2d5c24b5987
[ "Apache-2.0" ]
null
null
null
27.478261
85
0.620253
994,763
package com.serifgungor.hesaplamaornegi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText etSayi1,etSayi2; Button btnTopla,btnCikar,btnCarp,btnBol; TextView tvSonuc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvSonuc = findViewById(R.id.tvSonuc); btnTopla = findViewById(R.id.btnTopla); btnCikar = findViewById(R.id.btnCikar); btnCarp = findViewById(R.id.btnCarp); btnBol = findViewById(R.id.btnBol); etSayi1 = findViewById(R.id.etSayi1); etSayi2 = findViewById(R.id.etSayi2); btnCikar.setOnClickListener(this); btnCarp.setOnClickListener(this); btnBol.setOnClickListener(this); btnTopla.setOnClickListener(this); } @Override public void onClick(View v) { /* View sınıfı tıklayan nesnenin bilgilerini içerir. Edittext nesnesi içerisinden gelen tüm değerler String'dir. */ int sayi1 = Integer.valueOf(etSayi1.getText().toString()); int sayi2 = Integer.valueOf(etSayi2.getText().toString()); int sonuc = 0; switch (v.getId()){ case R.id.btnTopla: sonuc = sayi1+sayi2; break; case R.id.btnCikar: sonuc = sayi1-sayi2; break; case R.id.btnBol: sonuc = sayi1/sayi2; break; case R.id.btnCarp: sonuc = sayi1*sayi2; break; } tvSonuc.setText(""+sonuc); } }
922e7e40d4dfafafbb40279a2a46b8cc4a4c2816
9,323
java
Java
library/src/main/java/com/carlos2927/java_memory_leak_fixer_android_extension/AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo.java
Carlos2927/AndroidPlatformMemoryWatcher
508815d1dc1115af1a1e52dae46ced54fc2d5358
[ "Apache-2.0" ]
null
null
null
library/src/main/java/com/carlos2927/java_memory_leak_fixer_android_extension/AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo.java
Carlos2927/AndroidPlatformMemoryWatcher
508815d1dc1115af1a1e52dae46ced54fc2d5358
[ "Apache-2.0" ]
null
null
null
library/src/main/java/com/carlos2927/java_memory_leak_fixer_android_extension/AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo.java
Carlos2927/AndroidPlatformMemoryWatcher
508815d1dc1115af1a1e52dae46ced54fc2d5358
[ "Apache-2.0" ]
null
null
null
46.849246
259
0.543602
994,764
package com.carlos2927.java_memory_leak_fixer_android_extension; import android.app.Activity; import android.os.Build; import android.text.InputFilter; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.util.Log; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.TextView; import com.carlos2927.java.memoryleakfixer.InnerClassHelper; import com.carlos2927.java.memoryleakfixer.JavaReflectUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * 解决由android.view.accessibility.AccessibilityNodeInfo#sPool静态持有间接引用Context的变量引发的内存泄漏 */ public class AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo extends AndroidFrameworkStaticFiledWatcher { public static final int CompatAndroidSDK = Build.VERSION_CODES.JELLY_BEAN; Class cls; Class cls_Editor$UndoInputFilter; Class cls_Editor; Class cls_TextView$ChangeWatcher; List<AccessibilityNodeInfo> accessibilityNodeInfoList = new ArrayList<>(); private AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo(){ } private static AndroidFrameworkStaticFiledWatcher Instance; public static AndroidFrameworkStaticFiledWatcher getInstance(){ synchronized (AndroidFrameworkStaticFiledWatcher.class){ if(Instance == null){ Instance = new AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo(); } } return Instance; } private CharSequence getOriginalText(AccessibilityNodeInfo accessibilityNodeInfo){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ Field field = JavaReflectUtils.getField(AccessibilityNodeInfo.class,"mOriginalText"); if(field != null){ try { return (CharSequence) field.get(accessibilityNodeInfo); } catch (Exception e) { e.printStackTrace(); } } Method method = JavaReflectUtils.getMethod(AccessibilityNodeInfo.class,"getOriginalText"); if(method != null){ try { return (CharSequence) method.invoke(accessibilityNodeInfo); }catch (Exception e){ e.printStackTrace(); } } // accessibilityNodeInfo.getText(); stopWatch(); // 在高版本系统中获取不到mOriginalText时就不再监测了 }else { return accessibilityNodeInfo.getText(); } return null; } boolean isNeedRelease(CharSequence charSequence){ if(cls == null){ try { cls = Class.forName("android.text.method.ReplacementTransformationMethod$SpannedReplacementCharSequence"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } if(cls.isInstance(charSequence)){ try { Spanned spanned = (Spanned) JavaReflectUtils.getField(cls,"mSpanned").get(charSequence); if(spanned instanceof SpannableStringBuilder){ Activity activity = null; SpannableStringBuilder spannableStringBuilder = (SpannableStringBuilder) spanned; InputFilter[] filters = spannableStringBuilder.getFilters(); if(filters != null){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){ if(cls_Editor$UndoInputFilter == null){ try { cls_Editor$UndoInputFilter = Class.forName("android.widget.Editor$UndoInputFilter"); for(InputFilter inputFilter:filters){ if(cls_Editor$UndoInputFilter.isInstance(inputFilter)){ try { Object mEditor = JavaReflectUtils.getField(cls_Editor$UndoInputFilter,"mEditor").get(inputFilter); if(mEditor != null){ if(cls_Editor == null){ cls_Editor = Class.forName("android.widget.Editor"); } TextView textView = (TextView) JavaReflectUtils.getField(cls_Editor,"mTextView").get(mEditor); if(textView != null){ activity = InnerClassHelper.getActivityFromContext(textView.getContext()); break; } } }catch (Exception e){ e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } }else{ // Can we should compat ICE_CREAM_SANDWICH(14) and ICE_CREAM_SANDWICH_MR1(15) now? } } if(activity == null){ activity = checkSpannableStringBuilder_mSpans(spannableStringBuilder); } if(activity != null){ boolean isActivityDestroyed = InnerClassHelper.isActivityDestroyed(activity); if(isActivityDestroyed){ Log.i(AndroidPlatformMemoryWatcher.TAG,String.format("AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo %s is destroyed,The AccessibilityNodeInfo that related this activity will invoke setText(null)",activity.toString())); } return isActivityDestroyed; } } } catch (IllegalAccessException e) { e.printStackTrace(); } }else if(SpannableStringBuilder.class.isInstance(charSequence)){ Activity activity = checkSpannableStringBuilder_mSpans((SpannableStringBuilder) charSequence); if(activity != null){ boolean isActivityDestroyed = InnerClassHelper.isActivityDestroyed(activity); if(isActivityDestroyed){ Log.i(AndroidPlatformMemoryWatcher.TAG,String.format("AndroidFrameworkMemoryLeakWatcherForAccessibilityNodeInfo %s is destroyed,The AccessibilityNodeInfo that related this activity will invoke setText(null)",activity.toString())); } return isActivityDestroyed; } } return false; } public Activity checkSpannableStringBuilder_mSpans(SpannableStringBuilder spannableStringBuilder){ try { Object[] mSpans = (Object[]) JavaReflectUtils.getField(SpannableStringBuilder.class,"mSpans").get(spannableStringBuilder); if(cls_TextView$ChangeWatcher == null){ cls_TextView$ChangeWatcher = Class.forName("android.widget.TextView$ChangeWatcher"); } Activity activity = null; for(Object obj:mSpans){ if(cls_TextView$ChangeWatcher.isInstance(obj)){ List<Field> fieldList = InnerClassHelper.getSyntheticFields(cls_TextView$ChangeWatcher); if(fieldList != null){ for(Field field:fieldList){ field.setAccessible(true); Object target = field.get(obj); if(TextView.class.isInstance(target)){ TextView textView = (TextView)target; activity = InnerClassHelper.getActivityFromContext(textView.getContext()); break; } } if(activity != null){ return activity; } } } } }catch (Exception e){ e.printStackTrace(); } return null; } @Override public void watch() { if(!checkNeedWatch()){ return; } for(int i = 0;i<50;i++){ AccessibilityNodeInfo accessibilityNodeInfo = AccessibilityNodeInfo.obtain(); CharSequence charSequence = getOriginalText(accessibilityNodeInfo); if(charSequence == null){ break; } if(isNeedRelease(charSequence)){ accessibilityNodeInfo.setText(null); } accessibilityNodeInfoList.add(accessibilityNodeInfo); } for(AccessibilityNodeInfo accessibilityNodeInfo:accessibilityNodeInfoList){ accessibilityNodeInfo.recycle(); } accessibilityNodeInfoList.clear(); } }
922e7e9a7fc68c146d84f4036144915b11f2d7cc
4,681
java
Java
src/test/java/com/arangodb/springframework/core/mapping/EdgeMappingTest.java
PauloFerreira25/spring-data
e513ec2fae59a06cf8452143eee6bc35a43d5c6b
[ "Apache-2.0" ]
96
2017-12-15T09:03:34.000Z
2022-03-17T15:48:20.000Z
src/test/java/com/arangodb/springframework/core/mapping/EdgeMappingTest.java
PauloFerreira25/spring-data
e513ec2fae59a06cf8452143eee6bc35a43d5c6b
[ "Apache-2.0" ]
175
2018-01-12T15:51:10.000Z
2022-03-18T08:45:57.000Z
src/test/java/com/arangodb/springframework/core/mapping/EdgeMappingTest.java
PauloFerreira25/spring-data
e513ec2fae59a06cf8452143eee6bc35a43d5c6b
[ "Apache-2.0" ]
64
2018-03-05T11:04:37.000Z
2022-03-14T09:25:21.000Z
35.462121
113
0.76928
994,765
/* * DISCLAIMER * * Copyright 2018 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package com.arangodb.springframework.core.mapping; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import com.arangodb.springframework.AbstractArangoTest; import com.arangodb.springframework.annotation.From; import com.arangodb.springframework.annotation.To; import com.arangodb.springframework.core.mapping.testdata.BasicEdgeLazyTestEntity; import com.arangodb.springframework.core.mapping.testdata.BasicEdgeTestEntity; import com.arangodb.springframework.core.mapping.testdata.BasicTestEntity; /** * @author Mark Vollmary * */ public class EdgeMappingTest extends AbstractArangoTest { @Test public void edgeFromTo() { final BasicTestEntity e1 = new BasicTestEntity(); template.insert(e1); final BasicTestEntity e2 = new BasicTestEntity(); template.insert(e2); final BasicEdgeTestEntity e0 = new BasicEdgeTestEntity(e1, e2); template.insert(e0); final BasicEdgeTestEntity document = template.find(e0.id, BasicEdgeTestEntity.class).get(); assertThat(document, is(notNullValue())); assertThat(document.getFrom(), is(notNullValue())); assertThat(document.getFrom().getId(), is(e1.getId())); assertThat(document.getTo(), is(notNullValue())); assertThat(document.getTo().getId(), is(e2.getId())); } @Test public void edgeFromToLazy() { final BasicTestEntity e1 = new BasicTestEntity(); template.insert(e1); final BasicTestEntity e2 = new BasicTestEntity(); template.insert(e2); final BasicEdgeLazyTestEntity e0 = new BasicEdgeLazyTestEntity(e1, e2); template.insert(e0); final BasicEdgeLazyTestEntity document = template.find(e0.id, BasicEdgeLazyTestEntity.class).get(); assertThat(document, is(notNullValue())); assertThat(document.getFrom(), is(notNullValue())); assertThat(document.getFrom().getId(), is(e1.getId())); assertThat(document.getTo(), is(notNullValue())); assertThat(document.getTo().getId(), is(e2.getId())); } public static class EdgeConstructorWithFromToParamsTestEntity extends BasicEdgeTestEntity { @From private final BasicTestEntity from; @To private final BasicTestEntity to; public EdgeConstructorWithFromToParamsTestEntity(final BasicTestEntity from, final BasicTestEntity to) { super(); this.from = from; this.to = to; } } @Test public void edgeConstructorWithFromToParams() { final BasicTestEntity from = new BasicTestEntity(); final BasicTestEntity to = new BasicTestEntity(); template.insert(from); template.insert(to); final EdgeConstructorWithFromToParamsTestEntity edge = new EdgeConstructorWithFromToParamsTestEntity(from, to); template.insert(edge); final EdgeConstructorWithFromToParamsTestEntity document = template .find(edge.id, EdgeConstructorWithFromToParamsTestEntity.class).get(); assertThat(document, is(notNullValue())); assertThat(document.from.id, is(from.id)); assertThat(document.to.id, is(to.id)); } public static class EdgeConstructorWithFromToLazyParamsTestEntity extends BasicEdgeTestEntity { @From private final BasicTestEntity from; @To private final BasicTestEntity to; public EdgeConstructorWithFromToLazyParamsTestEntity(final BasicTestEntity from, final BasicTestEntity to) { super(); this.from = from; this.to = to; } } @Test public void edgeConstructorWithFromToLazyParams() { final BasicTestEntity from = new BasicTestEntity(); final BasicTestEntity to = new BasicTestEntity(); template.insert(from); template.insert(to); final EdgeConstructorWithFromToLazyParamsTestEntity edge = new EdgeConstructorWithFromToLazyParamsTestEntity( from, to); template.insert(edge); final EdgeConstructorWithFromToLazyParamsTestEntity document = template .find(edge.id, EdgeConstructorWithFromToLazyParamsTestEntity.class).get(); assertThat(document, is(notNullValue())); assertThat(document.from.getId(), is(from.id)); assertThat(document.to.getId(), is(to.id)); } }
922e7f58544570660c0e69f4888cae8155488990
3,897
java
Java
app/src/main/java/net/yupol/transmissionremote/app/notifications/BackgroundUpdateJob.java
luk1337/TransmissionRemote
7749040eaa9698618efbf34469b0273f99e90461
[ "Apache-2.0" ]
138
2016-06-08T16:14:43.000Z
2022-03-21T22:53:03.000Z
app/src/main/java/net/yupol/transmissionremote/app/notifications/BackgroundUpdateJob.java
luk1337/TransmissionRemote
7749040eaa9698618efbf34469b0273f99e90461
[ "Apache-2.0" ]
75
2016-05-07T18:19:03.000Z
2021-05-13T10:09:16.000Z
app/src/main/java/net/yupol/transmissionremote/app/notifications/BackgroundUpdateJob.java
luk1337/TransmissionRemote
7749040eaa9698618efbf34469b0273f99e90461
[ "Apache-2.0" ]
47
2016-08-18T17:53:09.000Z
2022-02-19T13:52:23.000Z
36.764151
137
0.68001
994,766
package net.yupol.transmissionremote.app.notifications; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.evernote.android.job.Job; import com.evernote.android.job.JobCreator; import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.request.listener.RequestListener; import net.yupol.transmissionremote.app.TransmissionRemote; import net.yupol.transmissionremote.app.model.json.Torrents; import net.yupol.transmissionremote.app.server.Server; import net.yupol.transmissionremote.app.transport.RequestExecutor; import net.yupol.transmissionremote.app.transport.request.TorrentGetRequest; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class BackgroundUpdateJob extends Job { private static final String TAG_UPDATE_TORRENTS = "tag_update_torrents"; private static final String TAG = BackgroundUpdateJob.class.getSimpleName(); @NonNull @Override protected Result onRunJob(@NonNull Params params) { Context context = getContext(); List<Server> servers = TransmissionRemote.getApplication(context).getServers(); final CountDownLatch countDownLatch = new CountDownLatch(servers.size()); final RequestExecutor requestExecutor = new RequestExecutor(context); final FinishedTorrentsNotificationManager finishedTorrentsNotificationManager = new FinishedTorrentsNotificationManager(context); for (final Server server : servers) { requestExecutor.executeRequest(new TorrentGetRequest(), server, new RequestListener<Torrents>() { @Override public void onRequestSuccess(Torrents torrents) { finishedTorrentsNotificationManager.checkForFinishedTorrents(server, torrents); countDownLatch.countDown(); } @Override public void onRequestFailure(SpiceException spiceException) { Log.e(TAG, "Failed to retrieve torrent list from " + server.getName() + "(" + server.getHost() + ")"); countDownLatch.countDown(); } }); } try { countDownLatch.await(2, TimeUnit.MINUTES); } catch (InterruptedException e) { requestExecutor.unregisterAllListeners(); return Result.FAILURE; } return Result.SUCCESS; } public static void schedule(boolean onlyUnmeteredNetwork) { Set<JobRequest> pendingJobs = JobManager.instance().getAllJobRequestsForTag(TAG_UPDATE_TORRENTS); if (pendingJobs.size() > 0) { return; // Already scheduled } JobRequest.Builder builder = new JobRequest.Builder(TAG_UPDATE_TORRENTS) .setPeriodic(JobRequest.MIN_INTERVAL, (long) (0.75 * JobRequest.MIN_INTERVAL)); if (onlyUnmeteredNetwork) { builder.setRequiredNetworkType(JobRequest.NetworkType.UNMETERED); } else { builder.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED); } builder.setRequirementsEnforced(true) .build() .schedule(); } public static void cancelAll() { JobManager.instance().cancelAllForTag(TAG_UPDATE_TORRENTS); } public static class Creator implements JobCreator { @Nullable @Override public Job create(@NonNull String tag) { switch (tag) { case TAG_UPDATE_TORRENTS: return new BackgroundUpdateJob(); default: return null; } } } }
922e8018b936a1e39b08393128359b38f9a40ae5
1,007
java
Java
chapter_005/src/test/java/ru/job4j/list/SimpleStackTest.java
inflatone/job4j
02e9dff86ac051adfb9d9b75346e6696e351e1fb
[ "Apache-2.0" ]
null
null
null
chapter_005/src/test/java/ru/job4j/list/SimpleStackTest.java
inflatone/job4j
02e9dff86ac051adfb9d9b75346e6696e351e1fb
[ "Apache-2.0" ]
2
2020-04-18T13:20:43.000Z
2020-07-01T19:04:59.000Z
chapter_005/src/test/java/ru/job4j/list/SimpleStackTest.java
sane5ever/job4j
02e9dff86ac051adfb9d9b75346e6696e351e1fb
[ "Apache-2.0" ]
2
2019-03-04T15:03:31.000Z
2020-03-11T12:34:29.000Z
25.820513
85
0.705065
994,767
package ru.job4j.list; import org.junit.Test; import java.util.stream.IntStream; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; /** * Контейнер Stack с использованием динамического контейнера * на базе связанного списка. Тестирование. * * @author Alexander Savchenko * @version 1.0 * @since 2018-11-19 */ public class SimpleStackTest { private SimpleStack<Integer> stack = new SimpleStack<>(); @Test public void whenEmptyStackPollInvocationShouldReturnNull() { assertNull(this.stack.poll()); } @Test public void whenOneElementPushPollInvocationShouldReturnIt() { this.stack.push(0); assertThat(this.stack.poll(), is(0)); } @Test public void whenFiveElementPushPollInvocationShouldReturnThemInReverse() { IntStream.range(0, 5).forEach(this.stack::push); IntStream.range(0, 5).forEach(i -> assertThat(this.stack.poll(), is(4 - i))); } }
922e813816cf98b2017b0825c4177b1c8cfd2f41
248
java
Java
src/main/java/wooteco/subway/line/exception/section/InvalidDistanceException.java
Be-poz/atdd-subway-fare
7c6c272367ea1a148c7e6899dc0a34a4dfd5b625
[ "MIT" ]
null
null
null
src/main/java/wooteco/subway/line/exception/section/InvalidDistanceException.java
Be-poz/atdd-subway-fare
7c6c272367ea1a148c7e6899dc0a34a4dfd5b625
[ "MIT" ]
null
null
null
src/main/java/wooteco/subway/line/exception/section/InvalidDistanceException.java
Be-poz/atdd-subway-fare
7c6c272367ea1a148c7e6899dc0a34a4dfd5b625
[ "MIT" ]
null
null
null
24.8
64
0.754032
994,768
package wooteco.subway.line.exception.section; public class InvalidDistanceException extends SectionException { private static final String MESSAGE = "INVALID_DISTANCE"; public InvalidDistanceException() { super(MESSAGE); } }
922e826acb5375472bb88d064c98a29fb7b67628
7,878
java
Java
tf-api-impl/src/main/java/edu/gatech/gtri/trustmark/v1_0/impl/io/xml/producers/TrustmarkDefinitionXmlProducer.java
Trustmark-Initiative/tmf-api
53b26db18d09bde7be688a75ebe84d635bfbe4e6
[ "Apache-2.0" ]
1
2020-09-01T16:00:52.000Z
2020-09-01T16:00:52.000Z
tf-api-impl/src/main/java/edu/gatech/gtri/trustmark/v1_0/impl/io/xml/producers/TrustmarkDefinitionXmlProducer.java
Trustmark-Initiative/tmf-api
53b26db18d09bde7be688a75ebe84d635bfbe4e6
[ "Apache-2.0" ]
10
2020-07-21T20:28:08.000Z
2022-01-21T23:44:13.000Z
tf-api-impl/src/main/java/edu/gatech/gtri/trustmark/v1_0/impl/io/xml/producers/TrustmarkDefinitionXmlProducer.java
Trustmark-Initiative/tmf-api
53b26db18d09bde7be688a75ebe84d635bfbe4e6
[ "Apache-2.0" ]
1
2020-05-28T23:46:21.000Z
2020-05-28T23:46:21.000Z
45.017143
155
0.687357
994,769
package edu.gatech.gtri.trustmark.v1_0.impl.io.xml.producers; import edu.gatech.gtri.trustmark.v1_0.impl.io.IdUtility; import edu.gatech.gtri.trustmark.v1_0.io.xml.XmlProducer; import edu.gatech.gtri.trustmark.v1_0.model.AssessmentStep; import edu.gatech.gtri.trustmark.v1_0.model.ConformanceCriterion; import edu.gatech.gtri.trustmark.v1_0.model.Source; import edu.gatech.gtri.trustmark.v1_0.model.Term; import edu.gatech.gtri.trustmark.v1_0.model.TrustmarkDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.util.UUID; import static edu.gatech.gtri.trustmark.v1_0.impl.TrustmarkFrameworkConstants.NAMESPACE_URI; /** * Created by brad on 1/7/16. */ public class TrustmarkDefinitionXmlProducer implements XmlProducer<TrustmarkDefinition> { private static final Logger log = LoggerFactory.getLogger(TrustmarkDefinitionXmlProducer.class); @Override public Class<TrustmarkDefinition> getSupportedType() { return TrustmarkDefinition.class; } @Override public void serialize(TrustmarkDefinition td, XMLStreamWriter xmlWriter) throws XMLStreamException { log.debug("Writing XML for TD[" + td.getMetadata().getIdentifier() + "]..."); xmlWriter.writeAttribute(NAMESPACE_URI, "id", td.getId() == null ? IdUtility.trustmarkDefinitionId() : td.getId()); writeMetadata(td, td.getMetadata(), xmlWriter); if (td.getTerms() != null && td.getTerms().size() > 0) { log.debug("Writing " + td.getTerms().size() + " terms..."); xmlWriter.writeStartElement(NAMESPACE_URI, "Terms"); for (Term term : td.getTermsSorted()) { log.debug("Writing term[" + term.getName() + "]..."); xmlWriter.writeStartElement(NAMESPACE_URI, "Term"); XmlProducerUtility.writeXml(term, xmlWriter); xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); } if (td.getSources() != null && td.getSources().size() > 0) { log.debug("Writing " + td.getSources().size() + " sources..."); xmlWriter.writeStartElement(NAMESPACE_URI, "Sources"); for (Source source : td.getSources()) { log.debug("Writing source[" + source.getIdentifier() + "]..."); xmlWriter.writeStartElement(NAMESPACE_URI, "Source"); XmlProducerUtility.writeXml(source, xmlWriter); xmlWriter.writeEndElement(); } log.debug("Writing end sources element..."); xmlWriter.writeEndElement(); } xmlWriter.writeStartElement(NAMESPACE_URI, "ConformanceCriteria"); if (td.getConformanceCriteriaPreface() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "Preface"); xmlWriter.writeCData(td.getConformanceCriteriaPreface()); xmlWriter.writeEndElement(); } for (ConformanceCriterion crit : td.getConformanceCriteria()) { xmlWriter.writeStartElement(NAMESPACE_URI, "ConformanceCriterion"); XmlProducerUtility.writeXml(crit, xmlWriter); xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); xmlWriter.writeStartElement(NAMESPACE_URI, "AssessmentSteps"); if (td.getAssessmentStepPreface() != null) { XmlProducerUtility.writeCDataString(xmlWriter, "Preface", td.getAssessmentStepPreface()); } for (AssessmentStep step : td.getAssessmentSteps()) { xmlWriter.writeStartElement(NAMESPACE_URI, "AssessmentStep"); XmlProducerUtility.writeXml(step, xmlWriter); xmlWriter.writeEndElement(); } xmlWriter.writeEndElement(); xmlWriter.writeStartElement(NAMESPACE_URI, "IssuanceCriteria"); if (td.getIssuanceCriteria() != null) { xmlWriter.writeCData(td.getIssuanceCriteria()); } else { xmlWriter.writeCData("yes(all)"); } xmlWriter.writeEndElement(); //end "IssuanceCriteria" log.debug("Successfully wrote TD XML!"); }//end serialize() private static void writeMetadata(TrustmarkDefinition td, TrustmarkDefinition.Metadata metadata, XMLStreamWriter xmlWriter) throws XMLStreamException { xmlWriter.writeStartElement(NAMESPACE_URI, "Metadata"); XmlProducerUtility.writeMainIdentifyingInformation(xmlWriter, metadata); xmlWriter.writeStartElement(NAMESPACE_URI, "TrustmarkDefiningOrganization"); XmlProducerUtility.writeXml(metadata.getTrustmarkDefiningOrganization(), xmlWriter); xmlWriter.writeEndElement(); //end "TrustmarkDefiningOrganization" if (metadata.getTargetStakeholderDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "TargetStakeholderDescription"); xmlWriter.writeCharacters(metadata.getTargetStakeholderDescription()); xmlWriter.writeEndElement(); //end "TargetStakeholderDescription" } if (metadata.getTargetRecipientDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "TargetRecipientDescription"); xmlWriter.writeCharacters(metadata.getTargetRecipientDescription()); xmlWriter.writeEndElement(); //end "TargetRecipientDescription" } if (metadata.getTargetRelyingPartyDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "TargetRelyingPartyDescription"); xmlWriter.writeCharacters(metadata.getTargetRelyingPartyDescription()); xmlWriter.writeEndElement(); //end "TargetRelyingPartyDescription" } if (metadata.getTargetProviderDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "TargetProviderDescription"); xmlWriter.writeCharacters(metadata.getTargetProviderDescription()); xmlWriter.writeEndElement(); //end "TargetProviderDescription" } if (metadata.getProviderEligibilityCriteria() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "ProviderEligibilityCriteria"); xmlWriter.writeCharacters(metadata.getProviderEligibilityCriteria()); xmlWriter.writeEndElement(); //end "ProviderEligibilityCriteria" } if (metadata.getAssessorQualificationsDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "AssessorQualificationsDescription"); xmlWriter.writeCharacters(metadata.getAssessorQualificationsDescription()); xmlWriter.writeEndElement(); //end "AssessorQualificationsDescription" } if (metadata.getTrustmarkRevocationCriteria() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "TrustmarkRevocationCriteria"); xmlWriter.writeCharacters(metadata.getTrustmarkRevocationCriteria()); xmlWriter.writeEndElement(); //end "TrustmarkRevocationCriteria" } if (metadata.getExtensionDescription() != null) { xmlWriter.writeStartElement(NAMESPACE_URI, "ExtensionDescription"); xmlWriter.writeCharacters(metadata.getExtensionDescription()); xmlWriter.writeEndElement(); //end "ExtensionDescription" } XmlProducerUtility.writeLegalEase(xmlWriter, metadata); XmlProducerUtility.writeSupersessionInfo(xmlWriter, metadata); XmlProducerUtility.writeDeprecated(xmlWriter, metadata); XmlProducerUtility.writeSatisfies(xmlWriter, metadata); XmlProducerUtility.writeKnownConflicts(xmlWriter, metadata); XmlProducerUtility.writeKeywords(xmlWriter, metadata); xmlWriter.writeEndElement(); // end "Metadata" } }//end TrustmarkStatusReportXmlProducer
922e829376c36e49d2aa861aa04f43f155f2a921
7,483
java
Java
sdk/scheduler/src/main/java/com/mesosphere/sdk/offer/ResourceCleaner.java
krisis/dcos-commons
715d27f3e43a5e25b8ecb4beed97333b136fdd9a
[ "Apache-2.0" ]
1
2021-01-06T21:14:00.000Z
2021-01-06T21:14:00.000Z
sdk/scheduler/src/main/java/com/mesosphere/sdk/offer/ResourceCleaner.java
krisis/dcos-commons
715d27f3e43a5e25b8ecb4beed97333b136fdd9a
[ "Apache-2.0" ]
null
null
null
sdk/scheduler/src/main/java/com/mesosphere/sdk/offer/ResourceCleaner.java
krisis/dcos-commons
715d27f3e43a5e25b8ecb4beed97333b136fdd9a
[ "Apache-2.0" ]
null
null
null
38.772021
119
0.66337
994,770
package com.mesosphere.sdk.offer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.mesosphere.sdk.scheduler.recovery.FailureUtils; import org.apache.mesos.Protos; import org.apache.mesos.Protos.Offer; import org.apache.mesos.Protos.Resource; import com.mesosphere.sdk.state.StateStore; import com.mesosphere.sdk.state.StateStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Resource Cleaner provides recommended operations for cleaning up * unexpected Reserved resources and persistent volumes. */ public class ResourceCleaner { private static final Logger logger = LoggerFactory.getLogger(ResourceCleaner.class); // Only Persistent Volumes are DESTROYed private final Set<String> expectedPersistentVolumeIds; // Both Persistent Volumes AND Reserved Resources are UNRESERVEd private final Set<String> expectedReservedResourceIds; /** * Creates a new {@link ResourceCleaner} which retrieves expected resource * information from the provided {@link StateStore}. * * @throws StateStoreException * if there's a failure when retrieving resource information */ public ResourceCleaner(StateStore stateStore) { Collection<Resource> expectedResources = getExpectedResources(stateStore); this.expectedPersistentVolumeIds = getPersistentVolumeIds(expectedResources); this.expectedReservedResourceIds = getReservedResourceIds(expectedResources); } /** * Returns a list of operations which should be performed, given the provided list of Offers * from Mesos. The returned operations MUST be performed in the order in which they are * provided. */ public List<OfferRecommendation> evaluate(List<Offer> offers) { // ORDERING IS IMPORTANT: // The resource lifecycle is RESERVE -> CREATE -> DESTROY -> UNRESERVE // Therefore we *must* put any DESTROY calls before any UNRESERVE calls List<OfferRecommendation> recommendations = new ArrayList<OfferRecommendation>(); // First, find any unexpected persistent volumes which should be DESTROYed int offerResourceCount = 0; for (Offer offer : offers) { offerResourceCount += offer.getResourcesCount(); for (Resource toDestroy : selectUnexpectedResources( expectedPersistentVolumeIds, getPersistentVolumesById(offer))) { recommendations.add(new DestroyOfferRecommendation(offer, toDestroy)); } } int destroyRecommendationCount = recommendations.size(); // Then, find any unexpected persistent volumes AND resource reservations which should // (both) be UNRESERVEd for (Offer offer : offers) { for (Resource toUnreserve : selectUnexpectedResources( expectedReservedResourceIds, getReservedResourcesById(offer))) { recommendations.add(new UnreserveOfferRecommendation(offer, toUnreserve)); } } logger.info("{} offers with {} resources => {} destroy and {} unreserve operations", offers.size(), offerResourceCount, destroyRecommendationCount, recommendations.size() - destroyRecommendationCount); return recommendations; } /** * Returns a list of resources from {@code resourcesById} whose ids are not present in * {@code expectedIds}. */ private static Collection<Resource> selectUnexpectedResources( Set<String> expectedIds, Map<String, Resource> resourcesById) { List<Resource> unexpectedResources = new ArrayList<Resource>(); for (Map.Entry<String, Resource> entry : resourcesById.entrySet()) { if (!expectedIds.contains(entry.getKey())) { unexpectedResources.add(entry.getValue()); } } return unexpectedResources; } /** * Returns a list of all expected resources, which are extracted from all {@link org.apache.mesos.Protos.TaskInfo}s * produced by the provided {@link StateStore}. */ private static Collection<Resource> getExpectedResources(StateStore stateStore) throws StateStoreException { Collection<Resource> resources = new ArrayList<>(); for (Protos.TaskInfo taskInfo : stateStore.fetchTasks()) { if (FailureUtils.isLabeledAsFailed(taskInfo)) { continue; } // Get all resources from both the task level and the executor level resources.addAll(taskInfo.getResourcesList()); if (taskInfo.hasExecutor()) { resources.addAll(taskInfo.getExecutor().getResourcesList()); } } return resources; } /** * Returns the resource ids for all {@code resources} which represent persistent volumes, or * an empty list if no persistent volume resources were found. */ private static Set<String> getPersistentVolumeIds(Collection<Resource> resources) { Set<String> persistenceIds = new HashSet<>(); for (Resource resource : resources) { String persistenceId = ResourceUtils.getPersistenceId(resource); if (persistenceId != null) { persistenceIds.add(persistenceId); } } return persistenceIds; } /** * Returns the resource ids for all {@code resources} which represent reserved resources, or * an empty list if no reserved resources were found. */ private static Set<String> getReservedResourceIds(Collection<Resource> resources) { Set<String> resourceIds = new HashSet<>(); for (Resource resource : resources) { String resourceId = ResourceUtils.getResourceId(resource); if (resourceId != null) { resourceIds.add(resourceId); } } return resourceIds; } /** * Returns an ID -> Resource mapping of all disk resources listed in the provided {@link Offer}, * or an empty list of no disk resources are found. * @param offer The Offer being deconstructed. * @return The map of resources from the {@link Offer} */ private static Map<String, Resource> getPersistentVolumesById(Offer offer) { Map<String, Resource> volumes = new HashMap<String, Resource>(); for (Resource resource : offer.getResourcesList()) { String persistenceId = ResourceUtils.getPersistenceId(resource); if (persistenceId != null) { volumes.put(persistenceId, resource); } } return volumes; } /** * Returns an ID -> Resource mapping of all reservation resources listed in the provided * {@link Offer}, or an empty list if no reservation resources are found. */ private static Map<String, Resource> getReservedResourcesById(Offer offer) { Map<String, Resource> reservedResources = new HashMap<String, Resource>(); for (Resource resource : offer.getResourcesList()) { String resourceId = ResourceUtils.getResourceId(resource); if (resourceId != null) { reservedResources.put(resourceId, resource); } } return reservedResources; } }
922e83482fde8b2b2bb19da48147b04c428edd01
2,371
java
Java
commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/iti41/Iti41AuditStrategy.java
dynamicguy/ipf
f2f2289e1bb51da07fa23f9da927eefe6eeb54c1
[ "Apache-2.0" ]
11
2015-04-08T02:59:57.000Z
2022-03-17T18:25:44.000Z
commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/iti41/Iti41AuditStrategy.java
dynamicguy/ipf
f2f2289e1bb51da07fa23f9da927eefe6eeb54c1
[ "Apache-2.0" ]
3
2016-03-09T19:34:21.000Z
2020-07-01T12:14:50.000Z
commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/iti41/Iti41AuditStrategy.java
dynamicguy/ipf
f2f2289e1bb51da07fa23f9da927eefe6eeb54c1
[ "Apache-2.0" ]
15
2015-02-25T00:15:20.000Z
2021-12-20T13:52:04.000Z
43.109091
107
0.742303
994,771
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.commons.ihe.xds.iti41; import org.openehealth.ipf.commons.ihe.xds.core.audit.XdsSubmitAuditDataset; import org.openehealth.ipf.commons.ihe.xds.core.audit.XdsSubmitAuditStrategy30; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLSubmitObjectsRequest; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.EbXMLSubmitObjectsRequest30; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.ProvideAndRegisterDocumentSetRequestType; import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs30.lcm.SubmitObjectsRequest; /** * Audit strategy for ITI-41. * @author Dmytro Rud */ abstract class Iti41AuditStrategy extends XdsSubmitAuditStrategy30 { /** * Constructs the audit strategy. * @param serverSide * whether this is a server-side or a client-side strategy. * @param allowIncompleteAudit * whether this strategy should allow incomplete audit records * (parameter initially configurable via endpoint URL). */ public Iti41AuditStrategy(boolean serverSide, boolean allowIncompleteAudit) { super(serverSide, allowIncompleteAudit); } @Override public void enrichDatasetFromRequest(Object pojo, XdsSubmitAuditDataset auditDataset) { ProvideAndRegisterDocumentSetRequestType request = (ProvideAndRegisterDocumentSetRequestType)pojo; SubmitObjectsRequest submitObjectsRequest = request.getSubmitObjectsRequest(); if (submitObjectsRequest != null) { EbXMLSubmitObjectsRequest ebXML = new EbXMLSubmitObjectsRequest30(submitObjectsRequest); auditDataset.enrichDatasetFromSubmitObjectsRequest(ebXML); } } }
922e8386abd7ce00840c3f5342c5681afa195a03
17,512
java
Java
app/src/main/java/kos/progs/diary/NotificationTime.java
kos234/Student-s-diary
a5867c410432c1ad76bad17a1e6f1ecf43834d68
[ "Apache-2.0" ]
2
2020-10-12T02:02:33.000Z
2020-10-12T02:02:35.000Z
app/src/main/java/kos/progs/diary/NotificationTime.java
kos234/Student-s-diary
a5867c410432c1ad76bad17a1e6f1ecf43834d68
[ "Apache-2.0" ]
null
null
null
app/src/main/java/kos/progs/diary/NotificationTime.java
kos234/Student-s-diary
a5867c410432c1ad76bad17a1e6f1ecf43834d68
[ "Apache-2.0" ]
null
null
null
47.846995
286
0.481327
994,772
package kos.progs.diary; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import androidx.core.app.NotificationCompat; import kos.progs.diary.R; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Date; import static android.app.NotificationManager.IMPORTANCE_HIGH; import static android.app.NotificationManager.IMPORTANCE_LOW; import static android.content.Context.MODE_PRIVATE; import static android.content.Context.NOTIFICATION_SERVICE; public class NotificationTime extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { new notifer(context, intent).start(); } class notifer extends Thread { final Context context; final String CHANNEL_ID; private final static int NOTIFY_ID = 1; private final Intent intent; public notifer(Context context, Intent intent) { this.context = context; CHANNEL_ID = context.getString(R.string.NotifSettingsName); this.intent = intent; } public boolean onOneHour(int TimeHoursStart, int TimeMinsStart, int hourDate, int minDate) { int i = (TimeHoursStart * 60 + TimeMinsStart) - (hourDate * 60 + minDate); return i <= 60 && i >= 0; } @Override public void run() { String Type = null, Name = null, HourSay, MinSay, urlNot = null; int TimeHoursStart, TimeMinsStart, TimeHoursEnd, TimeMinsEnd, LastHoursEnd = 666, LastMinEnd = 666, min = 666, hour = 666; SharedPreferences settings = context.getSharedPreferences("Settings", MODE_PRIVATE); Date date = new Date(); switch (date.toString().substring(0, 3)) { case "Mon": if (settings.getBoolean("Monday", true)) urlNot = "Monday.txt"; break; case "Tue": if (settings.getBoolean("Tuesday", true)) urlNot = "Tuesday.txt"; break; case "Wed": if (settings.getBoolean("Wednesday", true)) urlNot = "Wednesday.txt"; break; case "Thu": if (settings.getBoolean("Thursday", true)) urlNot = "Thursday.txt"; break; case "Fri": if (settings.getBoolean("Thursday", true)) urlNot = "Friday.txt"; break; case "Sat": if (settings.getBoolean("SaturdaySettings", true)) if (settings.getBoolean("Saturday", true)) urlNot = "Saturday.txt"; break; } if (urlNot != null) { ArrayList<String> stringBuilder = new ArrayList<>(); try { FileInputStream read = context.openFileInput(urlNot); InputStreamReader reader = new InputStreamReader(read); BufferedReader bufferedReader = new BufferedReader(reader); String temp_read; while ((temp_read = bufferedReader.readLine()) != null) { stringBuilder.add(temp_read); } String[] dateTimes, dateTimesLast; for (int i = 0; i < stringBuilder.size(); i++) { dateTimes = generateDate(stringBuilder.get(i)); TimeHoursStart = Integer.parseInt(dateTimes[1]); TimeMinsStart = Integer.parseInt(dateTimes[2]); TimeHoursEnd = Integer.parseInt(dateTimes[3]); TimeMinsEnd = Integer.parseInt(dateTimes[4]); if (i != 0) { dateTimesLast = generateDate(stringBuilder.get(i - 1)); LastHoursEnd = Integer.parseInt(dateTimesLast[3]); LastMinEnd = Integer.parseInt(dateTimesLast[4]); } int hourDate = Integer.parseInt(date.toString().substring(11, 13)); int minDate = Integer.parseInt(date.toString().substring(14, 16)); if (i == 0 && onOneHour(TimeHoursStart, TimeMinsStart, hourDate, minDate)) { Type = context.getString(R.string.StartYrok); hour = TimeHoursStart - hourDate; if (hour != 0) min = hour * 60 + TimeMinsStart - minDate; else min = TimeMinsStart - minDate; hour = 0; while (min >= 60) { hour = hour + 1; min = min - 60; } Name = dateTimes[0]; } else if (icEndYrok(TimeHoursStart, TimeMinsStart, hourDate * 60 + minDate, TimeHoursEnd, TimeMinsEnd)) { hour = TimeHoursEnd - hourDate; if (hour != 0) min = hour * 60 + TimeMinsEnd - minDate; else min = TimeMinsEnd - minDate; hour = 0; while (min >= 60) { hour = hour + 1; min = min - 60; } Type = context.getString(R.string.EndYrok); Name = dateTimes[0]; } else if (icPeremena(LastHoursEnd, LastMinEnd, hourDate * 60 + minDate, TimeHoursStart, TimeMinsStart)) { hour = TimeHoursStart - hourDate; if (hour != 0) min = hour * 60 + TimeMinsStart - minDate; else min = TimeMinsStart - minDate; hour = 0; while (min >= 60) { hour = hour + 1; min = min - 60; } Type = context.getString(R.string.EndPeremen); Name = dateTimes[0]; } } bufferedReader.close(); reader.close(); read.close(); } catch (IOException ignored) { } if (min != 666) { HourSay = Padej(hour, true); MinSay = Padej(min, false); Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("notification", true); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, IMPORTANCE_LOW); notificationManager.createNotificationChannel(notificationChannel); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID) .setAutoCancel(true) .setPriority(IMPORTANCE_HIGH) .setVibrate(null) .setSound(null) .setSmallIcon(R.drawable.ic_stat_name) .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setContentTitle(Name) .setContentText(Type + ":" + HourSay + MinSay); notificationManager.notify(NOTIFY_ID, notificationBuilder.build()); } else { NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_stat_name) .setAutoCancel(true) .setVibrate(null) .setSound(null) .setContentTitle(Name) .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentText(Type + ":" + HourSay + MinSay); NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, builder.build()); } } else if(intent.getBooleanExtra("notification", false)) { NotificationManager notificationManager; notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); notificationManager.cancelAll(); } } } public String[] generateDate(String readString) { try { String[] returnStrings = new String[5], help = readString.split("="), helpTimes = help[0].split("-"), helpAmPmOne = helpTimes[0].split(" "), helpAmPmTwo = helpTimes[1].split(" "), helpTimeOne = helpAmPmOne[0].split(":"), helpTimeTwo = helpAmPmTwo[0].split(":"); returnStrings[0] = help[1] + ", " + help[2]; if (helpAmPmOne.length == 2 && helpAmPmTwo.length == 2) { if (helpAmPmOne[1].equals("PM")) returnStrings[1] = String.valueOf(Integer.parseInt(helpTimeOne[0]) + 12); else returnStrings[1] = helpTimeOne[0]; if (helpAmPmTwo[1].equals("PM")) returnStrings[3] = String.valueOf(Integer.parseInt(helpTimeTwo[0]) + 12); else returnStrings[3] = helpTimeTwo[0]; } else { returnStrings[1] = helpTimeOne[0]; returnStrings[3] = helpTimeTwo[0]; } returnStrings[2] = helpTimeOne[1]; returnStrings[4] = helpTimeTwo[1]; return returnStrings; } catch (Exception error) { errorStack(error, context); return new String[]{""}; } } private boolean icPeremena(int LastHoursStart, int LastMinsStart, int date, int TimeHoursStart, int TimeMinsStart){ return LastHoursStart * 60 + LastMinsStart <= date && date <= TimeHoursStart * 60 + TimeMinsStart; } private boolean icEndYrok(int TimeHoursStart, int TimeMinsStart, int date, int TimeHoursEnd, int TimeMinsEnd){ return TimeHoursStart * 60 + TimeMinsStart <= date && date <= TimeHoursEnd * 60 + TimeMinsEnd; } private String Padej(int kool, Boolean Type) { String say = ""; try { if (kool == 0) { if (!Type) say = " 0 " + context.getString(R.string._0_Min); } else if (kool == 1) { if (Type) say = " 1 " + context.getString(R.string._1_Hour); else say = " 1 " + context.getString(R.string._1_Min); } else if (kool >= 2 && kool <= 4) { if (Type) say = " " + kool + " " + context.getString(R.string._2_4_Hour); else say = " " + kool + " " + context.getString(R.string._2_4_Min); } else if (kool >= 5 && kool <= 20) { if (Type) say = " " + kool + " " + context.getString(R.string._5_20_Hour); else say = " " + kool + " " + context.getString(R.string._5_20_Min); } else { int koolobok = Integer.parseInt(Integer.toString(kool).substring(0, 1)); int lalala = Integer.parseInt(Integer.toString(kool).substring(Integer.toString(kool).length() - 1)); if (koolobok > 1 && lalala == 1) { if (Type) say = " " + kool + " " + context.getString(R.string._end_1_Hour); else say = " " + kool + " " + context.getString(R.string._end_1_Min); } else if (koolobok > 1 && lalala >= 2 && lalala <= 4) { if (Type) say = " " + kool + " " + context.getString(R.string._end_2_4_Hour); else say = " " + kool + " " + context.getString(R.string._end_2_4_Min); } else if (koolobok > 1 && lalala >= 5 && lalala <= 9) { if (!Type) say = " " + kool + " " + context.getString(R.string._end_5_9_Min); } else if (koolobok > 1 && lalala == 0) { if (!Type) say = " " + kool + " " + context.getString(R.string._end_0_Min); } } } catch (Exception error) { errorStack(error, context); } return say; } } public void errorStack(Exception error, Context context) { try { final Writer writer = new StringWriter(); error.printStackTrace(new PrintWriter(writer)); final StringBuilder log = new StringBuilder("Android API level - " + Build.VERSION.SDK_INT + "\n" + context.getString(R.string.app_name) + " - " + BuildConfig.VERSION_NAME + Build.VERSION.SDK_INT + "\nDevice - " + Build.DEVICE + " | " + Build.MODEL + "\nCurrent window - "); log.append("\n\nError:\n").append(writer.toString()); new Thread(() -> { try { HttpURLConnection con = (HttpURLConnection) new URL("https://students-diary.herokuapp.com/write").openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8)); wr.write(log.toString().replace("'", "!")); wr.flush(); wr.close(); BufferedReader iny = new BufferedReader( new InputStreamReader(con.getInputStream())); String output; StringBuilder response = new StringBuilder(); while ((output = iny.readLine()) != null) { response.append(output); } iny.close(); if (!response.toString().equals("ok")) throw new Exception("no ok"); } catch (Exception e) { e.printStackTrace(); } }).start(); File mFolder = new File(context.getExternalFilesDir(null) + "/errors"); File file = new File(mFolder.getAbsolutePath() + "/" + new Date()); if (!mFolder.exists()) { mFolder.mkdir(); } if (!file.exists()) { file.createNewFile(); } FileOutputStream write = new FileOutputStream(file); write.write(log.toString().getBytes()); write.close(); error.printStackTrace(); MainActivity.ToastMakeText(context, context.getString(R.string.error_not)); } catch (Exception p) { p.printStackTrace(); } } }
922e845cb3bfa4d89c741855224edfc1e6247e92
1,817
java
Java
Obj2-TP_Encuestas/src/investigador/Investigador.java
EnzoGalarza/TP_Encuestas
eaa3df7a4630ad761fe0e94e50bf76aba8354205
[ "MIT" ]
null
null
null
Obj2-TP_Encuestas/src/investigador/Investigador.java
EnzoGalarza/TP_Encuestas
eaa3df7a4630ad761fe0e94e50bf76aba8354205
[ "MIT" ]
null
null
null
Obj2-TP_Encuestas/src/investigador/Investigador.java
EnzoGalarza/TP_Encuestas
eaa3df7a4630ad761fe0e94e50bf76aba8354205
[ "MIT" ]
null
null
null
23.597403
114
0.766648
994,773
package investigador; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; import encuesta.Encuesta; import observer.Observador; import pregunta.Pregunta; import pregunta.PreguntaNula; import proyecto.Proyecto; import respuesta.Respuesta; import workflow.Workflow; public class Investigador implements Observador{ private String user; private String password; private List<Proyecto> proyectos; public Investigador(String user, String password) { this.user = user; this.password = password; this.proyectos = new ArrayList<Proyecto>(); } public String getUser() { return this.user; } public String getPassword() { return this.password; } public List<Proyecto> getProyectos() { return this.proyectos; } public void agregarProyecto(Proyecto unProyecto) { this.proyectos.add(unProyecto); } public Proyecto crearProyecto(String unaDescripcion, String unProposito) { Proyecto nuevo = new Proyecto(unaDescripcion, unProposito); proyectos.add(nuevo); return nuevo; } public Boolean tieneProyectos() { return !proyectos.isEmpty(); } @Override public void update(Encuesta e, Pregunta p, Respuesta r) { //Hacer algo?? } public Encuesta crearEncuesta(Proyecto proyecto1, Integer cantRespuestasCompletasEsperadas, LocalDate unaFecha) { Workflow workflow = new Workflow(new PreguntaNula()); Encuesta unaEncuesta = new Encuesta(workflow, cantRespuestasCompletasEsperadas, unaFecha); proyecto1.agregarEncuesta(unaEncuesta); return unaEncuesta; } public Long cantidadDeEncuestasEn(Proyecto unProyecto) { return proyectos.stream().filter(proyecto -> proyecto.equals(unProyecto)).count(); } public void setearPregunta(Encuesta encuesta, Pregunta pregunta1) { encuesta.setPregunta(pregunta1); } }
922e84ac2d1e7a7c7e2fff2d8f781f8873aa3220
795
java
Java
src/main/java/tae/cosmetics/gui/util/packet/client/CPacketHeldItemChangeModule.java
ItsYoungDaddy/Templar-Cosmetics-Beta
0d68d0309e431db3c68325a09cd2ad4b4073e3f6
[ "MIT", "BSD-3-Clause" ]
32
2020-04-24T22:22:19.000Z
2022-03-30T11:43:26.000Z
src/main/java/tae/cosmetics/gui/util/packet/client/CPacketHeldItemChangeModule.java
ItsYoungDaddy/Templar-Cosmetics-Beta
0d68d0309e431db3c68325a09cd2ad4b4073e3f6
[ "MIT", "BSD-3-Clause" ]
2
2020-07-07T19:48:08.000Z
2020-09-19T16:11:19.000Z
src/main/java/tae/cosmetics/gui/util/packet/client/CPacketHeldItemChangeModule.java
ItsYoungDaddy/Templar-Cosmetics-Beta
0d68d0309e431db3c68325a09cd2ad4b4073e3f6
[ "MIT", "BSD-3-Clause" ]
10
2020-05-31T08:14:39.000Z
2021-09-14T17:18:31.000Z
24.090909
86
0.757233
994,774
package tae.cosmetics.gui.util.packet.client; import java.awt.Color; import net.minecraft.network.play.client.CPacketHeldItemChange; import tae.cosmetics.gui.util.packet.AbstractPacketModule; public class CPacketHeldItemChangeModule extends AbstractPacketModule { private CPacketHeldItemChange packet; public CPacketHeldItemChangeModule(CPacketHeldItemChange packet, long timestamp) { super("Sent when player changes hotbar slot.", timestamp, packet); this.packet = packet; } @Override public void drawText(int x, int y) { fontRenderer.drawString("CPacketHeldItemChange", x, y, Color.WHITE.getRGB()); if(!minimized) { fontRenderer.drawString("Slot: " + packet.getSlotId(), x, y, Color.WHITE.getRGB()); } } @Override public boolean type() { return true; } }
922e85b4c97e20b756ec13693ad09361b2132980
286
java
Java
st-demo/src/main/java/no/lwb/mysc/servicedemo/mybatis/domain/City.java
aspiringwei/mysc
382d08a768570605d8ad9011e7adf123848bc29e
[ "MIT" ]
null
null
null
st-demo/src/main/java/no/lwb/mysc/servicedemo/mybatis/domain/City.java
aspiringwei/mysc
382d08a768570605d8ad9011e7adf123848bc29e
[ "MIT" ]
null
null
null
st-demo/src/main/java/no/lwb/mysc/servicedemo/mybatis/domain/City.java
aspiringwei/mysc
382d08a768570605d8ad9011e7adf123848bc29e
[ "MIT" ]
null
null
null
13.619048
47
0.713287
994,775
package no.lwb.mysc.servicedemo.mybatis.domain; import lombok.Data; import java.io.Serializable; /** * @author WeiBin Lin */ @Data public class City implements Serializable { private Long id; private String name; private String state; private String country; }
922e87053700d1977ed9b32bef140952421c3d7e
13,329
java
Java
Model/src/main/java/org/eupathdb/common/errors/ErrorHandler.java
ErythronDB/EbrcWebsiteCommon
ac4435408cd87743c7a7edd27f90ffd485cac3cc
[ "Apache-2.0" ]
null
null
null
Model/src/main/java/org/eupathdb/common/errors/ErrorHandler.java
ErythronDB/EbrcWebsiteCommon
ac4435408cd87743c7a7edd27f90ffd485cac3cc
[ "Apache-2.0" ]
24
2020-05-18T16:17:03.000Z
2022-03-31T13:56:07.000Z
Model/src/main/java/org/eupathdb/common/errors/ErrorHandler.java
ErythronDB/EbrcWebsiteCommon
ac4435408cd87743c7a7edd27f90ffd485cac3cc
[ "Apache-2.0" ]
2
2020-01-10T14:20:28.000Z
2020-04-06T13:16:35.000Z
40.14759
123
0.680021
994,776
package org.eupathdb.common.errors; import static org.eupathdb.common.errors.ErrorHandlerHelpers.getAttributeMapText; import static org.eupathdb.common.errors.ErrorHandlerHelpers.valueOrDefault; import static org.gusdb.fgputil.FormatUtil.NL; import static org.gusdb.fgputil.FormatUtil.formatDateTime; import static org.gusdb.fgputil.FormatUtil.getInnerClassLog4jName; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; import org.eupathdb.common.errors.ErrorHandlerHelpers.ErrorCategory; import org.gusdb.fgputil.Timer; import org.gusdb.fgputil.db.pool.ConnectionPoolConfig; import org.gusdb.fgputil.db.pool.DatabaseInstance; import org.gusdb.fgputil.web.RequestSnapshot; import org.gusdb.wdk.errors.ClientErrorBundle; import org.gusdb.wdk.errors.ErrorBundle; import org.gusdb.wdk.errors.ErrorContext; import org.gusdb.wdk.model.WdkModel; public class ErrorHandler { private static final Logger LOG = Logger.getLogger(ErrorHandler.class); private static final String ERROR_START = "##ERROR_START##"; private static final String ERROR_END = "##ERROR_END##"; private static final String SECTION_DIV = "************************************************" + NL; private final Properties _filters; private final List<ErrorCategory> _categories; public ErrorHandler(Properties filters, List<ErrorCategory> categories) { _filters = filters; _categories = categories; } public void handleError(ErrorBundle errors, ErrorContext context) { // do nothing and return if no errors if (!errors.hasErrors()) return; String searchText = getErrorText(errors, context); // check to see if this error matches a filter String matchedFilterKey = matchFilter(searchText, context.getRequestData(), _filters); String fullErrorText = new StringBuilder(ERROR_START).append(NL) .append("Matched Filter: ").append(matchedFilterKey).append(NL).append(NL) .append(searchText).append(NL).append(ERROR_END).append(NL).toString(); // determine where to log this error based on context and filter match Logger errorLog = !(errors instanceof ClientErrorBundle) ? (matchedFilterKey != null ? IgnoredErrorLog.getLogger() : RetainedErrorLog.getLogger()) : (matchedFilterKey != null ? IgnoredClientErrorLog.getLogger() : RetainedClientErrorLog.getLogger()); errorLog.error(fullErrorText); if (matchedFilterKey == null && context.isSiteMonitored()) { // error passes through filters; email if it doesn't fall into an existing category ErrorCategory category = matchCategory(searchText, _categories); if (category == null || category.isFixed() || category.isEmailWorthy()) { // error did not match filter or category, category should have been fixed, or category should always send email sendMail(fullErrorText, context); } } } private static String getErrorText(ErrorBundle errors, ErrorContext context) { String doubleNewline = NL + NL; RequestSnapshot requestData = context.getRequestData(); WdkModel model = context.getWdkModel(); return new StringBuilder() .append(SECTION_DIV) .append("Date: ").append(formatDateTime(context.getErrorDate())).append(NL) .append("Request URI: ").append(valueOrDefault(requestData.getContextUri(), "<unable to determine>")).append(NL) .append("Remote Host: ").append(valueOrDefault(requestData.getRemoteHost(), "<not set>")).append(NL) .append("Referred from: ").append(valueOrDefault(requestData.getReferrer(), "<not set>")).append(NL) .append("User Agent: ").append(valueOrDefault(requestData.getUserAgent(), "<not set>")).append(NL) // "JkEnvVar SERVER_ADDR" is required in Apache configuration .append("Server Addr: ").append(valueOrDefault((String)context.getRequestAttributeMap().get("SERVER_ADDR"), "<not set> Is 'JkEnvVar SERVER_ADDR' set in the Apache configuration?")).append(NL) .append("Server Name: " ).append(valueOrDefault(requestData.getServerName(), "<unknown>")).append(NL) .append("Session ID: ").append(context.getThreadContextBundle().getShortSessionId()).append(NL) .append("Request ID: ").append(context.getThreadContextBundle().getRequestId()).append(NL) .append("Request duration at error: ").append(context.getThreadContextBundle().getRequestDuration()).append(NL) .append("Date of last webapp reload: ").append(formatDateTime(new Date(model.getStartupTime()))).append(NL) .append("Time since last webapp reload: ").append( Timer.getDurationString(context.getErrorDate().getTime() - model.getStartupTime())).append(NL) .append("Log4j Marker: ").append(context.getLogMarker()).append(doubleNewline) .append(SECTION_DIV) .append("Project ID: ").append(model.getProjectId()).append(NL) .append("User DB: ").append(getDbInfo(model.getUserDb())).append(NL) .append("App DB: ").append(getDbInfo(model.getAppDb())).append(doubleNewline) .append(SECTION_DIV) .append("Request Parameters (query string or posted form data)").append(doubleNewline) .append(getAttributeMapText(requestData.getRequestParamMap(), (list,q) -> String.join(", ", list))) .append(NL) .append(SECTION_DIV) .append("Associated Request-Scope Attributes").append(doubleNewline) .append(getAttributeMapText(context.getRequestAttributeMap(), (value, key) -> (key.toLowerCase().startsWith("email") || key.toLowerCase().startsWith("passw")) ? "*****" : value.toString())) .append(NL) .append(SECTION_DIV) .append("Session Attributes").append(doubleNewline) .append(getAttributeMapText(context.getSessionAttributeMap())).append(NL) //.append(SECTION_DIV) //.append("ServletContext Attributes").append(doubleNewline) //.append(getAttributeMapText(context.getServletContextAttributes())).append(NL) .append(SECTION_DIV) .append("Detailed Description").append(doubleNewline) .append(valueOrDefault(errors.getDetailedDescription(), "")).append(NL) .toString(); } private static String getDbInfo(DatabaseInstance db) { ConnectionPoolConfig config = db.getConfig(); return new StringBuilder() .append(config.getLogin()).append("@").append(config.getConnectionUrl()) .append(" | Connections: Active { max=").append(config.getMaxActive()) .append(", current=").append(db.getActiveCount()) .append(" }, Idle { range=[").append(config.getMinIdle()) .append("..").append(config.getMaxIdle()) .append("], current=").append(db.getIdleCount()) .append(" }").toString(); } /** * Check for matches to filters. Filters are regular expressions in a property file. The file is optional. * In which case, no filtering is performed. * * Matches are checked against the text of errors and stacktraces. * * Property file example 1. A simple check for missing step ids. * * noStepForUser = The Step #\\d+ of user .+ doesn't exist * * Compound filtering can be configured with specific subkeys in the property file (the primary key is * always required). * * Property file example 2. Filter when exceptions contain the words "twoPartName is null" and also the * referer is empty. * * twoPartNameIsNull = twoPartName is null twoPartNameIsNull.referer = * * Allowed subkeys are referer ip **/ private static String matchFilter(String searchText, RequestSnapshot requestData, Properties filters) { LOG.debug("Will use the following text as filter input:\n" + searchText); Set<String> propertyNames = filters.stringPropertyNames(); for (String key : propertyNames) { // don't check subkeys yet if (key.contains(".")) continue; String regex = filters.getProperty(key); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(searchText); LOG.debug("Checking against filter: " + regex); if (m.find()) { LOG.debug("Match!"); /** * Found match for primary filter. Now check for additional matches from any subkey filters. Return on * first match. **/ boolean checkedSubkeys = false; String refererFilter = filters.getProperty(key + ".referer"); String ipFilter = filters.getProperty(key + ".ip"); if (refererFilter != null) { checkedSubkeys = true; String referer = valueOrDefault(requestData.getReferrer(), ""); if (refererFilter.equals(referer)) return key + " = " + regex + " AND " + key + ".referer = " + refererFilter; } if (ipFilter != null) { checkedSubkeys = true; String remoteHost = valueOrDefault(requestData.getRemoteHost(), ""); if (ipFilter.equals(remoteHost)) return key + " = " + regex + " AND " + key + ".ip = " + ipFilter; } // subkeys were checked and no matches in subkeys, // so match is not sufficient to filter if (checkedSubkeys) { LOG.debug("Matched primary filter but not any subkeys; moving to next filter."); continue; } // Otherwise no subkeys were checked (so primary filter match is sufficient) return key + " = " + regex; } } // did not match any filter return null; } private static ErrorCategory matchCategory(String searchText, List<ErrorCategory> categories) { for (ErrorCategory category : categories) { boolean matches = true; for (String matchString : category.getMatchStrings()) { // searchText must match each regex in category to be "found" if (searchText.indexOf(matchString) == -1) { matches = false; break; } } if (matches) { return category; } } return null; } private static void sendMail(String body, ErrorContext context) { String from = "tomcat@" + context.getRequestData().getServerName(); List<String> recipients = context.getAdminEmails(); String subject = context.getWdkModel().getProjectId() + " " + context.getErrorLocation().getLabel() + " Error - " + context.getRequestData().getRemoteHost(); if (recipients.isEmpty()) { // Replaced SITE_ADMIN_EMAIL in model.prop with adminEmail attribute in model-config.xml LOG.error("adminEmail is not configured in model-config.xml; cannot send exception report."); return; } try { Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); Session session = Session.getDefaultInstance(props, null); session.setDebug(false); Message msg = new MimeMessage(session); InternetAddress addressFrom = new InternetAddress(from); List<InternetAddress> addressList = new ArrayList<InternetAddress>(); for (String address : recipients) { try { addressList.add(new InternetAddress(address)); } catch (AddressException ae) { // ignore bad address } } InternetAddress[] addressTo = addressList.toArray(new InternetAddress[0]); msg.setRecipients(Message.RecipientType.TO, addressTo); msg.setFrom(addressFrom); msg.setSubject(subject); msg.setContent(body, "text/plain"); Transport.send(msg); } catch (MessagingException me) { LOG.error(me); } } /** * Contains server errors that matched filters */ private static final class IgnoredErrorLog { private static final Logger _logger = Logger.getLogger(getInnerClassLog4jName(IgnoredErrorLog.class)); private IgnoredErrorLog() {} public static Logger getLogger() { return _logger; } } /** * Contains server errors that didn't match filters */ private static final class RetainedErrorLog { private static final Logger _logger = Logger.getLogger(getInnerClassLog4jName(RetainedErrorLog.class)); private RetainedErrorLog() {} public static Logger getLogger() { return _logger; } } /** * Contains client errors that matched filters */ private static final class IgnoredClientErrorLog { private static final Logger _logger = Logger.getLogger(getInnerClassLog4jName(IgnoredClientErrorLog.class)); private IgnoredClientErrorLog() {} public static Logger getLogger() { return _logger; } } /** * Contains client errors that didn't match filters */ private static final class RetainedClientErrorLog { private static final Logger _logger = Logger.getLogger(getInnerClassLog4jName(RetainedClientErrorLog.class)); private RetainedClientErrorLog() {} public static Logger getLogger() { return _logger; } } }
922e87165d547768252926bfd6da2058372156c9
1,760
java
Java
log-agent/log-agent-common/src/main/java/com/didichuxing/datachannel/agent/common/metrics/lib/MetricMutablePeriodGaugeLong.java
fengzhongye/LogiAM
98c15e0237a38ec436632bb096d886c51b303edc
[ "Apache-2.0" ]
105
2021-07-09T02:05:10.000Z
2022-03-31T08:20:40.000Z
log-agent/log-agent-common/src/main/java/com/didichuxing/datachannel/agent/common/metrics/lib/MetricMutablePeriodGaugeLong.java
fengzhongye/LogiAM
98c15e0237a38ec436632bb096d886c51b303edc
[ "Apache-2.0" ]
12
2021-07-13T00:56:55.000Z
2022-02-25T04:10:11.000Z
log-agent/log-agent-common/src/main/java/com/didichuxing/datachannel/agent/common/metrics/lib/MetricMutablePeriodGaugeLong.java
fengzhongye/LogiAM
98c15e0237a38ec436632bb096d886c51b303edc
[ "Apache-2.0" ]
32
2021-07-19T06:39:15.000Z
2022-02-25T13:43:52.000Z
22.564103
90
0.614773
994,777
/** * Kuaidadi.com Inc. * Copyright (c) 2012-2015 All Rights Reserved. */ package com.didichuxing.datachannel.agent.common.metrics.lib; import com.didichuxing.datachannel.agent.common.metrics.MetricsRecordBuilder; /** * * @author liujianhui * @version:2015年11月11日 上午11:04:06 */ public class MetricMutablePeriodGaugeLong extends MetricMutablePeriodGauge<Long> { private volatile long value; /** * Construct a mutable long gauge metric * @param name of the gauge * @param description of the gauge * @param initValue the initial value of the gauge */ public MetricMutablePeriodGaugeLong(String name, String description, long initValue) { super(name, description); this.value = initValue; } public synchronized void incr() { ++value; setChanged(); } /** * Increment by delta * @param delta of the increment */ public synchronized void incr(long delta) { value += delta; setChanged(); } public synchronized void decr() { --value; setChanged(); } /** * decrement by delta * @param delta of the decrement */ public synchronized void decr(long delta) { value -= delta; setChanged(); } /** * Set the value of the metric * @param value to set */ public void set(long value) { this.value = value; setChanged(); } public void doSnapshot(MetricsRecordBuilder builder, boolean all) { builder.addGauge(name, description, value); } /** * set the value of the metric with 0 * @see MetricMutablePeriodGauge#reset() */ public synchronized void reset() { this.value = 0; } }
922e87230d9011717a53770c8ca24afee5b3e8bd
3,348
java
Java
pengsoft-security/src/main/java/com/pengsoft/security/service/UserService.java
pengsoftdotcom/pengsoft-java
2916f772bbad0dccf24d6687209db1508dc98398
[ "Apache-2.0" ]
null
null
null
pengsoft-security/src/main/java/com/pengsoft/security/service/UserService.java
pengsoftdotcom/pengsoft-java
2916f772bbad0dccf24d6687209db1508dc98398
[ "Apache-2.0" ]
null
null
null
pengsoft-security/src/main/java/com/pengsoft/security/service/UserService.java
pengsoftdotcom/pengsoft-java
2916f772bbad0dccf24d6687209db1508dc98398
[ "Apache-2.0" ]
null
null
null
26.824
105
0.626305
994,778
package com.pengsoft.security.service; import java.util.List; import java.util.Optional; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import com.pengsoft.security.domain.Role; import com.pengsoft.security.domain.User; import com.pengsoft.security.validation.Password; import com.pengsoft.support.service.EntityService; /** * The service interface of {@link User}. * * @author kenaa@example.com * @since 1.0.0 */ public interface UserService extends EntityService<User, String> { /** * Create user from weixin. * * @param mpOpenid The weixin mp open id. * @return the created user */ User createFromWeixin(String mpOpenid); /** * Save one user without validation. * * @param user {@link User} * @return the saved user */ User saveWithoutValidation(User user); /** * Change password. * * @param id The user id. * @param oldPassword The old password. * @param newPassword The new password. */ void changePassword(@NotBlank String id, @NotBlank String oldPassword, @Password String newPassword); /** * Reset password. * * @param id The user id. * @param password The password to be reset. */ void resetPassword(@NotBlank String id, @NotBlank String password); /** * Grant roles. * * @param user The {@link User}. * @param roles The {@link Role}s to be granted. */ void grantRoles(@NotNull User user, List<Role> roles); /** * Set the primary role. * * @param user The {@link User}. * @param role The primary {@link Role}. */ void setPrimaryRole(@NotNull User user, @NotNull Role role); /** * Save the sign in date and clear the sign in failure count. * * @param username The username. */ void signInSuccess(@NotBlank String username); /** * Save the sign in failure count. * * @param username The username. * @param allowSignInFailure The maximum count of sign in failure. */ void signInFailure(@NotBlank String username, int allowSignInFailure); /** * Bind user's email, mp_openid, mobile. * * @param username The user's username. * @param value The bind value * @param type The bind type in user, email, mp_openid, mobile */ void bind(@NotBlank String username, String value, @NotBlank String type); /** * Returns an {@link Optional} of a {@link User} with the given username. * * @param username {@link User}' username. */ Optional<User> findOneByUsername(@NotBlank String username); /** * Returns an {@link Optional} of a {@link User} with the given mobile. * * @param mobile {@link User}' mobile. */ Optional<User> findOneByMobile(@NotBlank String mobile); /** * Returns an {@link Optional} of a {@link User} with the given email. * * @param email {@link User}' email. */ Optional<User> findOneByEmail(@NotBlank String email); /** * Returns an {@link Optional} of a {@link User} with the given weixin mp open * id. * * @param mpOpenid {@link User}' mpOpenid. */ Optional<User> findOneByMpOpenid(@NotBlank String mpOpenid); }
922e883083c7e7cfe6a2bdc1599b625b8cc8fcfa
3,202
java
Java
Smile/test/smile/neighbor/CoverTreeSpeedTest.java
BookmanHan/smile
7055068d64117eac65f2a3227c47a235553058f8
[ "Apache-2.0" ]
1
2016-10-12T18:02:52.000Z
2016-10-12T18:02:52.000Z
Smile/test/smile/neighbor/CoverTreeSpeedTest.java
50573750/smile
7055068d64117eac65f2a3227c47a235553058f8
[ "Apache-2.0" ]
null
null
null
Smile/test/smile/neighbor/CoverTreeSpeedTest.java
50573750/smile
7055068d64117eac65f2a3227c47a235553058f8
[ "Apache-2.0" ]
1
2017-04-07T18:32:04.000Z
2017-04-07T18:32:04.000Z
33.354167
131
0.569019
994,779
/****************************************************************************** * Confidential Proprietary * * (c) Copyright Haifeng Li 2011, All Rights Reserved * ******************************************************************************/ package smile.neighbor; import smile.data.AttributeDataset; import smile.data.NominalAttribute; import smile.data.parser.DelimitedTextParser; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import smile.math.distance.EuclideanDistance; /** * * @author Haifeng Li */ public class CoverTreeSpeedTest { double[][] x = null; double[][] testx = null; CoverTree<double[]> coverTree = null; public CoverTreeSpeedTest() { long start = System.currentTimeMillis(); DelimitedTextParser parser = new DelimitedTextParser(); parser.setResponseIndex(new NominalAttribute("class"), 0); try { AttributeDataset train = parser.parse("USPS Train", this.getClass().getResourceAsStream("/smile/data/usps/zip.train")); AttributeDataset test = parser.parse("USPS Test", this.getClass().getResourceAsStream("/smile/data/usps/zip.test")); x = train.toArray(new double[train.size()][]); testx = test.toArray(new double[test.size()][]); } catch (Exception ex) { System.err.println(ex); } double time = (System.currentTimeMillis() - start) / 1000.0; System.out.format("Loading data: %.2fs\n", time); start = System.currentTimeMillis(); coverTree = new CoverTree<double[]>(x, new EuclideanDistance()); time = (System.currentTimeMillis() - start) / 1000.0; System.out.format("Building cover tree: %.2fs\n", time); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of nearest method, of class CoverTree. */ @Test public void testCoverTree() { long start = System.currentTimeMillis(); for (int i = 0; i < testx.length; i++) { coverTree.nearest(testx[i]); } double time = (System.currentTimeMillis() - start) / 1000.0; System.out.format("NN: %.2fs\n", time); start = System.currentTimeMillis(); for (int i = 0; i < testx.length; i++) { coverTree.knn(testx[i], 10); } time = (System.currentTimeMillis() - start) / 1000.0; System.out.format("10-NN: %.2fs\n", time); start = System.currentTimeMillis(); List<Neighbor<double[], double[]>> n = new ArrayList<Neighbor<double[], double[]>>(); for (int i = 0; i < testx.length; i++) { coverTree.range(testx[i], 8.0, n); n.clear(); } time = (System.currentTimeMillis() - start) / 1000.0; System.out.format("Range: %.2fs\n", time); } }
922e88dd545f0da0c4ec89b7581dde8b24b6ded0
3,202
java
Java
app/src/main/java/com/chame/simplesmsforwarder/MainActivity.java
ChameleonIVCR/SimpleSMSForwarder
0854232b1e65f4b4ae6dc6258752621e6884177b
[ "MIT" ]
null
null
null
app/src/main/java/com/chame/simplesmsforwarder/MainActivity.java
ChameleonIVCR/SimpleSMSForwarder
0854232b1e65f4b4ae6dc6258752621e6884177b
[ "MIT" ]
null
null
null
app/src/main/java/com/chame/simplesmsforwarder/MainActivity.java
ChameleonIVCR/SimpleSMSForwarder
0854232b1e65f4b4ae6dc6258752621e6884177b
[ "MIT" ]
null
null
null
38.578313
111
0.739538
994,780
package com.chame.simplesmsforwarder; import android.content.Intent; import android.os.Bundle; import androidx.lifecycle.ViewModelProvider; import com.chame.simplesmsforwarder.models.EventViewModel; import com.chame.simplesmsforwarder.ui.login.LoginActivity; import com.chame.simplesmsforwarder.utils.DataAssistant; import com.chame.simplesmsforwarder.models.AppViewModel; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.chame.simplesmsforwarder.databinding.ActivityMainBinding; import com.google.android.material.snackbar.Snackbar; import java.lang.ref.WeakReference; public class MainActivity extends AppCompatActivity { public static WeakReference<MainActivity> weakActivity; private DataAssistant dataAssistant; private AppViewModel appViewModel; private EventViewModel eventViewModel; private ActivityMainBinding binding; public static MainActivity getInstance() { return weakActivity.get(); } public DataAssistant getDataAssistant() { return dataAssistant; } public AppViewModel getAppViewModel() { return appViewModel; } public EventViewModel getEventViewModel() { return eventViewModel; } public void setSnackbar(String msg) { Snackbar.make( findViewById(R.id.nav_host_fragment_activity_main), msg, Snackbar.LENGTH_LONG ).show( ); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); weakActivity = new WeakReference<>(MainActivity.this); dataAssistant = new DataAssistant(this); appViewModel = new ViewModelProvider .AndroidViewModelFactory(this.getApplication()) .create(AppViewModel.class); eventViewModel = new ViewModelProvider(this).get(EventViewModel.class); appViewModel.setEventPropagator(eventViewModel); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(findViewById(R.id.mainToolbar)); BottomNavigationView navView = findViewById(R.id.nav_view); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(binding.navView, navController); // Login Intent intent = new Intent(MainActivity.this, LoginActivity.class); MainActivity.this.startActivity(intent); } }
922e8a8362efb5b4d7c86450f96e97e706391f2e
9,984
java
Java
kie-wb-common-forms/kie-wb-common-forms-editor/kie-wb-common-forms-editor-client/src/main/java/org/kie/workbench/common/forms/editor/client/editor/rendering/EditorFieldLayoutComponent.java
tkobayas/kie-wb-common
2c69347f0f634268fb7cca77ccf9e1311f1486e9
[ "Apache-2.0" ]
34
2017-05-21T11:28:40.000Z
2021-07-03T13:15:03.000Z
kie-wb-common-forms/kie-wb-common-forms-editor/kie-wb-common-forms-editor-client/src/main/java/org/kie/workbench/common/forms/editor/client/editor/rendering/EditorFieldLayoutComponent.java
tkobayas/kie-wb-common
2c69347f0f634268fb7cca77ccf9e1311f1486e9
[ "Apache-2.0" ]
2,576
2017-03-14T00:57:07.000Z
2022-03-29T07:52:38.000Z
kie-wb-common-forms/kie-wb-common-forms-editor/kie-wb-common-forms-editor-client/src/main/java/org/kie/workbench/common/forms/editor/client/editor/rendering/EditorFieldLayoutComponent.java
tkobayas/kie-wb-common
2c69347f0f634268fb7cca77ccf9e1311f1486e9
[ "Apache-2.0" ]
158
2017-03-15T08:55:40.000Z
2021-11-19T14:07:17.000Z
35.404255
113
0.633914
994,781
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.forms.editor.client.editor.rendering; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.enterprise.inject.Specializes; import javax.inject.Inject; import com.google.gwt.user.client.ui.IsWidget; import org.gwtbootstrap3.client.ui.Modal; import org.jboss.errai.ui.client.local.spi.TranslationService; import org.kie.workbench.common.forms.dynamic.client.rendering.FieldLayoutComponent; import org.kie.workbench.common.forms.dynamic.client.rendering.FieldRendererManager; import org.kie.workbench.common.forms.dynamic.service.shared.FormRenderingContext; import org.kie.workbench.common.forms.editor.client.editor.FormEditorContext; import org.kie.workbench.common.forms.editor.client.editor.FormEditorHelper; import org.kie.workbench.common.forms.editor.client.editor.events.FormEditorSyncPaletteEvent; import org.kie.workbench.common.forms.editor.client.editor.properties.FieldPropertiesRenderer; import org.kie.workbench.common.forms.editor.client.editor.properties.FieldPropertiesRendererHelper; import org.kie.workbench.common.forms.editor.service.shared.FormEditorRenderingContext; import org.kie.workbench.common.forms.model.FieldDefinition; import org.kie.workbench.common.forms.service.shared.FieldManager; import org.uberfire.backend.vfs.Path; import org.uberfire.ext.layout.editor.api.editor.LayoutComponent; import org.uberfire.ext.layout.editor.client.api.HasDragAndDropSettings; import org.uberfire.ext.layout.editor.client.api.HasModalConfiguration; import org.uberfire.ext.layout.editor.client.api.ModalConfigurationContext; import org.uberfire.ext.layout.editor.client.api.RenderingContext; @Specializes @Dependent public class EditorFieldLayoutComponent extends FieldLayoutComponent implements HasDragAndDropSettings, HasModalConfiguration { public final String[] SETTINGS_KEYS = new String[]{FORM_ID, FIELD_ID}; protected FieldPropertiesRenderer propertiesRenderer; protected Event<FormEditorSyncPaletteEvent> syncPaletteEvent; protected FieldManager fieldManager; protected FormEditorHelper editorHelper; boolean showProperties = false; private FieldPropertiesRendererHelper propertiesRendererHelper; private ModalConfigurationContext configContext; private Optional<String> fieldId = Optional.empty(); private Optional<String> formId = Optional.empty(); @Inject public EditorFieldLayoutComponent(FieldRendererManager fieldRendererManager, TranslationService translationService, FieldPropertiesRenderer propertiesRenderer, FieldManager fieldManager, Event<FormEditorSyncPaletteEvent> syncPaletteEvent) { super(fieldRendererManager, translationService); this.propertiesRenderer = propertiesRenderer; this.fieldManager = fieldManager; this.syncPaletteEvent = syncPaletteEvent; } @Override public void init(FormRenderingContext renderingContext, FieldDefinition field) { super.init(renderingContext, field); initPropertiesConfig(); } protected void initPropertiesConfig() { propertiesRendererHelper = new FieldPropertiesRendererHelper() { @Override public FormRenderingContext getCurrentRenderingContext() { return renderingContext; } @Override public FieldDefinition getCurrentField() { return field; } @Override public Set<String> getAvailableModelFields(final FieldDefinition fieldDefinition) { return new TreeSet<>(editorHelper.getCompatibleModelFields(fieldDefinition)); } @Override public List<String> getCompatibleFieldTypes(FieldDefinition fieldDefinition) { return editorHelper.getCompatibleFieldTypes(fieldDefinition); } @Override public void onClose() { showProperties = false; if (configContext != null) { configContext.configurationCancelled(); } } @Override public void onPressOk(FieldDefinition fieldCopy) { EditorFieldLayoutComponent.this.onPressOk(fieldCopy); } @Override public FieldDefinition onFieldTypeChange(FieldDefinition field, String newType) { FieldDefinition fieldCopy = fieldManager.getFieldFromProvider(newType, field.getFieldTypeInfo()); fieldCopy.copyFrom(field); fieldCopy.setId(field.getId()); fieldCopy.setName(field.getName()); return fieldCopy; } @Override public FieldDefinition onFieldBindingChange(FieldDefinition field, String newBinding) { return editorHelper.switchToField(field, newBinding); } @Override public Path getPath() { return ((FormEditorRenderingContext) renderingContext).getFormPath(); } }; } protected void onPressOk(FieldDefinition fieldCopy) { editorHelper.saveFormField(field, fieldCopy); this.field = fieldCopy; this.fieldId = Optional.of(fieldCopy.getId()); initComponent(); renderContent(); showProperties = false; if (configContext != null) { LayoutComponent layoutComponent = configContext.getLayoutComponent(); addComponentParts(layoutComponent); configContext.getComponentProperties().put(FORM_ID, getFormId()); configContext.getComponentProperties().put(FIELD_ID, field.getId()); configContext.configurationFinished(); configContext = null; } syncPaletteEvent.fire(new FormEditorSyncPaletteEvent(getFormId())); } @Override public String[] getSettingsKeys() { return SETTINGS_KEYS; } @Override public void setSettingValue(String key, String value) { if (FORM_ID.equals(key)) { formId = Optional.of(value); } else if (FIELD_ID.equals(key)) { fieldId = Optional.of(value); } } @Override public String getSettingValue(String key) { if (FORM_ID.equals(key)) { if (renderingContext != null) { return renderingContext.getRootForm().getId(); } if (formId.isPresent()) { return formId.get(); } return formId.isPresent() ? formId.get() : ""; } else if (FIELD_ID.equals(key)) { if (field != null) { return field.getId(); } if (fieldId.isPresent()) { return fieldId.get(); } } return null; } @Override public Map<String, String> getMapSettings() { Map<String, String> settings = new HashMap<>(); settings.put(FORM_ID, getSettingValue(FORM_ID)); settings.put(FIELD_ID, getSettingValue(FIELD_ID)); return settings; } @Override public Modal getConfigurationModal(final ModalConfigurationContext ctx) { showProperties = true; configContext = ctx; if (field == null) { initContent(ctx.getComponentProperties()); } else { propertiesRenderer.render(propertiesRendererHelper); } return propertiesRenderer.getView().getPropertiesModal(); } @Override protected IsWidget generateContent(RenderingContext ctx) { LayoutComponent component = ctx.getComponent(); if (fieldRenderer == null) { initContent(component.getProperties()); } else { renderContent(); } return content; } protected void initContent(Map<String, String> properties) { if (field != null) { return; } if (!fieldId.isPresent()) { fieldId = Optional.ofNullable(properties.get(FIELD_ID)); } if (!formId.isPresent()) { formId = Optional.ofNullable(properties.get(FORM_ID)); } editorHelper = FormEditorContext.getActiveEditorHelper(); init(editorHelper.getRenderingContext(), editorHelper.getFormField(fieldId.get())); renderContent(); if (showProperties) { propertiesRenderer.render(propertiesRendererHelper); } } FieldPropertiesRendererHelper getPropertiesRendererHelper() { return propertiesRendererHelper; } }
922e8b496cf2eb33ba153e8b596a272ed1f68fb6
5,257
java
Java
kstream/src/main/java/com/ks/process/operation/Operation.java
Z88897050/kska
26307f5c721bf39d0846792ac366e51bc5669f3a
[ "Apache-2.0" ]
null
null
null
kstream/src/main/java/com/ks/process/operation/Operation.java
Z88897050/kska
26307f5c721bf39d0846792ac366e51bc5669f3a
[ "Apache-2.0" ]
4
2021-03-02T00:17:35.000Z
2022-03-08T22:51:38.000Z
kstream/src/main/java/com/ks/process/operation/Operation.java
yoloz/kstreamSample
26307f5c721bf39d0846792ac366e51bc5669f3a
[ "Apache-2.0" ]
1
2018-11-16T01:43:56.000Z
2018-11-16T01:43:56.000Z
34.585526
118
0.644284
994,782
package com.ks.process.operation; import com.ks.error.KConfigException; import static com.ks.process.KUtils.*; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KTable; import org.apache.kafka.streams.kstream.KeyValueMapper; import org.apache.kafka.streams.kstream.Predicate; import org.apache.kafka.streams.kstream.ValueMapper; import java.util.Map; import java.util.Properties; /** * operation.operator * <p> * operation.com.ks.name 执行操作的kSource名称 * <p> * operation.table.store 如果操作的kSource是table,提供自定义的storeName,会生成topic. * table-table建议配置 * stream-stream,stream-table不需要这个配置 */ public abstract class Operation { public final static String operator = "operation.operator"; public final static String operatorKS = "operation.ks.name"; final String kSourceName; final String _operator; final String tableStoreName; Operation(Properties properties) { this._operator = nonNullEmpty(properties, operator); this.kSourceName = nonNullEmpty(properties, operatorKS); this.tableStoreName = properties.getProperty("operation.table.store", ""); } /** * 获取输出实现 * * @param target operator * @param conf operation configuration * @return operation {@link Operation} */ public static Operation getImpl(String target, Properties conf) { switch (target) { case "filter": return new FilterImpl(conf); case "mapper": return new MapperImpl(conf); case "window": return new WinAggImpl(conf); case "join": case "leftJoin": case "outerJoin": return new JoinImpl(conf); case "convertTime": return new ConvertTimeImpl(conf); case "convertKV": return new ConvertKVImpl(conf); default: throw new KConfigException("operation operator '" + target + "' not support..."); } } /** * mapper value * * @param object kStream,kTable * @param valueMapper valueMapper {@link ValueMapper} * @return kStream or kTable */ @SuppressWarnings("unchecked") Object mapValues(Object object, ValueMapper<String, String> valueMapper) { if (object instanceof KTable) { if (!tableStoreName.isEmpty()) { return ((KTable<String, String>) object).mapValues(valueMapper, Serdes.String(), tableStoreName); } else return ((KTable<String, String>) object).mapValues(valueMapper); } else return ((KStream<String, String>) object).mapValues(valueMapper); } /** * mapper key or mapper K-V * * @param object kStream or kTable * @param keyValueMapper keyValueMapper {@link KeyValueMapper} * @return kStream or kTable */ @SuppressWarnings("unchecked") Object mapKeyValue(Object object, KeyValueMapper<String, String, KeyValue<String, String>> keyValueMapper) { if (object instanceof KTable) object = ((KTable<String, String>) object).toStream(); return ((KStream<String, String>) object).map(keyValueMapper); } /** * Materialize this changelog stream to a topic and creates a new {@code KTable} from the topic. * The specified topic should be manually created before it is used (i.e., before the Kafka Streams application is * started). * * @param object kStream or kTable * @param throughTopic through topic name * @return kStream or kTable */ @SuppressWarnings("unchecked") Object through(Object object, String throughTopic) { if (object instanceof KTable) object = ((KTable<String, String>) object).through(Serdes.String(), Serdes.String(), throughTopic); return ((KStream<String, String>) object).through(Serdes.String(), Serdes.String(), throughTopic); } /** * filter value * * @param object kStream or kTable * @param predicate predicate {@link Predicate} * @return kStream or kTable */ @SuppressWarnings("unchecked") Object filter(Object object, Predicate<String, String> predicate) { if (object instanceof KTable) { if (!tableStoreName.isEmpty()) { return ((KTable<String, String>) object).filter(predicate, tableStoreName); } else return ((KTable<String, String>) object).filter(predicate); } else return ((KStream<String, String>) object).filter(predicate); } /** * default process for one kSource * <p> * otherwise,multi kSource you need to realize it.like join operation... */ public void process(Map<String, Object> kSources) { if (!kSources.containsKey(kSourceName)) throw new KConfigException(concat(" ", kSourceName, "does not exit...")); kSources.put(kSourceName, processImpl(kSources.get(kSourceName))); } /** * process impl * * @param kSources kStream or kTable * @return kStream or kTable */ abstract Object processImpl(Object... kSources); }
922e8c78c895a9bcc300c662594406de396dfbc8
1,497
java
Java
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/monitor/AbstractInstantaneousMetric.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
1,652
2016-04-18T10:34:30.000Z
2022-03-30T06:15:35.000Z
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/monitor/AbstractInstantaneousMetric.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
342
2016-07-27T10:38:01.000Z
2022-03-31T11:11:46.000Z
redis/redis-core/src/main/java/com/ctrip/xpipe/redis/core/monitor/AbstractInstantaneousMetric.java
coral-cloud/x-pipe
d4ad1d9039a83f55439b69ae7d6954171002fa39
[ "Apache-2.0" ]
492
2016-04-25T05:14:10.000Z
2022-03-16T01:40:38.000Z
27.722222
86
0.657983
994,783
package com.ctrip.xpipe.redis.core.monitor; import java.util.concurrent.atomic.AtomicInteger; public abstract class AbstractInstantaneousMetric implements InstantaneousMetric { private static final int STATS_METRIC_SAMPLES = 16; private final int statsMetricSamples; private final static long INIT_STATE = -1L; private long statsCount = INIT_STATE; private final long[] samples; private AtomicInteger index = new AtomicInteger(0); public AbstractInstantaneousMetric() { this(STATS_METRIC_SAMPLES); } public AbstractInstantaneousMetric(int statsMetricSamples) { this.statsMetricSamples = statsMetricSamples; samples = new long[statsMetricSamples]; } @Override public long getInstantaneousMetric() { if (statsCount < 1) { return 0; } long result = 0L; for(long sample : samples) { result += sample; } long base = statsCount > statsMetricSamples ? statsMetricSamples : statsCount; return result / base; } @Override public void trackInstantaneousMetric(long currentStats) { int idx = index.getAndIncrement() % statsMetricSamples; samples[idx] = getSample(currentStats); if (statsCount == INIT_STATE) { index.set(0); } else { index.set(index.get() % statsMetricSamples); } statsCount ++; } protected abstract long getSample(long currentStats); }
922e8cb3b1082cd6108b8e9874a65996e4f5247f
800
java
Java
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetVmDataByPoolIdQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
1
2019-01-12T06:46:55.000Z
2019-01-12T06:46:55.000Z
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetVmDataByPoolIdQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
null
null
null
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetVmDataByPoolIdQuery.java
UranusBlockStack/ovirt-engine
fe3c90ed3e74e6af9497c826c82e653382946ae1
[ "Apache-2.0" ]
2
2016-03-09T16:37:23.000Z
2022-01-19T13:12:27.000Z
27.586207
113
0.69
994,784
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public class GetVmDataByPoolIdQuery<P extends IdQueryParameters> extends QueriesCommandBase<P> { public GetVmDataByPoolIdQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { VM vm = DbFacade.getInstance() .getVmPoolDao() .getVmDataFromPoolByPoolGuid(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (vm != null) { VmHandler.updateVmInitFromDB(vm.getStaticData(), true); } getQueryReturnValue().setReturnValue(vm); } }
922e8e004d4850c14714fbf9a5998227b9c08843
2,470
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/TweetsAdapter.java
btanishq/SimpleTweet
c2c145f7ae1382ddacc467be7057ac07cdf1a35b
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/TweetsAdapter.java
btanishq/SimpleTweet
c2c145f7ae1382ddacc467be7057ac07cdf1a35b
[ "MIT" ]
3
2021-03-06T10:59:34.000Z
2021-03-15T08:07:12.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/TweetsAdapter.java
btanishq/SimpleTweet
c2c145f7ae1382ddacc467be7057ac07cdf1a35b
[ "MIT" ]
null
null
null
27.444444
93
0.682996
994,785
package com.codepath.apps.restclienttemplate; import android.content.Context; import android.media.Image; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.codepath.apps.restclienttemplate.models.Tweet; import org.w3c.dom.Text; import java.util.List; public class TweetsAdapter extends RecyclerView.Adapter<TweetsAdapter.ViewHolder>{ Context context; List<Tweet> tweets; public TweetsAdapter(Context context, List<Tweet> tweets) { this.context = context; this.tweets = tweets; } //For each row, inflate layout @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_tweet, parent, false); return new ViewHolder(view); } // Bind values based on the position of the element @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Tweet tweet = tweets.get(position); holder.bind(tweet); } @Override public int getItemCount() { return tweets.size(); } public void clear() { tweets.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Tweet> tweetList) { tweets.addAll(tweetList); notifyDataSetChanged(); } // Define a viewholder public class ViewHolder extends RecyclerView.ViewHolder { ImageView ivProfileImage; TextView tvBody; TextView tvScreenName; TextView tvTimestamp; public ViewHolder(@NonNull View itemView) { super(itemView); ivProfileImage = itemView.findViewById(R.id.ivProfileImage); tvBody = itemView.findViewById(R.id.tvBody); tvScreenName = itemView.findViewById(R.id.tvScreenName); tvTimestamp = itemView.findViewById(R.id.tvtTimestamp); } public void bind(Tweet tweet) { tvBody.setText (tweet.body); tvScreenName.setText(tweet.user.screenName); tvTimestamp.setText(tweet.timestamp); Glide.with(context).load(tweet.user.profileImageUrl).into(ivProfileImage); } } }
922e8e2eeec29d6cb5d8f647515c4cd537237a94
357
java
Java
src/main/java/com/ul/ims/apdu/encoding/exceptions/ValueNotSetException.java
mDL-ILP/apdukit-java
86644fb830a8cb6e0258ab969ad75d0145e96e6f
[ "BSD-3-Clause" ]
1
2022-03-14T14:51:28.000Z
2022-03-14T14:51:28.000Z
src/main/java/com/ul/ims/apdu/encoding/exceptions/ValueNotSetException.java
mDL-ILP/apdukit-java
86644fb830a8cb6e0258ab969ad75d0145e96e6f
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/ul/ims/apdu/encoding/exceptions/ValueNotSetException.java
mDL-ILP/apdukit-java
86644fb830a8cb6e0258ab969ad75d0145e96e6f
[ "BSD-3-Clause" ]
null
null
null
22.3125
64
0.689076
994,786
package com.ul.ims.apdu.encoding.exceptions; public class ValueNotSetException extends InvalidApduException { public String getValueName() { return valueName; } private String valueName; public ValueNotSetException(String valueName) { super("Value: "+valueName+" is not set"); this.valueName = valueName; } }
922e8e71aa0a3cf89d47a4c08ab5e1239aa05a95
2,405
java
Java
app/src/main/java/app/data/foundation/dagger/DataModule.java
VictorAlbertos/SubredditReader
bee758b267075ac9ade38b1f84e46bf2ea3dc98f
[ "Apache-2.0" ]
1
2016-09-19T18:22:46.000Z
2016-09-19T18:22:46.000Z
app/src/main/java/app/data/foundation/dagger/DataModule.java
VictorAlbertos/SubredditReader
bee758b267075ac9ade38b1f84e46bf2ea3dc98f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/app/data/foundation/dagger/DataModule.java
VictorAlbertos/SubredditReader
bee758b267075ac9ade38b1f84e46bf2ea3dc98f
[ "Apache-2.0" ]
null
null
null
34.855072
99
0.759667
994,787
/* * Copyright 2016 Victor Albertos * * 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 app.data.foundation.dagger; import android.content.Context; import android.support.annotation.StringRes; import app.data.foundation.Resources; import app.data.foundation.net.ApiModule; import app.data.sections.subreddits.GetRelativeTimeSpan; import app.data.sections.subreddits.GetRelativeTimeSpanBehaviour; import app.presentation.foundation.BaseApp; import com.google.gson.TypeAdapterFactory; import com.ryanharter.auto.value.gson.AutoValueGsonTypeAdapterFactory; import dagger.Module; import dagger.Provides; import io.reactivecache.ReactiveCache; import io.victoralbertos.jolyglot.GsonAutoValueSpeaker; import javax.inject.Singleton; /** * Resolve the dependencies for data layer. For networking dependencies {@see ApiModule}, which its * concrete implementation depends on the current build variant in order to be able to provide a * mock implementation for the networking layer. */ @Module(includes = {ApiModule.class}) public final class DataModule { @Singleton @Provides Resources provideUiUtils(BaseApp baseApp) { return new Resources() { @Override public String getString(@StringRes int idResource) { return baseApp.getString(idResource); } @Override public Context getContext() { return baseApp; } }; } @Singleton @Provides public ReactiveCache provideReactiveCache(BaseApp baseApp) { return new ReactiveCache.Builder() .using(baseApp.getFilesDir(), new GsonAutoValueSpeaker() { @Override protected TypeAdapterFactory autoValueGsonTypeAdapterFactory() { return new AutoValueGsonTypeAdapterFactory(); } }); } @Singleton @Provides public GetRelativeTimeSpan provideGetRelativeTimeSpan(BaseApp baseApp) { return new GetRelativeTimeSpanBehaviour(baseApp); } }
922e8ee57ee8fb5ceaec0628e90308ea684d210c
23,147
java
Java
src/ca/mcgill/ecse223/resto/model/RestoApp.java
1jayyaj1/RestoApp
47a2c2364edf7b8a5b9348dc0466fc058d396d65
[ "MIT" ]
null
null
null
src/ca/mcgill/ecse223/resto/model/RestoApp.java
1jayyaj1/RestoApp
47a2c2364edf7b8a5b9348dc0466fc058d396d65
[ "MIT" ]
null
null
null
src/ca/mcgill/ecse223/resto/model/RestoApp.java
1jayyaj1/RestoApp
47a2c2364edf7b8a5b9348dc0466fc058d396d65
[ "MIT" ]
null
null
null
24.136601
177
0.649069
994,788
/*PLEASE DO NOT EDIT THIS CODE*/ /*This code was generated using the UMPLE 1.27.0.3728.d139ed893 modeling language!*/ package ca.mcgill.ecse223.resto.model; import java.io.Serializable; import java.util.*; import java.sql.Date; import java.sql.Time; // line 3 "../../../../../RestoAppPersistence2.ump" // line 6 "../../../../../RestoApp-v7.ump" public class RestoApp implements Serializable { //------------------------ // MEMBER VARIABLES //------------------------ //RestoApp Associations private List<Reservation> reservations; private List<Table> tables; private Table takeOutTable; private List<Table> currentTables; private List<Order> orders; private List<Order> currentOrders; private Menu menu; private List<PricedMenuItem> pricedMenuItems; private List<Bill> bills; private List<TakeOut> takeOuts; //------------------------ // CONSTRUCTOR //------------------------ public RestoApp(Menu aMenu) { reservations = new ArrayList<Reservation>(); tables = new ArrayList<Table>(); currentTables = new ArrayList<Table>(); orders = new ArrayList<Order>(); currentOrders = new ArrayList<Order>(); if (aMenu == null || aMenu.getRestoApp() != null) { throw new RuntimeException("Unable to create RestoApp due to aMenu"); } menu = aMenu; pricedMenuItems = new ArrayList<PricedMenuItem>(); bills = new ArrayList<Bill>(); takeOuts = new ArrayList<TakeOut>(); } public RestoApp() { reservations = new ArrayList<Reservation>(); tables = new ArrayList<Table>(); currentTables = new ArrayList<Table>(); orders = new ArrayList<Order>(); currentOrders = new ArrayList<Order>(); menu = new Menu(this); pricedMenuItems = new ArrayList<PricedMenuItem>(); bills = new ArrayList<Bill>(); takeOuts = new ArrayList<TakeOut>(); } //------------------------ // INTERFACE //------------------------ public Reservation getReservation(int index) { Reservation aReservation = reservations.get(index); return aReservation; } /** * sorted by date and time */ public List<Reservation> getReservations() { List<Reservation> newReservations = Collections.unmodifiableList(reservations); return newReservations; } public int numberOfReservations() { int number = reservations.size(); return number; } public boolean hasReservations() { boolean has = reservations.size() > 0; return has; } public int indexOfReservation(Reservation aReservation) { int index = reservations.indexOf(aReservation); return index; } public Table getTable(int index) { Table aTable = tables.get(index); return aTable; } public List<Table> getTables() { List<Table> newTables = Collections.unmodifiableList(tables); return newTables; } public int numberOfTables() { int number = tables.size(); return number; } public boolean hasTables() { boolean has = tables.size() > 0; return has; } public int indexOfTable(Table aTable) { int index = tables.indexOf(aTable); return index; } public Table getTakeOutTable() { return takeOutTable; } public boolean hasTakeOutTable() { boolean has = takeOutTable != null; return has; } public Table getCurrentTable(int index) { Table aCurrentTable = currentTables.get(index); return aCurrentTable; } /** * subsets tables */ public List<Table> getCurrentTables() { List<Table> newCurrentTables = Collections.unmodifiableList(currentTables); return newCurrentTables; } public int numberOfCurrentTables() { int number = currentTables.size(); return number; } public boolean hasCurrentTables() { boolean has = currentTables.size() > 0; return has; } public int indexOfCurrentTable(Table aCurrentTable) { int index = currentTables.indexOf(aCurrentTable); return index; } public Order getOrder(int index) { Order aOrder = orders.get(index); return aOrder; } public List<Order> getOrders() { List<Order> newOrders = Collections.unmodifiableList(orders); return newOrders; } public int numberOfOrders() { int number = orders.size(); return number; } public boolean hasOrders() { boolean has = orders.size() > 0; return has; } public int indexOfOrder(Order aOrder) { int index = orders.indexOf(aOrder); return index; } public Order getCurrentOrder(int index) { Order aCurrentOrder = currentOrders.get(index); return aCurrentOrder; } /** * subsets orders */ public List<Order> getCurrentOrders() { List<Order> newCurrentOrders = Collections.unmodifiableList(currentOrders); return newCurrentOrders; } public int numberOfCurrentOrders() { int number = currentOrders.size(); return number; } public boolean hasCurrentOrders() { boolean has = currentOrders.size() > 0; return has; } public int indexOfCurrentOrder(Order aCurrentOrder) { int index = currentOrders.indexOf(aCurrentOrder); return index; } public Menu getMenu() { return menu; } public PricedMenuItem getPricedMenuItem(int index) { PricedMenuItem aPricedMenuItem = pricedMenuItems.get(index); return aPricedMenuItem; } public List<PricedMenuItem> getPricedMenuItems() { List<PricedMenuItem> newPricedMenuItems = Collections.unmodifiableList(pricedMenuItems); return newPricedMenuItems; } public int numberOfPricedMenuItems() { int number = pricedMenuItems.size(); return number; } public boolean hasPricedMenuItems() { boolean has = pricedMenuItems.size() > 0; return has; } public int indexOfPricedMenuItem(PricedMenuItem aPricedMenuItem) { int index = pricedMenuItems.indexOf(aPricedMenuItem); return index; } public Bill getBill(int index) { Bill aBill = bills.get(index); return aBill; } public List<Bill> getBills() { List<Bill> newBills = Collections.unmodifiableList(bills); return newBills; } public int numberOfBills() { int number = bills.size(); return number; } public boolean hasBills() { boolean has = bills.size() > 0; return has; } public int indexOfBill(Bill aBill) { int index = bills.indexOf(aBill); return index; } public TakeOut getTakeOut(int index) { TakeOut aTakeOut = takeOuts.get(index); return aTakeOut; } public List<TakeOut> getTakeOuts() { List<TakeOut> newTakeOuts = Collections.unmodifiableList(takeOuts); return newTakeOuts; } public int numberOfTakeOuts() { int number = takeOuts.size(); return number; } public boolean hasTakeOuts() { boolean has = takeOuts.size() > 0; return has; } public int indexOfTakeOut(TakeOut aTakeOut) { int index = takeOuts.indexOf(aTakeOut); return index; } public static int minimumNumberOfReservations() { return 0; } /* Code from template association_AddManyToOne */ public Reservation addReservation(Date aDate, Time aTime, int aNumberInParty, String aContactName, String aContactEmailAddress, String aContactPhoneNumber, Table... allTables) { return new Reservation(aDate, aTime, aNumberInParty, aContactName, aContactEmailAddress, aContactPhoneNumber, this, allTables); } public boolean addReservation(Reservation aReservation) { boolean wasAdded = false; if (reservations.contains(aReservation)) { return false; } RestoApp existingRestoApp = aReservation.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aReservation.setRestoApp(this); } else { reservations.add(aReservation); } wasAdded = true; return wasAdded; } public boolean removeReservation(Reservation aReservation) { boolean wasRemoved = false; //Unable to remove aReservation, as it must always have a restoApp if (!this.equals(aReservation.getRestoApp())) { reservations.remove(aReservation); wasRemoved = true; } return wasRemoved; } public boolean addReservationAt(Reservation aReservation, int index) { boolean wasAdded = false; if(addReservation(aReservation)) { if(index < 0 ) { index = 0; } if(index > numberOfReservations()) { index = numberOfReservations() - 1; } reservations.remove(aReservation); reservations.add(index, aReservation); wasAdded = true; } return wasAdded; } public boolean addOrMoveReservationAt(Reservation aReservation, int index) { boolean wasAdded = false; if(reservations.contains(aReservation)) { if(index < 0 ) { index = 0; } if(index > numberOfReservations()) { index = numberOfReservations() - 1; } reservations.remove(aReservation); reservations.add(index, aReservation); wasAdded = true; } else { wasAdded = addReservationAt(aReservation, index); } return wasAdded; } public static int minimumNumberOfTables() { return 0; } /* Code from template association_AddManyToOne */ public Table addTable(int aNumber, int aX, int aY, int aWidth, int aLength) { return new Table(aNumber, aX, aY, aWidth, aLength, this); } public boolean addTable(Table aTable) { boolean wasAdded = false; if (tables.contains(aTable)) { return false; } RestoApp existingRestoApp = aTable.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aTable.setRestoApp(this); } else { tables.add(aTable); } wasAdded = true; return wasAdded; } public boolean removeTable(Table aTable) { boolean wasRemoved = false; //Unable to remove aTable, as it must always have a restoApp if (!this.equals(aTable.getRestoApp())) { tables.remove(aTable); wasRemoved = true; } return wasRemoved; } public boolean addTableAt(Table aTable, int index) { boolean wasAdded = false; if(addTable(aTable)) { if(index < 0 ) { index = 0; } if(index > numberOfTables()) { index = numberOfTables() - 1; } tables.remove(aTable); tables.add(index, aTable); wasAdded = true; } return wasAdded; } public boolean addOrMoveTableAt(Table aTable, int index) { boolean wasAdded = false; if(tables.contains(aTable)) { if(index < 0 ) { index = 0; } if(index > numberOfTables()) { index = numberOfTables() - 1; } tables.remove(aTable); tables.add(index, aTable); wasAdded = true; } else { wasAdded = addTableAt(aTable, index); } return wasAdded; } public boolean setTakeOutTable(Table aNewTakeOutTable) { boolean wasSet = false; takeOutTable = aNewTakeOutTable; wasSet = true; return wasSet; } public static int minimumNumberOfCurrentTables() { return 0; } public boolean addCurrentTable(Table aCurrentTable) { boolean wasAdded = false; if (currentTables.contains(aCurrentTable)) { return false; } currentTables.add(aCurrentTable); wasAdded = true; return wasAdded; } public boolean removeCurrentTable(Table aCurrentTable) { boolean wasRemoved = false; if (currentTables.contains(aCurrentTable)) { currentTables.remove(aCurrentTable); wasRemoved = true; } return wasRemoved; } public boolean addCurrentTableAt(Table aCurrentTable, int index) { boolean wasAdded = false; if(addCurrentTable(aCurrentTable)) { if(index < 0 ) { index = 0; } if(index > numberOfCurrentTables()) { index = numberOfCurrentTables() - 1; } currentTables.remove(aCurrentTable); currentTables.add(index, aCurrentTable); wasAdded = true; } return wasAdded; } public boolean addOrMoveCurrentTableAt(Table aCurrentTable, int index) { boolean wasAdded = false; if(currentTables.contains(aCurrentTable)) { if(index < 0 ) { index = 0; } if(index > numberOfCurrentTables()) { index = numberOfCurrentTables() - 1; } currentTables.remove(aCurrentTable); currentTables.add(index, aCurrentTable); wasAdded = true; } else { wasAdded = addCurrentTableAt(aCurrentTable, index); } return wasAdded; } public static int minimumNumberOfOrders() { return 0; } /* Code from template association_AddManyToOne */ public Order addOrder(Date aDate, Time aTime, Table... allTables) { return new Order(aDate, aTime, this, allTables); } public boolean addOrder(Order aOrder) { boolean wasAdded = false; if (orders.contains(aOrder)) { return false; } RestoApp existingRestoApp = aOrder.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aOrder.setRestoApp(this); } else { orders.add(aOrder); } wasAdded = true; return wasAdded; } public boolean removeOrder(Order aOrder) { boolean wasRemoved = false; //Unable to remove aOrder, as it must always have a restoApp if (!this.equals(aOrder.getRestoApp())) { orders.remove(aOrder); wasRemoved = true; } return wasRemoved; } public boolean addOrderAt(Order aOrder, int index) { boolean wasAdded = false; if(addOrder(aOrder)) { if(index < 0 ) { index = 0; } if(index > numberOfOrders()) { index = numberOfOrders() - 1; } orders.remove(aOrder); orders.add(index, aOrder); wasAdded = true; } return wasAdded; } public boolean addOrMoveOrderAt(Order aOrder, int index) { boolean wasAdded = false; if(orders.contains(aOrder)) { if(index < 0 ) { index = 0; } if(index > numberOfOrders()) { index = numberOfOrders() - 1; } orders.remove(aOrder); orders.add(index, aOrder); wasAdded = true; } else { wasAdded = addOrderAt(aOrder, index); } return wasAdded; } public static int minimumNumberOfCurrentOrders() { return 0; } public boolean addCurrentOrder(Order aCurrentOrder) { boolean wasAdded = false; if (currentOrders.contains(aCurrentOrder)) { return false; } currentOrders.add(aCurrentOrder); wasAdded = true; return wasAdded; } public boolean removeCurrentOrder(Order aCurrentOrder) { boolean wasRemoved = false; if (currentOrders.contains(aCurrentOrder)) { currentOrders.remove(aCurrentOrder); wasRemoved = true; } return wasRemoved; } public boolean addCurrentOrderAt(Order aCurrentOrder, int index) { boolean wasAdded = false; if(addCurrentOrder(aCurrentOrder)) { if(index < 0 ) { index = 0; } if(index > numberOfCurrentOrders()) { index = numberOfCurrentOrders() - 1; } currentOrders.remove(aCurrentOrder); currentOrders.add(index, aCurrentOrder); wasAdded = true; } return wasAdded; } public boolean addOrMoveCurrentOrderAt(Order aCurrentOrder, int index) { boolean wasAdded = false; if(currentOrders.contains(aCurrentOrder)) { if(index < 0 ) { index = 0; } if(index > numberOfCurrentOrders()) { index = numberOfCurrentOrders() - 1; } currentOrders.remove(aCurrentOrder); currentOrders.add(index, aCurrentOrder); wasAdded = true; } else { wasAdded = addCurrentOrderAt(aCurrentOrder, index); } return wasAdded; } public static int minimumNumberOfPricedMenuItems() { return 0; } /* Code from template association_AddManyToOne */ public PricedMenuItem addPricedMenuItem(double aPrice, MenuItem aMenuItem) { return new PricedMenuItem(aPrice, this, aMenuItem); } public boolean addPricedMenuItem(PricedMenuItem aPricedMenuItem) { boolean wasAdded = false; if (pricedMenuItems.contains(aPricedMenuItem)) { return false; } RestoApp existingRestoApp = aPricedMenuItem.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aPricedMenuItem.setRestoApp(this); } else { pricedMenuItems.add(aPricedMenuItem); } wasAdded = true; return wasAdded; } public boolean removePricedMenuItem(PricedMenuItem aPricedMenuItem) { boolean wasRemoved = false; //Unable to remove aPricedMenuItem, as it must always have a restoApp if (!this.equals(aPricedMenuItem.getRestoApp())) { pricedMenuItems.remove(aPricedMenuItem); wasRemoved = true; } return wasRemoved; } public boolean addPricedMenuItemAt(PricedMenuItem aPricedMenuItem, int index) { boolean wasAdded = false; if(addPricedMenuItem(aPricedMenuItem)) { if(index < 0 ) { index = 0; } if(index > numberOfPricedMenuItems()) { index = numberOfPricedMenuItems() - 1; } pricedMenuItems.remove(aPricedMenuItem); pricedMenuItems.add(index, aPricedMenuItem); wasAdded = true; } return wasAdded; } public boolean addOrMovePricedMenuItemAt(PricedMenuItem aPricedMenuItem, int index) { boolean wasAdded = false; if(pricedMenuItems.contains(aPricedMenuItem)) { if(index < 0 ) { index = 0; } if(index > numberOfPricedMenuItems()) { index = numberOfPricedMenuItems() - 1; } pricedMenuItems.remove(aPricedMenuItem); pricedMenuItems.add(index, aPricedMenuItem); wasAdded = true; } else { wasAdded = addPricedMenuItemAt(aPricedMenuItem, index); } return wasAdded; } public static int minimumNumberOfBills() { return 0; } /* Code from template association_AddManyToOne */ public Bill addBill(Order aOrder, Seat... allIssuedForSeats) { return new Bill(aOrder, this, allIssuedForSeats); } public boolean addBill(Bill aBill) { boolean wasAdded = false; if (bills.contains(aBill)) { return false; } RestoApp existingRestoApp = aBill.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aBill.setRestoApp(this); } else { bills.add(aBill); } wasAdded = true; return wasAdded; } public boolean removeBill(Bill aBill) { boolean wasRemoved = false; //Unable to remove aBill, as it must always have a restoApp if (!this.equals(aBill.getRestoApp())) { bills.remove(aBill); wasRemoved = true; } return wasRemoved; } public boolean addBillAt(Bill aBill, int index) { boolean wasAdded = false; if(addBill(aBill)) { if(index < 0 ) { index = 0; } if(index > numberOfBills()) { index = numberOfBills() - 1; } bills.remove(aBill); bills.add(index, aBill); wasAdded = true; } return wasAdded; } public boolean addOrMoveBillAt(Bill aBill, int index) { boolean wasAdded = false; if(bills.contains(aBill)) { if(index < 0 ) { index = 0; } if(index > numberOfBills()) { index = numberOfBills() - 1; } bills.remove(aBill); bills.add(index, aBill); wasAdded = true; } else { wasAdded = addBillAt(aBill, index); } return wasAdded; } public static int minimumNumberOfTakeOuts() { return 0; } /* Code from template association_AddManyToOne */ public TakeOut addTakeOut(int aPhoneNumber, String aTakeOutName, Order aOrder) { return new TakeOut(aPhoneNumber, aTakeOutName, aOrder, this); } public boolean addTakeOut(TakeOut aTakeOut) { boolean wasAdded = false; if (takeOuts.contains(aTakeOut)) { return false; } RestoApp existingRestoApp = aTakeOut.getRestoApp(); boolean isNewRestoApp = existingRestoApp != null && !this.equals(existingRestoApp); if (isNewRestoApp) { aTakeOut.setRestoApp(this); } else { takeOuts.add(aTakeOut); } wasAdded = true; return wasAdded; } public boolean removeTakeOut(TakeOut aTakeOut) { boolean wasRemoved = false; //Unable to remove aTakeOut, as it must always have a restoApp if (!this.equals(aTakeOut.getRestoApp())) { takeOuts.remove(aTakeOut); wasRemoved = true; } return wasRemoved; } public boolean addTakeOutAt(TakeOut aTakeOut, int index) { boolean wasAdded = false; if(addTakeOut(aTakeOut)) { if(index < 0 ) { index = 0; } if(index > numberOfTakeOuts()) { index = numberOfTakeOuts() - 1; } takeOuts.remove(aTakeOut); takeOuts.add(index, aTakeOut); wasAdded = true; } return wasAdded; } public boolean addOrMoveTakeOutAt(TakeOut aTakeOut, int index) { boolean wasAdded = false; if(takeOuts.contains(aTakeOut)) { if(index < 0 ) { index = 0; } if(index > numberOfTakeOuts()) { index = numberOfTakeOuts() - 1; } takeOuts.remove(aTakeOut); takeOuts.add(index, aTakeOut); wasAdded = true; } else { wasAdded = addTakeOutAt(aTakeOut, index); } return wasAdded; } public void delete() { while (reservations.size() > 0) { Reservation aReservation = reservations.get(reservations.size() - 1); aReservation.delete(); reservations.remove(aReservation); } while (tables.size() > 0) { Table aTable = tables.get(tables.size() - 1); aTable.delete(); tables.remove(aTable); } takeOutTable = null; currentTables.clear(); while (orders.size() > 0) { Order aOrder = orders.get(orders.size() - 1); aOrder.delete(); orders.remove(aOrder); } currentOrders.clear(); Menu existingMenu = menu; menu = null; if (existingMenu != null) { existingMenu.delete(); } while (pricedMenuItems.size() > 0) { PricedMenuItem aPricedMenuItem = pricedMenuItems.get(pricedMenuItems.size() - 1); aPricedMenuItem.delete(); pricedMenuItems.remove(aPricedMenuItem); } while (bills.size() > 0) { Bill aBill = bills.get(bills.size() - 1); aBill.delete(); bills.remove(aBill); } while (takeOuts.size() > 0) { TakeOut aTakeOut = takeOuts.get(takeOuts.size() - 1); aTakeOut.delete(); takeOuts.remove(aTakeOut); } } // line 9 "../../../../../RestoAppPersistence2.ump" public void reinitialize(){ Reservation.reinitializeAutouniqueResNumber(this.getReservations()); Order.reinitializeAutouniqueNumber(this.getOrders()); //MenuItem.reinitializeUniqueMenuItemName(this.menu.getItems()); Table.reinitializeUniqueNumber(this.getCurrentTables()); } //------------------------ // DEVELOPER CODE - PROVIDED AS-IS //------------------------ // line 6 "../../../../../RestoAppPersistence2.ump" private static final long serialVersionUID = -2683593616927798071L ; }
922e8f5fb6d9de67810f6bdf631301cef4ef85b5
640
java
Java
src/main/java/br/com/cas10/pgman/utils/SizeUtils.java
fernandopeinado/pg_manager
30841e2b387861e99a57d9b0db4fb1110992d73e
[ "Apache-2.0" ]
1
2019-08-13T00:44:41.000Z
2019-08-13T00:44:41.000Z
src/main/java/br/com/cas10/pgman/utils/SizeUtils.java
fernandopeinado/pg_manager
30841e2b387861e99a57d9b0db4fb1110992d73e
[ "Apache-2.0" ]
7
2020-05-15T21:01:38.000Z
2022-02-16T01:16:58.000Z
src/main/java/br/com/cas10/pgman/utils/SizeUtils.java
fernandopeinado/pg_manager
30841e2b387861e99a57d9b0db4fb1110992d73e
[ "Apache-2.0" ]
4
2015-05-06T21:46:54.000Z
2021-12-01T17:21:52.000Z
24.615385
88
0.640625
994,789
package br.com.cas10.pgman.utils; import java.text.DecimalFormat; public class SizeUtils { private static final String[] UNITS = new String[] { "bytes", "Kb", "Mb", "Gb", "Tb" }; private static final long MULTIPLIER = 1024; private static final long THRESHOLD = 100 * MULTIPLIER; public static String prettyPrintSize(Long size) { DecimalFormat format = new DecimalFormat("#,##0"); int unit = 0; if (size == null) { size = 0L; } else { while (size >= THRESHOLD && unit < 4) { size = (long) Math.ceil((double) size / (double) MULTIPLIER); unit++; } } return format.format(size) + " " + UNITS[unit]; } }
922e8fbf275886819605cfd666e6977f0fb75f53
16,567
java
Java
flink-runtime/src/main/java/org/apache/flink/runtime/deployment/TaskDeploymentDescriptorFactory.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
2
2022-03-15T02:09:22.000Z
2022-03-24T09:46:30.000Z
flink-runtime/src/main/java/org/apache/flink/runtime/deployment/TaskDeploymentDescriptorFactory.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
7
2021-12-18T18:39:23.000Z
2022-03-11T12:56:01.000Z
flink-runtime/src/main/java/org/apache/flink/runtime/deployment/TaskDeploymentDescriptorFactory.java
wgzhao/flink
6af0b9965293cb732a540b9364b6aae76a9b356a
[ "Apache-2.0" ]
1
2022-01-12T17:13:55.000Z
2022-01-12T17:13:55.000Z
48.44152
136
0.696264
994,790
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.deployment; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.JobID; import org.apache.flink.runtime.blob.BlobWriter; import org.apache.flink.runtime.blob.PermanentBlobKey; import org.apache.flink.runtime.checkpoint.JobManagerTaskRestore; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor.MaybeOffloaded; import org.apache.flink.runtime.execution.ExecutionState; import org.apache.flink.runtime.executiongraph.Execution; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.executiongraph.ExecutionVertex; import org.apache.flink.runtime.executiongraph.IntermediateResult; import org.apache.flink.runtime.executiongraph.IntermediateResultPartition; import org.apache.flink.runtime.executiongraph.InternalExecutionGraphAccessor; import org.apache.flink.runtime.executiongraph.JobInformation; import org.apache.flink.runtime.executiongraph.TaskInformation; import org.apache.flink.runtime.io.network.partition.ResultPartitionID; import org.apache.flink.runtime.io.network.partition.ResultPartitionType; import org.apache.flink.runtime.jobgraph.IntermediateDataSetID; import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID; import org.apache.flink.runtime.jobgraph.JobType; import org.apache.flink.runtime.scheduler.strategy.ConsumedPartitionGroup; import org.apache.flink.runtime.shuffle.ShuffleDescriptor; import org.apache.flink.runtime.shuffle.UnknownShuffleDescriptor; import org.apache.flink.types.Either; import org.apache.flink.util.CompressedSerializedValue; import org.apache.flink.util.SerializedValue; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Function; /** * Factory of {@link TaskDeploymentDescriptor} to deploy {@link * org.apache.flink.runtime.taskmanager.Task} from {@link Execution}. */ public class TaskDeploymentDescriptorFactory { private final ExecutionAttemptID executionId; private final int attemptNumber; private final MaybeOffloaded<JobInformation> serializedJobInformation; private final MaybeOffloaded<TaskInformation> taskInfo; private final JobID jobID; private final PartitionLocationConstraint partitionDeploymentConstraint; private final int subtaskIndex; private final List<ConsumedPartitionGroup> consumedPartitionGroups; private final Function<IntermediateResultPartitionID, IntermediateResultPartition> resultPartitionRetriever; private final BlobWriter blobWriter; private TaskDeploymentDescriptorFactory( ExecutionAttemptID executionId, int attemptNumber, MaybeOffloaded<JobInformation> serializedJobInformation, MaybeOffloaded<TaskInformation> taskInfo, JobID jobID, PartitionLocationConstraint partitionDeploymentConstraint, int subtaskIndex, List<ConsumedPartitionGroup> consumedPartitionGroups, Function<IntermediateResultPartitionID, IntermediateResultPartition> resultPartitionRetriever, BlobWriter blobWriter) { this.executionId = executionId; this.attemptNumber = attemptNumber; this.serializedJobInformation = serializedJobInformation; this.taskInfo = taskInfo; this.jobID = jobID; this.partitionDeploymentConstraint = partitionDeploymentConstraint; this.subtaskIndex = subtaskIndex; this.consumedPartitionGroups = consumedPartitionGroups; this.resultPartitionRetriever = resultPartitionRetriever; this.blobWriter = blobWriter; } public TaskDeploymentDescriptor createDeploymentDescriptor( AllocationID allocationID, @Nullable JobManagerTaskRestore taskRestore, Collection<ResultPartitionDeploymentDescriptor> producedPartitions) throws IOException { return new TaskDeploymentDescriptor( jobID, serializedJobInformation, taskInfo, executionId, allocationID, subtaskIndex, attemptNumber, taskRestore, new ArrayList<>(producedPartitions), createInputGateDeploymentDescriptors()); } private List<InputGateDeploymentDescriptor> createInputGateDeploymentDescriptors() throws IOException { List<InputGateDeploymentDescriptor> inputGates = new ArrayList<>(consumedPartitionGroups.size()); for (ConsumedPartitionGroup consumedPartitionGroup : consumedPartitionGroups) { // If the produced partition has multiple consumers registered, we // need to request the one matching our sub task index. // TODO Refactor after removing the consumers from the intermediate result partitions IntermediateResultPartition resultPartition = resultPartitionRetriever.apply(consumedPartitionGroup.getFirst()); int numConsumers = resultPartition.getConsumerVertexGroups().get(0).size(); int queueToRequest = subtaskIndex % numConsumers; IntermediateResult consumedIntermediateResult = resultPartition.getIntermediateResult(); IntermediateDataSetID resultId = consumedIntermediateResult.getId(); ResultPartitionType partitionType = consumedIntermediateResult.getResultType(); inputGates.add( new InputGateDeploymentDescriptor( resultId, partitionType, queueToRequest, getConsumedPartitionShuffleDescriptors( consumedIntermediateResult, consumedPartitionGroup))); } return inputGates; } private MaybeOffloaded<ShuffleDescriptor[]> getConsumedPartitionShuffleDescriptors( IntermediateResult intermediateResult, ConsumedPartitionGroup consumedPartitionGroup) throws IOException { MaybeOffloaded<ShuffleDescriptor[]> serializedShuffleDescriptors = intermediateResult.getCachedShuffleDescriptors(consumedPartitionGroup); if (serializedShuffleDescriptors == null) { serializedShuffleDescriptors = computeConsumedPartitionShuffleDescriptors(consumedPartitionGroup); intermediateResult.cacheShuffleDescriptors( consumedPartitionGroup, serializedShuffleDescriptors); } return serializedShuffleDescriptors; } private MaybeOffloaded<ShuffleDescriptor[]> computeConsumedPartitionShuffleDescriptors( ConsumedPartitionGroup consumedPartitionGroup) throws IOException { ShuffleDescriptor[] shuffleDescriptors = new ShuffleDescriptor[consumedPartitionGroup.size()]; // Each edge is connected to a different result partition int i = 0; for (IntermediateResultPartitionID partitionId : consumedPartitionGroup) { shuffleDescriptors[i++] = getConsumedPartitionShuffleDescriptor( resultPartitionRetriever.apply(partitionId), partitionDeploymentConstraint); } return serializeAndTryOffloadShuffleDescriptors(shuffleDescriptors); } private MaybeOffloaded<ShuffleDescriptor[]> serializeAndTryOffloadShuffleDescriptors( ShuffleDescriptor[] shuffleDescriptors) throws IOException { final CompressedSerializedValue<ShuffleDescriptor[]> compressedSerializedValue = CompressedSerializedValue.fromObject(shuffleDescriptors); final Either<SerializedValue<ShuffleDescriptor[]>, PermanentBlobKey> serializedValueOrBlobKey = BlobWriter.tryOffload(compressedSerializedValue, jobID, blobWriter); if (serializedValueOrBlobKey.isLeft()) { return new TaskDeploymentDescriptor.NonOffloaded<>(serializedValueOrBlobKey.left()); } else { return new TaskDeploymentDescriptor.Offloaded<>(serializedValueOrBlobKey.right()); } } public static TaskDeploymentDescriptorFactory fromExecutionVertex( ExecutionVertex executionVertex, int attemptNumber) throws IOException { InternalExecutionGraphAccessor internalExecutionGraphAccessor = executionVertex.getExecutionGraphAccessor(); return new TaskDeploymentDescriptorFactory( executionVertex.getCurrentExecutionAttempt().getAttemptId(), attemptNumber, getSerializedJobInformation(internalExecutionGraphAccessor), getSerializedTaskInformation( executionVertex.getJobVertex().getTaskInformationOrBlobKey()), internalExecutionGraphAccessor.getJobID(), internalExecutionGraphAccessor.getPartitionLocationConstraint(), executionVertex.getParallelSubtaskIndex(), executionVertex.getAllConsumedPartitionGroups(), internalExecutionGraphAccessor::getResultPartitionOrThrow, internalExecutionGraphAccessor.getBlobWriter()); } private static MaybeOffloaded<JobInformation> getSerializedJobInformation( InternalExecutionGraphAccessor internalExecutionGraphAccessor) { Either<SerializedValue<JobInformation>, PermanentBlobKey> jobInformationOrBlobKey = internalExecutionGraphAccessor.getJobInformationOrBlobKey(); if (jobInformationOrBlobKey.isLeft()) { return new TaskDeploymentDescriptor.NonOffloaded<>(jobInformationOrBlobKey.left()); } else { return new TaskDeploymentDescriptor.Offloaded<>(jobInformationOrBlobKey.right()); } } private static MaybeOffloaded<TaskInformation> getSerializedTaskInformation( Either<SerializedValue<TaskInformation>, PermanentBlobKey> taskInfo) { return taskInfo.isLeft() ? new TaskDeploymentDescriptor.NonOffloaded<>(taskInfo.left()) : new TaskDeploymentDescriptor.Offloaded<>(taskInfo.right()); } public static ShuffleDescriptor getConsumedPartitionShuffleDescriptor( IntermediateResultPartition consumedPartition, PartitionLocationConstraint partitionDeploymentConstraint) { Execution producer = consumedPartition.getProducer().getCurrentExecutionAttempt(); ExecutionState producerState = producer.getState(); Optional<ResultPartitionDeploymentDescriptor> consumedPartitionDescriptor = producer.getResultPartitionDeploymentDescriptor(consumedPartition.getPartitionId()); ResultPartitionID consumedPartitionId = new ResultPartitionID(consumedPartition.getPartitionId(), producer.getAttemptId()); return getConsumedPartitionShuffleDescriptor( consumedPartitionId, consumedPartition.getResultType(), consumedPartition.isConsumable(), producerState, partitionDeploymentConstraint, consumedPartitionDescriptor.orElse(null)); } @VisibleForTesting static ShuffleDescriptor getConsumedPartitionShuffleDescriptor( ResultPartitionID consumedPartitionId, ResultPartitionType resultPartitionType, boolean isConsumable, ExecutionState producerState, PartitionLocationConstraint partitionDeploymentConstraint, @Nullable ResultPartitionDeploymentDescriptor consumedPartitionDescriptor) { // The producing task needs to be RUNNING or already FINISHED if ((resultPartitionType.isPipelined() || isConsumable) && consumedPartitionDescriptor != null && isProducerAvailable(producerState)) { // partition is already registered return consumedPartitionDescriptor.getShuffleDescriptor(); } else if (partitionDeploymentConstraint == PartitionLocationConstraint.CAN_BE_UNKNOWN) { // The producing task might not have registered the partition yet // // Currently, UnknownShuffleDescriptor will be created only if there is an intra-region // blocking edge in the graph. This means that when its consumer restarts, the // producer of the UnknownShuffleDescriptors will also restart. Therefore, it's safe to // cache UnknownShuffleDescriptors and there's no need to update the cache when the // corresponding partition becomes consumable. return new UnknownShuffleDescriptor(consumedPartitionId); } else { // throw respective exceptions throw handleConsumedPartitionShuffleDescriptorErrors( consumedPartitionId, resultPartitionType, isConsumable, producerState); } } private static RuntimeException handleConsumedPartitionShuffleDescriptorErrors( ResultPartitionID consumedPartitionId, ResultPartitionType resultPartitionType, boolean isConsumable, ExecutionState producerState) { String msg; if (isProducerFailedOrCanceled(producerState)) { msg = "Trying to consume an input partition whose producer has been canceled or failed. " + "The producer is in state " + producerState + "."; } else { msg = String.format( "Trying to consume an input partition whose producer " + "is not ready (result type: %s, partition consumable: %s, producer state: %s, partition id: %s).", resultPartitionType, isConsumable, producerState, consumedPartitionId); } return new IllegalStateException(msg); } private static boolean isProducerAvailable(ExecutionState producerState) { return producerState == ExecutionState.RUNNING || producerState == ExecutionState.INITIALIZING || producerState == ExecutionState.FINISHED || producerState == ExecutionState.SCHEDULED || producerState == ExecutionState.DEPLOYING; } private static boolean isProducerFailedOrCanceled(ExecutionState producerState) { return producerState == ExecutionState.CANCELING || producerState == ExecutionState.CANCELED || producerState == ExecutionState.FAILED; } /** * Defines whether the partition's location must be known at deployment time or can be unknown * and, therefore, updated later. */ public enum PartitionLocationConstraint { MUST_BE_KNOWN, CAN_BE_UNKNOWN; public static PartitionLocationConstraint fromJobType(JobType jobType) { switch (jobType) { case BATCH: return CAN_BE_UNKNOWN; case STREAMING: return MUST_BE_KNOWN; default: throw new IllegalArgumentException( String.format( "Unknown JobType %s. Cannot derive partition location constraint for it.", jobType)); } } } }
922e91ae216bc41608b696f8789d7771e4b3f335
1,059
java
Java
com/github/jaiimageio/impl/plugins/tiff/TIFFZLibCompressor.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
com/github/jaiimageio/impl/plugins/tiff/TIFFZLibCompressor.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
com/github/jaiimageio/impl/plugins/tiff/TIFFZLibCompressor.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
15.573529
117
0.31067
994,791
/* */ package com.github.jaiimageio.impl.plugins.tiff; /* */ /* */ import javax.imageio.ImageWriteParam; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class TIFFZLibCompressor /* */ extends TIFFDeflater /* */ { /* */ public TIFFZLibCompressor(ImageWriteParam param, int predictor) { /* 60 */ super("ZLib", 8, param, predictor); /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/com/github/jaiimageio/impl/plugins/tiff/TIFFZLibCompressor.class * Java compiler version: 5 (49.0) * JD-Core Version: 1.1.3 */
922e932309be9935e582251d42ce1e6f33a45fb5
1,142
java
Java
sor/src/main/java/com/bazaarvoice/emodb/sor/core/Expanded.java
sibasish-palo/emodb
b17149af391bcf0f00ce012e57fd9f28647e39c0
[ "Apache-2.0" ]
57
2016-08-26T15:26:44.000Z
2022-02-16T07:35:27.000Z
sor/src/main/java/com/bazaarvoice/emodb/sor/core/Expanded.java
sibasish-palo/emodb
b17149af391bcf0f00ce012e57fd9f28647e39c0
[ "Apache-2.0" ]
238
2016-08-25T18:13:49.000Z
2022-03-31T13:29:35.000Z
sor/src/main/java/com/bazaarvoice/emodb/sor/core/Expanded.java
sibasish-palo/emodb
b17149af391bcf0f00ce012e57fd9f28647e39c0
[ "Apache-2.0" ]
60
2016-08-25T19:25:13.000Z
2022-03-25T14:55:38.000Z
30.052632
96
0.725919
994,792
package com.bazaarvoice.emodb.sor.core; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; /** The result of resolving a sequence of deltas in the presence of the compaction algorithm. */ public class Expanded { private final Resolved _resolved; private final PendingCompaction _pendingCompaction; private final int _numPersistentDeltas; private final long _numDeletedDeltas; public Expanded(Resolved resolved, @Nullable PendingCompaction pendingCompaction, int numPersistentDeltas, long numDeletedDeltas) { _resolved = checkNotNull(resolved, "resolved"); _pendingCompaction = pendingCompaction; _numPersistentDeltas = numPersistentDeltas; _numDeletedDeltas = numDeletedDeltas; } public Resolved getResolved() { return _resolved; } public PendingCompaction getPendingCompaction() { return _pendingCompaction; } public int getNumPersistentDeltas() { return _numPersistentDeltas; } public long getNumDeletedDeltas() { return _numDeletedDeltas; } }
922e93618ba5389ea4651cbacf8a10436c81f487
6,750
java
Java
src/main/java/thymeleafexamples/stsm/web/controller/SeedStarterMngController.java
gary-huang/thymeleaf-spring-rest-apache-httpclient
9e0c81ea90013368727acb264c8d8082befd92f0
[ "Apache-2.0" ]
1
2018-07-06T20:06:23.000Z
2018-07-06T20:06:23.000Z
src/main/java/thymeleafexamples/stsm/web/controller/SeedStarterMngController.java
gary-huang/thymeleaf-spring-rest-apache-httpclient
9e0c81ea90013368727acb264c8d8082befd92f0
[ "Apache-2.0" ]
null
null
null
src/main/java/thymeleafexamples/stsm/web/controller/SeedStarterMngController.java
gary-huang/thymeleaf-spring-rest-apache-httpclient
9e0c81ea90013368727acb264c8d8082befd92f0
[ "Apache-2.0" ]
null
null
null
41.925466
158
0.683852
994,793
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package thymeleafexamples.stsm.web.controller; import java.util.*; import java.util.concurrent.CompletableFuture; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.http.client.*; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.AsyncRestTemplate; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.ModelAndView; import thymeleafexamples.stsm.business.models.Quote; import thymeleafexamples.stsm.business.models.User; import thymeleafexamples.stsm.business.models.Value; import thymeleafexamples.stsm.business.services.GitHubLookupService; @Controller public class SeedStarterMngController { final Log logger = LogFactory.getLog(getClass()); RestTemplate restTemplate = new RestTemplate(); RestTemplate normalRT = new RestTemplate(); AsyncRestTemplate asyncTemplate = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory()); @Autowired private GitHubLookupService gitHubLookupService; public SeedStarterMngController() { super(); // uncomment to apache HTTP request factory // restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); ((SimpleClientHttpRequestFactory)this.restTemplate.getRequestFactory()).setReadTimeout(0); } private Quote makeRESTReqForQuoteAsyncRT() { ListenableFuture<ResponseEntity<Quote>> quoteFuture = this.asyncTemplate.getForEntity("https://gturnquist-quoters.cfapps.io/api/random", Quote.class); Quote retQuote = new Quote(); try { ResponseEntity<Quote> res = quoteFuture.get(); retQuote = res.getBody(); } catch (Exception e) { retQuote.setType("Error"); Value errVal = new Value(); errVal.setId(-1L); errVal.setQuote("Exception: " + e.getMessage()); retQuote.setValue(errVal); } return retQuote; } private Quote makeRESTReqForQuoteSyncRT() { Quote quote = this.restTemplate.getForObject("https://gturnquist-quoters.cfapps.io/api/random", Quote.class); return quote; } private String makeRESTReqForGithubSpringAsync() { String res = ""; try { CompletableFuture<User> page1 = gitHubLookupService.findUser("PivotalSoftware"); CompletableFuture<User> page2 = gitHubLookupService.findUser("CloudFoundry"); CompletableFuture<User> page3 = gitHubLookupService.findUser("Spring-Projects"); // Wait until they are all done CompletableFuture.allOf(page1,page2,page3).join(); res += page1.get().toString() + "\n" + page2.get().toString() + "\n" + page3.get().toString(); } catch (Exception e) { res = e.getMessage(); } return res; } private String makeRESTPOSTReq() { MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); bodyMap.add("id", "2"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(bodyMap, headers); String returnString = "POST WILL FAIL MOST LIKELY DUE TO LOCALHOST SERVER NOT RUNNING"; try { ResponseEntity<String> ret = this.restTemplate.postForEntity("http://localhost:9001/uppercase", request, String.class); returnString = ret.getBody(); } catch (Exception e) { returnString = e.getMessage(); } return returnString; } @RequestMapping({"/resttemplatetest"}) public ModelAndView handleRequest() { Quote quote = makeRESTReqForQuoteSyncRT(); // Quote asyncQuote = makeRESTReqForQuoteAsyncRT(); logger.info("Return View: " + quote); ModelAndView mav = new ModelAndView("resttemplatetest.html"); mav.addObject("springasync", makeRESTReqForGithubSpringAsync()); mav.addObject("postres", makeRESTPOSTReq()); mav.addObject("syncquotetype", quote.getType()); mav.addObject("syncquoteval", quote.getValue().getQuote()); mav.addObject("reqfactory", restTemplate.getRequestFactory().toString()); // mav.addObject("asyncquotetype", asyncQuote.getType()); // mav.addObject("asyncquoteval", asyncQuote.getValue().getQuote()); return mav; } @RequestMapping({"/singleresttemplatetest"}) public ModelAndView handleSingleRequest() { Quote quote = makeRESTReqForQuoteSyncRT(); logger.info("Return View: " + quote); ModelAndView mav = new ModelAndView("resttemplatetest.html"); mav.addObject("syncquotetype", quote.getType()); mav.addObject("syncquoteval", quote.getValue().getQuote()); return mav; } @RequestMapping({"/asyncresttemplatetest"}) public ModelAndView handleRequestAsyncTemplate() { Quote asyncQuote = makeRESTReqForQuoteAsyncRT(); logger.info("Return View: " + asyncQuote); ModelAndView mav = new ModelAndView("resttemplatetest.html"); mav.addObject("asyncquotetype", asyncQuote.getType()); mav.addObject("asyncquoteval", asyncQuote.getValue().getQuote()); return mav; } }
922e94728073dc1b6845d0a3f30f071a1f8b5c0d
2,378
java
Java
components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcGrowIssueTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcGrowIssueTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
components/camel-sql/src/test/java/org/apache/camel/processor/aggregate/jdbc/JdbcGrowIssueTest.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
38.354839
108
0.693019
994,794
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor.aggregate.jdbc; import org.apache.camel.Exchange; import org.apache.camel.support.DefaultExchange; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class JdbcGrowIssueTest extends AbstractJdbcAggregationTestSupport { private static final Logger LOG = LoggerFactory.getLogger(JdbcGrowIssueTest.class); private static final int SIZE = 1024; @Test public void testGrowIssue() throws Exception { // a 1kb string for testing StringBuilder sb = new StringBuilder(SIZE); for (int i = 0; i < SIZE; i++) { sb.append("X"); } Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(sb.toString(), String.class); // the key final String key = "foo"; // we update using the same key, which means we should be able to do this within the file size limit for (int i = 0; i < SIZE; i++) { LOG.debug("Updating " + i); exchange = repoAddAndGet(key, exchange); } // get the last Exchange data = repo.get(context, key); LOG.info(data.toString()); assertTrue(data.getIn().getBody(String.class).startsWith("XXX"), "Should start with 'XXX'"); int length = data.getIn().getBody(String.class).length(); assertEquals(1024, length, "Length should be 1024, was " + length); } }
922e962f78b1acd33ce07ae526d5f27883a7197f
450
java
Java
src/main/java/com/game/sdk/dolls/service/ChannelService.java
lqwluckyer/dolls
7488f64959c1979989450f8700af2b7e87201ba0
[ "Apache-2.0" ]
4
2019-04-25T07:38:52.000Z
2021-03-09T01:57:08.000Z
src/main/java/com/game/sdk/dolls/service/ChannelService.java
jeanpg/dolls
7488f64959c1979989450f8700af2b7e87201ba0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/game/sdk/dolls/service/ChannelService.java
jeanpg/dolls
7488f64959c1979989450f8700af2b7e87201ba0
[ "Apache-2.0" ]
1
2020-11-20T16:17:24.000Z
2020-11-20T16:17:24.000Z
26.470588
53
0.773333
994,795
package com.game.sdk.dolls.service; import com.game.sdk.dolls.request.channel.ChannelReq; import com.game.sdk.dolls.response.EasyUIResp; /** * Created by Administrator on 2019-01-22. */ public interface ChannelService { EasyUIResp getChannelByGameId(Integer gameId); EasyUIResp getChannelList(ChannelReq req); EasyUIResp saveChannel(ChannelReq req); EasyUIResp removeChannel(ChannelReq req); EasyUIResp getSimpleChannel(); }
922e96ab6f8b989e7e215ca36fd787f0472da9b6
4,815
java
Java
server/src/main/java/com/decathlon/ara/web/rest/advice/ResponseDtoValidator.java
TroyonGuillaume/ara
c606cea442caf09934b29f69ad8ebfdfb3605f24
[ "Apache-2.0" ]
86
2019-04-04T13:52:41.000Z
2022-01-11T16:13:01.000Z
server/src/main/java/com/decathlon/ara/web/rest/advice/ResponseDtoValidator.java
TroyonGuillaume/ara
c606cea442caf09934b29f69ad8ebfdfb3605f24
[ "Apache-2.0" ]
430
2019-04-09T20:11:40.000Z
2022-03-19T07:26:45.000Z
server/src/main/java/com/decathlon/ara/web/rest/advice/ResponseDtoValidator.java
TroyonGuillaume/ara
c606cea442caf09934b29f69ad8ebfdfb3605f24
[ "Apache-2.0" ]
22
2019-05-15T13:34:47.000Z
2022-03-18T18:02:53.000Z
50.15625
118
0.57757
994,796
/****************************************************************************** * Copyright (C) 2019 by the ARA Contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ package com.decathlon.ara.web.rest.advice; import com.decathlon.ara.web.rest.util.HeaderUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @Slf4j @ControllerAdvice @RestController public class ResponseDtoValidator extends ResponseEntityExceptionHandler { private static final String MESSAGE_SEPARATOR = "{{NEW_LINE}}"; /** * Transforms DTO validation annotation failures to proper error messages to be returned to the client via HTTP * headers.<br> * Annotations like {@link javax.validation.constraints.Size @Size}, * {@link javax.validation.constraints.NotNull @NotNull} or {@link javax.validation.constraints.Pattern @Pattern}. * * @param ex the validation exception with field binding errors * @param headers the headers where errors will be written to the response * @param status (unused) * @param request the current request, whose resource name is extracted * @return a Bad Request response entity with populated errors in headers */ @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { StringBuilder message = new StringBuilder(); for (FieldError error : ex.getBindingResult().getFieldErrors()) { message .append((message.length() == 0) ? "" : MESSAGE_SEPARATOR) .append(error.getDefaultMessage()); } headers.add(HeaderUtil.MESSAGE, message.toString()); headers.add(HeaderUtil.ERROR, "error.validation"); headers.add(HeaderUtil.PARAMS, getResourceName(request)); return ResponseEntity.badRequest().headers(headers).build(); } /** * Returns the resource name for a given API URL.<br> * If the URL is a project URL, "projects" is returned.<br> * If the URL is a resource inside a project, that resource name is returned. * * @param request the HTTP request made to the ARA's API server * (with eg. URL "/api/projects/some-project/some-resources/api") * @return the name of the resource from the URL of the request (eg. "some-resources") */ String getResourceName(WebRequest request) { String description = request.getDescription(false); String[] uriParts = description.split("/"); String resourceName; if (uriParts.length >= 5) { resourceName = uriParts[4]; } else if (uriParts.length >= 3) { resourceName = uriParts[2]; // TODO Will return plural version ("countries" instead of "country") } else { log.error("No resource in {}", description); resourceName = "unknown"; } return resourceName; } }
922e97a9af272556958a769bfe9b5564db1b58cc
1,174
java
Java
hasor-db/src/main/java/net/hasor/db/jdbc/PreparedStatementCallback.java
yanqinghao/hasor
362f23024b7fee679083c510c888826008bf2708
[ "Apache-2.0" ]
828
2015-01-07T04:49:44.000Z
2021-06-01T06:52:08.000Z
hasor-db/src/main/java/net/hasor/db/jdbc/PreparedStatementCallback.java
giscafer/hasor
3c7f5a99d908abca217d2ba145cb900a095048bc
[ "Apache-2.0" ]
89
2018-11-02T09:32:41.000Z
2021-05-31T16:28:47.000Z
hasor-db/src/main/java/net/hasor/db/jdbc/PreparedStatementCallback.java
giscafer/hasor
3c7f5a99d908abca217d2ba145cb900a095048bc
[ "Apache-2.0" ]
248
2015-01-29T02:39:14.000Z
2021-05-31T08:58:54.000Z
33.428571
77
0.735897
994,797
/* * Copyright 2002-2008 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 net.hasor.db.jdbc; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 通用的回调接口。用来执行基于 {@link PreparedStatement} 上的任意数量任意类型数据库操作。 * @version : 2013-10-9 * @author Thomas Risberg * @author Juergen Hoeller * @author 赵永春 (kenaa@example.com) */ @FunctionalInterface public interface PreparedStatementCallback<T> { /** * 执行一个 JDBC 操作。开发者不需要关心数据库连接的状态和事务。 * @param ps 一个可用的 PreparedStatement 对象连接 * @return 返回操作执行的最终结果。 */ public T doInPreparedStatement(PreparedStatement ps) throws SQLException; }
922e98b7ffe51362af1c5301d347c90547509a5a
2,283
java
Java
nginious-server/src/test/java/com/nginious/http/serialize/SerializableArrayBean.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-server/src/test/java/com/nginious/http/serialize/SerializableArrayBean.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-server/src/test/java/com/nginious/http/serialize/SerializableArrayBean.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
23.060606
75
0.755147
994,798
/** * Copyright 2012 NetDigital Sweden AB * * 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.nginious.http.serialize; import com.nginious.http.annotation.Serializable; @Serializable public class SerializableArrayBean { private boolean[] booleanArrayValue; private double[] doubleArrayValue; private float[] floatArrayValue; private int[] intArrayValue; private long[] longArrayValue; private short[] shortArrayValue; private String[] stringArrayValue; public SerializableArrayBean() { super(); } public boolean[] getBooleanArrayValue() { return booleanArrayValue; } public void setBooleanArrayValue(boolean[] booleanArrayValue) { this.booleanArrayValue = booleanArrayValue; } public double[] getDoubleArrayValue() { return doubleArrayValue; } public void setDoubleArrayValue(double[] doubleArrayValue) { this.doubleArrayValue = doubleArrayValue; } public float[] getFloatArrayValue() { return floatArrayValue; } public void setFloatArrayValue(float[] floatArrayValue) { this.floatArrayValue = floatArrayValue; } public int[] getIntArrayValue() { return intArrayValue; } public void setIntArrayValue(int[] intArrayValue) { this.intArrayValue = intArrayValue; } public long[] getLongArrayValue() { return longArrayValue; } public void setLongArrayValue(long[] longArrayValue) { this.longArrayValue = longArrayValue; } public short[] getShortArrayValue() { return shortArrayValue; } public void setShortArrayValue(short[] shortArrayValue) { this.shortArrayValue = shortArrayValue; } public String[] getStringArrayValue() { return this.stringArrayValue; } public void setStringArrayValue(String[] stringArrayValue) { this.stringArrayValue = stringArrayValue; } }
922e9913692e5f4f1df943c240327a62af30e99a
3,205
java
Java
src/test/java/org/syphr/puzzle/coins/RunnerTest.java
syphr42/puzzle-coins
bcd5f87412e899aad0010f17218e010247b249f8
[ "Apache-2.0" ]
null
null
null
src/test/java/org/syphr/puzzle/coins/RunnerTest.java
syphr42/puzzle-coins
bcd5f87412e899aad0010f17218e010247b249f8
[ "Apache-2.0" ]
null
null
null
src/test/java/org/syphr/puzzle/coins/RunnerTest.java
syphr42/puzzle-coins
bcd5f87412e899aad0010f17218e010247b249f8
[ "Apache-2.0" ]
null
null
null
30.52381
92
0.604368
994,799
/** * Copyright 2018 Gregory Moyer and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.syphr.puzzle.coins; import static org.junit.jupiter.api.Assertions.*; import static org.syphr.puzzle.coins.DataGenerator.*; import java.util.Arrays; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; import org.syphr.puzzle.coins.RunResult.Outcome; class RunnerTest { @Test void success() { Runner runner = new Runner(new Strategy() { @Override public Coin findUnique(Set<Coin> coins, Scale scale) { scale.compare(coin(1), coin(1)); return coins.iterator().next(); } }); List<Coin> coins = coins(1); Scenario scenario = scenario(coins, coins.get(0)); List<RunResult> results = runner.run(new MonitoredScale(), Arrays.asList(scenario)); assertEquals(1, results.size()); RunResult result = results.get(0); assertEquals(Outcome.SUCCESS, result.getOutcome()); assertEquals(1, result.getWeighings()); } @Test void noCoinFound() { Runner runner = new Runner(new Strategy() { @Override public Coin findUnique(Set<Coin> coins, Scale scale) { scale.compare(coin(1), coin(1)); scale.compare(coin(1), coin(1)); return null; } }); List<Coin> coins = coins(1); Scenario scenario = scenario(coins, coins.get(0)); List<RunResult> results = runner.run(new MonitoredScale(), Arrays.asList(scenario)); assertEquals(1, results.size()); RunResult result = results.get(0); assertEquals(Outcome.NO_COIN, result.getOutcome()); assertEquals(2, result.getWeighings()); } @Test void wrongCoinFound() { Runner runner = new Runner(new Strategy() { @Override public Coin findUnique(Set<Coin> coins, Scale scale) { scale.compare(coin(1), coin(1)); scale.compare(coin(1), coin(1)); scale.compare(coin(1), coin(1)); return coins.iterator().next(); } }); List<Coin> coins = coins(1, 2); Scenario scenario = scenario(coins, coins.get(1)); List<RunResult> results = runner.run(new MonitoredScale(), Arrays.asList(scenario)); assertEquals(1, results.size()); RunResult result = results.get(0); assertEquals(Outcome.WRONG_COIN, result.getOutcome()); assertEquals(3, result.getWeighings()); } }
922e99920cbb6a000714846f3144bf2c84483e38
880
java
Java
spring-boot-demo-nacos/src/main/java/com/xkcoding/nacos/controller/DiscoverController.java
angke666/spring-boot-demo
cb53b87bd8b0749bb868f02169984369e74f6a74
[ "MIT" ]
null
null
null
spring-boot-demo-nacos/src/main/java/com/xkcoding/nacos/controller/DiscoverController.java
angke666/spring-boot-demo
cb53b87bd8b0749bb868f02169984369e74f6a74
[ "MIT" ]
null
null
null
spring-boot-demo-nacos/src/main/java/com/xkcoding/nacos/controller/DiscoverController.java
angke666/spring-boot-demo
cb53b87bd8b0749bb868f02169984369e74f6a74
[ "MIT" ]
null
null
null
28.387097
93
0.785227
994,800
package com.xkcoding.nacos.controller; import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @ClassName DiscoverController * @Description TODO * @Author 钱进 * @Date 2020/6/9 17:36 * @Version 1.0 **/ @RestController public class DiscoverController { @NacosInjected private NamingService namingService; @GetMapping("/discovery") public List<Instance> discovery(@RequestParam String serviceName) throws NacosException { return namingService.getAllInstances(serviceName); } }
922e9afc2be57bba2e4cc759fa7716fa1e49e08c
6,486
java
Java
src/zeprs/org/cidrz/webapp/dynasite/struts/action/EncounterArchiveListAction.java
ICTatRTI/zeprs
1a41ef20cc4c0e59e506d0c9eca8e926b07b9c8c
[ "Apache-2.0" ]
3
2017-12-27T19:21:36.000Z
2020-03-24T13:19:06.000Z
src/zeprs/org/cidrz/webapp/dynasite/struts/action/EncounterArchiveListAction.java
ICTatRTI/zeprs
1a41ef20cc4c0e59e506d0c9eca8e926b07b9c8c
[ "Apache-2.0" ]
null
null
null
src/zeprs/org/cidrz/webapp/dynasite/struts/action/EncounterArchiveListAction.java
ICTatRTI/zeprs
1a41ef20cc4c0e59e506d0c9eca8e926b07b9c8c
[ "Apache-2.0" ]
6
2018-01-10T15:34:11.000Z
2020-03-09T08:24:03.000Z
39.072289
152
0.694419
994,801
/* * Copyright 2003, 2004, 2005, 2006 Research Triangle Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ package org.cidrz.webapp.dynasite.struts.action; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.cidrz.webapp.dynasite.dao.EncounterValueArchiveDAO; import org.cidrz.webapp.dynasite.struts.action.generic.BaseAction; import org.cidrz.webapp.dynasite.utils.DatabaseUtils; import org.cidrz.webapp.dynasite.utils.DateUtils; import org.cidrz.webapp.dynasite.valueobject.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.Principal; import java.sql.Connection; import java.sql.Date; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; /** * Provides listing of changes to values in an encounter. */ public class EncounterArchiveListAction extends BaseAction { /** * Commons Logging instance. */ private static Log log = LogFactory.getFactory().getInstance(EncounterArchiveListAction.class); protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Principal userPrincipal = request.getUserPrincipal(); String username = userPrincipal.getName(); Date beginDate = null; Date endDate = null; String task = null; String zeprsId = null; // month java.util.Calendar c = java.util.Calendar.getInstance(); c.add(java.util.Calendar.MONTH, -1); java.util.Date date1monthpast = c.getTime(); String DATE_FORMAT = "yyyy-MM-dd"; java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(TimeZone.getDefault()); String date1monthpastStr = sdf.format(date1monthpast); java.sql.Date date1monthpastSql = java.sql.Date.valueOf(date1monthpastStr); request.setAttribute("date1monthpast", date1monthpast); request.setAttribute("date1monthpastSql", date1monthpastSql); java.sql.Date dateNow = DateUtils.getNow(); request.setAttribute("dateNow", dateNow); // week java.util.Calendar c2 = java.util.Calendar.getInstance(); c2.add(java.util.Calendar.WEEK_OF_YEAR, -1); java.util.Date date1weekpast = c2.getTime(); java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat(DATE_FORMAT); sdf2.setTimeZone(TimeZone.getDefault()); String date1weekpastStr = sdf2.format(date1weekpast); java.sql.Date date1weekpastSql = java.sql.Date.valueOf(date1weekpastStr); request.setAttribute("date1weekpastSql", date1weekpastSql); // quarter java.util.Calendar c3 = java.util.Calendar.getInstance(); c3.add(java.util.Calendar.MONTH, -3); java.util.Date quarterPast = c3.getTime(); java.text.SimpleDateFormat sdf3 = new java.text.SimpleDateFormat(DATE_FORMAT); sdf2.setTimeZone(TimeZone.getDefault()); String quarterPastStr = sdf3.format(quarterPast); java.sql.Date quarterPastSql = java.sql.Date.valueOf(quarterPastStr); request.setAttribute("quarterPastSql", quarterPastSql); //String systemState = String.valueOf(SystemStateManager.getCurrentState()); //request.setAttribute("systemState",systemState); if (request.getParameter("bdate") != null) { beginDate = Date.valueOf(String.valueOf(request.getParameter("bdate"))); request.setAttribute("date1weekpastSql", beginDate); } else { beginDate = date1weekpastSql; } if (request.getParameter("edate") != null) { endDate = Date.valueOf(String.valueOf(request.getParameter("edate"))); request.setAttribute("endDate", endDate); } else { endDate = dateNow; } if (request.getParameter("task") != null) { task = String.valueOf(request.getParameter("task")); } if (request.getParameter("zeprsId") != null) { zeprsId = String.valueOf(request.getParameter("zeprsId")); } Connection conn = null; try { conn = DatabaseUtils.getZEPRSConnection(username); List resolvedItems = new ArrayList(); List items = null; if (zeprsId != null) { items = EncounterValueArchiveDAO.getAll(conn, zeprsId); } else { items = EncounterValueArchiveDAO.getAll(conn, beginDate, endDate); } for (int i = 0; i < items.size(); i++) { EncounterValueArchive encounterValueArchive = (EncounterValueArchive) items.get(i); Long pageItemId = encounterValueArchive.getPageItemId(); PageItem pageItem = (PageItem) DynaSiteObjects.getPageItems().get(pageItemId); Long value = null; Long previousValue = null; if (pageItem != null) { FormField formField = null; try { formField = pageItem.getForm_field(); } catch (Exception e) { log.error(e); } try { value = Long.decode(encounterValueArchive.getValue()); previousValue = Long.decode(encounterValueArchive.getPreviousValue()); if (formField.getType().equals("Enum")) { try { FieldEnumeration fieldEnum = (FieldEnumeration) DynaSiteObjects.getFieldEnumerations().get(value); encounterValueArchive.setValue(fieldEnum.getEnumeration()); FieldEnumeration fieldEnum2 = (FieldEnumeration) DynaSiteObjects.getFieldEnumerations().get(previousValue); encounterValueArchive.setPreviousValue(fieldEnum2.getEnumeration()); } catch (Exception e) { // it's ok } } } catch (NumberFormatException e) { // it's not an enum, or is something else... } } else { // value = encounterValueArchive.getValue(); // previousValue = encounterValueArchive.getPreviousValue(); } resolvedItems.add(encounterValueArchive); } request.setAttribute("items", resolvedItems); } catch (ServletException e) { log.error(e); } finally { if (conn != null && !conn.isClosed()) { conn.close(); } } return mapping.findForward("success"); } }
922e9bf99ac5e4f53708670be5c5f67a44543d62
2,554
java
Java
zeus-webapp/src/main/java/com/zmops/iot/web/product/controller/ProductServiceController.java
jiumoji/zeus-iot
3c747397b2f37a21fa9b1c6e9eac8f310da7b163
[ "Apache-2.0" ]
513
2021-08-19T05:39:53.000Z
2022-03-23T06:48:41.000Z
zeus-webapp/src/main/java/com/zmops/iot/web/product/controller/ProductServiceController.java
jiumoji/zeus-iot
3c747397b2f37a21fa9b1c6e9eac8f310da7b163
[ "Apache-2.0" ]
2
2022-02-09T07:21:24.000Z
2022-02-09T10:15:18.000Z
zeus-webapp/src/main/java/com/zmops/iot/web/product/controller/ProductServiceController.java
jiumoji/zeus-iot
3c747397b2f37a21fa9b1c6e9eac8f310da7b163
[ "Apache-2.0" ]
83
2021-08-28T20:52:25.000Z
2022-03-30T01:22:20.000Z
32.329114
118
0.738841
994,802
package com.zmops.iot.web.product.controller; import com.zmops.iot.domain.BaseEntity; import com.zmops.iot.model.page.Pager; import com.zmops.iot.model.response.ResponseData; import com.zmops.iot.web.product.dto.ProductServiceDto; import com.zmops.iot.web.product.dto.param.ProductSvcParam; import com.zmops.iot.web.product.service.ProductSvcService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author nantian created at 2021/8/4 16:33 * <p> * 产品物模型: 服务 */ @RestController @RequestMapping("/product/service") public class ProductServiceController { @Autowired ProductSvcService productSvcService; /** * 服务分页列表 */ @RequestMapping("/getServiceByPage") public Pager<ProductServiceDto> getServiceByPage(@Validated @RequestBody ProductSvcParam productSvcParam) { return productSvcService.getServiceByPage(productSvcParam); } /** * 服务列表 */ @RequestMapping("/list") public ResponseData list(@Validated @RequestBody ProductSvcParam productSvcParam) { return ResponseData.success(productSvcService.list(productSvcParam)); } /** * 根据服务 获取参数列表 */ @RequestMapping("/param/list") public ResponseData paramList(@RequestParam("serviceId") long serviceId) { return ResponseData.success(productSvcService.paramList(serviceId)); } /** * 服务创建 */ @RequestMapping("/create") public ResponseData create(@Validated(BaseEntity.Create.class) @RequestBody ProductServiceDto productServiceDto) { productServiceDto.setId(null); return ResponseData.success(productSvcService.create(productServiceDto)); } /** * 服务修改 */ @RequestMapping("/update") public ResponseData update(@Validated(BaseEntity.Update.class) @RequestBody ProductServiceDto productServiceDto) { return ResponseData.success(productSvcService.update(productServiceDto)); } /** * 服务删除 */ @RequestMapping("/delete") public ResponseData delete(@Validated(BaseEntity.Delete.class) @RequestBody ProductServiceDto productServiceDto) { productSvcService.delete(productServiceDto.getIds()); return ResponseData.success(productServiceDto.getIds()); } }
922e9c25a7e30072a0cb8804b724d8dc60cb4fe2
971
java
Java
src/main/java/com/badfic/philbot/data/phil/MemeCommandEntity.java
badfic/phil-bot-java
7a811363bf468fbfc494910eba86ef736ae3fc29
[ "Apache-2.0" ]
2
2020-11-20T09:28:52.000Z
2020-12-11T03:45:06.000Z
src/main/java/com/badfic/philbot/data/phil/MemeCommandEntity.java
badfic/phil-bot-java
7a811363bf468fbfc494910eba86ef736ae3fc29
[ "Apache-2.0" ]
63
2020-09-24T21:49:43.000Z
2022-01-04T09:47:44.000Z
src/main/java/com/badfic/philbot/data/phil/MemeCommandEntity.java
badfic/phil-bot-java
7a811363bf468fbfc494910eba86ef736ae3fc29
[ "Apache-2.0" ]
2
2020-10-19T03:50:14.000Z
2020-12-23T23:07:34.000Z
17.654545
55
0.639547
994,803
package com.badfic.philbot.data.phil; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "meme_command") public class MemeCommandEntity { @Id private String name; @Column private String url; @Transient private Boolean urlIsImage; public MemeCommandEntity() { } public MemeCommandEntity(String name, String url) { this.name = name; this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Boolean getUrlIsImage() { return urlIsImage; } public void setUrlIsImage(Boolean urlIsImage) { this.urlIsImage = urlIsImage; } }
922e9c85c3d37948f054ea315851ada2eb681a38
436
java
Java
PaymentsDemo/src/main/java/com/cloudelements/demo/util/CustomSessionTokenService.java
GuyVanWert/usecase-references
56c102377dfaab801d75073aa8b546cb5c8b887a
[ "MIT" ]
null
null
null
PaymentsDemo/src/main/java/com/cloudelements/demo/util/CustomSessionTokenService.java
GuyVanWert/usecase-references
56c102377dfaab801d75073aa8b546cb5c8b887a
[ "MIT" ]
null
null
null
PaymentsDemo/src/main/java/com/cloudelements/demo/util/CustomSessionTokenService.java
GuyVanWert/usecase-references
56c102377dfaab801d75073aa8b546cb5c8b887a
[ "MIT" ]
1
2020-11-18T20:09:48.000Z
2020-11-18T20:09:48.000Z
22.947368
103
0.763761
994,804
package com.cloudelements.demo.util; import org.springframework.stereotype.Service; import lombok.Data; /* * Acts as a singleton throughout the entire app. * Upon element selection, the element String is set * Upon retrieval of the token response via the exposed /authListener webhook, the sessionToken is set */ @Service @Data public class CustomSessionTokenService { public String token = ""; public String element = ""; }
922e9cbda20f75c35d1a83aabcaff6d3e0c5a0dd
3,595
java
Java
src/test/java/eu/unicore/security/consignor/SimpleGenerateTest.java
UNICORE-EU/securityLibrary
91cf905ae173033f4029d36c519447594859a75b
[ "BSD-3-Clause" ]
1
2020-05-15T18:23:32.000Z
2020-05-15T18:23:32.000Z
src/test/java/eu/unicore/security/consignor/SimpleGenerateTest.java
UNICORE-EU/securityLibrary
91cf905ae173033f4029d36c519447594859a75b
[ "BSD-3-Clause" ]
1
2021-12-10T13:06:01.000Z
2021-12-10T13:06:01.000Z
src/test/java/eu/unicore/security/consignor/SimpleGenerateTest.java
UNICORE-EU/securityLibrary
91cf905ae173033f4029d36c519447594859a75b
[ "BSD-3-Clause" ]
null
null
null
29.219512
115
0.70256
994,805
/* * Copyright (c) 2007, 2008 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licencing information. * * Created on Apr 25, 2007 * Author: K. Benedyczak <lyhxr@example.com> */ package eu.unicore.security.consignor; import static org.junit.Assert.*; import java.security.cert.X509Certificate; import javax.security.auth.x500.X500Principal; import org.junit.Test; import eu.emi.security.authn.x509.impl.X500NameUtils; import eu.unicore.samly2.SAMLConstants.AuthNClasses; import eu.unicore.security.TestBase; import eu.unicore.security.UnicoreSecurityFactory; import eu.unicore.security.ValidationResult; import xmlbeans.org.oasis.saml2.assertion.AssertionDocument; /** * @author K. Benedyczak */ public class SimpleGenerateTest extends TestBase { @Test public void test1() { try { ConsignorAPI impl = UnicoreSecurityFactory.getConsignorAPI(); ConsignorAssertion token = impl.generateConsignorToken(issuerDN2, issuerCert1, privKey2, 0, 5, AuthNClasses.TLS, "127.0.0.1"); System.out.println("-------------------------------------------\n" + "Consignor token:"); System.out.println(token.getXMLBeanDoc().xmlText(xmlOpts)); AssertionDocument doc = token.getXMLBeanDoc(); ConsignorAssertion parsedToken = new ConsignorAssertion(doc); if (!parsedToken.isSigned()) fail("Assertion doesn't report itself as signed"); ValidationResult res = impl.verifyConsignorToken(parsedToken, issuerCert2[0]); if (!res.isValid()) fail(res.getInvalidResaon()); assertEquals("127.0.0.1", parsedToken.getXMLBean().getAuthnStatementArray(0).getSubjectLocality().getAddress()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(true); } @Test public void test2() { try { ConsignorAPI impl = UnicoreSecurityFactory.getConsignorAPI(); X500Principal c1 = issuerCert1[0].getSubjectX500Principal(); ConsignorAssertion token = impl.generateConsignorToken(issuerDN2, issuerCert1, AuthNClasses.TLS, "127.0.0.1"); System.out.println("-------------------------------------------\n" + "Consignor token:"); System.out.println(token.getXMLBeanDoc().xmlText(xmlOpts)); AssertionDocument doc = token.getXMLBeanDoc(); ConsignorAssertion parsedToken = new ConsignorAssertion(doc); if (parsedToken.isSigned()) fail("Assertion maliciously report itself as signed"); ValidationResult res = impl.verifyConsignorToken(parsedToken, issuerCert2[0]); if (!res.isValid()) fail(res.getInvalidResaon()); X509Certificate []cert = parsedToken.getConsignor(); X500Principal c2 = cert[0].getSubjectX500Principal(); System.out.println("Consignor read back is: " + c2); if (!X500NameUtils.rfc3280Equal(c1, c2)) fail("Consignor is not the same after parsing"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(true); } @Test public void testExpiredCert1() { try { ConsignorAPI impl = UnicoreSecurityFactory.getConsignorAPI(); ConsignorAssertion token = impl.generateConsignorToken(issuerDN2, expiredCert, AuthNClasses.TLS, "127.0.0.1"); AssertionDocument doc = token.getXMLBeanDoc(); ConsignorAssertion parsedToken = new ConsignorAssertion(doc); ValidationResult res = impl.verifyConsignorToken(parsedToken, expiredCert[0]); if (res.isValid()) fail("Assertion issued with expired cert was accepted"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } assertTrue(true); } }
922e9cf9127e3eddc47fb5eac0844fd6272f98aa
10,617
java
Java
src/libSBML/src/bindings/java/java-files/org/sbml/libsbml/SBMLIdConverter.java
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
src/libSBML/src/bindings/java/java-files/org/sbml/libsbml/SBMLIdConverter.java
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
src/libSBML/src/bindings/java/java-files/org/sbml/libsbml/SBMLIdConverter.java
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
36.993031
116
0.710182
994,806
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.2 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.sbml.libsbml; /** * Converter for replacing object identifiers. <p> * <p style='color: #777; font-style: italic'> This class of objects is defined by libSBML only and has no direct equivalent in terms of SBML components. It is a class used in the implementation of extra functionality provided by libSBML. </p> <p> * This converter translates all instances of a given identifier (i.e., SBML object 'id' * attribute value) of type 'SId' in a {@link Model} to another identifier. It does this based on a list of source * identifiers, translating each one to its corresponding replacement value * in a list of replacement identifiers. It also updates all references to * the identifiers so replaced. (More technically, it replaces all values * known as type <code>SIdRef</code> in the SBML Level&nbsp;3 specifications.) <p> * This converter only searches the global SId namespace for the {@link Model} child of the * {@link SBMLDocument}. It does not replace any IDs or SIdRefs for LocalParameters, nor * does it replace any UnitSIds or UnitSIdRefs. It likewise does not replace any IDs * in a new namespace introduced by a package, such as the PortSId namespace * from the Hierarchical Model Composition package, nor any {@link Model} objects that are * not the direct child of the {@link SBMLDocument}, such as the ModelDefinitions from * the Hierarchical Model Composition package. <p> * If, however, a package introduces a new element with an 'id' attribute * of type SId, any attribute of type SIdRef, or child of type SIdRef (such as * a new Math child of a package element), those IDs will be replaced if they * match a source identifier. <p> * <h2>Configuration and use of {@link SBMLIdConverter}</h2> <p> * {@link SBMLIdConverter} is enabled by creating a {@link ConversionProperties} object with * the option <code>'renameSIds'</code>, and passing this properties object to * {@link SBMLDocument#convert(ConversionProperties)}. * The converter accepts two options, and both must * be set or else no conversion is performed: <p> * <ul> * <li> <code>'currentIds':</code> A comma-separated list of identifiers to replace. * <li> <code>'newIds':</code> A comma-separated list of identifiers to use as the * replacements. The values should correspond one-to-one with the identifiers * in <code>'currentIds'</code> that should be replaced. * * </ul> <p> * <p> * <h2>General information about the use of SBML converters</h2> <p> * The use of all the converters follows a similar approach. First, one * creates a {@link ConversionProperties} object and calls * {@link ConversionProperties#addOption(ConversionOption)} * on this object with one argument: a text string that identifies the desired * converter. (The text string is specific to each converter; consult the * documentation for a given converter to find out how it should be enabled.) <p> * Next, for some converters, the caller can optionally set some * converter-specific properties using additional calls to * {@link ConversionProperties#addOption(ConversionOption)}. * Many converters provide the ability to * configure their behavior to some extent; this is realized through the use * of properties that offer different options. The default property values * for each converter can be interrogated using the method * {@link SBMLConverter#getDefaultProperties()} on the converter class in question . <p> * Finally, the caller should invoke the method * {@link SBMLDocument#convert(ConversionProperties)} * with the {@link ConversionProperties} object as an argument. <p> * <h3>Example of invoking an SBML converter</h3> <p> * The following code fragment illustrates an example using * {@link SBMLReactionConverter}, which is invoked using the option string * <code>'replaceReactions':</code> <p> <pre class='fragment'> {@link ConversionProperties} props = new {@link ConversionProperties}(); if (props != null) { props.addOption('replaceReactions'); } else { // Deal with error. } </pre> <p> * In the case of {@link SBMLReactionConverter}, there are no options to affect * its behavior, so the next step is simply to invoke the converter on * an {@link SBMLDocument} object. Continuing the example code: <p> <pre class='fragment'> // Assume that the variable 'document' has been set to an {@link SBMLDocument} object. status = document.convert(config); if (status != libsbml.LIBSBML_OPERATION_SUCCESS) { // Handle error somehow. System.out.println('Error: conversion failed due to the following:'); document.printErrors(); } </pre> <p> * Here is an example of using a converter that offers an option. The * following code invokes {@link SBMLStripPackageConverter} to remove the * SBML Level&nbsp;3 <em>Layout</em> package from a model. It sets the name * of the package to be removed by adding a value for the option named * <code>'package'</code> defined by that converter: <p> <pre class='fragment'> {@link ConversionProperties} config = new {@link ConversionProperties}(); if (config != None) { config.addOption('stripPackage'); config.addOption('package', 'layout'); status = document.convert(config); if (status != LIBSBML_OPERATION_SUCCESS) { // Handle error somehow. System.out.println('Error: unable to strip the Layout package'); document.printErrors(); } } else { // Handle error somehow. System.out.println('Error: unable to create {@link ConversionProperties} object'); } </pre> <p> * <h3>Available SBML converters in libSBML</h3> <p> * LibSBML provides a number of built-in converters; by convention, their * names end in <em>Converter</em>. The following are the built-in converters * provided by libSBML 5.19.0: <p> * @copydetails doc_list_of_libsbml_converters */ public class SBMLIdConverter extends SBMLConverter { private long swigCPtr; protected SBMLIdConverter(long cPtr, boolean cMemoryOwn) { super(libsbmlJNI.SBMLIdConverter_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } protected static long getCPtr(SBMLIdConverter obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected static long getCPtrAndDisown (SBMLIdConverter obj) { long ptr = 0; if (obj != null) { ptr = obj.swigCPtr; obj.swigCMemOwn = false; } return ptr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; libsbmlJNI.delete_SBMLIdConverter(swigCPtr); } swigCPtr = 0; } super.delete(); } /** * @internal */ public static void init() { libsbmlJNI.SBMLIdConverter_init(); } /** * Creates a new {@link SBMLIdConverter} object. */ public SBMLIdConverter() { this(libsbmlJNI.new_SBMLIdConverter__SWIG_0(), true); } /** * Copy constructor; creates a copy of an {@link SBMLIdConverter} * object. <p> * @param obj the {@link SBMLIdConverter} object to copy. */ public SBMLIdConverter(SBMLIdConverter obj) { this(libsbmlJNI.new_SBMLIdConverter__SWIG_1(SBMLIdConverter.getCPtr(obj), obj), true); } /** * Creates and returns a deep copy of this {@link SBMLIdConverter} * object. <p> * @return a (deep) copy of this converter. */ public SBMLConverter cloneObject() { long cPtr = libsbmlJNI.SBMLIdConverter_cloneObject(swigCPtr, this); return (cPtr == 0) ? null : new SBMLIdConverter(cPtr, true); } /** * Returns <code>true</code> if this converter object's properties match the given * properties. <p> * A typical use of this method involves creating a {@link ConversionProperties} * object, setting the options desired, and then calling this method on * an {@link SBMLIdConverter} object to find out if the object's * property values match the given ones. This method is also used by * {@link SBMLConverterRegistry#getConverterFor(ConversionProperties)} * to search across all registered converters for one matching particular * properties. <p> * @param props the properties to match. <p> * @return <code>true</code> if this converter's properties match, <code>false</code> * otherwise. */ public boolean matchesProperties(ConversionProperties props) { return libsbmlJNI.SBMLIdConverter_matchesProperties(swigCPtr, this, ConversionProperties.getCPtr(props), props); } /** * Perform the conversion. <p> * This method causes the converter to do the actual conversion work, * that is, to convert the {@link SBMLDocument} object set by * {@link SBMLConverter#setDocument(SBMLDocument)} and * with the configuration options set by * {@link SBMLConverter#setProperties(ConversionProperties)}. <p> * <p> * @return integer value indicating success/failure of the * function. The possible values * returned by this function are: * <ul> * <li> {@link libsbmlConstants#LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS} * <li> {@link libsbmlConstants#LIBSBML_OPERATION_FAILED LIBSBML_OPERATION_FAILED} * <li> {@link libsbmlConstants#LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT} * <li> {@link libsbmlConstants#LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE} * <li> {@link libsbmlConstants#LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE} * </ul> */ public int convert() { return libsbmlJNI.SBMLIdConverter_convert(swigCPtr, this); } /** * Returns the default properties of this converter. <p> * A given converter exposes one or more properties that can be adjusted * in order to influence the behavior of the converter. This method * returns the <em>default</em> property settings for this converter. It is * meant to be called in order to discover all the settings for the * converter object. <p> * @return the {@link ConversionProperties} object describing the default properties * for this converter. */ public ConversionProperties getDefaultProperties() { return new ConversionProperties(libsbmlJNI.SBMLIdConverter_getDefaultProperties(swigCPtr, this), true); } }
922e9ddaaeba64c562fb7a8a3a755f2c346f0e38
1,893
java
Java
streamx-console/streamx-console-service/src/main/java/com/streamxhub/streamx/console/base/utils/IPUtil.java
LinMingQiang/streamx
f19fb87a64b81759f6672f24ff3e0a0e06a50310
[ "ECL-2.0", "Apache-2.0" ]
4
2021-06-08T06:12:15.000Z
2021-08-02T02:30:53.000Z
streamx-console/streamx-console-service/src/main/java/com/streamxhub/streamx/console/base/utils/IPUtil.java
wkwzzc/streamx
ddb3c7c243407738b8f0a029291188f9fdd76e3b
[ "ECL-2.0", "Apache-2.0" ]
1
2021-04-25T01:58:13.000Z
2021-04-25T01:58:13.000Z
streamx-console/streamx-console-service/src/main/java/com/streamxhub/streamx/console/base/utils/IPUtil.java
wkwzzc/streamx
ddb3c7c243407738b8f0a029291188f9fdd76e3b
[ "ECL-2.0", "Apache-2.0" ]
2
2021-06-08T09:05:09.000Z
2021-08-02T03:20:48.000Z
35.716981
99
0.671421
994,807
/* * Copyright (c) 2019 The StreamX Project * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.streamxhub.streamx.console.base.utils; import javax.servlet.http.HttpServletRequest; /** * @author benjobs */ public class IPUtil { private static final String UNKNOWN = "unknown"; protected IPUtil() { } /** * 获取 IP地址 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址, X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址 */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; } }
922e9f8bc401f1f4d43fdae56f2099bedd0af017
1,208
java
Java
datahub-sdk-public/src/main/java/com/aliyun/datahub/model/UpdateSubscriptionRequest.java
chzeze/aliyun-datahub-sdk-java
ec849bd450ac66c35970efb0d51cc2d3e5fa4eec
[ "Apache-2.0" ]
18
2017-01-09T15:06:19.000Z
2021-10-12T06:49:34.000Z
datahub-sdk-public/src/main/java/com/aliyun/datahub/model/UpdateSubscriptionRequest.java
chzeze/aliyun-datahub-sdk-java
ec849bd450ac66c35970efb0d51cc2d3e5fa4eec
[ "Apache-2.0" ]
2
2018-11-02T01:51:31.000Z
2018-11-29T10:01:07.000Z
datahub-sdk-public/src/main/java/com/aliyun/datahub/model/UpdateSubscriptionRequest.java
chzeze/aliyun-datahub-sdk-java
ec849bd450ac66c35970efb0d51cc2d3e5fa4eec
[ "Apache-2.0" ]
16
2017-02-08T03:02:39.000Z
2021-03-26T11:42:54.000Z
24.16
98
0.611755
994,808
package com.aliyun.datahub.model; import com.aliyun.datahub.exception.InvalidParameterException; public class UpdateSubscriptionRequest { private String projectName; private String topicName; private String subId; private String comment; public UpdateSubscriptionRequest(String project, String topic, String subId, String comment) { if (project == null) { throw new InvalidParameterException("project name is null"); } if (topic == null) { throw new InvalidParameterException("topic name is null"); } if (subId == null) { throw new InvalidParameterException("sub id is null"); } if (comment == null) { throw new InvalidParameterException("comment is null"); } this.projectName = project; this.topicName = topic; this.subId = subId; this.comment = comment; } public String getProjectName() { return projectName; } public String getTopicName() { return topicName; } public String getSubId() { return subId; } public String getComment() { return comment; } }
922e9fda51316aeefa930642b53ac9586fac86a3
513
java
Java
sandbox/src/main/java/stqa/pft/sandbox/MyFirstProgram.java
ccbooba/java_pft
9b06005eab162ff3e142e8de468284851b9604f3
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/stqa/pft/sandbox/MyFirstProgram.java
ccbooba/java_pft
9b06005eab162ff3e142e8de468284851b9604f3
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/stqa/pft/sandbox/MyFirstProgram.java
ccbooba/java_pft
9b06005eab162ff3e142e8de468284851b9604f3
[ "Apache-2.0" ]
null
null
null
23.318182
114
0.615984
994,809
package stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] args) { hello("World"); Square s = new Square(6); Rectangle r = new Rectangle(3,4); System.out.println("Area of a square with side length of " + s.l + " equals " + s.area()); System.out.println("Area of a rectangle with side lengths of " + r.a + " and " + r.b + " equals " + r.area()); } public static void hello(String somebody) { System.out.println("Hello, " + somebody + "!"); } }
922ea00faf3cea0347fad381ea3e927788d42d85
2,014
java
Java
server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtConfiguration.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
78
2016-03-16T19:50:28.000Z
2022-01-29T10:36:15.000Z
server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtConfiguration.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
4,148
2015-09-14T15:59:06.000Z
2022-03-31T10:29:10.000Z
server/protocols/jwt/src/main/java/org/apache/james/jwt/JwtConfiguration.java
codejamninja/james-project
6ce8443b69e8e0d6576c42c9c14b8a0e5d54e9c1
[ "Apache-2.0" ]
64
2015-07-10T14:59:52.000Z
2021-12-24T09:40:29.000Z
44.755556
106
0.599801
994,810
/**************************************************************** * 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.james.jwt; import java.util.Optional; import com.google.common.base.Preconditions; public class JwtConfiguration { private static final boolean DEFAULT_VALUE = true; private final Optional<String> jwtPublicKeyPem; public JwtConfiguration(Optional<String> jwtPublicKeyPem) { Preconditions.checkState(validPublicKey(jwtPublicKeyPem), "The provided public key is not valid"); this.jwtPublicKeyPem = jwtPublicKeyPem; } private boolean validPublicKey(Optional<String> jwtPublicKeyPem) { PublicKeyReader reader = new PublicKeyReader(); return jwtPublicKeyPem.map(value -> reader.fromPEM(Optional.of(value)).isPresent()) .orElse(DEFAULT_VALUE); } public Optional<String> getJwtPublicKeyPem() { return jwtPublicKeyPem; } }
922ea082afcf6ba8c1b9902335c08b32f643b1ee
180
java
Java
src/main/java/com/Camera/WorkingPrincipleOfTheCamera/App.java
gurkanguldas/WorkingPrincipleOfTheCamera
387161a9d700df6c71b09c8eed9d8a0c379d7d6b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/Camera/WorkingPrincipleOfTheCamera/App.java
gurkanguldas/WorkingPrincipleOfTheCamera
387161a9d700df6c71b09c8eed9d8a0c379d7d6b
[ "Apache-2.0" ]
null
null
null
src/main/java/com/Camera/WorkingPrincipleOfTheCamera/App.java
gurkanguldas/WorkingPrincipleOfTheCamera
387161a9d700df6c71b09c8eed9d8a0c379d7d6b
[ "Apache-2.0" ]
null
null
null
15
47
0.588889
994,811
package com.Camera.WorkingPrincipleOfTheCamera; public class App { public static void main( String[] args ) { //Frame.Show(); Canvas.Show(); } }
922ea1da1e3436a2d78407459993cf7713071074
1,975
java
Java
addons/cloudevents/cloudevents-spring-boot-addon/src/main/java/org/kie/kogito/addon/cloudevents/spring/SpringTopicDiscovery.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
818
2019-06-04T11:46:27.000Z
2022-03-31T05:01:40.000Z
addons/cloudevents/cloudevents-spring-boot-addon/src/main/java/org/kie/kogito/addon/cloudevents/spring/SpringTopicDiscovery.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
1,832
2019-05-27T08:22:28.000Z
2022-03-31T16:26:41.000Z
addons/cloudevents/cloudevents-spring-boot-addon/src/main/java/org/kie/kogito/addon/cloudevents/spring/SpringTopicDiscovery.java
fjtirado/kogito-runtimes
6b0dfae7c62b6bb3eecce275e9a4a00e5a51ab6a
[ "Apache-2.0" ]
124
2019-05-27T08:39:27.000Z
2022-03-25T01:14:10.000Z
35.267857
91
0.714937
994,812
/* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * 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.kie.kogito.addon.cloudevents.spring; import java.util.ArrayList; import java.util.List; import org.kie.kogito.addon.cloudevents.AbstractTopicDiscovery; import org.kie.kogito.event.KogitoEventStreams; import org.kie.kogito.event.Topic; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SpringTopicDiscovery extends AbstractTopicDiscovery { // in the future we should be implementation agnostic @Value(value = "${kogito.addon.cloudevents.kafka." + KogitoEventStreams.INCOMING + "}") String incomingStreamTopic; @Value(value = "${kogito.addon.cloudevents.kafka." + KogitoEventStreams.OUTGOING + "}") String outgoingStreamTopic; @Override protected List<Topic> getTopics() { final List<Topic> topics = new ArrayList<>(); if (incomingStreamTopic != null && !incomingStreamTopic.isEmpty()) { final Topic incoming = DEFAULT_INCOMING_CHANNEL; incoming.setName(incomingStreamTopic); topics.add(incoming); } if (outgoingStreamTopic != null && !outgoingStreamTopic.isEmpty()) { final Topic outgoing = DEFAULT_OUTGOING_CHANNEL; outgoing.setName(outgoingStreamTopic); topics.add(outgoing); } return topics; } }
922ea28694a312a4e1758aafab827a2e3387ea63
2,064
java
Java
src/main/java/io/proleap/vb6/asg/visitor/impl/VbTypeAssignmentVisitorImpl.java
sbragagnolo/proleap-vb6-parser
226d819d829535989a9d44ba8b0edecd08523b51
[ "MIT" ]
47
2018-04-30T04:16:02.000Z
2022-03-24T03:31:00.000Z
src/main/java/io/proleap/vb6/asg/visitor/impl/VbTypeAssignmentVisitorImpl.java
sbragagnolo/proleap-vb6-parser
226d819d829535989a9d44ba8b0edecd08523b51
[ "MIT" ]
3
2018-06-11T18:17:49.000Z
2022-02-08T11:57:39.000Z
src/main/java/io/proleap/vb6/asg/visitor/impl/VbTypeAssignmentVisitorImpl.java
sbragagnolo/proleap-vb6-parser
226d819d829535989a9d44ba8b0edecd08523b51
[ "MIT" ]
18
2018-03-31T09:37:56.000Z
2022-03-18T07:56:44.000Z
29.628571
85
0.791707
994,813
/* * Copyright (C) 2017, Ulrich Wolffgang <nnheo@example.com> * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package io.proleap.vb6.asg.visitor.impl; import io.proleap.vb6.VisualBasic6Parser; import io.proleap.vb6.asg.inference.impl.TypeAssignmentInferenceImpl; import io.proleap.vb6.asg.metamodel.Module; import io.proleap.vb6.asg.metamodel.Program; public class VbTypeAssignmentVisitorImpl extends AbstractVbParserVisitorImpl { public VbTypeAssignmentVisitorImpl(final Module module) { super(module); } @Override public Boolean visitArgCall(final VisualBasic6Parser.ArgCallContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } @Override public Boolean visitForNextStmt(final VisualBasic6Parser.ForNextStmtContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } @Override public Boolean visitLetStmt(final VisualBasic6Parser.LetStmtContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } @Override public Boolean visitRedimSubStmt(final VisualBasic6Parser.RedimSubStmtContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } @Override public Boolean visitSetStmt(final VisualBasic6Parser.SetStmtContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } @Override public Boolean visitVsAssign(final VisualBasic6Parser.VsAssignContext ctx) { final Program program = module.getProgram(); new TypeAssignmentInferenceImpl().addTypeAssignment(ctx, program); return visitChildren(ctx); } }
922ea31678b78ed3c0ea6448de30fb497b297ecd
17,528
java
Java
main/test/com/tramchester/testSupport/reference/TramTransportDataForTestFactory.java
ThoughtWorksInc/tramchester
0ed9adec4dbd24ee1ea21948ae1154065f24e602
[ "Apache-2.0" ]
4
2018-02-01T11:33:29.000Z
2019-10-03T01:49:57.000Z
main/test/com/tramchester/testSupport/reference/TramTransportDataForTestFactory.java
ThoughtWorksInc/tramchester
0ed9adec4dbd24ee1ea21948ae1154065f24e602
[ "Apache-2.0" ]
8
2019-10-28T17:07:51.000Z
2019-11-21T15:08:52.000Z
main/test/com/tramchester/testSupport/reference/TramTransportDataForTestFactory.java
ThoughtWorksInc/tramchester
0ed9adec4dbd24ee1ea21948ae1154065f24e602
[ "Apache-2.0" ]
2
2018-05-26T23:15:44.000Z
2019-07-25T23:04:16.000Z
47.245283
153
0.691066
994,814
package com.tramchester.testSupport.reference; import com.netflix.governator.guice.lazy.LazySingleton; import com.tramchester.dataimport.loader.TransportDataFactory; import com.tramchester.domain.*; import com.tramchester.domain.id.IdFor; import com.tramchester.domain.id.StringIdFor; import com.tramchester.domain.input.MutableTrip; import com.tramchester.domain.input.PlatformStopCall; import com.tramchester.domain.places.MutableStation; import com.tramchester.domain.places.NaptanArea; import com.tramchester.domain.places.RouteStation; import com.tramchester.domain.places.Station; import com.tramchester.domain.reference.GTFSPickupDropoffType; import com.tramchester.domain.time.ProvidesNow; import com.tramchester.domain.time.TramTime; import com.tramchester.repository.TransportData; import com.tramchester.repository.TransportDataContainer; import com.tramchester.testSupport.TestEnv; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import static com.tramchester.domain.reference.TransportMode.Tram; import static com.tramchester.domain.time.TramTime.of; import static com.tramchester.testSupport.reference.KnownLocations.*; import static com.tramchester.testSupport.reference.KnownTramRoute.*; import static com.tramchester.testSupport.reference.TramTransportDataForTestFactory.TramTransportDataForTest.INTERCHANGE; import static java.lang.String.format; @LazySingleton public class TramTransportDataForTestFactory implements TransportDataFactory { private static final Logger logger = LoggerFactory.getLogger(TramTransportDataForTestFactory.class); private final TramTransportDataForTest container; private final DataSourceID dataSourceID = DataSourceID.tfgm; @Inject public TramTransportDataForTestFactory(ProvidesNow providesNow) { container = new TramTransportDataForTest(providesNow); } @PostConstruct public void start() { logger.info("starting"); populateTestData(container); logger.info(container.toString()); logger.info("started"); } @PreDestroy public void stop() { logger.info("stop"); container.dispose(); logger.info("stopped"); } public TramTransportDataForTest getTestData() { return container; } public TransportData getData() { return getTestData(); } private void populateTestData(TransportDataContainer container) { MutableAgency agency = new MutableAgency(DataSourceID.tfgm, MutableAgency.METL, "Metrolink"); MutableRoute routeA = createTramRoute(CornbrookTheTraffordCentre); MutableRoute routeB = createTramRoute(RochdaleShawandCromptonManchesterEastDidisbury); MutableRoute routeC = createTramRoute(EastDidisburyManchesterShawandCromptonRochdale); MutableRoute routeD = createTramRoute(ManchesterAirportWythenshaweVictoria); agency.addRoute(routeA); agency.addRoute(routeB); agency.addRoute(routeC); agency.addRoute(routeD); container.addAgency(agency); MutableService serviceA = new MutableService(TramTransportDataForTest.serviceAId); MutableService serviceB = new MutableService(TramTransportDataForTest.serviceBId); MutableService serviceC = new MutableService(TramTransportDataForTest.serviceCId); MutableService serviceD = new MutableService(TramTransportDataForTest.serviceDId); LocalDate startDate = LocalDate.of(2014, 2, 10); LocalDate endDate = LocalDate.of(2020, 8, 15); MutableServiceCalendar serviceCalendarA = new MutableServiceCalendar(startDate, endDate, DayOfWeek.MONDAY); MutableServiceCalendar serviceCalendarB = new MutableServiceCalendar(startDate, endDate, DayOfWeek.MONDAY); MutableServiceCalendar serviceCalendarC = new MutableServiceCalendar(startDate, endDate,DayOfWeek.MONDAY); MutableServiceCalendar serviceCalendarD = new MutableServiceCalendar(startDate, endDate,DayOfWeek.MONDAY); serviceA.setCalendar(serviceCalendarA); serviceB.setCalendar(serviceCalendarB); serviceC.setCalendar(serviceCalendarC); serviceD.setCalendar(serviceCalendarD); routeA.addService(serviceA); routeB.addService(serviceB); routeC.addService(serviceC); routeD.addService(serviceD); container.addRoute(routeA); container.addRoute(routeB); container.addRoute(routeC); container.addRoute(routeD); // tripA: FIRST_STATION -> SECOND_STATION -> INTERCHANGE -> LAST_STATION MutableTrip tripA = new MutableTrip(StringIdFor.createId(TramTransportDataForTest.TRIP_A_ID), "headSign", serviceA, routeA, Tram); serviceA.addTrip(tripA); MutableStation first = createStation(TramTransportDataForTest.FIRST_STATION, StringIdFor.createId("area1"), "startStation", nearAltrincham, dataSourceID); addAStation(container, first); addRouteStation(container, first, routeA); PlatformStopCall stopA = createStop(container, tripA, first, of(7, 55), of(8, 0), 1); tripA.addStop(stopA); // trip Z, firstNameDup - for composite station testing MutableTrip tripZ = new MutableTrip(StringIdFor.createId("tripZ"), "for dup", serviceD, routeD, Tram); serviceD.addTrip(tripZ); MutableStation firstDupName = createStation(TramTransportDataForTest.FIRST_STATION_DUP_NAME, StringIdFor.createId("area1"), "startStation", nearAltrincham, dataSourceID); addAStation(container, firstDupName); addRouteStation(container, firstDupName, routeD); PlatformStopCall stopZ = createStop(container, tripZ, firstDupName, of(12, 0), of(12, 0), 1); tripZ.addStop(stopZ); // trip Z, firstNameDup2 - for composite station testing MutableStation firstDup2Name = createStation(TramTransportDataForTest.FIRST_STATION_DUP2_NAME, StringIdFor.createId("area1"), "startStation", nearAltrincham, dataSourceID); addAStation(container, firstDup2Name); addRouteStation(container, firstDup2Name, routeD); PlatformStopCall stopZZ = createStop(container, tripZ, firstDup2Name, of(12, 0), of(12, 0), 2); tripZ.addStop(stopZZ); routeD.addTrip(tripZ); MutableStation second = createStation(TramTransportDataForTest.SECOND_STATION, StringIdFor.createId("area1"), "secondStation", atRoundthornTram, dataSourceID); addAStation(container, second); addRouteStation(container, second, routeA); PlatformStopCall stopB = createStop(container, tripA, second, of(8, 11), of(8, 11), 2); tripA.addStop(stopB); MutableStation interchangeStation = createStation(INTERCHANGE, StringIdFor.createId("area3"), "cornbrookStation", nearShudehill, dataSourceID); addAStation(container, interchangeStation); addRouteStation(container, interchangeStation, routeA); PlatformStopCall stopC = createStop(container, tripA, interchangeStation, of(8, 20), of(8, 20), 3); tripA.addStop(stopC); MutableStation last = createStation(TramTransportDataForTest.LAST_STATION, StringIdFor.createId("area4"), "endStation", nearPiccGardens, dataSourceID); addAStation(container, last); addRouteStation(container, last, routeA); PlatformStopCall stopD = createStop(container, tripA, last, of(8, 40), of(8, 40), 4); tripA.addStop(stopD); // service A routeA.addTrip(tripA); MutableStation stationFour = createStation(TramTransportDataForTest.STATION_FOUR, StringIdFor.createId("area4"), "Station4", nearKnutsfordBusStation, dataSourceID); addAStation(container, stationFour); // trip ZZ, fourthNameDup - for composite station testing MutableTrip tripZZ = new MutableTrip(StringIdFor.createId("tripZZ"), "for dup of 4", serviceA, routeD, Tram); serviceA.addTrip(tripZZ); MutableStation fourDupName = createStation(TramTransportDataForTest.STATION_FOUR_DUP_NAME, StringIdFor.createId("area4"), "Station4", nearKnutsfordBusStation, dataSourceID); addAStation(container, fourDupName); addRouteStation(container, fourDupName, routeD); PlatformStopCall fourDupStop = createStop(container, tripZZ, fourDupName, of(13, 0), of(13, 0), 1); tripZZ.addStop(fourDupStop); routeD.addTrip(tripZZ); MutableStation stationFive = createStation(TramTransportDataForTest.STATION_FIVE, StringIdFor.createId("area5"), "Station5", nearStockportBus, dataSourceID); addAStation(container, stationFive); // MutableTrip tripC = new MutableTrip(StringIdFor.createId("tripCId"), "headSignC", serviceC, routeC, Tram); serviceC.addTrip(tripC); PlatformStopCall stopG = createStop(container, tripC, interchangeStation, of(8, 26), of(8, 27), 1); addRouteStation(container, interchangeStation, routeC); PlatformStopCall stopH = createStop(container, tripC, stationFive, of(8, 31), of(8, 33), 2); addRouteStation(container, stationFive, routeC); tripC.addStop(stopG); tripC.addStop(stopH); routeC.addTrip(tripC); // INTERCHANGE -> STATION_FOUR addRouteStation(container, stationFour, routeB); addRouteStation(container, interchangeStation, routeB); createInterchangeToStation4Trip(container,routeB, serviceB, interchangeStation, stationFour, LocalTime.of(8, 26), "tripBId"); createInterchangeToStation4Trip(container,routeB, serviceB, interchangeStation, stationFour, LocalTime.of(9, 10), "tripB2Id"); createInterchangeToStation4Trip(container,routeB, serviceB, interchangeStation, stationFour, LocalTime.of(9, 20), "tripB3Id"); container.addTrip(tripA); container.addTrip(tripC); container.addService(serviceA); container.addService(serviceB); container.addService(serviceC); container.reportNumbers(); } private MutableStation createStation(String station, IdFor<NaptanArea> areaId, String stationName, KnownLocations knownLocation, DataSourceID dataSourceID) { return new MutableStation(Station.createId(station), areaId, stationName, knownLocation.latLong(), knownLocation.grid(), dataSourceID); } // private MutableStation createStation(String station, IdFor<NaptanArea> areaId, String stationName, LatLong latLong, GridPosition gridPosition, // DataSourceID dataSourceID) { // return new MutableStation(Station.createId(station), areaId, stationName, latLong, gridPosition, dataSourceID); // } private MutableRoute createTramRoute(KnownTramRoute knownRoute) { return new MutableRoute(knownRoute.getFakeId(), knownRoute.shortName(), knownRoute.name(), TestEnv.MetAgency(), knownRoute.mode()); } private void addAStation(TransportDataContainer container, MutableStation station) { container.addStation(station); } private static void addRouteStation(TransportDataContainer container, MutableStation station, Route route) { RouteStation routeStation = new RouteStation(station, route); container.addRouteStation(routeStation); station.addRoutePickUp(route); station.addRouteDropOff(route); } private static void createInterchangeToStation4Trip(TransportDataContainer container, MutableRoute route, MutableService service, MutableStation interchangeStation, MutableStation station, LocalTime startTime, String tripId) { MutableTrip trip = new MutableTrip(StringIdFor.createId(tripId), "headSignTripB2", service, route, Tram); PlatformStopCall stop1 = createStop(container,trip, interchangeStation, of(startTime), of(startTime.plusMinutes(5)), 1); trip.addStop(stop1); PlatformStopCall stop2 = createStop(container,trip, station, of(startTime.plusMinutes(5)), of(startTime.plusMinutes(8)), 2); trip.addStop(stop2); route.addTrip(trip); service.addTrip(trip); container.addTrip(trip); } private static PlatformStopCall createStop(TransportDataContainer container, MutableTrip trip, MutableStation station, TramTime arrivalTime, TramTime departureTime, int sequenceNum) { String platformId = station.getId() + "1"; final String platformName = format("%s platform 1", station.getName()); MutablePlatform platform = new MutablePlatform(StringIdFor.createId(platformId), station, platformName, station.getDataSourceID(), "1", station.getAreaId(), station.getLatLong(), station.getGridPosition(), station.isMarkedInterchange()); container.addPlatform(platform); station.addPlatform(platform); return new PlatformStopCall(platform, station, arrivalTime, departureTime, sequenceNum, GTFSPickupDropoffType.Regular, GTFSPickupDropoffType.Regular, trip); } public static class TramTransportDataForTest extends TransportDataContainer { private static final IdFor<Service> serviceAId = StringIdFor.createId("serviceAId"); private static final IdFor<Service> serviceBId = StringIdFor.createId("serviceBId"); private static final IdFor<Service> serviceCId = StringIdFor.createId("serviceCId"); private static final IdFor<Service> serviceDId = StringIdFor.createId("serviceDId"); private static final String METROLINK_PREFIX = "9400ZZ"; public static final String TRIP_A_ID = "tripAId"; public static final String FIRST_STATION = METROLINK_PREFIX + "FIRST"; public static final String FIRST_STATION_DUP_NAME = METROLINK_PREFIX + "FIRSTDUP"; public static final String FIRST_STATION_DUP2_NAME = METROLINK_PREFIX + "FIRSTDUP2"; public static final String SECOND_STATION = METROLINK_PREFIX + "SECOND"; public static final String LAST_STATION = METROLINK_PREFIX + "LAST"; public static final String INTERCHANGE = TramStations.Cornbrook.getRawId(); private static final String STATION_FOUR = METROLINK_PREFIX + "FOUR"; private static final String STATION_FOUR_DUP_NAME = METROLINK_PREFIX + "FOURDUP"; private static final String STATION_FIVE = METROLINK_PREFIX + "FIVE"; public TramTransportDataForTest(ProvidesNow providesNow) { super(providesNow, "TramTransportDataForTest"); } public Station getFirst() { return getStationById(StringIdFor.createId(FIRST_STATION)); } public Station getFirstDupName() { return getStationById(StringIdFor.createId(FIRST_STATION_DUP_NAME)); } public Station getFirstDup2Name() { return getStationById(StringIdFor.createId(FIRST_STATION_DUP2_NAME)); } public Station getSecond() { return getStationById(StringIdFor.createId(SECOND_STATION)); } public Station getInterchange() { return getStationById(StringIdFor.createId(INTERCHANGE)); } public Station getLast() { return getStationById(StringIdFor.createId(LAST_STATION)); } public Station getFifthStation() { return getStationById(StringIdFor.createId(STATION_FIVE)); } public Station getFourthStation() { return getStationById(StringIdFor.createId(STATION_FOUR)); } public Station getFourthStationDupName() { return getStationById(StringIdFor.createId(STATION_FOUR_DUP_NAME)); } public Route getRouteA() { return getRouteById(CornbrookTheTraffordCentre.getFakeId()); } public Route getRouteB() { return getRouteById(RochdaleShawandCromptonManchesterEastDidisbury.getFakeId()); } public Route getRouteC() { return getRouteById(EastDidisburyManchesterShawandCromptonRochdale.getFakeId()); } public Route getRouteD() { return getRouteById(ManchesterAirportWythenshaweVictoria.getFakeId()); } @Override public Map<DataSourceID, FeedInfo> getFeedInfos() { FeedInfo info = new FeedInfo("publisherName", "publisherUrl", "timezone", "lang", LocalDate.of(2016, 5, 25), LocalDate.of(2016, 6, 30), "version"); Map<DataSourceID, FeedInfo> result = new HashMap<>(); result.put(DataSourceID.unknown, info); return result; } } }
922ea38f297c002dba0f350586237be5db5a9cc8
7,845
java
Java
app/src/main/java/com/ggstudios/utils/LinkUtils.java
idunnololz/LoLCraft
b4831e7136d53cdaf4f2bc6153bef9d00a804fb9
[ "Apache-2.0" ]
1
2016-11-17T19:22:52.000Z
2016-11-17T19:22:52.000Z
app/src/main/java/com/ggstudios/utils/LinkUtils.java
idunnololz/LoLCraft
b4831e7136d53cdaf4f2bc6153bef9d00a804fb9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/ggstudios/utils/LinkUtils.java
idunnololz/LoLCraft
b4831e7136d53cdaf4f2bc6153bef9d00a804fb9
[ "Apache-2.0" ]
null
null
null
44.322034
107
0.617463
994,815
package com.ggstudios.utils; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.ggstudios.lolcraft.ChampionInfo; import java.util.HashMap; public class LinkUtils { private static final String LINK_CS = "http://www.championselect.net/champions/%s"; private static final String LINK_MOBAFIRE = "http://www.mobafire.com/league-of-legends/champion/%s-%d"; private static final String LINK_PROBUILDS = "http://www.probuilds.net/champions/%s"; private static final HashMap<String, String> keyToCsName = new HashMap<>(); static { keyToCsName.put("MonkeyKing", "Wukong"); } private static final HashMap<Integer, Integer> keyToMobafireId = new HashMap<>(); static { keyToMobafireId.put(266, 114); // Aatrox keyToMobafireId.put(103, 89); // Ahri keyToMobafireId.put(84, 50); // Akali keyToMobafireId.put(12, 4); // Alistar keyToMobafireId.put(32, 23); // Amumu keyToMobafireId.put(34, 25); // Anivia keyToMobafireId.put(22, 13); // Ashe keyToMobafireId.put(268, 121); // Azir keyToMobafireId.put(432, 124); // bard keyToMobafireId.put(53, 34); // Blitzcrank keyToMobafireId.put(63, 74); // Brand keyToMobafireId.put(201, 119); // Braum keyToMobafireId.put(51, 67); // Cait keyToMobafireId.put(69, 66); // Cassiopeia keyToMobafireId.put(31, 22); // Cho'Gath keyToMobafireId.put(42, 31); // Corki keyToMobafireId.put(122, 98); // Darius keyToMobafireId.put(131, 102); // Diana keyToMobafireId.put(36, 26); // Dr. Mundo keyToMobafireId.put(119, 99); // Draven keyToMobafireId.put(60, 106); // Elise keyToMobafireId.put(28, 19); // Evelynn keyToMobafireId.put(81, 47); // Ezreal keyToMobafireId.put(9, 38); // Fiddlesticks keyToMobafireId.put(114, 94); // Fiora keyToMobafireId.put(105, 87); // Fizz keyToMobafireId.put(3, 57); // Galio keyToMobafireId.put(41, 30); // Gangplank keyToMobafireId.put(86, 51); // Garen keyToMobafireId.put(150, 120); // Gnar keyToMobafireId.put(79, 45); // Gragas keyToMobafireId.put(104, 85); // Graves keyToMobafireId.put(120, 96); // Hecarim keyToMobafireId.put(74, 40); // Heimerdinger keyToMobafireId.put(39, 64); // Irelia keyToMobafireId.put(40, 29); // Janna keyToMobafireId.put(59, 71); // Jarvan IV keyToMobafireId.put(24, 15); // Jax keyToMobafireId.put(126, 100); // Jayce keyToMobafireId.put(222, 116); // Jinx keyToMobafireId.put(429, 122); // Kalista keyToMobafireId.put(43, 69); // Karma keyToMobafireId.put(30, 21); // Karthus keyToMobafireId.put(38, 27); // Kassadin keyToMobafireId.put(55, 36); // Katarina keyToMobafireId.put(10, 2); // Kayle keyToMobafireId.put(85, 49); // Kennen keyToMobafireId.put(121, 105); // Kha'Zix keyToMobafireId.put(96, 54); // Kog'Maw keyToMobafireId.put(7, 63); // LeBlanc keyToMobafireId.put(64, 73); // Lee Sin keyToMobafireId.put(89, 79); // Leona keyToMobafireId.put(127, 113); // Lissandra keyToMobafireId.put(236, 115); // Lucian keyToMobafireId.put(117, 95); // Lulu keyToMobafireId.put(99, 62); // Lux keyToMobafireId.put(54, 35); // Malphite keyToMobafireId.put(90, 52); // Malzahar keyToMobafireId.put(57, 70); // Maokai keyToMobafireId.put(11, 3); // Master Yi keyToMobafireId.put(21, 59); // Miss Fortune keyToMobafireId.put(82, 46); // Mordekaiser keyToMobafireId.put(25, 16); // Morgana keyToMobafireId.put(267, 108); // Nami keyToMobafireId.put(75, 37); // Nasus keyToMobafireId.put(111, 93); // Nautilus keyToMobafireId.put(76, 42); // Nidalee keyToMobafireId.put(56, 72); // Nocturne keyToMobafireId.put(20, 12); // Nunu keyToMobafireId.put(2, 53); // Olaf keyToMobafireId.put(61, 77); // Orianna keyToMobafireId.put(80, 44); // Pantheon keyToMobafireId.put(78, 43); // Poppy keyToMobafireId.put(133, 111); // Quinn keyToMobafireId.put(33, 24); // Rammus keyToMobafireId.put(421, 123); // Rek'Sai keyToMobafireId.put(58, 68); // Renekton keyToMobafireId.put(107, 103); // Rengar keyToMobafireId.put(92, 83); // Riven keyToMobafireId.put(68, 75); // Rumble keyToMobafireId.put(13, 5); // Ryze keyToMobafireId.put(113, 91); // Sejuani keyToMobafireId.put(35, 41); // Shaco keyToMobafireId.put(98, 48); // Shen keyToMobafireId.put(102, 86); // Shyvana keyToMobafireId.put(27, 18); // Singed keyToMobafireId.put(14, 6); // Sion keyToMobafireId.put(15, 7); // Sivir keyToMobafireId.put(72, 81); // Skarner keyToMobafireId.put(37, 60); // Sona keyToMobafireId.put(16, 8); // Soraka keyToMobafireId.put(50, 61); // Swain keyToMobafireId.put(134, 104); // Syndra keyToMobafireId.put(91, 82); // Talon keyToMobafireId.put(44, 32); // Taric keyToMobafireId.put(17, 9); // Teemo keyToMobafireId.put(412, 110); // Thresh keyToMobafireId.put(18, 10); // Tristana keyToMobafireId.put(48, 65); // Trundle keyToMobafireId.put(23, 14); // Tryndamere keyToMobafireId.put(4, 28); // Twisted Fate keyToMobafireId.put(29, 20); // Twitch keyToMobafireId.put(77, 39); // Udyr keyToMobafireId.put(6, 58); // Urgot keyToMobafireId.put(110, 97); // Varus keyToMobafireId.put(67, 76); // Vayne keyToMobafireId.put(45, 33); // Veigar keyToMobafireId.put(161, 118); // Vel'Koz keyToMobafireId.put(254, 109); // Vi keyToMobafireId.put(112, 90); // Viktor keyToMobafireId.put(8, 56); // Vladimir keyToMobafireId.put(106, 88); // Volibear keyToMobafireId.put(19, 11); // Warwick keyToMobafireId.put(62, 80); // Wukong keyToMobafireId.put(101, 84); // Xerath keyToMobafireId.put(5, 55); // Xin Zhao keyToMobafireId.put(157, 117); // Yasuo keyToMobafireId.put(83, 78); // Yorick keyToMobafireId.put(154, 112); // Zac keyToMobafireId.put(238, 107); // Zed keyToMobafireId.put(115, 92); // Ziggs keyToMobafireId.put(26, 17); // Zilean keyToMobafireId.put(143, 101); // Zyra } private static String championKeyToCsName(String key) { String s = keyToCsName.get(key); return s == null ? key : s; } private static int championKeyToMobafireId(int id) { Integer i = keyToMobafireId.get(id); return i == null ? id : i; } public static void launchCs(Context context, ChampionInfo info) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(LINK_CS, championKeyToCsName(info.getKey())))); context.startActivity(browserIntent); } public static void launchMobafire(Context context, ChampionInfo info) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(LINK_MOBAFIRE, championKeyToCsName(info.getKey()), championKeyToMobafireId(info.getId())))); context.startActivity(browserIntent); } public static void launchProbuilds(Context context, ChampionInfo info) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(LINK_PROBUILDS, championKeyToCsName(info.getKey())))); context.startActivity(browserIntent); } }
922ea6c293dd5b02a28caea61d3295f54a657425
1,345
java
Java
core/src/main/java/org/keycloak/services/clientregistration/DefaultClientRegistrationProviderFactory.java
yqclouds/keycloak
21cd7f4e64d1290779a527fb0764b90d5000c147
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/keycloak/services/clientregistration/DefaultClientRegistrationProviderFactory.java
yqclouds/keycloak
21cd7f4e64d1290779a527fb0764b90d5000c147
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/keycloak/services/clientregistration/DefaultClientRegistrationProviderFactory.java
yqclouds/keycloak
21cd7f4e64d1290779a527fb0764b90d5000c147
[ "Apache-2.0" ]
null
null
null
32.853659
100
0.757238
994,816
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.services.clientregistration; import org.keycloak.stereotype.ProviderFactory; import org.springframework.stereotype.Component; /** * @author <a href="mailto:hzdkv@example.com">Stian Thorgersen</a> */ @Component("DefaultClientRegistrationProviderFactory") @ProviderFactory(id = "default", providerClasses = ClientRegistrationProvider.class) public class DefaultClientRegistrationProviderFactory implements ClientRegistrationProviderFactory { @Override public ClientRegistrationProvider create() { return new DefaultClientRegistrationProvider(); } @Override public String getId() { return "default"; } }
922ea7cec7316068c37a26a6eb581039282b17b5
2,986
java
Java
src/projects/examples/MushroomClassification.java
NiklasJohansen/FunWithMachineLearning
37b2167b5f3d44dda9ef0a1f37abbdb41fa116a5
[ "MIT" ]
2
2017-08-17T19:55:52.000Z
2019-04-07T12:17:45.000Z
src/projects/examples/MushroomClassification.java
NiklasJohansen/FunWithMachineLearning
37b2167b5f3d44dda9ef0a1f37abbdb41fa116a5
[ "MIT" ]
null
null
null
src/projects/examples/MushroomClassification.java
NiklasJohansen/FunWithMachineLearning
37b2167b5f3d44dda9ef0a1f37abbdb41fa116a5
[ "MIT" ]
null
null
null
43.275362
120
0.698928
994,817
package projects.examples; import neuralnetwork.NeuralNetwork; import neuralnetwork.datautils.AccuracyTester; import neuralnetwork.datautils.ClassificationNormalizer; import neuralnetwork.datautils.Dataset; import neuralnetwork.training.Backpropagation; import neuralnetwork.training.NetworkTrainer; import java.io.IOException; import java.util.Arrays; /** * This example shows how the network can be trained to distinguish between * poisonous and edible mushrooms. More information on the data is available * on the linked website. * * The dataset is property of UCI Machine Learning Repository * Link: https://archive.ics.uci.edu/ml/datasets/mushroom * * @author Niklas Johansen * @version 1.0 */ public class MushroomClassification { public static void main(String[] args) throws IOException { // Imports the dataset and adds it to the normalizer Dataset dataset = new Dataset( "https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data"); ClassificationNormalizer normalizer = new ClassificationNormalizer(); normalizer.addDataset(dataset.getTrainingSamples(), Dataset.ClassPosition.FIRST); System.out.println(normalizer); int nInputNeurons = normalizer.getNumberOfAttributes(); int nOutputNeurons = normalizer.getNumberOfClasses(); int nHiddenNeurons = nInputNeurons * 3 / 2; // Configures and builds the neural network NeuralNetwork network = new NeuralNetwork(); network.addNeuronLayer(nInputNeurons); // Input layer network.addNeuronLayer(nHiddenNeurons); // Hidden layer network.addNeuronLayer(nOutputNeurons); // Output layer network.build(); // Creates and configures the trainer double[][][] trainingData = normalizer.getNormalizedTrainingData(); NetworkTrainer trainer = new Backpropagation(trainingData[0], trainingData[1], 0.6, 0.7); trainer.setProgressCallbackAction(100, () -> System.out.println(trainer.getEpoch() + " " + trainer.getMeanSquaredError())); // Trains the network trainer.trainNetwork(network,0.00001, 1000); System.out.println(trainer.getTrainingResultString()); // Tests the accuracy of the trained network on separate test samples AccuracyTester tester = new AccuracyTester(dataset.getTestSamples(), Dataset.ClassPosition.FIRST); tester.testClassification(network); System.out.println(tester.getTestResults()); // Example classification String[] attributes = {"b","s","w","t","l","f","c","b","n","e","c","s","s","w","w","p","w","o","p","k","n","g"}; double[] normalizedInput = normalizer.getNormalizedAttributes(attributes); double[] result = network.compute(normalizedInput); System.out.println("\nExample: " + Arrays.toString(attributes) + " => " + normalizer.getClassMatchString(result)); } }
922ea83285e44f54ff0938ce5a908d5b42e89697
1,845
java
Java
src/main/java/pl/sternik/pb/weekend/services/GieldaServiceJPAImpl.java
pawelbabiuch/sternik-gielda
04ff2d362357f10b34f7357916dc9a482e03a226
[ "Unlicense" ]
null
null
null
src/main/java/pl/sternik/pb/weekend/services/GieldaServiceJPAImpl.java
pawelbabiuch/sternik-gielda
04ff2d362357f10b34f7357916dc9a482e03a226
[ "Unlicense" ]
null
null
null
src/main/java/pl/sternik/pb/weekend/services/GieldaServiceJPAImpl.java
pawelbabiuch/sternik-gielda
04ff2d362357f10b34f7357916dc9a482e03a226
[ "Unlicense" ]
null
null
null
24.6
72
0.688889
994,818
package pl.sternik.pb.weekend.services; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import pl.sternik.pb.weekend.entities.Samochod; import pl.sternik.pb.weekend.repositories.NoSuchSamochodException; import pl.sternik.pb.weekend.repositories.springdata.SamochodRepository; @Service @Qualifier("spring-data") public class GieldaServiceJPAImpl implements GieldaService { @Autowired private SamochodRepository bazaDanych; @Override public List<Samochod> findAll() { List<Samochod> l = new ArrayList<>(); for (Samochod item : bazaDanych.findAll()) { l.add(item); } return l; } @Override public List<Samochod> findAllToSell() { List<Samochod> l = new ArrayList<>(); for (Samochod item : bazaDanych.findAll()) { l.add(item); } return l; } @Override public Optional<Samochod> findByVin(Long id) { return Optional.ofNullable(bazaDanych.findByVin(id)); } @Override public Optional<Samochod> create(Samochod samochod) { return Optional.of(bazaDanych.save(samochod)); } @Override public Optional<Samochod> edit(Samochod samochod) { return Optional.of(bazaDanych.save(samochod)); } @Override public Optional<Boolean> deleteByVin(Long id) { bazaDanych.delete(id); return Optional.of(Boolean.TRUE); } @Override public List<Samochod> findLatest3() { return Collections.emptyList(); } @Override public List<Samochod> findCrashed() { // TODO Auto-generated method stub return null; } }
922ea94a8de1a6414ed14b20cfd832e945a3da15
404
java
Java
client/src/main/java/client/cs4224c/util/TimeUtility.java
SGywzhang/mangoDB
f3e95146ab1111c73952f39570ca0bd6a248f271
[ "Apache-2.0" ]
1
2019-11-06T08:46:57.000Z
2019-11-06T08:46:57.000Z
client/src/main/java/client/cs4224c/util/TimeUtility.java
SGywzhang/mangoDB
f3e95146ab1111c73952f39570ca0bd6a248f271
[ "Apache-2.0" ]
null
null
null
client/src/main/java/client/cs4224c/util/TimeUtility.java
SGywzhang/mangoDB
f3e95146ab1111c73952f39570ca0bd6a248f271
[ "Apache-2.0" ]
null
null
null
25.25
142
0.752475
994,819
package client.cs4224c.util; import org.apache.commons.lang3.time.FastDateFormat; import java.util.Date; import java.util.TimeZone; public class TimeUtility { private static final FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS z", TimeZone.getTimeZone("UTC")); public static String format(Date date) { return fastDateFormat.format(date); } }
922ea9fd8e662fcf6b6ce6b112cd9ef4c4cf7733
7,801
java
Java
src/test/java/org/rpgrunner/j2me/character/movement/PlayerMovementTest.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
src/test/java/org/rpgrunner/j2me/character/movement/PlayerMovementTest.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
src/test/java/org/rpgrunner/j2me/character/movement/PlayerMovementTest.java
carlsonsantana/rpg_runner_j2me
58d67d62b000940a339acb1d21df9a27f93d10e4
[ "MIT" ]
null
null
null
30.354086
79
0.663376
994,820
package org.rpgrunner.j2me.character.movement; import javax.microedition.lcdui.game.GameCanvas; import junit.framework.Assert; import junit.framework.TestCase; import org.rpgrunner.Direction; import org.rpgrunner.character.GameCharacter; import org.rpgrunner.character.movement.PlayerMovement; import org.rpgrunner.test.helper.KeyHelper; import org.rpgrunner.test.mock.character.CharacterSpy; import org.rpgrunner.test.mock.character.SimpleCharacter; public abstract class PlayerMovementTest extends TestCase { public void testExecuteWithoutPressedButton() { SimpleCharacter character = new SimpleCharacter(); PlayerMovement playerMovement = create(character); byte direction = character.getDirection(); playerMovement.execute(); Assert.assertEquals(direction, character.getDirection()); } public void testMoveUp() { testMove(Direction.UP, KeyHelper.UP_KEYS); } public void testMoveRight() { testMove(Direction.RIGHT, KeyHelper.RIGHT_KEYS); } public void testMoveDown() { testMove(Direction.DOWN, KeyHelper.DOWN_KEYS); } public void testMoveLeft() { testMove(Direction.LEFT, KeyHelper.LEFT_KEYS); } private void testMove(final byte direction, final int[] keys) { for (int i = 0, length = keys.length; i < length; i++) { int key = keys[i]; testMove(direction, key); } } private void testMove( final byte direction, final int keyDirection ) { SimpleCharacter character = new SimpleCharacter(); PlayerMovement playerMovement = create(character); playerMovement.pressKey(keyDirection); playerMovement.execute(); Assert.assertEquals(direction, character.getDirection()); } public void testMoveUpReleaseKey() { testReleaseKey(Direction.UP, KeyHelper.UP_KEYS); } public void testMoveRightReleaseKey() { testReleaseKey(Direction.RIGHT, KeyHelper.RIGHT_KEYS); } public void testMoveDownReleaseKey() { testReleaseKey(Direction.DOWN, KeyHelper.DOWN_KEYS); } public void testMoveLeftReleaseKey() { testReleaseKey(Direction.LEFT, KeyHelper.LEFT_KEYS); } private void testReleaseKey(final byte direction, final int[] keys) { for (int i = 0, length = keys.length; i < length; i++) { int key = keys[i]; testReleaseKeyFirst(direction, key); testReleaseKeyLast(direction, key); } } private void testReleaseKeyFirst( final byte direction, final int keyDirection ) { SimpleCharacter character = new SimpleCharacter(); PlayerMovement playerMovement = create(character); int reverseDirectionKey = getReverseDirectionKey(direction); playerMovement.pressKey(reverseDirectionKey); playerMovement.pressKey(keyDirection); playerMovement.releaseKey(reverseDirectionKey); playerMovement.execute(); Assert.assertEquals(direction, character.getDirection()); } private void testReleaseKeyLast( final byte direction, final int keyDirection ) { SimpleCharacter character = new SimpleCharacter(); PlayerMovement playerMovement = create(character); int reverseDirectionKey = getReverseDirectionKey(direction); playerMovement.pressKey(keyDirection); playerMovement.pressKey(reverseDirectionKey); playerMovement.releaseKey(reverseDirectionKey); playerMovement.execute(); Assert.assertEquals(direction, character.getDirection()); } public void testInteract() { for ( int i = 0, length = KeyHelper.ACTION_KEYS.length; i < length; i++ ) { int key = KeyHelper.ACTION_KEYS[i]; checkInteract(key); } } private void checkInteract(final int key) { CharacterSpy character = new CharacterSpy(null); PlayerMovement playerMovement = create(character); playerMovement.pressKey(key); playerMovement.execute(); Assert.assertFalse(character.isInteractCalled()); playerMovement.releaseKey(key); playerMovement.execute(); Assert.assertTrue(character.isInteractCalled()); } public void testDoNotInteractTwiceForSamePressedKey() { for ( int i = 0, length = KeyHelper.ACTION_KEYS.length; i < length; i++ ) { int key = KeyHelper.ACTION_KEYS[i]; checkDoNotInteractTwiceForSamePressedKey(key); } } private void checkDoNotInteractTwiceForSamePressedKey(final int key) { CharacterSpy character = new CharacterSpy(null); PlayerMovement playerMovement = create(character); playerMovement.pressKey(key); playerMovement.releaseKey(key); playerMovement.execute(); character.resetInteractCalled(); playerMovement.execute(); Assert.assertFalse(character.isInteractCalled()); } public void testDoNothingWhenReleaseAllKeys() { for ( int i = 0, length = KeyHelper.ACTION_KEYS.length; i < length; i++ ) { int key = KeyHelper.ACTION_KEYS[i]; checkDontInteractWhenReleaseAllKeys(key); } } private void checkDontInteractWhenReleaseAllKeys(final int key) { CharacterSpy character = new CharacterSpy(null); PlayerMovement playerMovement = create(character); playerMovement.pressKey(key); playerMovement.releaseAllKeys(); playerMovement.releaseKey(key); playerMovement.execute(); Assert.assertFalse(character.isInteractCalled()); } public void testDontMoveUpWhenReleaseAllKeys() { checkDontMoveWhenReleaseAllKeys(Direction.UP, KeyHelper.UP_KEYS); } public void testDontMoveRightWhenReleaseAllKeys() { checkDontMoveWhenReleaseAllKeys(Direction.RIGHT, KeyHelper.RIGHT_KEYS); } public void testDontMoveDownWhenReleaseAllKeys() { checkDontMoveWhenReleaseAllKeys(Direction.DOWN, KeyHelper.DOWN_KEYS); } public void testDontMoveLeftWhenReleaseAllKeys() { checkDontMoveWhenReleaseAllKeys(Direction.LEFT, KeyHelper.LEFT_KEYS); } private void checkDontMoveWhenReleaseAllKeys( final byte direction, final int[] keys ) { for (int i = 0, length = keys.length; i < length; i++) { int key = keys[i]; checkDontMoveWhenReleaseAllKeys(direction, key); } } private void checkDontMoveWhenReleaseAllKeys( final byte direction, final int keyDirection ) { SimpleCharacter character = new SimpleCharacter(); PlayerMovement playerMovement = create(character); int reverseDirectionKey = getReverseDirectionKey(direction); playerMovement.pressKey(reverseDirectionKey); playerMovement.execute(); playerMovement.pressKey(keyDirection); playerMovement.releaseAllKeys(); playerMovement.execute(); Assert.assertFalse(direction == character.getDirection()); } private int getReverseDirectionKey(final byte direction) { byte reverseDirection = Direction.invertDirection(direction); if (Direction.isUp(reverseDirection)) { return GameCanvas.UP; } else if (Direction.isRight(reverseDirection)) { return GameCanvas.RIGHT; } else if (Direction.isDown(reverseDirection)) { return GameCanvas.DOWN; } else { return GameCanvas.LEFT; } } protected abstract PlayerMovement create(GameCharacter character); }
922eaa15899e980a5236fa7763ef5f5979e7fa7a
769
java
Java
src/main/java/edu/put/ma/descs/contacts/ContactsInspector.java
mantczak/descs-standalone
13c9777b2d6461743772583ea0a6de9994b7ca9f
[ "MIT" ]
2
2016-12-19T17:46:36.000Z
2017-04-21T10:51:42.000Z
src/main/java/edu/put/ma/descs/contacts/ContactsInspector.java
mantczak/descs-standalone
13c9777b2d6461743772583ea0a6de9994b7ca9f
[ "MIT" ]
13
2020-07-03T15:18:00.000Z
2022-02-01T11:02:18.000Z
src/main/java/edu/put/ma/descs/contacts/ContactsInspector.java
mantczak/descs-standalone
13c9777b2d6461743772583ea0a6de9994b7ca9f
[ "MIT" ]
1
2021-12-16T08:49:38.000Z
2021-12-16T08:49:38.000Z
23.30303
94
0.784135
994,821
package edu.put.ma.descs.contacts; import java.util.List; import org.biojava.nbio.structure.Chain; import com.google.common.collect.ImmutableList; import edu.put.ma.model.ModelProperties; import edu.put.ma.model.MoleculeType; public interface ContactsInspector { boolean isValid(); void constructInContactResiduesMatrix(List<Chain> model, ModelProperties modelProperties); String getInContactResiduesMatrixString(); ImmutableList<Boolean> getContactsOfResidueByIndex(int residueIndex); String getAtomNamePairsString(); int getThreadsCount(); void setThreadsCount(int threadsCount); void setExpression(String expressionString, MoleculeType moleculeType); void setExpression(String expressionString); void close(); }
922eab74d306d0b709545010eeee26a9283ee5be
51,694
java
Java
src/com/bjwg/main/util/MyUtils.java
liangjinx/BJWG
f0186f8d369af0fb682f24bb4b98b2cdb0d6a893
[ "Apache-2.0" ]
null
null
null
src/com/bjwg/main/util/MyUtils.java
liangjinx/BJWG
f0186f8d369af0fb682f24bb4b98b2cdb0d6a893
[ "Apache-2.0" ]
null
null
null
src/com/bjwg/main/util/MyUtils.java
liangjinx/BJWG
f0186f8d369af0fb682f24bb4b98b2cdb0d6a893
[ "Apache-2.0" ]
null
null
null
22.458028
278
0.595208
994,822
package com.bjwg.main.util; import java.io.IOException; import java.math.BigDecimal; import java.net.InetAddress; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bjwg.main.base.PhoneBaseData; import com.bjwg.main.constant.CommConstant; import com.bjwg.main.constant.LoginConstants; import com.bjwg.main.model.MyEarnings; import com.bjwg.main.model.PagerArg; import com.bjwg.main.model.User; import com.bjwg.main.model.UserArea; import com.bjwg.main.model.UserLoginModel; import com.sun.org.apache.bcel.internal.generic.NEW; /** * 工具类 * * @author Administrator * */ public class MyUtils { public static final Logger logger = LoggerFactory.getLogger("LOGISTICS-COMPONENT"); /** * 判断list是否为空 * * @param list * @return */ public static boolean isNotEmpty(List<?> list) { return list != null && list.size() > 0; } /** * 判断list是否为空 * * @param list * @return null true */ public static boolean isListEmpty(List<?> list) { return list == null || list.size() == 0; } /** * 判断map是否为空 * * @param list * @return */ public static boolean isMapEmpty(Map<?, ?> map) { return map == null || map.size() == 0; } /** * 判断integer是否大于0 * * @param i * @return */ public static boolean isIntegerGtZero(Integer i) { return i != null && i.intValue() > 0; } /** * 获取当前时间,未格式化 * * @return */ public static Date getCurrentDate() { return new Date(); } /** * 时间格式化 * * @return */ @SuppressWarnings("deprecation") public static Date dateFormat(String dateStr) { return new Date(dateStr); } /** * 格式化时间 * * @param mode * 格式 * @return */ public static Date dateFormat(String data, int mode) throws Exception { String format = "yyyy-MM-dd HH:mm:ss"; switch (mode) { case 1: format = "yyyy/MM/dd HH:mm:ss"; break; case 2: format = "yyyy.MM.dd HH:mm:ss"; break; case 3: format = "yyyy年MM月dd日 HH:mm:ss"; break; case 4: format = "yyyyMMddHHmmss"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(data); } /** * 获取当前时间yyyy-MM-dd HH:mm:ss * * @param mode * 格式 * @return */ public static String getYYYYMMDDHHmmss(int mode) { String format = "yyyy-MM-dd HH:mm:ss"; switch (mode) { case 1: format = "yyyy/MM/dd HH:mm:ss"; break; case 2: format = "yyyy.MM.dd HH:mm:ss"; break; case 3: format = "yyyy年MM月dd日 HH:mm:ss"; break; case 4: format = "yyyyMMddHHmmss"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(new Date()); } /** * 获取当前时间yyyy-MM-dd * * @param mode * 格式 * @return */ public static String getYYYYMMDD(int mode) { String format = "yyyy-MM-dd"; switch (mode) { case 1: format = "yyyy/MM/dd"; break; case 2: format = "yyyy.MM.dd"; break; case 3: format = "yyyy年MM月dd日"; break; case 4: format = "yyyyMMdd"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(new Date()); } /** * 获取当前时间yyyy-MM * * @param mode * 格式 * @return */ public static String getYYYYMM(int mode) { String format = "yyyy-MM"; switch (mode) { case 1: format = "yyyy/MM"; break; case 2: format = "yyyy.MM"; break; case 3: format = "yyyy年MM月"; break; case 4: format = "yyyyMM"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(new Date()); } /** * 格式化时间 * * @param mode * 格式 * @return */ public static String dateFormat2(Date data, int mode) throws Exception { String format = "yyyy-MM-dd HH:mm:ss"; switch (mode) { case 1: format = "yyyy/MM/dd HH:mm:ss"; break; case 2: format = "yyyy.MM.dd HH:mm:ss"; break; case 3: format = "yyyy年MM月dd日 HH:mm:ss"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 格式化时间 格式:n(分钟/小时/天)前 * * @param date * @return * @throws Exception */ public static String dateFormat3(Date date) throws Exception { Date now = new Date(); long minute = 60; long hour = 3600; long day = 3600 * 24; long x = (now.getTime() - date.getTime()) / 1000; if (x < 60) { return "1分钟前"; } else if (x > minute && x < hour) { return (int) x / minute + "分钟前"; } else if (x > hour && x < day) { return x / hour + "小时前"; } else if (x > day && x < (day * 15)) { return x / day + "天前"; } else { return dateFormat2(date, 0); } } /** * 格式化时间yyyy-MM-dd HH:mm * * @param mode * 格式 * @return */ public static String dateFormat3(Date data, int mode) throws Exception { String format = "yyyy-MM-dd HH:mm"; switch (mode) { case 1: format = "yyyy/MM/dd HH:mm"; break; case 2: format = "yyyy.MM.dd HH:mm"; break; case 3: format = "yyyy年MM月dd日 HH:mm"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 格式化时间 格式:昨天 HH:mm、前天 HH:mm、日期(yyyy-MM-dd) * * @param date * @return * @throws Exception */ public static String dateFormat4(Date date) throws Exception { long days = calcDays(new Date(), date); if (days == 0) { return "今天 " + dateFormat6(date, 0); } else if (days == -1) { return "昨天 " + dateFormat6(date, 0); } else if (days == -2) { return "前天 " + dateFormat6(date, 0); } else { return dateFormat3(date, 0); } } /** * 格式化时间 格式:昨天 、前天、日期(yyyy-MM-dd) * * @param date * @return * @throws Exception */ public static String dateFormat5(Date date) throws Exception { long days = calcDays(new Date(), date); if (days == 0) { return "今天 "; } else if (days == -1) { return "昨天 "; } else if (days == -2) { return "前天 "; } else { return dateFormat4(date, 0); } } /** * 格式化时间 * * @param mode * 格式 * @return */ public static Date dateFormat4(String dateStr, int mode) throws Exception { String format = "yyyy-MM-dd"; switch (mode) { case 1: format = "yyyy/MM/dd"; break; case 2: format = "yyyy.MM.dd"; break; case 3: format = "yyyy年MM月dd日"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(dateStr); } /** * 格式化时间 * * @param mode * 格式 * @return */ public static String dateFormat4(Date date, int mode) throws Exception { String format = "yyyy-MM-dd"; switch (mode) { case 1: format = "yyyy/MM/dd"; break; case 2: format = "yyyy.MM.dd"; break; case 3: format = "yyyy年MM月dd日"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } /** * 格式化时间 yyyy-MM * * @param mode * 格式 * @return */ public static String dateFormat5(Date data, int mode) throws Exception { String format = "yyyy-MM"; switch (mode) { case 1: format = "yyyy/MM"; break; case 2: format = "yyyy.MM"; break; case 3: format = "yyyy年MM月"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 格式化时间 yyyy-MM * * @param mode * 格式 * @return */ public static Date dateFormat5(String dataStr, int mode) throws Exception { String format = "yyyy-MM"; switch (mode) { case 1: format = "yyyy/MM"; break; case 2: format = "yyyy.MM"; break; case 3: format = "yyyy年MM月"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.parse(dataStr); } /** * 格式化时间 HH:mm * * @param mode * 格式 * @return */ public static String dateFormat6(Date data, int mode) throws Exception { String format = "HH:mm"; switch (mode) { case 1: format = "HH/mm"; break; case 2: format = "HH.mm"; break; case 3: format = "HH时mm分"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 格式化时间 HH:mm:ss * * @param mode * 格式 * @return */ public static String dateFormat7(Date data, int mode) throws Exception { String format = "HH:mm:ss"; switch (mode) { case 1: format = "HH/mm/ss"; break; case 2: format = "HH.mm.ss"; break; case 3: format = "HH时mm分ss秒"; break; default: break; } SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 格式化时间 HH * * @param mode * 格式 * @return */ public static String dateFormat8(Date data) throws Exception { String format = "HH"; SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(data); } /** * 时间相加 * * @param date * @param hours * 小时 * @return */ public static Date addDate(Date date, int hours) { return new Date(date.getTime() + hours * 60 * 60 * 1000); } /** * 时间相加 * * @param date * @param minitues * 分钟 * @return */ public static Date addDate2(Date date, int minitues) { return new Date(date.getTime() + minitues * 60 * 1000); } /** * 时间相加 * * @param date * @param sec * 秒 * @return */ public static Date addDateSec(Date date, int sec) { return new Date(date.getTime() + sec * 1000); } /** * 时间相加 * * @param date * @param day * 天 * @return */ public static String addDate3(Date date, int day) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(calendar.DATE, day);// 把日期往后增加一天.整数往后推,负数往前移动 date = calendar.getTime(); // 这个时间就是日期往后推一天的结果 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateString = formatter.format(date); return dateString; } /** * 时间相加 * * @param date * @param day * 天 * @return */ public static String addDate4(Date date, int day) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(calendar.DATE, day);// 把日期往后增加一天.整数往后推,负数往前移动 date = calendar.getTime(); // 这个时间就是日期往后推一天的结果 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(date); return dateString; } /** * 获取随机数 * * @param len * 最大十位数 * @return */ public static int random(int len) { Random rdm = new Random(len); int intRd = Math.abs(rdm.nextInt()); return intRd; } /** * 将字符串封装成List<String> * * @param s * 字符串是以^符号进行连接的 * @return */ public static List<String> convertToList(String s) { String[] s1 = s.split("\\^"); List<String> list = new ArrayList<String>(); for (int i = 0; i < s1.length; i += 3) { list.add(s1[i]); } return list; } /** * 将字符串封装成List<String[]> * * @param s * 字符串是以^符号进行连接的 * @return */ public static List<String[]> convertToList2(String s) { String[] s1 = s.split("\\^"); List<String[]> list = new ArrayList<String[]>(); String[] s2 = null; for (int i = 0; i < s1.length; i += 3) { s2 = new String[3]; s2[0] = s1[i]; s2[1] = s1[i + 1]; s2[2] = s1[i + 2]; list.add(s2); } return list; } /** * 判断字符串是否为数字 * * @param str * @return */ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; } /** * 正则表达式匹配 * * @param regex * @param orginal * @return */ @SuppressWarnings("unused") private static boolean isMatch1(String regex, String orginal) { if (orginal == null || orginal.trim().equals("")) { return false; } Pattern pattern = Pattern.compile(regex); Matcher isNum = pattern.matcher(orginal); return isNum.matches(); } /** * ip地址转成整数. * * @param ip * @return */ public static long ip2long(String ip) { String[] ips = ip.split("[.]"); long num = 16777216L * Long.parseLong(ips[0]) + 65536L * Long.parseLong(ips[1]) + 256 * Long.parseLong(ips[2]) + Long.parseLong(ips[3]); return num; } /** * 整数转成ip地址. * * @param ipLong * @return */ public static String long2ip(long ipLong) { // long ipLong = 1037591503; long mask[] = { 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 }; long num = 0; StringBuffer ipInfo = new StringBuffer(); for (int i = 0; i < 4; i++) { num = (ipLong & mask[i]) >> (i * 8); if (i > 0) ipInfo.insert(0, "."); ipInfo.insert(0, Long.toString(num, 10)); } return ipInfo.toString(); } /** * 计算分钟 * * @param s * @return */ public static Integer calcMinute(String s) { String[] t = s.split(":"); return Integer.valueOf(t[0]) * 60 + Integer.valueOf(t[1]); } /** * 计算分钟 * * @param hours * 小时 * @return */ public static String calcMinute(Integer s) { int t = s % 60; return s / 60 + ":" + ((t < 10) ? "0" + t : t); } /** * 计算秒 * * @param s * @return */ public static Integer calcSecs(String s) { String[] t = s.split(":"); return Integer.valueOf(t[0]) * 60 * 60 + Integer.valueOf(t[1]) *60 + Integer.valueOf(t[2]); } /** * 计算地球上任意两点(经纬度)距离 * * @param long1 * 第一点经度 * @param lat1 * 第一点纬度 * @param long2 * 第二点经度 * @param lat2 * 第二点纬度 * @return 返回距离 单位:米 */ public static double Distance(double long1, double lat1, double long2, double lat2) { double a, b, R; R = 6378137; // 地球半径 lat1 = lat1 * Math.PI / 180.0; lat2 = lat2 * Math.PI / 180.0; a = lat1 - lat2; b = (long1 - long2) * Math.PI / 180.0; double d; double sa2, sb2; sa2 = Math.sin(a / 2.0); sb2 = Math.sin(b / 2.0); d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2)); return d; } /** * 根据经纬度获取地址 * * @param longitude * @param latitude * @return * @throws HttpException * @throws IOException */ public static String getBaiduMapArea(double longitude, double latitude) throws HttpException, IOException { HttpClient client = new HttpClient(); client.setConnectionTimeout(6 * 1000); // Latitude: Longitude: String url = ToolKit.getInstance().getSingleConfig( "baidu_map_interface") + "?callback=renderReverse&location=" + latitude + "," + longitude + "&output=json&pois=0&ak=" + ToolKit.getInstance().getSingleConfig("baidu_map_ak"); // http://api.map.baidu.com/geocoder/v2/?ak=您的密钥&callback=renderReverse&location=39.983424,116.322987&output=json&pois=0 GetMethod getMethod = new GetMethod(url); int statusCode = client.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { String sms = getMethod.getResponseBodyAsString(); ConsoleUtil.println("result:" + sms); sms = sms.replaceAll("renderReverse&&renderReverse", ""); sms = sms.substring(1, sms.length() - 1); ConsoleUtil.println("result: 0000 " + sms); return sms; } return null; } /** * 解析百度地图返回的地区数据 * * @param sms * @return * @throws Exception */ public static String[] parseMapJson(String sms) throws Exception { net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(sms); String[] citys = new String[4]; if (object.getString("status").equals("0")) { Integer cityCode = object.getJSONObject("result") .getInt("cityCode"); JSONObject obj = object.getJSONObject("result").getJSONObject( "addressComponent"); String city = obj.getString("city"); citys[0] = city; citys[1] = cityCode + ""; citys[2] = obj.getString("province"); citys[3] = object.getJSONObject("result").getString( "formatted_address"); return citys; } return null; } /** * 获取百度地图的经纬度 * * @param address * @return * @throws Exception */ public static String getBaiduMapResult(String address) throws Exception { HttpClient client = new HttpClient(); client.setConnectionTimeout(6 * 1000); String url = ToolKit.getInstance().getSingleConfig( "baidu_map_interface") + "?address=" + URLEncoder.encode(address) + "&output=json&ak=" + ToolKit.getInstance().getSingleConfig("baidu_map_ak"); // "http://api.map.baidu.com/geocoder/v2/?address="+URLEncoder.encode(address)+"&output=json&ak=DqTGazNxpb6tujm41W2ULrtb"; GetMethod getMethod = new GetMethod(url); int statusCode = client.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { String sms = getMethod.getResponseBodyAsString(); ConsoleUtil.println("result:" + sms); return sms; } return null; } /** * 解析百度地图返回的经纬度数据 * * @param sms * @return * @throws Exception */ public static Double[] parseJson(String sms) throws Exception { net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(sms); if (object.getString("status").equals("0")) { object = object.getJSONObject("result").getJSONObject("location"); ConsoleUtil.println(object.getDouble("lng") + "-->" + object.getDouble("lat")); Double[] d = new Double[] { object.getDouble("lng"), object.getDouble("lat") }; return d; } return null; } /** * 格式化距离显示 * * @param d * @return */ public static String formatDistance(Double d) { int k = d.intValue() / 1000; int l = d.intValue() % 1000; if (k < 1) { k = d.intValue(); if (k < 300) return "<300m"; return k + "m"; } else { l = l / 100; return k + "." + l + "km"; } } /** * 格式化距离显示 * @param d * @return */ public static String formatDistance2(Double d){ int k = d.intValue() / 1000; int l = d.intValue() % 1000; if(k < 1){ int s = l % 100; if(d.intValue()<300){ return "<0.3km"; } return "0."+ (int)(d / 100) + "km"; }else{ l = l / 100; return k + "." + l +"km"; } } /** * 返回正确的地址 * * @param d * @return */ public static String getLocalHttpUrl(String s, String webroot) { if (StringUtils.isNotEmpty(s)) { if (s.startsWith("http://") || s.startsWith("https://")) { return s; } else { return webroot + s; } } return ""; } /** * 返回图片地址,没有则返回默认图片地址 * * @param d * @return */ public static String getLocalHttpUrl(String s, String webroot, Integer categoryId, boolean flag) { if (StringUtils.isNotEmpty(s)) { if (s.startsWith("http://") || s.startsWith("https://")) { return s; } else { return webroot + s; } } else if (flag) { return webroot + "resources/images/index_sort" + categoryId + ".png"; } return ""; } /** * 图片服务器返回的图片地址,没有则返回默认图片地址 webroot 服务器 webroot2 图片服务器 * * @param sHOP_LOGO * @return */ public static String getHeadImgUrl(String logo, String webroot, String webrootImg, Integer categoryId, String handle) { if (StringUtils.isNotEmpty(logo)) { if (logo.startsWith("http://") || logo.startsWith("https://")) { return logo; } else { return webrootImg + logo + handle; } } else { // 没有图片默认 return webroot + "resources/images/defaul_headurl.png"; } } /** * 图片服务器返回的图片地址,没有则返回默认图片地址 webroot 服务器 webroot2 图片服务器 * * @param sHOP_LOGO * @return */ public static String getImgUrl(String logo, String webroot, String webrootImg, Integer categoryId, String handle) { if (StringUtils.isNotEmpty(logo)) { if (logo.startsWith("http://") || logo.startsWith("https://")) { return logo; } else { return webrootImg + logo + handle; } } else { // 没有图片默认 return webroot + "resources/images/index_sort" + categoryId + ".png"; } } /** * 图片服务器返回的图片地址,没有则返回默认图片地址 webroot 服务器 webroot2 图片服务器 * * @param sHOP_LOGO * @return */ public static String getImgUrl(String logo, String webroot, String webrootImg, Integer categoryId, String handle, boolean flag) { if (StringUtils.isNotEmpty(logo)) { if (logo.startsWith("http://") || logo.startsWith("https://")) { return logo; } else { return webrootImg + logo + handle; } } else if (flag) { // 没有图片默认 return webroot + "resources/images/index_sort" + categoryId + ".png"; } return null; } /** * 返回不同项目的图片地址,没有则返回默认图片地址 * * @return */ public static String getLocalHttpUrl(String s, String webroot, String webRoot2, int source, Integer categoryId, boolean flag) { String path = ""; // 录入工具 if (source < 3) { path = webRoot2; } else { path = webroot; } if (StringUtils.isNotEmpty(s)) { if (s.startsWith("http://") || s.startsWith("https://")) { return s; } else { return path + s; } } else if (flag) { // 没有图片默认 return webroot + "resources/images/index_sort" + categoryId + ".png"; } return ""; } /** * 比较两个时间之间相差多少天 * * @param date1 * 较小的时间(null则默认为当前时间) * @param date2 * 较大的时间(null则默认为当前时间) * @return * @throws ParseException */ public static int compareDate(Date date1, Date date2) throws ParseException { date1 = date1 == null ? new Date() : date1; date2 = date2 == null ? new Date() : date2; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); date1 = sdf.parse(sdf.format(date1)); date2 = sdf.parse(sdf.format(date2)); Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); long time1 = calendar.getTimeInMillis(); calendar.setTime(date2); long time2 = calendar.getTimeInMillis(); return Integer.parseInt(String.valueOf((time2 - time1) / (1000 * 3600 * 24))); } /** * 转换服务范围 * * @param s * @return */ public static Integer convertArea(String s) { if ("500M".equals(s.toUpperCase()) || "500M以内".equals(s.toUpperCase())) { return 1; } else if ("1KM".equals(s.toUpperCase()) || "1KM以内".equals(s.toUpperCase())) { return 2; } else if ("3KM".equals(s) || "3KM以内".equals(s.toUpperCase())) { return 3; } else if ("5KM".equals(s) || "5KM以内".equals(s.toUpperCase())) { return 4; } else if ("全城".equals(s) || "全程以内".equals(s.toUpperCase())) { return 5; } else if ("不限".equals(s) || "不限以内".equals(s.toUpperCase())) { return 6; } return 0; } /** * 转换服务范围 * * @param s * @return */ public static String convertArea(Integer i) { switch (i) { case 1: return "500M"; case 2: return "1KM"; case 3: return "3KM"; case 4: return "5KM"; case 5: return "全城"; case 6: return "不限"; default: break; } return ""; } /** * 手机验证码 * * @return */ public static String getVerify() { // ,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z String str = "0,1,2,3,4,5,6,7,8,9"; String str2[] = str.split(",");// 将字符串以,分割 int sum = 0;// 计数器 for (int i = 0; i < str2.length; ++i) { ++sum; if (0 == sum % 10) { ConsoleUtil.println("");// 没十个数据换行 } } ConsoleUtil.println(""); Random rand = new Random();// 创建Random类的对象rand int index = 0; String randStr = "";// 创建内容为空字符串对象randStr // Scanner scan = new Scanner(System.in);//创建Scanner类的对象 // while (!scan.next().equals("#"))//判断从键盘输入的是否是字符# // { randStr = "";// 清空字符串对象randStr中的值 for (int i = 0; i < 4; ++i) { index = rand.nextInt(str2.length - 1);// 在0到str2.length-1生成一个伪随机数赋值给index randStr += str2[index];// 将对应索引的数组与randStr的变量值相连接 } ConsoleUtil.println("验证码:" + randStr);// 输出所求的验证码的值 // } return randStr; } /** * 获取len位随机数 * * @return */ public static String getRandomNumber(int len) { // ,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z String str = "0,1,2,3,4,5,6,7,8,9"; String str2[] = str.split(",");// 将字符串以,分割 int sum = 0;// 计数器 for (int i = 0; i < str2.length; ++i) { ++sum; if (0 == sum % 10) { ConsoleUtil.println("");// 没十个数据换行 } System.out.print(str2[i] + " "); } ConsoleUtil.println(""); Random rand = new Random();// 创建Random类的对象rand int index = 0; String randStr = "";// 创建内容为空字符串对象randStr // Scanner scan = new Scanner(System.in);//创建Scanner类的对象 // while (!scan.next().equals("#"))//判断从键盘输入的是否是字符# // { randStr = "";// 清空字符串对象randStr中的值 for (int i = 0; i < len; ++i) { index = rand.nextInt(str2.length - 1);// 在0到str2.length-1生成一个伪随机数赋值给index randStr += str2[index];// 将对应索引的数组与randStr的变量值相连接 } // ConsoleUtil.println("验证码:" + randStr);// 输出所求的验证码的值 // } return randStr; } /** * 判断是否为手机号 * * @param mobiles * @return 是 true */ public static boolean isMobileNO(String mobiles) { Pattern p = Pattern .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); Matcher m = p.matcher(mobiles); return m.matches(); } /** * 判断是否为手机号 * * @param mobiles * @return 是 true */ public static boolean isMobileNO2(String mobiles) { Pattern p = Pattern.compile("^((1)+\\d{10})$"); Matcher m = p.matcher(mobiles); return m.matches(); } /** * 判断是否为身份证号 * * @param mobiles * @return 是 true */ public static boolean isIDCard(String idcard) { String rex = "^[0-9+]\\d{13,17}|[0-9+]\\d{13,17}x"; Pattern pattern = Pattern.compile(rex); Matcher m = pattern.matcher("42028119891014111x"); return m.matches(); } /** * 价格区间判断 * @param scope * @param value * @return */ public static long isInScope(List<Long> nums,Long salesNum) { for (int i = 0; i < nums.size(); i++) { //数量大于最大的区间的值 if(salesNum >= nums.get(i).longValue()){ return nums.get(i).longValue(); } } return 0l; } /** * 价格区间判断 * @param scope * @param value * @return */ public static boolean isInScope(String scope, String value) { Pattern pattern = Pattern.compile("^(\\(|\\[)\\d+,\\s*\\d+(\\)|\\])$"); Matcher matcher = pattern.matcher(scope); if (!matcher.find()) { return false; } String[] scopes = scope.split(","); Float valueF = Float.valueOf(value); Float min = Float.valueOf(scopes[0].substring(1)); //最小值 if ("[".equals(String.valueOf(scopes[0].charAt(0)))) { if (valueF < min) return false; } //最大值 Float max = Float.valueOf(scopes[1].substring(0, scopes[1].length() - 1)); if ("]".equals(String.valueOf(scopes[1].charAt(scopes[1].length() - 1)))) { if (valueF >= max) return false; } /*if ("(".equals(String.valueOf(scopes[0].charAt(0)))) { if (valueF <= min) return false; } else if ("[".equals(String.valueOf(scopes[0].charAt(0)))) { if (valueF < min) return false; } Float max = Float.valueOf(scopes[1].substring(0, scopes[1].length() - 1)); if (")".equals(String.valueOf(scopes[1].charAt(scopes[1].length() - 1)))) { if (valueF >= max) return false; } else if ("]".equals(String.valueOf(scopes[1].charAt(scopes[1].length() - 1)))) { if (valueF > max) return false; } */ return true; } /** * 解析qq登录错误信息文本 * * @return */ public JSONObject ParseQQLoginErrorMsg(String result) { if (result.contains("callback") && result.contains("error")) { result = result.replace("callback", "").replace("(", "") .replace(")", "").replace(";", ""); JSONObject object = JSONObject.fromObject(result.trim()); return object; } return null; } /** * app端传递的参数解析成json放入session中 * * @return */ public static void appParamsToJsonSetSession(HttpServletRequest request, String sessionKey) { Map<String, String[]> map = request.getParameterMap(); JSONObject object = new JSONObject(); if (map != null && map.size() > 0) { String value = null; String redirectUrl = null; if (map.containsKey(CommConstant.REDIRECT_URL)) { redirectUrl = map.get(CommConstant.REDIRECT_URL)[0]; } String appendStr = ""; for (Map.Entry<String, String[]> m : map.entrySet()) { value = m.getValue()[0]; object.put(m.getKey(), value); if (!CommConstant.REDIRECT_URL.equals(m.getKey())) { appendStr += "&" + m.getKey() + "=" + value; } } if (StringUtils.isAllNotEmpty(redirectUrl, appendStr)) { redirectUrl += appendStr.replaceFirst("&", "?"); object.put(CommConstant.REDIRECT_URL, redirectUrl); } } request.getSession().setAttribute(sessionKey, object.toString()); } /** * 从session中取得app端传递的参数解析成json * * @return */ public static JSONObject appParamsToJsonFromSession( HttpServletRequest request, String sessionKey) { String appParam = (String) request.getSession() .getAttribute(sessionKey); JSONObject object = new JSONObject(); if (StringUtils.isNotEmpty(appParam)) { object = JSONObject.fromObject(appParam); } return object; } /** * 判断两个日期是否是同一天 * * @param date * @param minitues * 分钟 * @return */ public static boolean isSameDay(Date date, Date date2) { Calendar calDateA = Calendar.getInstance(); calDateA.setTime(date); Calendar calDateB = Calendar.getInstance(); calDateB.setTime(date2); return calDateA.get(Calendar.YEAR) == calDateB.get(Calendar.YEAR) && calDateA.get(Calendar.MONTH) == calDateB.get(Calendar.MONTH) && calDateA.get(Calendar.DAY_OF_MONTH) == calDateB .get(Calendar.DAY_OF_MONTH); } /** * 替换旧的jsonarray数据 * * @param jsonArr1 * 原始的array * @param jsonArr2 * 新修改的array * @param keyConstant * array中的obj其中的一个key,必须jsonArr1和jsonArr2中都有且一样 * @return */ public static JSONArray replaceIndexJsonObject(String jsonArr1, String jsonArr2, String keyConstant) { JSONArray array = JSONArray.fromObject(jsonArr1); // 修改后的数据 JSONArray array2 = JSONArray.fromObject(jsonArr2); JSONObject jsonObject = null; JSONObject jsonObject2 = null; JSONArray array3 = new JSONArray(); array3 = array; if (!array2.isEmpty()) { // 循环修改的数据 for (int j = 0; j < array2.size(); j++) { jsonObject2 = array2.getJSONObject(j); // 取得修改的是哪个数据 for (int k = 1; k < 5; k++) { String key = keyConstant + k; if (jsonObject2.containsKey(key)) { int count = 0; for (int i = 0; i < array.size(); i++) { jsonObject = array.getJSONObject(i); if (!jsonObject.containsKey(key)) { count++; } else { array3.remove(i); array3.add(i, jsonObject2); } if (count == array.size()) { array3.add(i, jsonObject2); break; } } } } } } return array3; } /** * 将user对象放入到session中 * * @param date * @param minitues * 分钟 * @return */ public static void setSessionUser(HttpServletRequest request, UserLoginModel user) { JSONObject jsonObject = JSONObject.fromObject(user); request.getSession().setAttribute(CommConstant.SESSION_MANAGER,jsonObject.toString()); } /** * 将user对象放入到session中 * * @param date * @param minitues * 分钟 * @return */ public static User getSessionUser(HttpServletRequest request) { User user = null; String jsonString = (String) request.getSession().getAttribute( CommConstant.SESSION_MANAGER); if (StringUtils.isNotEmpty(jsonString)) { JSONObject jsonObject = JSONObject.fromObject(jsonString); user = (User) JSONObject.toBean(jsonObject, User.class); } return user; } /** * 计算日期天数 * * @param date * @param minitues * 分钟 * @return */ public static long calcDays(Date date1, Date date2) { // 当前时间处理 Calendar cal = Calendar.getInstance(); cal.setTime(date1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); // 给定时间处理 Calendar setCal = Calendar.getInstance(); setCal.setTime(date2); setCal.set(Calendar.HOUR_OF_DAY, 0); setCal.set(Calendar.MINUTE, 0); setCal.set(Calendar.SECOND, 0); setCal.set(Calendar.MILLISECOND, 0); long dayDiff = (setCal.getTimeInMillis() - cal.getTimeInMillis()) / (1000 * 60 * 60 * 24); // ConsoleUtil.println(dayDiff); return dayDiff; } /** * 计算日期天数(包括时分秒) * * @param date * @param minitues * 分钟 * @return */ public static long calcDays2(Date date1, Date date2) { // 当前时间处理 Calendar cal = Calendar.getInstance(); cal.setTime(date1); // 给定时间处理 Calendar setCal = Calendar.getInstance(); setCal.setTime(date2); long dayDiff = (setCal.getTimeInMillis() - cal.getTimeInMillis()) / (1000 * 60 * 60 * 24); //ConsoleUtil.println(dayDiff); return dayDiff; } /** * 计算日期秒数(包括时分秒) * * @param date * @param minitues * 分钟 * @return */ public static long calcSecs(Date date1, Date date2) { // 当前时间处理 Calendar cal = Calendar.getInstance(); cal.setTime(date1); // 给定时间处理 Calendar setCal = Calendar.getInstance(); setCal.setTime(date2); long dayDiff = (setCal.getTimeInMillis() - cal.getTimeInMillis()) / (1000); //ConsoleUtil.println(dayDiff); return dayDiff; } /** * 判断是否手机端 * * @param request * @return * @throws Exception */ public static boolean isPhone(HttpServletRequest request) throws Exception { String u = request.getHeader("user-agent").toLowerCase(); ConsoleUtil.println(u); Pattern pattern = Pattern .compile("/applewebkit.*mobile.*/ || /applewebkit/"); Matcher m = pattern.matcher(u); // android终端或者uc浏览器 if (u.indexOf("android") > -1 || u.indexOf("linux") > -1 // 是否为iPhone或者QQHD浏览器 || u.indexOf("iphone") > -1 || u.indexOf("mac") > -1 // 是否iPad || u.indexOf("ipad") > -1 // 是否为移动终端 || !!m.matches()) { return true; //return false; } return false; /* * trident: u.indexOf('Trident') > -1, //IE内核 presto: * u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') * > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') * == -1, //火狐内核 mobile: , ios: !!u.match(/\\(i[^;]+;( U;)? CPU.+Mac OS * X/), //ios终端 android: , iPhone: , iPad: , webApp: u.indexOf('Safari') * == -1 //是否web应该程序,没有头部与底部 }; } language:(navigator.browserLanguage || * navigator.language).toLowerCase() } * * window.location.href="URL" */ } /** * 判断是否IOS手机端 * * @param request * @return * @throws Exception */ public static boolean isIosPhone(HttpServletRequest request) throws Exception { String u = request.getHeader("user-agent").toLowerCase(); ConsoleUtil.println(u); Pattern pattern = Pattern.compile("/\\(i[^;]+;( U;)? CPU.+Mac OS X/"); Matcher m = pattern.matcher(u); // return u.indexOf("iphone") > -1 || u.indexOf("ipad") > -1 || // !!m.matches(); return false; } /** * 判断是否IOS手机端 * * @param request * @return * @throws Exception */ public static boolean isIosPhone2(HttpServletRequest request) throws Exception { String u = request.getHeader("user-agent").toLowerCase(); Pattern pattern = Pattern.compile("/\\(i[^;]+;( U;)? CPU.+Mac OS X/"); Matcher m = pattern.matcher(u); return u.indexOf("iphone") > -1 || u.indexOf("ipad") > -1 || !!m.matches(); } /** * 判断是否为微信端 * * @param request * @return * @throws Exception */ public static boolean isWx(HttpServletRequest request) throws Exception { String u = request.getHeader("user-agent").toLowerCase(); ConsoleUtil.println(u); return u.indexOf("micromessenger") > -1; } /** * 获取周几 * @param date * @return */ public static int getWeek(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int week = cal.get(Calendar.DAY_OF_WEEK) - 1; //0表示周末 if(week == 0){ return 7; } return week; } /** * 通过HttpServletRequest返回IP地址 * * @param request * HttpServletRequest * @return ip String * @throws Exception */ public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; try { // ipAddress = this.getRequest().getRemoteAddr(); ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (Exception e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } } catch (Exception e) { e.printStackTrace(); } return ipAddress; } /** * 通过ip地址获取经纬度 * @return */ public static UserArea getUserAreaForLatAndLong(HttpServletRequest request,UserArea userArea){ String ip = getIpAddr(request); if(StringUtils.isNotEmpty(ip)){ try { if(userArea == null){ //部署线上 String url ="http://api.map.baidu.com/location/ip?ak=DqTGazNxpb6tujm41W2ULrtb&coor=bd09ll&ip=125.94.97.127"; // String url ="http://api.map.baidu.com/location/ip?ak=DqTGazNxpb6tujm41W2ULrtb&coor=bd09ll&ip="+ip; String jsonRes = Connect.getUrlString(url); logger.info("百度ip获取位置后 jsonRes:" + jsonRes); ConsoleUtil.println("百度ip获取位置后 jsonRes:" + jsonRes); JSONObject object = Json.string2json(jsonRes); userArea = new UserArea(); // 详细内容 JSONObject content = object.getJSONObject("content"); userArea.setAddress(content.getString("address")); JSONObject detail = content.getJSONObject("address_detail"); userArea.setCity(detail.getString("city")); String baiduCode = detail.getString("city_code"); userArea.setCity_code(baiduCode); userArea.setProvince(detail.getString("province")); JSONObject point = content.getJSONObject("point"); userArea.setLongitude(point.getDouble("x"));// 经度 userArea.setLatitude(point.getDouble("y"));// 纬度 userArea.setStatus(object.getString("status")); } } catch (Exception e) { e.printStackTrace(); logger.error("通过ip地址获取经纬度",e); } } return userArea; } /** * 获取WEB—INF的绝对路径 * @return * @throws Exception */ public static String getProjectWebInfoPath() throws Exception{ //取得根目录路径 String rootPath=MyUtils.class.getResource("/").getFile().toString(); ConsoleUtil.println(rootPath); return rootPath.replace("/classes/", ""); } /** * 获取WebRoot的绝对路径 * @return * @throws Exception */ public static String getProjectWebRootPath() throws Exception{ //取得根目录路径 String rootPath=MyUtils.class.getResource("/").getFile().toString(); ConsoleUtil.println(rootPath); return rootPath.replace("/WEB-INF/classes/", ""); } /** * 计算范围值,是否可获取对应的状态 * @return * @throws Exception */ public static boolean calcRangeReturnStatus(String range,Integer compareValue) throws Exception{ if(StringUtils.isEmptyNo(range)){ return false; } String[] r = range.split("~"); if(r.length < 2){ if(compareValue >= Integer.valueOf(r[0])){ return true; } return false; }else{ if(Integer.valueOf(r[0]) <= compareValue && compareValue <= Integer.valueOf(r[1])){ return true; } return false; } } /** * 获取最大值 * @return * @throws Exception */ public static Long obtainMax(List<MyEarnings> list) throws Exception{ Long n = null; for (MyEarnings mer : list) { if(null == n){ n = mer.getPaincbuyProjectId(); } if(n < mer.getPaincbuyProjectId()){ n = mer.getPaincbuyProjectId(); } } return n; } /** * 拼接完整的地址 * @return * @throws Exception */ public static String getCompleteAddress(Long provinceId,Long cityId,String address) throws Exception{ String provinceName = PhoneBaseData.getInstance().getArea_V2Name(provinceId+""); String cityName = PhoneBaseData.getInstance().getArea_V2Name(cityId+""); if (provinceName == null) { provinceName = ""; } if (cityName == null) { cityName = ""; } if (provinceName.equals(cityName)) { cityName = ""; } address = provinceName + cityName + address; return address; } public void test(HttpServletRequest request) { } /** * 计算分页栏分页数值 * @param perPages 页大小 * @param countRows 总记录数 * @param currentPage 当前页 * @param showPageNum 分页栏要显示的数值数量 * @return */ public static PagerArg calcPagerNum(int perPages, int countRows,int currentPage, int showPageNum){ //Map<String, Object> result = new HashMap<String, Object>(); int pageCount = (int) Math.ceil((double)countRows/perPages); int offset = (int) Math.floor((double)showPageNum/2); int beginPage = currentPage-offset; int endPage = currentPage+offset; if(beginPage<1){ endPage += Math.abs(beginPage)+1; beginPage=1; } if(endPage>pageCount){ endPage = pageCount; } if(endPage == pageCount){ beginPage = endPage-offset*2; if(beginPage<1) beginPage=1; } if(beginPage == 1){ endPage = 1+offset*2; if(endPage>pageCount) endPage=pageCount; } int lastPage = currentPage-1; int nextPage = currentPage+1; if(lastPage<beginPage){ lastPage = beginPage; } if(nextPage>endPage){ nextPage = endPage; } /*result.put("beginPage", beginPage); result.put("endPage", endPage); result.put("lastPage", lastPage); result.put("currentPage", currentPage); result.put("nextPage", nextPage); result.put("rowCount", countRows); result.put("pageCount",pageCount); return result;*/ return new PagerArg(beginPage, endPage, lastPage, currentPage, nextPage, countRows, pageCount); } public static void main(String[] args) throws Exception { /*String rex = "^[0-9+]\\d{13,17}|[0-9+]\\d{13,17}x"; Pattern pattern = Pattern.compile(rex); Matcher m = pattern.matcher("42028119891014111x"); ConsoleUtil.println(m.matches()); calcDays2(MyUtils.dateFormat("2015-07-06 10:00:00", 0), new Date()); BigDecimal money = new BigDecimal(2); ConsoleUtil.println(money.multiply(new BigDecimal(100)).intValue()); ConsoleUtil.println(dateFormat("20141030133525", 4)); SortedMap<String, String> packageParams = new TreeMap<String, String>(); packageParams.put("appid","wxbe1733e33bb01bdf"); packageParams.put("attach","324764"); packageParams.put("bank_type","CFT"); packageParams.put("cash_fee","1"); packageParams.put("fee_type","CNY"); packageParams.put("is_subscribe","Y"); packageParams.put("mch_id","1252770301"); packageParams.put("nonce_str","172608RtuS"); packageParams.put("openid","ouH5Awi4P38BF55zMVOjm0Vigw-U"); packageParams.put("out_trade_no","1507094310"); packageParams.put("result_code","SUCCESS"); packageParams.put("return_code","SUCCESS"); packageParams.put("sign","ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7"); packageParams.put("time_end","20150709172619"); packageParams.put("total_fee","1"); packageParams.put("trade_type","JSAPI"); packageParams.put("transaction_id","1001450064201507090375450932"); StringBuffer sb = new StringBuffer(); Set es = packageParams.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); String v = (String) entry.getValue(); if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { sb.append(k + "=" + v + "&"); } ConsoleUtil.println("sign - key :"+k+"- > value :"+v); } sb.append("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"); ConsoleUtil.println("md5 sb:" + sb); String sign = MD5.GetMD5Code(sb.toString(), "UTF-8").toUpperCase(); ConsoleUtil.println("packge签名:" + sign);*/ //企业代码+用户密码 // String s = "hzdhlzxhzd158"; // ConsoleUtil.println(MD5.GetMD5Code(s)); // // ConsoleUtil.println(ToolKit.getInstance().getSingleConfig("xxxx")); // String s1="[{\"categoryId\":90,\"userId\":105,\"shopId\":344828,\"serviceId\":1169,\"purchaseNum\":1,\"name\":\"水杯\",\"path\":\"/upload/2015-07-23/1437615657429411198.jpg\",\"price\":0.01,\"summary\":\"一个黄色的水杯\"}]"; // // JSONArray array = JSONArray.fromObject(s1); // // for (int j = 0; j < array.size(); j++) { // // ConsoleUtil.println(array.getJSONObject(j).getLong("serviceId")); // } //对所有待签名参数按照字段名的 ASCII 码从小到大排序 /*SortedMap<String, String> packageParams = new TreeMap<String, String>(); packageParams.put("accesstoken", "9jnerlff23u8ed01np9g6ysbhsh0dvcs"); packageParams.put("appid", "wx17ef1eaef46752cb"); packageParams.put("url", "http://open.weixin.qq.com/"); packageParams.put("timestamp", "1384841012"); packageParams.put("noncestr", "123456"); String addrsign = Sha1Util.createSHA1Sign(packageParams); String strSrc = "accesstoken=9jnerlff23u8ed01np9g6ysbhsh0dvcs&appid=wx17ef1eaef46752cb&noncestr=123456&timestamp=1384841012&url=http://open.weixin.qq.com/"; //ca604c740945587544a9cc25e58dd090f200e6fb //accesstoken=9jnerlff23u8ed01np9g6ysbhsh0dvcs&appid=wx17ef1eaef46752cb&noncestr=123456&timestamp=1384841012&url=http://open.weixin.qq.com/ //accesstoken=9jnerlff23u8ed01np9g6ysbhsh0dvcs&appid=wx17ef1eaef46752cb&noncestr=123456&timestamp=1384841012&url=http://open.weixin.qq.com/ ConsoleUtil.println(addrsign); ConsoleUtil.println(addrsign.equalsIgnoreCase("ca604c740945587544a9cc25e58dd090f200e6fb")); SortedMap<String, String> finalpackage = new TreeMap<String, String>(); String timestamp = String.valueOf(System.currentTimeMillis() / 1000); String prepay_id2 = "prepay_id=1101000000140415649af9fc314aa427"; finalpackage.put("appid", "wxd930ea5d5a258f4f"); finalpackage.put("partnerid", "1900000109"); finalpackage.put("prepayid", "1101000000140415649af9fc314aa427"); finalpackage.put("package", "Sign=WXPay"); finalpackage.put("noncestr", "9q3vfhm7l33rus21toc8fndupq76itje"); finalpackage.put("timestamp", "1398746574"); StringBuffer sb = new StringBuffer(); Set es = finalpackage.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); String v = (String) entry.getValue(); if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { sb.append(k + "=" + v + "&"); } ConsoleUtil.println("sign - key :"+k+"- > value :"+v); } //sb.append("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"); ConsoleUtil.println("md5 sb:" + sb); String sign = MD5.GetMD5Code(sb.toString().substring(0,sb.toString().length() - 1), "UTF-8").toUpperCase(); ConsoleUtil.println("packge签名:" + sign);*/ /*ConsoleUtil.println(MD5.GetMD5Code("bjwg")); JSONObject jo = new JSONObject(); jo.put("28天断奶仔猪1头", 0); jo.put("仔猪喂养至出栏所需", 0); jo.put("饲料", 0); jo.put("疫苗", 0); jo.put("保健费用", 0); jo.put("疾病治疗中草药费用", 0); jo.put("人工成本", 0); jo.put("固定资产折旧等", 0); ConsoleUtil.println(jo.toString()); ConsoleUtil.println(new BigDecimal(2).divide(new BigDecimal(150.0),4,BigDecimal.ROUND_HALF_UP));*/ SimpleDateFormat df=new SimpleDateFormat("E(MM月dd日) a hh:mm"); System.out.println(df.format(new Date())); /*Calendar calendar = Calendar.getInstance(Locale.CHINA); calendar.setTime(new Date()); System.out.println("周"+calendar.);*/ System.out.println(MD5.GetMD5Code(MD5.GetMD5Code("123456")+ LoginConstants.LOGIN_PASSWORD_PARAM)); String u = "mozilla/5.0 (iphone; cpu iphone os 7_1 like mac os x) applewebkit/537.51.2 (khtml, like gecko) mobile/11d167 micromessenger/6.2.2 nettype/3g+ language/zh_cn"; Pattern pattern = Pattern.compile("/micromessenger"); Matcher m = pattern.matcher(u); System.out.println(u.indexOf("micromessenger") > -1); } }
922eac40033cea15d623c4871d7add4eeebb62bd
91
java
Java
src/main/groovy/com/happinesea/ec/rws/lib/bean/enumerated/package-info.java
happinesea/rws-lib
72e5e398a030e6a3ffec100f29624af3deeb1b7d
[ "MIT" ]
2
2018-02-16T01:31:26.000Z
2018-05-10T08:54:43.000Z
src/main/groovy/com/happinesea/ec/rws/lib/bean/enumerated/package-info.java
happinesea/rws-lib
72e5e398a030e6a3ffec100f29624af3deeb1b7d
[ "MIT" ]
1
2018-05-04T08:54:21.000Z
2018-05-04T08:54:21.000Z
src/main/groovy/com/happinesea/ec/rws/lib/bean/enumerated/package-info.java
happinesea/rws-lib
72e5e398a030e6a3ffec100f29624af3deeb1b7d
[ "MIT" ]
null
null
null
22.75
50
0.736264
994,823
/** * rws-lib全体に利用する列挙を格納するパッケージ */ package com.happinesea.ec.rws.lib.bean.enumerated;
922ead86f750b2377182cb06c3e2d238ad012cd3
5,680
java
Java
statuslayout/src/main/java/io/github/mayunfei/statuslayout/StatusLayout.java
MaYunFei/StatusLayout
4020f9461e1b8049c2b550ce99f9783c68d44efa
[ "Apache-2.0" ]
1
2019-01-26T09:40:49.000Z
2019-01-26T09:40:49.000Z
statuslayout/src/main/java/io/github/mayunfei/statuslayout/StatusLayout.java
MaYunFei/StatusLayout
4020f9461e1b8049c2b550ce99f9783c68d44efa
[ "Apache-2.0" ]
null
null
null
statuslayout/src/main/java/io/github/mayunfei/statuslayout/StatusLayout.java
MaYunFei/StatusLayout
4020f9461e1b8049c2b550ce99f9783c68d44efa
[ "Apache-2.0" ]
null
null
null
32.090395
124
0.626232
994,824
package io.github.mayunfei.statuslayout; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewStub; import android.widget.FrameLayout; /** * 状态 * Created by mayunfei on 17-7-7. */ public class StatusLayout extends FrameLayout { public interface OnRetryListener { void onRetry(View view); } private OnRetryListener retryListener; public View mContentView; public ViewStub mLoadingView; public ViewStub mEmptyView; public ViewStub mNetWorkView; public ViewStub mErrorView; private int mEmptyViewResID; // emptyVIewId private int mNetWorkViewResID; private int mLoadingViewResID; private int mContentViewResID; private int mErrorViewResID; private int mRetryResID; /** * 存放布局集合 */ private SparseArray<View> layoutSparseArray = new SparseArray(); public StatusLayout(@NonNull Context context) { this(context, null); } public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } private void init(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.StatusLayout, defStyleAttr, 0); try { int indexCount = typedArray.getIndexCount(); for (int i = 0; i < indexCount; i++) { int attr = typedArray.getIndex(i); if (attr == R.styleable.StatusLayout_emptyView) { mEmptyViewResID = typedArray.getResourceId(R.styleable.StatusLayout_emptyView, -1); mEmptyView = new ViewStub(context); mEmptyView.setLayoutResource(mEmptyViewResID); } else if (attr == R.styleable.StatusLayout_networkView) { mNetWorkViewResID = typedArray.getResourceId(R.styleable.StatusLayout_networkView, -1); mNetWorkView = new ViewStub(context); mNetWorkView.setLayoutResource(mNetWorkViewResID); } else if (attr == R.styleable.StatusLayout_loadingView) { mLoadingViewResID = typedArray.getResourceId(R.styleable.StatusLayout_loadingView, -1); mLoadingView = new ViewStub(context); mLoadingView.setLayoutResource(mLoadingViewResID); } else if (attr == R.styleable.StatusLayout_errorView) { mErrorViewResID = typedArray.getResourceId(R.styleable.StatusLayout_errorView, -1); mErrorView = new ViewStub(context); mErrorView.setLayoutResource(mErrorViewResID); } else if (attr == R.styleable.StatusLayout_retryId) { mRetryResID = typedArray.getResourceId(R.styleable.StatusLayout_retryId, -1); } } } catch (Exception e) { e.printStackTrace(); } finally { typedArray.recycle(); } } @Override protected void onFinishInflate() { super.onFinishInflate(); int childCount = getChildCount(); if (getChildCount() != 1) { throw new IllegalStateException("StatusLayout can host only one direct child"); } mContentView = getChildAt(0); mContentViewResID = mContentView.getId(); layoutSparseArray.put(mContentViewResID, mContentView); addViewSub(mEmptyView); addViewSub(mErrorView); addViewSub(mNetWorkView); addViewSub(mLoadingView); } private void addViewSub(ViewStub viewStub) { if (viewStub != null) addView(viewStub); } public void showEmpty() { showView(mEmptyViewResID, mEmptyView); } public void showNetWorkError() { showView(mNetWorkViewResID, mNetWorkView); } public void showLoading() { showView(mLoadingViewResID, mLoadingView); } public void showError() { showView(mErrorViewResID, mErrorView); } public void showContent() { showView(mContentView); } public void showView(int viewResId, ViewStub subView) { if (viewResId == -1) return; View view = layoutSparseArray.get(viewResId); if (view == null && subView != null) { view = subView.inflate(); layoutSparseArray.put(viewResId, view); View retryView = view.findViewById(mRetryResID); if (retryView != null && retryListener != null) { retryListener.onRetry(view); } } showView(view); } private void showView(View showView) { if (showView == null) { return; } for (int i = 0; i < layoutSparseArray.size(); i++) { View view = layoutSparseArray.valueAt(i); if (view.equals(showView)) { view.setVisibility(VISIBLE); } else { view.setVisibility(GONE); } } } public OnRetryListener getRetryListener() { return retryListener; } public void setRetryListener(OnRetryListener retryListener) { this.retryListener = retryListener; } }
922eb0e97f90ddd58a4c082cb7c45043b3901b1a
386
java
Java
spring-boot-tests/spring-boot-lvzhu-tests/src/main/java/com/lvzhu/springboot/lvzhu/mvc/controller/TestController.java
ljmomo/spring-boot
c575e531de140926585a381dcc933938e5b9f1b4
[ "Apache-2.0" ]
null
null
null
spring-boot-tests/spring-boot-lvzhu-tests/src/main/java/com/lvzhu/springboot/lvzhu/mvc/controller/TestController.java
ljmomo/spring-boot
c575e531de140926585a381dcc933938e5b9f1b4
[ "Apache-2.0" ]
null
null
null
spring-boot-tests/spring-boot-lvzhu-tests/src/main/java/com/lvzhu/springboot/lvzhu/mvc/controller/TestController.java
ljmomo/spring-boot
c575e531de140926585a381dcc933938e5b9f1b4
[ "Apache-2.0" ]
null
null
null
21.444444
62
0.795337
994,825
package com.lvzhu.springboot.lvzhu.mvc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/test") public class TestController { @ResponseBody @RequestMapping("/hello") public String hello() { return "world"; } }
922eb1524498b63b999fcd9b3d8874b71511d950
1,178
java
Java
src/main/java/org/olat/modules/lecture/LectureBlockToTaxonomyLevel.java
JHDSonline/OpenOLAT
449e1f1753162aac458dda15a6baac146ecbdb16
[ "Apache-2.0" ]
191
2018-03-29T09:55:44.000Z
2022-03-23T06:42:12.000Z
src/main/java/org/olat/modules/lecture/LectureBlockToTaxonomyLevel.java
JHDSonline/OpenOLAT
449e1f1753162aac458dda15a6baac146ecbdb16
[ "Apache-2.0" ]
68
2018-05-11T06:19:00.000Z
2022-01-25T18:03:26.000Z
src/main/java/org/olat/modules/lecture/LectureBlockToTaxonomyLevel.java
JHDSonline/OpenOLAT
449e1f1753162aac458dda15a6baac146ecbdb16
[ "Apache-2.0" ]
139
2018-04-27T09:46:11.000Z
2022-03-27T08:52:50.000Z
30.435897
82
0.717776
994,826
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.modules.lecture; import org.olat.modules.taxonomy.TaxonomyLevel; /** * * Initial date: 15 juin 2018<br> * @author srosse, dycjh@example.com, http://www.frentix.com * */ public interface LectureBlockToTaxonomyLevel { public Long getKey(); public LectureBlock getLectureBlock(); public TaxonomyLevel getTaxonomyLevel(); }
922eb1bfa16506a80d418dd5ae95e7a014b15d33
2,027
java
Java
server/src/main/java/org/eclipse/lsp/cobol/service/delegates/completions/CopybookNameCompletion.java
IgorCATech/che-che4z-lsp-for-cobol
b77af7ef9bb4970112da6ec35bddddab6883192e
[ "Apache-2.0" ]
null
null
null
server/src/main/java/org/eclipse/lsp/cobol/service/delegates/completions/CopybookNameCompletion.java
IgorCATech/che-che4z-lsp-for-cobol
b77af7ef9bb4970112da6ec35bddddab6883192e
[ "Apache-2.0" ]
null
null
null
server/src/main/java/org/eclipse/lsp/cobol/service/delegates/completions/CopybookNameCompletion.java
IgorCATech/che-che4z-lsp-for-cobol
b77af7ef9bb4970112da6ec35bddddab6883192e
[ "Apache-2.0" ]
null
null
null
31.184615
97
0.772077
994,827
/* * Copyright (c) 2022 Broadcom. * The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Broadcom, Inc. - initial API and implementation * */ package org.eclipse.lsp.cobol.service.delegates.completions; import com.google.inject.Inject; import com.google.inject.Singleton; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp.cobol.service.CobolDocumentModel; import org.eclipse.lsp.cobol.service.CopybookNameService; import org.eclipse.lsp4j.CompletionItem; import org.eclipse.lsp4j.CompletionItemKind; import javax.annotation.Nullable; import java.util.Collection; import static java.util.stream.Collectors.toList; import static org.eclipse.lsp.cobol.service.delegates.completions.CompletionOrder.COPYBOOKS; /** * This class provides completion suggestions for copybooks present in the local copy path in the * workspace */ @Slf4j @Singleton public class CopybookNameCompletion implements Completion { private final CopybookNameService copybookNameService; @Inject public CopybookNameCompletion(CopybookNameService copybookNameService) { this.copybookNameService = copybookNameService; } @Override public @NonNull Collection<CompletionItem> getCompletionItems( @NonNull String token, @Nullable CobolDocumentModel document) { return copybookNameService.getNames().stream() .filter(DocumentationUtils.startsWithIgnoreCase(token)) .map(this::toCopybookCompletion) .collect(toList()); } private CompletionItem toCopybookCompletion(String name) { CompletionItem item = new CompletionItem(name); item.setLabel(name); item.setInsertText(name); item.setSortText(COPYBOOKS.prefix + name); item.setKind(CompletionItemKind.Class); return item; } }
922eb1ee42f0e0c2e898823e99b87a5fa20eef3e
2,593
java
Java
src/main/java/act/cli/ascii_table/spec/IASCIITable.java
kehao-study/act_compile
b9381a9a0a83297bad7aebe8898f6ef12852ce03
[ "Apache-2.0" ]
776
2015-06-17T01:08:11.000Z
2022-03-18T10:58:56.000Z
src/main/java/act/cli/ascii_table/spec/IASCIITable.java
kehao-study/act_compile
b9381a9a0a83297bad7aebe8898f6ef12852ce03
[ "Apache-2.0" ]
1,390
2015-05-25T20:24:44.000Z
2022-01-24T23:49:33.000Z
src/main/java/act/cli/ascii_table/spec/IASCIITable.java
benstonezhang/actframework
2554aced980de115939bfad4d003c74ff8f04112
[ "Apache-2.0" ]
149
2015-05-29T08:38:34.000Z
2022-02-12T16:01:29.000Z
31.083333
83
0.715052
994,828
/** * Copyright (C) 2011 K Venkata Sudhakar <upchh@example.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package act.cli.ascii_table.spec; /*- * #%L * ACT Framework * %% * Copyright (C) 2014 - 2017 ActFramework * %% * 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. * #L% */ import act.cli.ascii_table.ASCIITableHeader; /** * Interface specifying ASCII table APIs. * * @author K Venkata Sudhakar (upchh@example.com) * @version 1.0 * */ public interface IASCIITable { int ALIGN_LEFT = -1; int ALIGN_CENTER = 0; int ALIGN_RIGHT = 1; int ALIGN_AUTO = Integer.MAX_VALUE; int DEFAULT_HEADER_ALIGN = ALIGN_CENTER; int DEFAULT_DATA_ALIGN = ALIGN_AUTO; /** * Prints the ASCII table to console. * * @param header * @param data */ void printTable(String[] header, String[][] data); void printTable(String[] header, String[][] data, int dataAlign); void printTable(String[] header, int headerAlign, String[][] data, int dataAlign); void printTable(ASCIITableHeader[] headerObjs, String[][] data); void printTable(IASCIITableAware asciiTableAware); /** * Returns the ASCII table as string which can be rendered in console or JSP. * * @param header * @param data * @return */ String getTable(String[] header, String[][] data); String getTable(String[] header, String[][] data, int dataAlign); String getTable(String[] header, int headerAlign, String[][] data, int dataAlign); String getTable(ASCIITableHeader[] headerObjs, String[][] data); String getTable(IASCIITableAware asciiTableAware); }
922eb3d9698da2f6bcaf2e3296f7c3d2055f874a
50,747
java
Java
proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/CloudStorageRegexFileSet.java
googleapis/java-dlp
92a69a5375aad0c3539ff0c55a2d5406533d7059
[ "Apache-2.0" ]
13
2019-10-15T10:44:53.000Z
2022-03-23T10:44:41.000Z
proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/CloudStorageRegexFileSet.java
googleapis/java-dlp
92a69a5375aad0c3539ff0c55a2d5406533d7059
[ "Apache-2.0" ]
551
2019-10-14T23:52:30.000Z
2022-03-31T17:17:59.000Z
proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/CloudStorageRegexFileSet.java
googleapis/java-dlp
92a69a5375aad0c3539ff0c55a2d5406533d7059
[ "Apache-2.0" ]
19
2019-10-15T02:59:33.000Z
2021-11-16T13:03:26.000Z
35.939802
100
0.669498
994,829
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/privacy/dlp/v2/storage.proto package com.google.privacy.dlp.v2; /** * * * <pre> * Message representing a set of files in a Cloud Storage bucket. Regular * expressions are used to allow fine-grained control over which files in the * bucket to include. * Included files are those that match at least one item in `include_regex` and * do not match any items in `exclude_regex`. Note that a file that matches * items from both lists will _not_ be included. For a match to occur, the * entire file path (i.e., everything in the url after the bucket name) must * match the regular expression. * For example, given the input `{bucket_name: "mybucket", include_regex: * ["directory1/.*"], exclude_regex: * ["directory1/excluded.*"]}`: * * `gs://mybucket/directory1/myfile` will be included * * `gs://mybucket/directory1/directory2/myfile` will be included (`.*` matches * across `/`) * * `gs://mybucket/directory0/directory1/myfile` will _not_ be included (the * full path doesn't match any items in `include_regex`) * * `gs://mybucket/directory1/excludedfile` will _not_ be included (the path * matches an item in `exclude_regex`) * If `include_regex` is left empty, it will match all files by default * (this is equivalent to setting `include_regex: [".*"]`). * Some other common use cases: * * `{bucket_name: "mybucket", exclude_regex: [".*&#92;.pdf"]}` will include all * files in `mybucket` except for .pdf files * * `{bucket_name: "mybucket", include_regex: ["directory/[^/]+"]}` will * include all files directly under `gs://mybucket/directory/`, without matching * across `/` * </pre> * * Protobuf type {@code google.privacy.dlp.v2.CloudStorageRegexFileSet} */ public final class CloudStorageRegexFileSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.privacy.dlp.v2.CloudStorageRegexFileSet) CloudStorageRegexFileSetOrBuilder { private static final long serialVersionUID = 0L; // Use CloudStorageRegexFileSet.newBuilder() to construct. private CloudStorageRegexFileSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CloudStorageRegexFileSet() { bucketName_ = ""; includeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; excludeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CloudStorageRegexFileSet(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CloudStorageRegexFileSet( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); bucketName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { includeRegex_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } includeRegex_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000002) != 0)) { excludeRegex_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000002; } excludeRegex_.add(s); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { includeRegex_ = includeRegex_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000002) != 0)) { excludeRegex_ = excludeRegex_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2.DlpStorage .internal_static_google_privacy_dlp_v2_CloudStorageRegexFileSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2.DlpStorage .internal_static_google_privacy_dlp_v2_CloudStorageRegexFileSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2.CloudStorageRegexFileSet.class, com.google.privacy.dlp.v2.CloudStorageRegexFileSet.Builder.class); } public static final int BUCKET_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object bucketName_; /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @return The bucketName. */ @java.lang.Override public java.lang.String getBucketName() { java.lang.Object ref = bucketName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); bucketName_ = s; return s; } } /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @return The bytes for bucketName. */ @java.lang.Override public com.google.protobuf.ByteString getBucketNameBytes() { java.lang.Object ref = bucketName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); bucketName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int INCLUDE_REGEX_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList includeRegex_; /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @return A list containing the includeRegex. */ public com.google.protobuf.ProtocolStringList getIncludeRegexList() { return includeRegex_; } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @return The count of includeRegex. */ public int getIncludeRegexCount() { return includeRegex_.size(); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param index The index of the element to return. * @return The includeRegex at the given index. */ public java.lang.String getIncludeRegex(int index) { return includeRegex_.get(index); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param index The index of the value to return. * @return The bytes of the includeRegex at the given index. */ public com.google.protobuf.ByteString getIncludeRegexBytes(int index) { return includeRegex_.getByteString(index); } public static final int EXCLUDE_REGEX_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList excludeRegex_; /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @return A list containing the excludeRegex. */ public com.google.protobuf.ProtocolStringList getExcludeRegexList() { return excludeRegex_; } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @return The count of excludeRegex. */ public int getExcludeRegexCount() { return excludeRegex_.size(); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param index The index of the element to return. * @return The excludeRegex at the given index. */ public java.lang.String getExcludeRegex(int index) { return excludeRegex_.get(index); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param index The index of the value to return. * @return The bytes of the excludeRegex at the given index. */ public com.google.protobuf.ByteString getExcludeRegexBytes(int index) { return excludeRegex_.getByteString(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(bucketName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, bucketName_); } for (int i = 0; i < includeRegex_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, includeRegex_.getRaw(i)); } for (int i = 0; i < excludeRegex_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, excludeRegex_.getRaw(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(bucketName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, bucketName_); } { int dataSize = 0; for (int i = 0; i < includeRegex_.size(); i++) { dataSize += computeStringSizeNoTag(includeRegex_.getRaw(i)); } size += dataSize; size += 1 * getIncludeRegexList().size(); } { int dataSize = 0; for (int i = 0; i < excludeRegex_.size(); i++) { dataSize += computeStringSizeNoTag(excludeRegex_.getRaw(i)); } size += dataSize; size += 1 * getExcludeRegexList().size(); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.privacy.dlp.v2.CloudStorageRegexFileSet)) { return super.equals(obj); } com.google.privacy.dlp.v2.CloudStorageRegexFileSet other = (com.google.privacy.dlp.v2.CloudStorageRegexFileSet) obj; if (!getBucketName().equals(other.getBucketName())) return false; if (!getIncludeRegexList().equals(other.getIncludeRegexList())) return false; if (!getExcludeRegexList().equals(other.getExcludeRegexList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + BUCKET_NAME_FIELD_NUMBER; hash = (53 * hash) + getBucketName().hashCode(); if (getIncludeRegexCount() > 0) { hash = (37 * hash) + INCLUDE_REGEX_FIELD_NUMBER; hash = (53 * hash) + getIncludeRegexList().hashCode(); } if (getExcludeRegexCount() > 0) { hash = (37 * hash) + EXCLUDE_REGEX_FIELD_NUMBER; hash = (53 * hash) + getExcludeRegexList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.privacy.dlp.v2.CloudStorageRegexFileSet prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message representing a set of files in a Cloud Storage bucket. Regular * expressions are used to allow fine-grained control over which files in the * bucket to include. * Included files are those that match at least one item in `include_regex` and * do not match any items in `exclude_regex`. Note that a file that matches * items from both lists will _not_ be included. For a match to occur, the * entire file path (i.e., everything in the url after the bucket name) must * match the regular expression. * For example, given the input `{bucket_name: "mybucket", include_regex: * ["directory1/.*"], exclude_regex: * ["directory1/excluded.*"]}`: * * `gs://mybucket/directory1/myfile` will be included * * `gs://mybucket/directory1/directory2/myfile` will be included (`.*` matches * across `/`) * * `gs://mybucket/directory0/directory1/myfile` will _not_ be included (the * full path doesn't match any items in `include_regex`) * * `gs://mybucket/directory1/excludedfile` will _not_ be included (the path * matches an item in `exclude_regex`) * If `include_regex` is left empty, it will match all files by default * (this is equivalent to setting `include_regex: [".*"]`). * Some other common use cases: * * `{bucket_name: "mybucket", exclude_regex: [".*&#92;.pdf"]}` will include all * files in `mybucket` except for .pdf files * * `{bucket_name: "mybucket", include_regex: ["directory/[^/]+"]}` will * include all files directly under `gs://mybucket/directory/`, without matching * across `/` * </pre> * * Protobuf type {@code google.privacy.dlp.v2.CloudStorageRegexFileSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2.CloudStorageRegexFileSet) com.google.privacy.dlp.v2.CloudStorageRegexFileSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.privacy.dlp.v2.DlpStorage .internal_static_google_privacy_dlp_v2_CloudStorageRegexFileSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.privacy.dlp.v2.DlpStorage .internal_static_google_privacy_dlp_v2_CloudStorageRegexFileSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.privacy.dlp.v2.CloudStorageRegexFileSet.class, com.google.privacy.dlp.v2.CloudStorageRegexFileSet.Builder.class); } // Construct using com.google.privacy.dlp.v2.CloudStorageRegexFileSet.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); bucketName_ = ""; includeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); excludeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.privacy.dlp.v2.DlpStorage .internal_static_google_privacy_dlp_v2_CloudStorageRegexFileSet_descriptor; } @java.lang.Override public com.google.privacy.dlp.v2.CloudStorageRegexFileSet getDefaultInstanceForType() { return com.google.privacy.dlp.v2.CloudStorageRegexFileSet.getDefaultInstance(); } @java.lang.Override public com.google.privacy.dlp.v2.CloudStorageRegexFileSet build() { com.google.privacy.dlp.v2.CloudStorageRegexFileSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.privacy.dlp.v2.CloudStorageRegexFileSet buildPartial() { com.google.privacy.dlp.v2.CloudStorageRegexFileSet result = new com.google.privacy.dlp.v2.CloudStorageRegexFileSet(this); int from_bitField0_ = bitField0_; result.bucketName_ = bucketName_; if (((bitField0_ & 0x00000001) != 0)) { includeRegex_ = includeRegex_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.includeRegex_ = includeRegex_; if (((bitField0_ & 0x00000002) != 0)) { excludeRegex_ = excludeRegex_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000002); } result.excludeRegex_ = excludeRegex_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.privacy.dlp.v2.CloudStorageRegexFileSet) { return mergeFrom((com.google.privacy.dlp.v2.CloudStorageRegexFileSet) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.privacy.dlp.v2.CloudStorageRegexFileSet other) { if (other == com.google.privacy.dlp.v2.CloudStorageRegexFileSet.getDefaultInstance()) return this; if (!other.getBucketName().isEmpty()) { bucketName_ = other.bucketName_; onChanged(); } if (!other.includeRegex_.isEmpty()) { if (includeRegex_.isEmpty()) { includeRegex_ = other.includeRegex_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureIncludeRegexIsMutable(); includeRegex_.addAll(other.includeRegex_); } onChanged(); } if (!other.excludeRegex_.isEmpty()) { if (excludeRegex_.isEmpty()) { excludeRegex_ = other.excludeRegex_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureExcludeRegexIsMutable(); excludeRegex_.addAll(other.excludeRegex_); } onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.privacy.dlp.v2.CloudStorageRegexFileSet parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.privacy.dlp.v2.CloudStorageRegexFileSet) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object bucketName_ = ""; /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @return The bucketName. */ public java.lang.String getBucketName() { java.lang.Object ref = bucketName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); bucketName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @return The bytes for bucketName. */ public com.google.protobuf.ByteString getBucketNameBytes() { java.lang.Object ref = bucketName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); bucketName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @param value The bucketName to set. * @return This builder for chaining. */ public Builder setBucketName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bucketName_ = value; onChanged(); return this; } /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @return This builder for chaining. */ public Builder clearBucketName() { bucketName_ = getDefaultInstance().getBucketName(); onChanged(); return this; } /** * * * <pre> * The name of a Cloud Storage bucket. Required. * </pre> * * <code>string bucket_name = 1;</code> * * @param value The bytes for bucketName to set. * @return This builder for chaining. */ public Builder setBucketNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bucketName_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList includeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureIncludeRegexIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { includeRegex_ = new com.google.protobuf.LazyStringArrayList(includeRegex_); bitField0_ |= 0x00000001; } } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @return A list containing the includeRegex. */ public com.google.protobuf.ProtocolStringList getIncludeRegexList() { return includeRegex_.getUnmodifiableView(); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @return The count of includeRegex. */ public int getIncludeRegexCount() { return includeRegex_.size(); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param index The index of the element to return. * @return The includeRegex at the given index. */ public java.lang.String getIncludeRegex(int index) { return includeRegex_.get(index); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param index The index of the value to return. * @return The bytes of the includeRegex at the given index. */ public com.google.protobuf.ByteString getIncludeRegexBytes(int index) { return includeRegex_.getByteString(index); } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param index The index to set the value at. * @param value The includeRegex to set. * @return This builder for chaining. */ public Builder setIncludeRegex(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIncludeRegexIsMutable(); includeRegex_.set(index, value); onChanged(); return this; } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param value The includeRegex to add. * @return This builder for chaining. */ public Builder addIncludeRegex(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureIncludeRegexIsMutable(); includeRegex_.add(value); onChanged(); return this; } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param values The includeRegex to add. * @return This builder for chaining. */ public Builder addAllIncludeRegex(java.lang.Iterable<java.lang.String> values) { ensureIncludeRegexIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, includeRegex_); onChanged(); return this; } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @return This builder for chaining. */ public Builder clearIncludeRegex() { includeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * A list of regular expressions matching file paths to include. All files in * the bucket that match at least one of these regular expressions will be * included in the set of files, except for those that also match an item in * `exclude_regex`. Leaving this field empty will match all files by default * (this is equivalent to including `.*` in the list). * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string include_regex = 2;</code> * * @param value The bytes of the includeRegex to add. * @return This builder for chaining. */ public Builder addIncludeRegexBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureIncludeRegexIsMutable(); includeRegex_.add(value); onChanged(); return this; } private com.google.protobuf.LazyStringList excludeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureExcludeRegexIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { excludeRegex_ = new com.google.protobuf.LazyStringArrayList(excludeRegex_); bitField0_ |= 0x00000002; } } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @return A list containing the excludeRegex. */ public com.google.protobuf.ProtocolStringList getExcludeRegexList() { return excludeRegex_.getUnmodifiableView(); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @return The count of excludeRegex. */ public int getExcludeRegexCount() { return excludeRegex_.size(); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param index The index of the element to return. * @return The excludeRegex at the given index. */ public java.lang.String getExcludeRegex(int index) { return excludeRegex_.get(index); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param index The index of the value to return. * @return The bytes of the excludeRegex at the given index. */ public com.google.protobuf.ByteString getExcludeRegexBytes(int index) { return excludeRegex_.getByteString(index); } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param index The index to set the value at. * @param value The excludeRegex to set. * @return This builder for chaining. */ public Builder setExcludeRegex(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureExcludeRegexIsMutable(); excludeRegex_.set(index, value); onChanged(); return this; } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param value The excludeRegex to add. * @return This builder for chaining. */ public Builder addExcludeRegex(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureExcludeRegexIsMutable(); excludeRegex_.add(value); onChanged(); return this; } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param values The excludeRegex to add. * @return This builder for chaining. */ public Builder addAllExcludeRegex(java.lang.Iterable<java.lang.String> values) { ensureExcludeRegexIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, excludeRegex_); onChanged(); return this; } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @return This builder for chaining. */ public Builder clearExcludeRegex() { excludeRegex_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * A list of regular expressions matching file paths to exclude. All files in * the bucket that match at least one of these regular expressions will be * excluded from the scan. * Regular expressions use RE2 * [syntax](https://github.com/google/re2/wiki/Syntax); a guide can be found * under the google/re2 repository on GitHub. * </pre> * * <code>repeated string exclude_regex = 3;</code> * * @param value The bytes of the excludeRegex to add. * @return This builder for chaining. */ public Builder addExcludeRegexBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureExcludeRegexIsMutable(); excludeRegex_.add(value); onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2.CloudStorageRegexFileSet) } // @@protoc_insertion_point(class_scope:google.privacy.dlp.v2.CloudStorageRegexFileSet) private static final com.google.privacy.dlp.v2.CloudStorageRegexFileSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.privacy.dlp.v2.CloudStorageRegexFileSet(); } public static com.google.privacy.dlp.v2.CloudStorageRegexFileSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CloudStorageRegexFileSet> PARSER = new com.google.protobuf.AbstractParser<CloudStorageRegexFileSet>() { @java.lang.Override public CloudStorageRegexFileSet parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CloudStorageRegexFileSet(input, extensionRegistry); } }; public static com.google.protobuf.Parser<CloudStorageRegexFileSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CloudStorageRegexFileSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.privacy.dlp.v2.CloudStorageRegexFileSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
922eb3fa8b5f93e28a20191c7fed621afb1186cb
13,092
java
Java
src/main/java/org/mulinlab/varnote/cmdline/VarNoteCommandLine.java
mikeyhuang/VarNote
1bc061dc38cfa5542cd0744541fb3dad10179c3e
[ "BSD-3-Clause" ]
26
2019-05-18T18:28:13.000Z
2022-03-26T19:53:05.000Z
src/main/java/org/mulinlab/varnote/cmdline/VarNoteCommandLine.java
mikeyhuang/VarNote
1bc061dc38cfa5542cd0744541fb3dad10179c3e
[ "BSD-3-Clause" ]
7
2019-05-26T03:16:14.000Z
2022-03-11T23:10:24.000Z
src/main/java/org/mulinlab/varnote/cmdline/VarNoteCommandLine.java
mikeyhuang/VarNote
1bc061dc38cfa5542cd0744541fb3dad10179c3e
[ "BSD-3-Clause" ]
5
2019-05-26T07:24:19.000Z
2021-11-04T05:41:36.000Z
50.16092
172
0.624122
994,830
package org.mulinlab.varnote.cmdline; import org.mulinlab.varnote.cmdline.abstractclass.CMDProgram; import org.mulinlab.varnote.cmdline.constant.CommandLineDefaults; import org.mulinlab.varnote.constants.GlobalParameter; import htsjdk.samtools.util.Log; import htsjdk.samtools.util.StringUtil; import org.broadinstitute.barclay.argparser.*; import java.io.PrintStream; import java.lang.reflect.Modifier; import java.util.*; import java.util.function.BiConsumer; import java.util.stream.Collectors; public class VarNoteCommandLine { private static final Log log = Log.getInstance(VarNoteCommandLine.class); private static String initializeColor(final String color) { if (CommandLineDefaults.COLOR_STATUS) return color; else return ""; } private final static int HELP_SIMILARITY_FLOOR = CommandLineDefaults.HELP_SIMILARITY_FLOOR; private final static int MINIMUM_SUBSTRING_LENGTH = CommandLineDefaults.MINIMUM_SUBSTRING_LENGTH; private static final String KNRM = "\u001B[0m"; // reset private static final String RED = "\u001B[31m"; private static final String GREEN = "\u001B[32m"; private static final String CYAN = "\u001B[36m"; private static final String WHITE = "\u001B[37m"; private static final String BOLDRED = "\u001B[1m\u001B[31m"; protected static List<String> getPackageList() { final List<String> packageList = new ArrayList<String>(); packageList.add("org"); return packageList; } public static void main(final String[] args) { System.exit(new VarNoteCommandLine().instanceMain(args, getPackageList(), GlobalParameter.PRO_CMD)); } protected int instanceMain(final String[] args, final List<String> packageList, final String commandLineName) { final CMDProgram program = extractCommandLineProgram(args, packageList, commandLineName); if (null == program) return 1; // no program found! // we can lop off the first two arguments but it requires an array copy or alternatively we could update CLP to remove them // in the constructor do the former in this implementation. final String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); return program.instanceMain(mainArgs); } protected int instanceMain(final String[] args) { return instanceMain(args, getPackageList(), GlobalParameter.PRO_CMD); } public static CMDProgram extractCommandLineProgram(final String[] args, final List<String> packageList, final String commandLineName) { final Map<String, Class<?>> simpleNameToClass = new HashMap<>(); final List<String> missingAnnotationClasses = new ArrayList<>(); processAllCommandLinePrograms( packageList, (Class<CMDProgram> clazz, CommandLineProgramProperties clProperties) -> { // Check for missing annotations if (null == clProperties) { missingAnnotationClasses.add(clazz.getSimpleName()); } else if (!clProperties.omitFromCommandLine()) { /** We should check for missing annotations later **/ if (simpleNameToClass.containsKey(clazz.getSimpleName())) { throw new RuntimeException("Simple class name collision: " + clazz.getSimpleName()); } simpleNameToClass.put(clazz.getSimpleName(), clazz); } } ); if (!missingAnnotationClasses.isEmpty()) { throw new RuntimeException("The following classes are missing the required CommandLineProgramProperties annotation: " + missingAnnotationClasses.stream().collect(Collectors.joining((", ")))); } final Set<Class<?>> classes = new LinkedHashSet<>(); classes.addAll(simpleNameToClass.values()); if (args.length < 1 || args[0].equals("-h") || args[0].equals("--help")) { printUsage(System.out, classes, commandLineName); } else { if (simpleNameToClass.containsKey(args[0])) { final Class<?> clazz = simpleNameToClass.get(args[0]); try { final Object commandLineProgram = clazz.newInstance(); return (CMDProgram) commandLineProgram; } catch (final InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } printUsage(System.err, classes, commandLineName); printUnknown(classes, args[0]); } return null; } public static void processAllCommandLinePrograms( final List<String> packageList, final BiConsumer<Class<CMDProgram>, CommandLineProgramProperties> clpClassProcessor) { final ClassFinder classFinder = new ClassFinder(); packageList.forEach(pkg -> classFinder.find(pkg, CMDProgram.class)); for (final Class clazz : classFinder.getClasses()) { if (!clazz.isInterface() && !clazz.isSynthetic() && !clazz.isPrimitive() && !clazz.isLocalClass() && !Modifier.isAbstract(clazz.getModifiers())) { clpClassProcessor.accept(clazz, VarNoteCommandLine.getProgramProperty(clazz)); } } } public static CommandLineProgramProperties getProgramProperty(Class clazz) { return (CommandLineProgramProperties)clazz.getAnnotation(CommandLineProgramProperties.class); } public static void printUsage(final PrintStream destinationStream, final Set<Class<?>> classes, final String commandLineName) { final StringBuilder builder = new StringBuilder(); builder.append(BOLDRED + "USAGE: " + commandLineName + " " + GREEN + "<program name>" + BOLDRED + " [-h]\n\n" + KNRM) .append(BOLDRED + "Program Summary Table:\n" + KNRM); /** Group CommandLinePrograms by CommandLineProgramGroup **/ final Map<Class<? extends CommandLineProgramGroup>, CommandLineProgramGroup> programGroupClassToProgramGroupInstance = new LinkedHashMap<>(); final Map<CommandLineProgramGroup, List<Class<?>>> programsByGroup = new TreeMap<>(CommandLineProgramGroup.comparator); final Map<Class<?>, CommandLineProgramProperties> programsToProperty = new LinkedHashMap<>(); for (final Class<?> clazz : classes) { // Get the command line property for this command line program final CommandLineProgramProperties property = getProgramProperty(clazz); if (null == property) { throw new RuntimeException(String.format("The class '%s' is missing the required CommandLineProgramProperties annotation.", clazz.getSimpleName())); } else if (!property.omitFromCommandLine()) { // only if they are not omit from the command line programsToProperty.put(clazz, property); // Get the command line program group for the command line property // NB: we want to minimize the number of times we make a new instance, hence programGroupClassToProgramGroupInstance CommandLineProgramGroup programGroup = programGroupClassToProgramGroupInstance.get(property.programGroup()); if (null == programGroup) { try { programGroup = property.programGroup().newInstance(); } catch (final InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } programGroupClassToProgramGroupInstance.put(property.programGroup(), programGroup); } List<Class<?>> programs = programsByGroup.get(programGroup); if (null == programs) { programsByGroup.put(programGroup, programs = new ArrayList<>()); } programs.add(clazz); } } /** Print out the programs in each group **/ for (final Map.Entry<CommandLineProgramGroup, List<Class<?>>> entry : programsByGroup.entrySet()) { final CommandLineProgramGroup programGroup = entry.getKey(); builder.append(WHITE + "--------------------------------------------------------------------------------------\n" + KNRM); builder.append(String.format("%s%-48s %-45s%s\n", RED, programGroup.getName() + ":", programGroup.getDescription(), KNRM)); final List<Class<?>> sortedClasses = new ArrayList<>(); sortedClasses.addAll(entry.getValue()); Collections.sort(sortedClasses, new SimpleNameComparator()); for (final Class<?> clazz : sortedClasses) { final CommandLineProgramProperties clpProperties = programsToProperty.get(clazz); if (null == clpProperties) { throw new RuntimeException(String.format("Unexpected error: did not find the CommandLineProgramProperties annotation for '%s'", clazz.getSimpleName())); } builder.append(getDisplaySummaryForTool(clazz, clpProperties)); } builder.append(String.format("\n")); } builder.append(WHITE + "--------------------------------------------------------------------------------------\n" + KNRM); destinationStream.println(builder.toString()); } protected static String getDisplaySummaryForTool(final Class<?> toolClass, final CommandLineProgramProperties clpProperties) { final BetaFeature betaFeature = toolClass.getAnnotation(BetaFeature.class); final ExperimentalFeature experimentalFeature = toolClass.getAnnotation(ExperimentalFeature.class); final StringBuilder builder = new StringBuilder(); final String summaryLine; if (experimentalFeature != null) { summaryLine = String.format("%s%s %s%s", RED, "(EXPERIMENTAL Tool)", CYAN, clpProperties.oneLineSummary()); } else if (betaFeature != null) { summaryLine = String.format("%s%s %s%s", RED, "(BETA Tool)", CYAN, clpProperties.oneLineSummary()); } else { summaryLine = String.format("%s%s", CYAN, clpProperties.oneLineSummary()); } final String annotatedToolName = getDisplayNameForToolClass(toolClass); if (toolClass.getSimpleName().length() >= 45) { builder.append(String.format("%s %s %s%s\n", GREEN, annotatedToolName, summaryLine, KNRM)); } else { builder.append(String.format("%s %-45s%s%s\n", GREEN, annotatedToolName, summaryLine, KNRM)); } return builder.toString(); } protected static String getDisplayNameForToolClass(final Class<?> toolClass) { if (toolClass == null) { throw new IllegalArgumentException("A valid class is required to get a display name"); } return toolClass.getSimpleName(); } private static class SimpleNameComparator implements Comparator<Class> { @Override public int compare(final Class aClass, final Class bClass) { return aClass.getSimpleName().compareTo(bClass.getSimpleName()); } } public static void printUnknown(final Set<Class<?>> classes, final String command) { final Map<Class, Integer> distances = new HashMap<Class, Integer>(); int bestDistance = Integer.MAX_VALUE; int bestN = 0; // Score against all classes for (final Class clazz : classes) { final String name = clazz.getSimpleName(); final int distance; if (name.equals(command)) { throw new RuntimeException("Command matches: " + command); } if (name.startsWith(command) || (MINIMUM_SUBSTRING_LENGTH <= command.length() && name.contains(command))) { distance = 0; } else { distance = StringUtil.levenshteinDistance(command, name, 0, 2, 1, 4); } distances.put(clazz, distance); if (distance < bestDistance) { bestDistance = distance; bestN = 1; } else if (distance == bestDistance) { bestN++; } } // Upper bound on the similarity score if (0 == bestDistance && bestN == classes.size()) { bestDistance = HELP_SIMILARITY_FLOOR + 1; } // IntersetOutput similar matches System.err.println(String.format("'%s' is not a valid command. See VarNote -h for more information.", command)); if (bestDistance < HELP_SIMILARITY_FLOOR) { System.err.println(String.format("Did you mean %s?", (bestN < 2) ? "this" : "one of these")); for (final Class clazz : classes) { if (bestDistance == distances.get(clazz)) { System.err.println(String.format(" %s", clazz.getSimpleName())); } } } } }
922eb4606d133c54dbea675b523ddc57e954c467
3,559
java
Java
src/test/java/org/thinkit/framework/content/ConditionNodeKeyTest.java
myConsciousness/content-framework
a7897ece6bf76ffd5aff69bc6dac1f85116dac54
[ "Apache-2.0" ]
6
2020-08-24T02:00:00.000Z
2021-12-05T02:43:59.000Z
src/test/java/org/thinkit/framework/content/ConditionNodeKeyTest.java
myConsciousness/content-framework
a7897ece6bf76ffd5aff69bc6dac1f85116dac54
[ "Apache-2.0" ]
13
2020-08-20T20:04:59.000Z
2021-01-10T02:28:04.000Z
src/test/java/org/thinkit/framework/content/ConditionNodeKeyTest.java
myConsciousness/content-framework
a7897ece6bf76ffd5aff69bc6dac1f85116dac54
[ "Apache-2.0" ]
1
2021-03-09T16:41:03.000Z
2021-03-09T16:41:03.000Z
32.063063
103
0.663951
994,831
/* * Copyright 2020 Kato Shinya. * * 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.thinkit.framework.content; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * {@link ConditionNodeKey} クラスのテストクラスです。 * * @author Kato Shinya * @since 1.0 * @version 1.0 */ public final class ConditionNodeKeyTest { /** * キー名 : conditionNodes */ private static final String KEY_CONDITION_NODES = "conditionNodes"; /** * キー名 : node */ private static final String KEY_NODE = "node"; /** * キー名 : conditionId */ private static final String KEY_CONDITION_ID = "conditionId"; /** * キー名 : exclude */ private static final String KEY_EXCLUDE = "exclude"; /** * キー名 : conditions */ private static final String KEY_CONDITIONS = "conditions"; /** * キー名 : condition */ private static final String KEY_CONDITION = "condition"; /** * キー名 : keyName */ private static final String KEY_KEY_NAME = "keyName"; /** * キー名 : operator */ private static final String KEY_OPERATOR = "operator"; /** * キー名 : operand */ private static final String KEY_OPERAND = "operand"; /** * <pre> * ❏ 概要 * {@link ConditionNodeKey} クラスの {@link ConditionNodeKey#getKey()} メソッドの機能を確認する。 * </pre> * * <pre> * ❏ 観点 * ・{@link ConditionNodeKey#CONDITION_NODES#getKey()} メソッドの返却値が <code>"conditionNodes"</code> であること * ・{@link ConditionNodeKey#NODE#getKey()} メソッドの返却値が <code>"node"</code> であること * ・{@link ConditionNodeKey#CONDITION_ID#getKey()} メソッドの返却値が <code>"conditionId"</code> であること * ・{@link ConditionNodeKey#EXCLUDE#getKey()} メソッドの返却値が <code>"exclude"</code> であること * ・{@link ConditionNodeKey#CONDITIONS#getKey()} メソッドの返却値が <code>"conditions"</code> であること * ・{@link ConditionNodeKey#CONDITION#getKey()} メソッドの返却値が <code>"condition"</code> であること * ・{@link ConditionNodeKey#KEY_NAME#getKey()} メソッドの返却値が <code>"keyName"</code> であること * ・{@link ConditionNodeKey#OPERAND#getKey()} メソッドの返却値が <code>"operand"</code> であること * ・{@link ConditionNodeKey#VALUE#getKey()} メソッドの返却値が <code>"value"</code> であること * </pre> * * <pre> * ❏ 留意点 * なし * </pre> */ @Test public void testGetKey() { assertEquals(KEY_CONDITION_NODES, ConditionNodeKey.CONDITION_NODES.getKey()); assertEquals(KEY_NODE, ConditionNodeKey.NODE.getKey()); assertEquals(KEY_CONDITION_ID, ConditionNodeKey.CONDITION_ID.getKey()); assertEquals(KEY_EXCLUDE, ConditionNodeKey.EXCLUDE.getKey()); assertEquals(KEY_CONDITIONS, ConditionNodeKey.CONDITIONS.getKey()); assertEquals(KEY_CONDITION, ConditionNodeKey.CONDITION.getKey()); assertEquals(KEY_KEY_NAME, ConditionNodeKey.KEY_NAME.getKey()); assertEquals(KEY_OPERATOR, ConditionNodeKey.OPERATOR.getKey()); assertEquals(KEY_OPERAND, ConditionNodeKey.OPERAND.getKey()); } }
922eb519e29e6ba64e78719fbde82d7ee59de75e
590
java
Java
src/main/java/de/cronn/jira/sync/mapping/ComponentMapper.java
cronn-de/jira-sync
4a662b76e6f3acda2ea219f21a35abb7f1caee46
[ "Apache-2.0" ]
12
2016-10-27T06:49:56.000Z
2020-09-16T08:30:26.000Z
src/main/java/de/cronn/jira/sync/mapping/ComponentMapper.java
cronn-de/jira-sync
4a662b76e6f3acda2ea219f21a35abb7f1caee46
[ "Apache-2.0" ]
8
2016-11-04T18:28:26.000Z
2020-05-28T13:34:35.000Z
src/main/java/de/cronn/jira/sync/mapping/ComponentMapper.java
cronn-de/jira-sync
4a662b76e6f3acda2ea219f21a35abb7f1caee46
[ "Apache-2.0" ]
11
2016-11-04T14:18:15.000Z
2020-10-13T09:37:25.000Z
34.705882
135
0.844068
994,832
package de.cronn.jira.sync.mapping; import java.util.Collection; import java.util.Set; import de.cronn.jira.sync.config.JiraProjectSync; import de.cronn.jira.sync.domain.JiraComponent; import de.cronn.jira.sync.service.JiraService; public interface ComponentMapper extends NamedResourceMapper<JiraComponent> { Set<JiraComponent> mapSourceToTarget(JiraService jiraService, Collection<JiraComponent> componentsToMap, JiraProjectSync projectSync); Set<JiraComponent> mapTargetToSource(JiraService jiraService, Collection<JiraComponent> componentsToMap, JiraProjectSync projectSync); }
922eb551cea45855041fc70a4ef9a70f6af02722
3,422
java
Java
aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/UpdateDistributionConfigurationRequestMarshaller.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
1
2022-01-04T04:11:16.000Z
2022-01-04T04:11:16.000Z
aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/UpdateDistributionConfigurationRequestMarshaller.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
null
null
null
aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/transform/UpdateDistributionConfigurationRequestMarshaller.java
vinayakpokharkar/aws-sdk-java
fd409dee8ae23fb8953e0bb4dbde65536a7e0514
[ "Apache-2.0" ]
null
null
null
49.594203
159
0.7782
994,833
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.imagebuilder.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.imagebuilder.model.*; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateDistributionConfigurationRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateDistributionConfigurationRequestMarshaller { private static final MarshallingInfo<String> DISTRIBUTIONCONFIGURATIONARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("distributionConfigurationArn").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build(); private static final MarshallingInfo<List> DISTRIBUTIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("distributions").build(); private static final MarshallingInfo<String> CLIENTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("clientToken") .defaultValueSupplier(com.amazonaws.util.IdempotentUtils.getGenerator()).build(); private static final UpdateDistributionConfigurationRequestMarshaller instance = new UpdateDistributionConfigurationRequestMarshaller(); public static UpdateDistributionConfigurationRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateDistributionConfigurationRequest updateDistributionConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (updateDistributionConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateDistributionConfigurationRequest.getDistributionConfigurationArn(), DISTRIBUTIONCONFIGURATIONARN_BINDING); protocolMarshaller.marshall(updateDistributionConfigurationRequest.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(updateDistributionConfigurationRequest.getDistributions(), DISTRIBUTIONS_BINDING); protocolMarshaller.marshall(updateDistributionConfigurationRequest.getClientToken(), CLIENTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
922eb5b7ffdd8038a0a8e1e57b33ec3d2591469e
722
java
Java
src/main/java/org/pioto/thermostat/mvc/package-info.java
pioto/thermostat
d49b588a3f32761b5f0678d85692e152b3c41db8
[ "MIT" ]
null
null
null
src/main/java/org/pioto/thermostat/mvc/package-info.java
pioto/thermostat
d49b588a3f32761b5f0678d85692e152b3c41db8
[ "MIT" ]
null
null
null
src/main/java/org/pioto/thermostat/mvc/package-info.java
pioto/thermostat
d49b588a3f32761b5f0678d85692e152b3c41db8
[ "MIT" ]
null
null
null
34.285714
75
0.727778
994,834
/** * Copyright 2015 Mike Kelly * * 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. */ /** * Web controllers, etc for the project. * @author Mike Kelly (upchh@example.com) * */ package org.pioto.thermostat.mvc;
922eb6417fc81186a5062c2c55979b8e8b071fa5
8,126
java
Java
limelight_webapp/src/main/java/org/yeastrc/limelight/limelight_webapp/spring_mvc_parts/user_account_pages/rest_controllers/User_Process_PublicAccessCode_Value_RestWebserviceController.java
guoci/limelight-core
6ce269903ebc5948dd844047d5a2b5580fdc5432
[ "Apache-2.0" ]
3
2019-02-21T21:23:04.000Z
2021-07-12T18:30:03.000Z
limelight_webapp/src/main/java/org/yeastrc/limelight/limelight_webapp/spring_mvc_parts/user_account_pages/rest_controllers/User_Process_PublicAccessCode_Value_RestWebserviceController.java
guoci/limelight-core
6ce269903ebc5948dd844047d5a2b5580fdc5432
[ "Apache-2.0" ]
5
2020-11-13T01:30:36.000Z
2021-11-24T22:18:53.000Z
limelight_webapp/src/main/java/org/yeastrc/limelight/limelight_webapp/spring_mvc_parts/user_account_pages/rest_controllers/User_Process_PublicAccessCode_Value_RestWebserviceController.java
guoci/limelight-core
6ce269903ebc5948dd844047d5a2b5580fdc5432
[ "Apache-2.0" ]
3
2021-01-31T18:42:54.000Z
2021-07-11T20:33:07.000Z
35.177489
162
0.807654
994,835
/* * Original author: Daniel Jaschob <djaschob .at. uw.edu> * * Copyright 2018 University of Washington - Seattle, WA * * 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.yeastrc.limelight.limelight_webapp.spring_mvc_parts.user_account_pages.rest_controllers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.LoggerFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.yeastrc.limelight.limelight_webapp.dao.ProjectDAO_IF; import org.yeastrc.limelight.limelight_webapp.db_dto.ProjectDTO; import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_BadRequest_InvalidParameter_Exception; import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_ErrorResponse_Base_Exception; import org.yeastrc.limelight.limelight_webapp.exceptions.webservice_access_exceptions.Limelight_WS_InternalServerError_Exception; import org.yeastrc.limelight.limelight_webapp.searchers.ProjectIdFor_Project_PublicAccessCode_PublicAccessCodeEnabled_Searcher_IF; import org.yeastrc.limelight.limelight_webapp.send_email_on_server_or_js_error.SendEmailOnServerOrJsError_ToConfiguredEmail_IF; import org.yeastrc.limelight.limelight_webapp.spring_mvc_parts.rest_controller_utils_common.Unmarshal_RestRequest_JSON_ToObject; import org.yeastrc.limelight.limelight_webapp.user_session_management.UserSession; import org.yeastrc.limelight.limelight_webapp.user_session_management.UserSessionBuilder; import org.yeastrc.limelight.limelight_webapp.user_session_management.UserSessionManager; import org.yeastrc.limelight.limelight_webapp.web_utils.MarshalObjectToJSON; /** * * */ @RestController public class User_Process_PublicAccessCode_Value_RestWebserviceController { private static final Logger log = LoggerFactory.getLogger( User_Process_PublicAccessCode_Value_RestWebserviceController.class ); @Autowired private ProjectIdFor_Project_PublicAccessCode_PublicAccessCodeEnabled_Searcher_IF projectIdFor_Project_PublicAccessCode_PublicAccessCodeEnabled_Searcher; @Autowired private ProjectDAO_IF projectDAO; @Autowired private UserSessionManager userSessionManager; @Autowired private SendEmailOnServerOrJsError_ToConfiguredEmail_IF sendEmailOnServerOrJsError_ToConfiguredEmail; @Autowired private Unmarshal_RestRequest_JSON_ToObject unmarshal_RestRequest_JSON_ToObject; @Autowired private MarshalObjectToJSON marshalObjectToJSON; /** * */ public User_Process_PublicAccessCode_Value_RestWebserviceController() { super(); // log.warn( "constructor no params called" ); } // Convert JSON to byte[] so can cache it // These 2 annotations work the same @PostMapping( path = { AA_UserAccount_RestWSControllerPaths_Constants.PATH_START_ALL + AA_UserAccount_RestWSControllerPaths_Constants.USER_PROCESS_PUBLIC_ACCESS_CODE_VALUE }, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE ) // @RequestMapping( // path = AA_RestWSControllerPaths_Constants., // method = RequestMethod.POST, // consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody ResponseEntity<byte[]> webserviceMethod( @RequestBody byte[] postBody, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse ) throws Exception { try { final String remoteIP = httpServletRequest.getRemoteAddr(); WebserviceRequest webserviceRequest = unmarshal_RestRequest_JSON_ToObject.getObjectFromJSONByteArray( postBody, WebserviceRequest.class ); WebserviceResponse webserviceResponse = processCode( webserviceRequest, remoteIP, httpServletRequest ); byte[] responseAsJSON = marshalObjectToJSON.getJSONByteArray( webserviceResponse ); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body( responseAsJSON ); } catch ( Limelight_WS_ErrorResponse_Base_Exception e ) { throw e; } catch ( Exception e ) { String msg = "Failed in controller: "; log.error( msg, e ); sendEmailOnServerOrJsError_ToConfiguredEmail.sendEmailOnServerOrJsError_ToConfiguredEmail(); throw new Limelight_WS_InternalServerError_Exception(); } } /** * @param webserviceRequest * @param remoteIP * @param httpServletRequest * @return * @throws Exception */ private WebserviceResponse processCode( WebserviceRequest webserviceRequest, String remoteIP, HttpServletRequest httpServletRequest ) throws Exception { if ( StringUtils.isEmpty( webserviceRequest.public_access_code_value ) ) { log.warn( "No public_access_code_value" ); throw new Limelight_WS_BadRequest_InvalidParameter_Exception(); } if ( webserviceRequest.projectId == null ) { log.warn( "No projectId" ); throw new Limelight_WS_BadRequest_InvalidParameter_Exception(); } String projectPublicAccessCode = webserviceRequest.public_access_code_value; WebserviceResponse webserviceResponse = new WebserviceResponse(); Integer projectId = projectIdFor_Project_PublicAccessCode_PublicAccessCodeEnabled_Searcher.getProjectId_Project_PublicAccessCode_PublicAccessCodeEnabled(projectPublicAccessCode); if ( projectId == null ) { webserviceResponse.invalidCode = true; return webserviceResponse; // EARLY RETURN } if ( projectId.intValue() != webserviceRequest.projectId ) { webserviceResponse.invalidCodeForProjectId = true; return webserviceResponse; // EARLY RETURN } ProjectDTO projectOnlyProjectLockedPublicAccessLevel = projectDAO.getProjectLockedPublicAccessLevelPublicAccessLockedForProjectId( projectId ); if ( projectOnlyProjectLockedPublicAccessLevel == null ) { webserviceResponse.invalidCode = true; return webserviceResponse; // EARLY RETURN } if ( ( ! projectOnlyProjectLockedPublicAccessLevel.isEnabled() ) || projectOnlyProjectLockedPublicAccessLevel.isMarkedForDeletion() ) { webserviceResponse.invalidCode = true; return webserviceResponse; // EARLY RETURN } UserSession userSession = UserSessionBuilder.getBuilder() .setPublicAccessCode( webserviceRequest.public_access_code_value ) .setProjectId_ForPublicAccessCode( projectId ) .build(); userSessionManager.setUserSession( userSession, httpServletRequest ); webserviceResponse.success = true; return webserviceResponse; } public static class WebserviceRequest { private String public_access_code_value; private Integer projectId; public void setPublic_access_code_value(String public_access_code_value) { this.public_access_code_value = public_access_code_value; } public void setProjectId(Integer projectId) { this.projectId = projectId; } } public static class WebserviceResponse { private boolean success; private boolean invalidCode; private boolean invalidCodeForProjectId; public boolean isSuccess() { return success; } public boolean isInvalidCode() { return invalidCode; } public boolean isInvalidCodeForProjectId() { return invalidCodeForProjectId; } } }
922eb659e443db83ad8b2549979e76dd65859e80
6,215
java
Java
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameExclusiveReadLockStrategy.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
4,262
2015-01-01T15:28:37.000Z
2022-03-31T04:46:41.000Z
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameExclusiveReadLockStrategy.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
3,408
2015-01-03T02:11:17.000Z
2022-03-31T20:07:56.000Z
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/GenericFileRenameExclusiveReadLockStrategy.java
ikyandhi/camel
c265fc7f1a49d3210de66e646238e3ce2abb7af1
[ "Apache-2.0" ]
5,505
2015-01-02T14:58:12.000Z
2022-03-30T19:23:41.000Z
38.128834
127
0.658407
994,836
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.file.strategy; import java.io.FileNotFoundException; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.component.file.GenericFile; import org.apache.camel.component.file.GenericFileEndpoint; import org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy; import org.apache.camel.component.file.GenericFileOperationFailedException; import org.apache.camel.component.file.GenericFileOperations; import org.apache.camel.spi.CamelLogger; import org.apache.camel.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Acquires exclusive read lock to the given file. Will wait until the lock is granted. After granting the read lock it * is released, we just want to make sure that when we start consuming the file its not currently in progress of being * written by third party. */ public class GenericFileRenameExclusiveReadLockStrategy<T> implements GenericFileExclusiveReadLockStrategy<T> { private static final Logger LOG = LoggerFactory.getLogger(GenericFileRenameExclusiveReadLockStrategy.class); private long timeout; private long checkInterval; private LoggingLevel readLockLoggingLevel = LoggingLevel.DEBUG; @Override public void prepareOnStartup(GenericFileOperations<T> operations, GenericFileEndpoint<T> endpoint) throws Exception { // noop } @Override public boolean acquireExclusiveReadLock(GenericFileOperations<T> operations, GenericFile<T> file, Exchange exchange) throws Exception { LOG.trace("Waiting for exclusive read lock to file: {}", file); // the trick is to try to rename the file, if we can rename then we have // exclusive read // since its a Generic file we cannot use java.nio to get a RW lock String newName = file.getFileName() + ".camelExclusiveReadLock"; // make a copy as result and change its file name GenericFile<T> newFile = operations.newGenericFile(); file.copyFrom(file, newFile); newFile.changeFileName(newName); StopWatch watch = new StopWatch(); boolean exclusive = false; while (!exclusive) { // timeout check if (timeout > 0) { long delta = watch.taken(); if (delta > timeout) { CamelLogger.log(LOG, readLockLoggingLevel, "Cannot acquire read lock within " + timeout + " millis. Will skip the file: " + file); // we could not get the lock within the timeout period, so // return false return false; } } try { exclusive = operations.renameFile(file.getAbsoluteFilePath(), newFile.getAbsoluteFilePath()); } catch (GenericFileOperationFailedException ex) { if (ex.getCause() instanceof FileNotFoundException) { exclusive = false; } else { throw ex; } } if (exclusive) { LOG.trace("Acquired exclusive read lock to file: {}", file); // rename it back so we can read it operations.renameFile(newFile.getAbsoluteFilePath(), file.getAbsoluteFilePath()); } else { boolean interrupted = sleep(); if (interrupted) { // we were interrupted while sleeping, we are likely being // shutdown so return false return false; } } } return true; } @Override public void releaseExclusiveReadLockOnAbort(GenericFileOperations<T> operations, GenericFile<T> file, Exchange exchange) throws Exception { // noop } @Override public void releaseExclusiveReadLockOnRollback(GenericFileOperations<T> operations, GenericFile<T> file, Exchange exchange) throws Exception { // noop } @Override public void releaseExclusiveReadLockOnCommit(GenericFileOperations<T> operations, GenericFile<T> file, Exchange exchange) throws Exception { // noop } private boolean sleep() { LOG.trace("Exclusive read lock not granted. Sleeping for {} millis.", checkInterval); try { Thread.sleep(checkInterval); return false; } catch (InterruptedException e) { LOG.debug("Sleep interrupted while waiting for exclusive read lock, so breaking out"); return true; } } public long getTimeout() { return timeout; } @Override public void setTimeout(long timeout) { this.timeout = timeout; } @Override public void setCheckInterval(long checkInterval) { this.checkInterval = checkInterval; } @Override public void setReadLockLoggingLevel(LoggingLevel readLockLoggingLevel) { this.readLockLoggingLevel = readLockLoggingLevel; } @Override public void setMarkerFiler(boolean markerFile) { // noop - we do not use marker file with the rename strategy } @Override public void setDeleteOrphanLockFiles(boolean deleteOrphanLockFiles) { // noop - we do not use marker file with the rename strategy } }
922eb6f3592fe907b167b4d110d3bafea9fbd9a7
5,264
java
Java
fastrpc-remoting/fastrpc-remoting-api/src/main/java/com/fast/fastrpc/transporter/AbstractClient.java
zonghaishang/fastrpc
5a64fb676d3a3a65a96ba38a2dbb8b09bf1f1336
[ "Apache-2.0" ]
5
2020-08-13T05:58:25.000Z
2020-10-12T02:12:09.000Z
fastrpc-remoting/fastrpc-remoting-api/src/main/java/com/fast/fastrpc/transporter/AbstractClient.java
zonghaishang/fastrpc
5a64fb676d3a3a65a96ba38a2dbb8b09bf1f1336
[ "Apache-2.0" ]
2
2021-12-14T21:51:37.000Z
2021-12-18T18:29:31.000Z
fastrpc-remoting/fastrpc-remoting-api/src/main/java/com/fast/fastrpc/transporter/AbstractClient.java
zonghaishang/fastrpc
5a64fb676d3a3a65a96ba38a2dbb8b09bf1f1336
[ "Apache-2.0" ]
2
2020-09-24T03:41:41.000Z
2020-09-28T02:03:25.000Z
30.08
122
0.617211
994,837
package com.fast.fastrpc.transporter; import com.fast.fastrpc.ChannelHandler; import com.fast.fastrpc.Client; import com.fast.fastrpc.RemotingException; import com.fast.fastrpc.channel.Channel; import com.fast.fastrpc.channel.ChannelPromise; import com.fast.fastrpc.channel.InvokeFuture; import com.fast.fastrpc.common.Constants; import com.fast.fastrpc.common.PrefixThreadFactory; import com.fast.fastrpc.common.URL; import com.fast.fastrpc.common.buffer.IoBuffer; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author yiji * @version : AbstractClient.java, v 0.1 2020-08-05 */ public abstract class AbstractClient extends AbstractPeer implements Client { protected volatile Channel channel; protected InetSocketAddress remoteAddress; protected int interval; protected int connectTimeout; protected volatile ScheduledFuture<?> future; protected static final ScheduledThreadPoolExecutor scheduledPool = new ScheduledThreadPoolExecutor(2, new PrefixThreadFactory("reconnect")); public AbstractClient(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); this.interval = url.getParameter(Constants.RECONNECT_KEY, 3000); this.connectTimeout = url.getParameter(Constants.CONNECT_TIMEOUT_KEY, 3000); // ready to connect to server. start(); } protected void start() throws RemotingException { try { this.remoteAddress = new InetSocketAddress(getUrl().getHost(), getUrl().getPort()); doOpen(); this.channel = doConnect(); if (logger.isInfoEnabled()) { logger.info("Success connect to server on " + this.remoteAddress); } } catch (Throwable e) { throw new RemotingException(null, this.remoteAddress, "Failed to connect to server on " + this.remoteAddress); } finally { // TCP reconnection is enabled by default scheduleReconnectIfRequired(); } } @Override public void connect() throws RemotingException { try { Channel channel = this.channel; if (channel == null) { this.channel = doConnect(); return; } if (channel.isActive()) return; shutdown(); this.channel = doConnect(); } catch (Throwable e) { throw new RemotingException(this.channel, "Failed to connect to server " + this.remoteAddress, e); } finally { scheduleReconnectIfRequired(); } } private void scheduleReconnectIfRequired() { if (this.interval > 0 && (this.future == null || this.future.isCancelled())) { this.future = scheduledPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { if (AbstractClient.this.isDestroyed()) { return; } connect(); } catch (RemotingException e) { logger.warn("Failed to reconnect to server on " + AbstractClient.this.remoteAddress, e); } } }, this.interval, this.interval, TimeUnit.MILLISECONDS); } } @Override public void write(Object msg, ChannelPromise promise) throws RemotingException { this.handler.write(this.channel, msg); } @Override public InvokeFuture shutdown() { return shutdown(this.shutdownTimeout); } @Override public InvokeFuture shutdown(int timeout) { doShutdown(timeout); Channel channel = this.channel; if (channel != null) return channel.shutdown(); return null; } @Override public void destroy() { if (destroyed.compareAndSet(false, true)) { /** * Terminate scheduling task(may be reconnecting). */ ScheduledFuture<?> future = this.future; if (future != null) { future.cancel(true); } shutdown(); } } @Override public SocketAddress localAddress() { Channel channel = this.channel; if (channel != null) return channel.localAddress(); return null; } @Override public SocketAddress remoteAddress() { return this.remoteAddress; } public int getConnectTimeout() { return connectTimeout; } @Override public boolean isActive() { Channel channel = this.channel; if (channel == null) return false; return channel.isActive(); } @Override public IoBuffer allocate() { return this.channel.allocate(); } @Override public IoBuffer allocate(int capacity) { return this.channel.allocate(capacity); } public abstract void doOpen() throws Throwable; public abstract Channel doConnect() throws RemotingException; public abstract void doShutdown(int timeout); }
922eb759a8069d00d2a96e481bbf90f6c698a546
3,625
java
Java
src/main/java/core/apis/last/entities/chartentities/TrackChart.java
TerikKek/Chuu
1161d4b56d635696c0ec33c1b73556a45208de42
[ "MIT" ]
106
2021-01-05T03:09:56.000Z
2022-03-31T09:05:37.000Z
src/main/java/core/apis/last/entities/chartentities/TrackChart.java
TerikKek/Chuu
1161d4b56d635696c0ec33c1b73556a45208de42
[ "MIT" ]
29
2021-01-17T22:21:27.000Z
2022-01-29T14:20:17.000Z
src/main/java/core/apis/last/entities/chartentities/TrackChart.java
TerikKek/Chuu
1161d4b56d635696c0ec33c1b73556a45208de42
[ "MIT" ]
20
2021-01-11T12:26:08.000Z
2022-03-19T20:32:41.000Z
37.760417
196
0.650759
994,838
package core.apis.last.entities.chartentities; import core.commands.utils.CommandUtil; import core.imagerenderer.ChartLine; import core.parsers.params.ChartParameters; import dao.entities.NowPlayingArtist; import dao.utils.LinkUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; public class TrackChart extends UrlCapsule { final boolean drawTitles; final boolean drawPlays; final boolean isAside; public TrackChart(String url, int pos, String trackName, String artistName, String mbid, int plays, boolean drawTitles, boolean drawPlays, boolean isAside) { super(url, pos, trackName, artistName, mbid, plays); this.drawTitles = drawTitles; this.drawPlays = drawPlays; this.isAside = isAside; } public TrackChart(String url, int pos, String trackName, String albumName, String mbid, boolean drawTitles, boolean drawPlays, boolean isAside) { super(url, pos, trackName, albumName, mbid); this.drawTitles = drawTitles; this.drawPlays = drawPlays; this.isAside = isAside; } public static BiFunction<JSONObject, Integer, UrlCapsule> getTrackParser(ChartParameters chartParameters) { return (trackObj, size) -> { String name = trackObj.getString("name"); int frequency = trackObj.getInt("playcount"); String artistName = trackObj.getJSONObject("artist").getString("name"); JSONArray image = trackObj.getJSONArray("image"); JSONObject bigImage = image.getJSONObject(image.length() - 1); return new TrackChart(bigImage.getString("#text"), size, name, artistName, null, frequency, chartParameters.isWriteTitles(), chartParameters.isWritePlays(), chartParameters.isAside()); }; } public static BiFunction<JSONObject, Integer, UrlCapsule> getDailyTrackParser(ChartParameters chartParameters) { return (jsonObject, ignored) -> { NowPlayingArtist x = AlbumChart.fromRecentTrack(jsonObject, TopEntity.TRACK); return new TrackChart(x.url(), 0, x.songName(), x.artistName(), x.artistMbid(), 1, chartParameters.isWriteTitles() , chartParameters.isWritePlays(), chartParameters.isAside()); }; } @Override public List<ChartLine> getLines() { List<ChartLine> list = new ArrayList<>(); if (drawTitles) { list.add(new ChartLine(getAlbumName(), ChartLine.Type.TITLE)); list.add(new ChartLine(getArtistName())); if (isAside) { Collections.reverse(list); } } if (drawPlays) { list.add(new ChartLine(getPlays() + " " + CommandUtil.singlePlural(getPlays(), "play", "plays"))); } return list; } @Override public String toEmbedDisplay() { return String.format(". **[%s - %s](%s)** - **%d** %s%n", CommandUtil.escapeMarkdown(getArtistName()) , CommandUtil.escapeMarkdown(getAlbumName()), LinkUtils.getLastFMArtistTrack(getArtistName(), getAlbumName()), getPlays(), CommandUtil.singlePlural(getPlays(), "play", "plays")); } @Override public String toChartString() { return String.format("%s - %s %d %s", getArtistName(), getAlbumName(), getPlays(), CommandUtil.singlePlural(getPlays(), "play", "plays")); } @Override public int getChartValue() { return getPlays(); } }
922eb7c7e15f1d402ab217226ae17eaf4acb95c1
4,501
java
Java
src/main/java/com/buuz135/industrial/item/addon/movility/ItemStackTransferAddon.java
temp1011/Industrial-Foregoing
ac2611bf24a68fe3de47d6ea790f1b7b9627963b
[ "MIT" ]
null
null
null
src/main/java/com/buuz135/industrial/item/addon/movility/ItemStackTransferAddon.java
temp1011/Industrial-Foregoing
ac2611bf24a68fe3de47d6ea790f1b7b9627963b
[ "MIT" ]
null
null
null
src/main/java/com/buuz135/industrial/item/addon/movility/ItemStackTransferAddon.java
temp1011/Industrial-Foregoing
ac2611bf24a68fe3de47d6ea790f1b7b9627963b
[ "MIT" ]
null
null
null
54.890244
269
0.72806
994,839
/* * This file is part of Industrial Foregoing. * * Copyright 2018, Buuz135 * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.buuz135.industrial.item.addon.movility; import com.buuz135.industrial.proxy.ItemRegistry; import com.buuz135.industrial.utils.RecipeUtils; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; public class ItemStackTransferAddon extends TransferAddon { public ItemStackTransferAddon(ActionMode mode) { super("itemstack_transfer_addon", mode); } @Override public void createRecipe() { RecipeUtils.addShapedRecipe(new ItemStack(this), "pcp", "dtd", "pcp", 'p', ItemRegistry.plastic, 'c', "chestWood", 'd', "dyeMagenta", 't', this.getMode() == ActionMode.PUSH ? Blocks.PISTON : Blocks.STICKY_PISTON); } @Override public boolean actionTransfer(World world, BlockPos pos, EnumFacing facing, int transferAmount) { TileEntity tileEntityOrigin = world.getTileEntity(pos); TileEntity tileEntityDestination = world.getTileEntity(pos.offset(facing)); if (tileEntityOrigin != null && tileEntityDestination != null && tileEntityOrigin.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing) && tileEntityDestination.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite())) { IItemHandler itemHandlerOrigin = getCapabilityOriginByMode(tileEntityOrigin, tileEntityDestination, facing); IItemHandler itemHandlerDestination = getCapabilityDestinationByMode(tileEntityOrigin, tileEntityDestination, facing); for (int i = 0; i < itemHandlerOrigin.getSlots(); ++i) { ItemStack input = itemHandlerOrigin.extractItem(i, transferAmount, true); if (!input.isEmpty()) { ItemStack result = ItemHandlerHelper.insertItem(itemHandlerDestination, input, true); int amountInserted = input.getCount() - result.getCount(); if (amountInserted > 0) { result = ItemHandlerHelper.insertItem(itemHandlerDestination, itemHandlerOrigin.extractItem(i, amountInserted, false), false); if (!result.isEmpty()) ItemHandlerHelper.insertItem(itemHandlerOrigin, result, false); return true; } } } } return false; } public IItemHandler getCapabilityOriginByMode(TileEntity origin, TileEntity destination, EnumFacing facing) { return this.getMode() == ActionMode.PUSH ? origin.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing) : destination.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()); } public IItemHandler getCapabilityDestinationByMode(TileEntity origin, TileEntity destination, EnumFacing facing) { return this.getMode() == ActionMode.PUSH ? destination.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite()) : origin.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing); } }
922eb7ec0ca3263ffaebfa6ab1c58283615931fc
1,505
java
Java
src/main/java/commands/implementations/TiktokCommands.java
Y0GAAAA/MonkeyBot
ca85e7d32b7971b17fc25ef391c6550ed2a8a5c9
[ "Unlicense" ]
null
null
null
src/main/java/commands/implementations/TiktokCommands.java
Y0GAAAA/MonkeyBot
ca85e7d32b7971b17fc25ef391c6550ed2a8a5c9
[ "Unlicense" ]
null
null
null
src/main/java/commands/implementations/TiktokCommands.java
Y0GAAAA/MonkeyBot
ca85e7d32b7971b17fc25ef391c6550ed2a8a5c9
[ "Unlicense" ]
null
null
null
34.454545
93
0.618734
994,840
package commands.implementations; import commands.dependencies.tiktok.TiktokVideoUrlResolver; import commands.invocation.CommandAttributes; import commands.invocation.MessageContext; import commands.responses.EmbedMessage; import commands.responses.ErrorMessage; import commands.responses.ResponseMessage; import commands.responses.VanillaMessage; import discord4j.discordjson.json.*; import discord4j.discordjson.possible.Possible; import java.net.URL; import java.util.Objects; public class TiktokCommands { public static final TiktokVideoUrlResolver tiktokResolver = new TiktokVideoUrlResolver(); kenaa@example.com( // helpText = "Embeds a tiktok video" //) public static ResponseMessage tiktok(MessageContext context, URL url) { String videoUrl = tiktokResolver.resolve(url); if (Objects.isNull(videoUrl) || videoUrl.isEmpty()) { return new ErrorMessage("invalid tiktok url"); } System.out.println("Resolved url : " + videoUrl); ImmutableEmbedVideoData videoData = EmbedVideoData.builder() .url(videoUrl) .build(); ImmutableEmbedData videoEmbed = EmbedData.builder() .url(videoUrl) .build(); return new EmbedMessage(videoEmbed); } }
922eb80c1da930f831f49e9fa3f96edcbd9805f1
1,284
java
Java
gen/com/goide/psi/impl/GoBuiltinCallExprImpl.java
jiuchongyangzy/tangxiaoyi
fb86fce6baa692d308cbbe85ffc8d36b2fd7be8d
[ "Apache-2.0" ]
null
null
null
gen/com/goide/psi/impl/GoBuiltinCallExprImpl.java
jiuchongyangzy/tangxiaoyi
fb86fce6baa692d308cbbe85ffc8d36b2fd7be8d
[ "Apache-2.0" ]
null
null
null
gen/com/goide/psi/impl/GoBuiltinCallExprImpl.java
jiuchongyangzy/tangxiaoyi
fb86fce6baa692d308cbbe85ffc8d36b2fd7be8d
[ "Apache-2.0" ]
null
null
null
23.345455
90
0.757009
994,841
// This is a generated file. Not intended for manual editing. package com.goide.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.goide.GoTypes.*; import com.goide.psi.*; public class GoBuiltinCallExprImpl extends GoExpressionImpl implements GoBuiltinCallExpr { public GoBuiltinCallExprImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof GoVisitor) ((GoVisitor)visitor).visitBuiltinCallExpr(this); else super.accept(visitor); } @Override @Nullable public GoBuiltinArgs getBuiltinArgs() { return findChildByClass(GoBuiltinArgs.class); } @Override @NotNull public GoReferenceExpression getReferenceExpression() { return findNotNullChildByClass(GoReferenceExpression.class); } @Override @Nullable public PsiElement getComma() { return findChildByType(COMMA); } @Override @NotNull public PsiElement getLparen() { return findNotNullChildByType(LPAREN); } @Override @Nullable public PsiElement getRparen() { return findChildByType(RPAREN); } }
922eb911f95ae5aa3d9b0724f73b020bccf80067
2,941
java
Java
src/main/java/se/turingturtles/implementations/ProjectCalculationsImp.java
The-Turing-Turtles/The-Turing-Turtles
107e7dc673f7ac63463a44ebd1cae24c37197712
[ "MIT" ]
null
null
null
src/main/java/se/turingturtles/implementations/ProjectCalculationsImp.java
The-Turing-Turtles/The-Turing-Turtles
107e7dc673f7ac63463a44ebd1cae24c37197712
[ "MIT" ]
2
2020-03-05T00:12:08.000Z
2020-04-23T20:27:00.000Z
src/main/java/se/turingturtles/implementations/ProjectCalculationsImp.java
The-Turing-Turtles/The-Turing-Turtles
107e7dc673f7ac63463a44ebd1cae24c37197712
[ "MIT" ]
4
2020-06-01T06:35:31.000Z
2021-12-07T22:10:57.000Z
35.433735
133
0.689221
994,842
package se.turingturtles.implementations; import se.turingturtles.application.ProjectCalculations; import se.turingturtles.application.ProjectManagement; import se.turingturtles.entities.Task; import se.turingturtles.entities.TeamMember; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.List; public class ProjectCalculationsImp implements ProjectCalculations { public double calculateEarnedValue(){ return calculateCompletedWorkPercentage()*ProjectManagementImp.getProject().getBudget(); } private double calculateCompletedWorkPercentage(){ ProjectFactory projectFactory = new ProjectFactory(); ProjectManagement projectManagement = projectFactory.makeProjectManagement(); List<Task> tasks = projectManagement.retrieveTasks(); int completedTasks = 0; if (tasks.size() == 0){ return 0; } for (int i=0; i<tasks.size(); i++){ if (tasks.get(i).getCompletion().equals("Completed")){ completedTasks++; } } return ((double)completedTasks/tasks.size()); } public double calculateScheduleVariance() { //We calculate the Schedule Variance based on calculateEV & calculateBCWS //EV = BCWS return calculateEarnedValue()-calculatePlannedValue(); } public double calculatePlannedValue(){ //PlannedValue = BCWS double projectRunTime = ChronoUnit.WEEKS.between(ProjectManagementImp.getProject().getProjectStartDate(), LocalDate.now()); double time = (projectRunTime/ ProjectManagementImp.getProject().getDuration()); //Calculating the Planned Value by getting the current week-startweek to get a runtime duration for the project so far //and then we divide that with total duration to get a "percentage" which we then use to multiply with total budget to get PV return time*ProjectManagementImp.getProject().getBudget(); } public double calculateCostVariance(){ //We assume that actual cost of work is entirely based on the total salaries return calculateEarnedValue() - calculateTotalSalaries(); } public double calculateTotalSalaries(){ List<TeamMember> members = ProjectManagementImp.getProject().getTeamMembers(); double totalSalary = 0; if (members.size() == 0) { return 0; } for (int i=0; i<members.size(); i++){ totalSalary += ((members.get(i).getHourlyWage())*(members.get(i).getTimeSpent())); } return totalSalary; } public void increaseBudget(double amount){ ProjectManagementImp.getProject().setBudget(ProjectManagementImp.getProject().getBudget() + amount); } public void decreaseBudget(double amount){ ProjectManagementImp.getProject().setBudget(ProjectManagementImp.getProject().getBudget() - amount); } }
922eb97f5bd153435b607cc4c3dc8c752d40ea1f
1,163
java
Java
src/main/java/org/oasis/plugin/OasisVersionSymbolType.java
jguglielmi/OasisPlugin
b7d68017bce9c2eb10f8a205969a0161c6221989
[ "Apache-2.0" ]
null
null
null
src/main/java/org/oasis/plugin/OasisVersionSymbolType.java
jguglielmi/OasisPlugin
b7d68017bce9c2eb10f8a205969a0161c6221989
[ "Apache-2.0" ]
1
2015-02-09T18:53:07.000Z
2015-02-10T12:32:56.000Z
src/main/java/org/oasis/plugin/OasisVersionSymbolType.java
jguglielmi/OasisPlugin
b7d68017bce9c2eb10f8a205969a0161c6221989
[ "Apache-2.0" ]
null
null
null
35.242424
132
0.758383
994,843
package org.oasis.plugin; import fitnesse.wikitext.parser.Maybe; import fitnesse.wikitext.parser.HtmlBuilder; import fitnesse.wikitext.parser.Matcher; import fitnesse.wikitext.parser.Parser; import fitnesse.wikitext.parser.Rule; import fitnesse.wikitext.parser.Symbol; import fitnesse.wikitext.parser.SymbolProvider; import fitnesse.wikitext.parser.SymbolType; public class OasisVersionSymbolType extends SymbolType implements Rule { public OasisVersionSymbolType() { super("Oasis Version"); String ver = GlobalEnv.getOasisVersion(); String bdate = GlobalEnv.getOasisBuildDate(); wikiMatcher(new Matcher().startLineOrCell().string("!version")); wikiRule(this); htmlTranslation(new HtmlBuilder("span").body(0, "OASIS version " + ver + " date " + bdate).attribute("class", "").inline()); } public static SymbolProvider getSymbolProvider() { return new SymbolProvider(new SymbolType[] {new OasisVersionSymbolType()}); } public fitnesse.wikitext.parser.Maybe<Symbol> parse(Symbol current, Parser parser) { // TODO Auto-generated method stub return new fitnesse.wikitext.parser.Maybe<Symbol>(current.add("")); } }
922ebbe8fcd8f2415b653708b6515c2148b990b4
817
java
Java
key/src/ProdArrayRecursive.java
matiashrnndz/programming-logic-with-key
e27cd8515079410c5d844d8e0b104771288cad5d
[ "MIT" ]
1
2021-11-07T23:26:23.000Z
2021-11-07T23:26:23.000Z
key/src/ProdArrayRecursive.java
matiashrnndz/programming-logic-with-key
e27cd8515079410c5d844d8e0b104771288cad5d
[ "MIT" ]
null
null
null
key/src/ProdArrayRecursive.java
matiashrnndz/programming-logic-with-key
e27cd8515079410c5d844d8e0b104771288cad5d
[ "MIT" ]
null
null
null
27.233333
61
0.468788
994,844
package key; public class ProdArrayRecursive { /*@ public normal_behavior @ requires arr != null; @ ensures \result == (\product int k; @ 0 <= k && k < arr.length; @ arr[k]); @ assignable \nothing; @*/ public int prodArrayRecursive(int[] arr) { return prodArrayRecursiveAux(arr, 0); } /*@ public normal_behavior @ requires arr != null; @ ensures \result == (\product int k; @ 0 <= k && k < arr.length; @ arr[k]); @ assignable \nothing; @*/ public int prodArrayRecursiveAux(int[] arr, int i) { if (i == arr.length) { return 1; } return arr[i] * prodArrayRecursiveAux(arr, ++i); } }
922ebc3cb82ccd305dc425adf95957efdcb0e553
1,617
java
Java
tinylog-impl/src/main/java/org/tinylog/throwable/UnpackThrowableFilter.java
sezinkarli/tinylog
43457422c0be5c47d1ea61a296a0bab92be0abff
[ "Apache-2.0" ]
390
2015-01-02T01:39:16.000Z
2021-03-06T12:15:22.000Z
tinylog-impl/src/main/java/org/tinylog/throwable/UnpackThrowableFilter.java
sezinkarli/tinylog
43457422c0be5c47d1ea61a296a0bab92be0abff
[ "Apache-2.0" ]
186
2015-06-09T11:57:13.000Z
2021-03-10T06:54:14.000Z
tinylog-impl/src/main/java/org/tinylog/throwable/UnpackThrowableFilter.java
sezinkarli/tinylog
43457422c0be5c47d1ea61a296a0bab92be0abff
[ "Apache-2.0" ]
85
2015-05-15T07:29:01.000Z
2021-02-26T07:17:45.000Z
25.666667
118
0.709338
994,845
/* * Copyright 2019 Martin Winandy * * 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.tinylog.throwable; import java.util.List; /** * Filter for unpacking configured throwables. * * <p> * The cause throwable instead of the original passed throwable will be used for all configured throwable class names, * if there is a cause throwable. * </p> */ public final class UnpackThrowableFilter extends AbstractThrowableFilter { /** */ public UnpackThrowableFilter() { this(null); } /** * @param arguments * Configured class names of throwables to unpack, separated by a vertical bar "|" */ public UnpackThrowableFilter(final String arguments) { super(arguments); } @Override public ThrowableData filter(final ThrowableData origin) { ThrowableData cause = origin.getCause(); if (cause != null) { List<String> classNames = getArguments(); if (classNames.isEmpty()) { return filter(cause); } for (String className : classNames) { if (className.equals(origin.getClassName())) { return filter(cause); } } } return origin; } }
922ebc69f035f7fb00a0933afb1708f28755efea
2,200
java
Java
palisade-service/src/unit-tests/java/uk/gov/gchq/palisade/service/palisade/CommonTestData.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
3
2020-07-13T09:43:55.000Z
2021-01-07T12:44:52.000Z
palisade-service/src/unit-tests/java/uk/gov/gchq/palisade/service/palisade/CommonTestData.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
66
2019-10-03T14:47:59.000Z
2022-01-24T03:36:02.000Z
palisade-service/src/unit-tests/java/uk/gov/gchq/palisade/service/palisade/CommonTestData.java
gchq/Palisade-services
105c35f7fe42216858cb1011c749e6f5db76b86f
[ "Apache-2.0", "CC-BY-4.0" ]
4
2020-05-07T20:39:11.000Z
2021-05-19T04:55:21.000Z
39.285714
109
0.738636
994,846
/* * Copyright 2018-2021 Crown Copyright * * 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 uk.gov.gchq.palisade.service.palisade; import uk.gov.gchq.palisade.service.palisade.model.AuditErrorMessage; import uk.gov.gchq.palisade.service.palisade.model.AuditablePalisadeSystemResponse; import uk.gov.gchq.palisade.service.palisade.model.PalisadeClientRequest; import java.util.Map; import java.util.UUID; public class CommonTestData { public static final Throwable ERROR = new Throwable("An error was thrown in the Palisade-Service"); public static final PalisadeClientRequest PALISADE_REQUEST; public static final AuditErrorMessage AUDIT_ERROR_MESSAGE; public static final AuditablePalisadeSystemResponse AUDITABLE_PALISADE_REQUEST; public static final AuditablePalisadeSystemResponse AUDITABLE_PALISADE_ERROR; public static final UUID COMMON_UUID = java.util.UUID.fromString("df3fc6ef-3f8c-48b4-ae1b-5f3d8ad32ead"); static { PALISADE_REQUEST = PalisadeClientRequest.Builder.create() .withUserId("testUserId") .withResourceId("/test/resourceId") .withContext(Map.of("purpose", "testContext")); } static { AUDIT_ERROR_MESSAGE = AuditErrorMessage.Builder .create(PALISADE_REQUEST, Map.of("messages", "10")).withError(ERROR); } static { AUDITABLE_PALISADE_REQUEST = AuditablePalisadeSystemResponse.Builder .create().withPalisadeRequest(PALISADE_REQUEST); } static { AUDITABLE_PALISADE_ERROR = AuditablePalisadeSystemResponse.Builder .create().withAuditErrorMessage(AUDIT_ERROR_MESSAGE); } }