id
int64
file_name
string
file_path
string
content
string
size
int64
language
string
extension
string
total_lines
int64
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
repo_name
string
repo_stars
int64
repo_forks
int64
repo_open_issues
int64
repo_license
string
repo_extraction_date
string
exact_duplicates_redpajama
bool
near_duplicates_redpajama
bool
exact_duplicates_githubcode
bool
exact_duplicates_stackv2
bool
exact_duplicates_stackv1
bool
near_duplicates_githubcode
bool
near_duplicates_stackv1
bool
near_duplicates_stackv2
bool
length
int64
1,317,042
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTypeParameter/test6/in/A.java
package p; class A<R,S>{ private int f; class B<T,R>{ } }
60
Java
.java
6
8.666667
15
0.636364
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
60
1,315,007
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MultiMove/test0/in/p1/A.java
package p1; import p2.C; public class A{ C c; p2.C p2c; }
59
Java
.java
6
8.666667
15
0.703704
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
59
1,319,476
A_test616.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_in/A_test616.java
package expression_in; public class A_test616 { public void foo() { A a= null; /*]*/a.getFile()/*]*/.getName(); } }
123
Java
.java
7
15.571429
34
0.626087
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
123
4,315,797
ParserPool.java
hzio_OpenJDK10/src/java.xml.ws/share/classes/com/sun/xml/internal/messaging/saaj/util/ParserPool.java
/* * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.messaging.saaj.util; import org.xml.sax.SAXException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; /** * Pool of SAXParser objects */ public class ParserPool { private final BlockingQueue<SAXParser> queue; private SAXParserFactory factory; public ParserPool(int capacity) { queue = new ArrayBlockingQueue<SAXParser>(capacity); factory = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", SAAJUtil.getSystemClassLoader()); try { factory.setFeature("jdk.xml.resetSymbolTable", true); } catch(SAXException | ParserConfigurationException e) { } factory.setNamespaceAware(true); for (int i = 0; i < capacity; i++) { try { queue.put(factory.newSAXParser()); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } catch (SAXException ex) { throw new RuntimeException(ex); } } } public SAXParser get() throws ParserConfigurationException, SAXException { try { return (SAXParser) queue.take(); } catch (InterruptedException ex) { throw new SAXException(ex); } } public boolean put(SAXParser parser) { return queue.offer(parser); } public void returnParser(SAXParser saxParser) { saxParser.reset(); put(saxParser); } }
3,148
Java
.java
76
35.421053
144
0.70817
hzio/OpenJDK10
2
4
0
GPL-2.0
9/5/2024, 12:08:58 AM (Europe/Amsterdam)
false
false
true
true
false
true
true
true
3,148
43,822
ZoomModel.java
JoanZapata_android-pdfview/android-pdfview/src/main/java/org/vudroid/core/models/ZoomModel.java
package org.vudroid.core.models; import org.vudroid.core.events.BringUpZoomControlsEvent; import org.vudroid.core.events.EventDispatcher; import org.vudroid.core.events.ZoomChangedEvent; import org.vudroid.core.events.ZoomListener; public class ZoomModel extends EventDispatcher { private float zoom = 1.0f; private static final float INCREMENT_DELTA = 0.05f; private boolean horizontalScrollEnabled; private boolean isCommited; public void setZoom(float zoom) { zoom = Math.max(zoom, 1.0f); if (this.zoom != zoom) { float oldZoom = this.zoom; this.zoom = zoom; isCommited = false; dispatch(new ZoomChangedEvent(zoom, oldZoom)); } } public float getZoom() { return zoom; } public void increaseZoom() { setZoom(getZoom() + INCREMENT_DELTA); } public void decreaseZoom() { setZoom(getZoom() - INCREMENT_DELTA); } public void toggleZoomControls() { dispatch(new BringUpZoomControlsEvent()); } public void setHorizontalScrollEnabled(boolean horizontalScrollEnabled) { this.horizontalScrollEnabled = horizontalScrollEnabled; } public boolean isHorizontalScrollEnabled() { return horizontalScrollEnabled; } public boolean canDecrement() { return zoom > 1.0f; } public void commit() { if (!isCommited) { isCommited = true; dispatch(new ZoomListener.CommitZoomEvent()); } } }
1,657
Java
.java
59
20.491525
76
0.63198
JoanZapata/android-pdfview
2,832
783
141
GPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,657
1,312,424
TestDecorator.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.junit.sampleproject/src/main/java/junit/extensions/TestDecorator.java
package junit.extensions; /*- * #%L * org.eclipse.jdt.ui.junit.sampleproject * %% * Copyright (C) 2020 Eclipse Foundation * %% * This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * #L% */ import junit.framework.*; /** * A Decorator for Tests. Use TestDecorator as the base class for defining new * test decorators. Test decorator subclasses can be introduced to add behaviour * before or after a test is run. */ public class TestDecorator extends Assert implements Test { protected Test fTest; public TestDecorator(Test test) { fTest = test; } /** * The basic run behaviour. */ public void basicRun(TestResult result) { fTest.run(result); } public int countTestCases() { return fTest.countTestCases(); } public void run(TestResult result) { basicRun(result); } public String toString() { return fTest.toString(); } public Test getTest() { return fTest; } }
1,249
Java
.java
44
26.136364
116
0.752508
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
1,249
1,315,610
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/UseSupertypeWherePossible/test29/in/A.java
package p; class A implements I { public void m() {} public void m1() {} protected A g() { return this; } } class A1 extends A{ protected A g() { g().m1(); return this; } }
187
Java
.java
14
11.357143
22
0.624277
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
187
1,319,668
TestCompoundWrite.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_in/TestCompoundWrite.java
package object_in; public class TestCompoundWrite { String field; public void foo() { field+= "d"; } }
111
Java
.java
7
13.714286
32
0.722772
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
111
1,314,877
Foo.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test20/in/Foo.java
package p; public class Foo<E, F, G extends Comparable<E>> { <H> H getFoo(H h) { return null; } { Foo f= new Foo(); f.getFoo(null); // <-- invoke here } }
171
Java
.java
10
14.5
49
0.606452
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
171
3,529,159
DefCardTyp.java
MEDEVIT_ecard/bundles/core/at.chipkarte.client/src/at/chipkarte/client/base/soap/constants/DefCardTyp.java
/* * Sämtliche Werknutzungs-und Verwertungsrechte an dieser Software liegen beim Hauptverband der österreichischen * Sozialversicherungsträger. Insbesondere ist die Veränderung der Software oder einzelner Teile untersagt. */ package at.chipkarte.client.base.soap.constants; /** * Konstanten für den Kartentyp bei Kartenleserstatus-Events. */ public final class DefCardTyp { private DefCardTyp() { // nothing to do } /** * e-card. */ public static final String ECARD_TEXT = "e-card"; /** * Ordinationskarte. */ public static final String OCARD_TEXT = "o-card (Ordinationskarte)"; /** * Pseudo-e-card. */ public static final String ECARD_SCHULUNG_TEXT = "schulungs-e-card (e-card für die Schulung)"; /** * Unbekannte Karte. */ public static final String UNKNOWN_CARD_TEXT = "unbekannte Karte"; /** * Keine Karte. */ public static final String EMPTY_CARD_TEXT = ""; }
979
Java
.java
33
25.212121
113
0.695043
MEDEVIT/ecard
3
0
0
EPL-1.0
9/4/2024, 11:31:34 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
973
3,599,647
SampleList.java
opensensorhub_osh-video/sensorhub-service-video/src/main/java/org/mp4parser/muxer/samples/SampleList.java
package org.mp4parser.muxer.samples; import org.mp4parser.Container; import org.mp4parser.muxer.RandomAccessSource; import org.mp4parser.muxer.Sample; import org.mp4parser.tools.Path; import java.util.AbstractList; import java.util.List; /** * Creates a list of <code>ByteBuffer</code>s that represent the samples of a given track. */ public class SampleList extends AbstractList<Sample> { List<Sample> samples; public SampleList(long trackId, Container isofile, RandomAccessSource source) { if (Path.getPaths(isofile, "moov/mvex/trex").isEmpty()) { samples = new DefaultMp4SampleList(trackId, isofile, source); } else { samples = new FragmentedMp4SampleList(trackId, isofile, source); } } @Override public Sample get(int index) { return samples.get(index); } @Override public int size() { return samples.size(); } }
928
Java
.java
28
28.178571
90
0.712682
opensensorhub/osh-video
3
7
2
MPL-2.0
9/4/2024, 11:34:47 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
928
1,316,281
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test63/in/A.java
package p; class A { public void m() {} public void m1() {} void t(){ new A(){ void g() throws InterruptedException{ A.super.wait(); } }; } }
161
Java
.java
12
10.833333
40
0.583893
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
161
1,318,774
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test25/in/A.java
class A { public static class Inner { } public A() { super(); new A.Inner(); } }
94
Java
.java
11
6.363636
26
0.604938
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
94
2,417,159
ProductCompositeServiceImpl.java
AcornPublishing_microservices-spring/Chapter13/microservices/product-composite-service/src/main/java/se/magnus/microservices/composite/product/services/ProductCompositeServiceImpl.java
package se.magnus.microservices.composite.product.services; import io.github.resilience4j.circuitbreaker.CircuitBreakerOpenException; import io.github.resilience4j.reactor.retry.RetryExceptionWrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import se.magnus.api.composite.product.*; import se.magnus.api.core.product.Product; import se.magnus.api.core.recommendation.Recommendation; import se.magnus.api.core.review.Review; import se.magnus.util.exceptions.NotFoundException; import se.magnus.util.http.ServiceUtil; import java.net.URL; import java.util.List; import java.util.stream.Collectors; @RestController public class ProductCompositeServiceImpl implements ProductCompositeService { private static final Logger LOG = LoggerFactory.getLogger(ProductCompositeServiceImpl.class); private final SecurityContext nullSC = new SecurityContextImpl(); private final ServiceUtil serviceUtil; private final ProductCompositeIntegration integration; @Autowired public ProductCompositeServiceImpl(ServiceUtil serviceUtil, ProductCompositeIntegration integration) { this.serviceUtil = serviceUtil; this.integration = integration; } @Override public Mono<Void> createCompositeProduct(ProductAggregate body) { return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalCreateCompositeProduct(sc, body)).then(); } public void internalCreateCompositeProduct(SecurityContext sc, ProductAggregate body) { try { logAuthorizationInfo(sc); LOG.debug("createCompositeProduct: creates a new composite entity for productId: {}", body.getProductId()); Product product = new Product(body.getProductId(), body.getName(), body.getWeight(), null); integration.createProduct(product); if (body.getRecommendations() != null) { body.getRecommendations().forEach(r -> { Recommendation recommendation = new Recommendation(body.getProductId(), r.getRecommendationId(), r.getAuthor(), r.getRate(), r.getContent(), null); integration.createRecommendation(recommendation); }); } if (body.getReviews() != null) { body.getReviews().forEach(r -> { Review review = new Review(body.getProductId(), r.getReviewId(), r.getAuthor(), r.getSubject(), r.getContent(), null); integration.createReview(review); }); } LOG.debug("createCompositeProduct: composite entities created for productId: {}", body.getProductId()); } catch (RuntimeException re) { LOG.warn("createCompositeProduct failed: {}", re.toString()); throw re; } } @Override public Mono<ProductAggregate> getCompositeProduct(int productId, int delay, int faultPercent) { return Mono.zip( values -> createProductAggregate((SecurityContext) values[0], (Product) values[1], (List<Recommendation>) values[2], (List<Review>) values[3], serviceUtil.getServiceAddress()), ReactiveSecurityContextHolder.getContext().defaultIfEmpty(nullSC), integration.getProduct(productId, delay, faultPercent) .onErrorMap(RetryExceptionWrapper.class, retryException -> retryException.getCause()) .onErrorReturn(CircuitBreakerOpenException.class, getProductFallbackValue(productId)), integration.getRecommendations(productId).collectList(), integration.getReviews(productId).collectList()) .doOnError(ex -> LOG.warn("getCompositeProduct failed: {}", ex.toString())) .log(); } @Override public Mono<Void> deleteCompositeProduct(int productId) { return ReactiveSecurityContextHolder.getContext().doOnSuccess(sc -> internalDeleteCompositeProduct(sc, productId)).then(); } private void internalDeleteCompositeProduct(SecurityContext sc, int productId) { try { logAuthorizationInfo(sc); LOG.debug("deleteCompositeProduct: Deletes a product aggregate for productId: {}", productId); integration.deleteProduct(productId); integration.deleteRecommendations(productId); integration.deleteReviews(productId); LOG.debug("deleteCompositeProduct: aggregate entities deleted for productId: {}", productId); } catch (RuntimeException re) { LOG.warn("deleteCompositeProduct failed: {}", re.toString()); throw re; } } private Product getProductFallbackValue(int productId) { LOG.warn("Creating a fallback product for productId = {}", productId); if (productId == 13) { String errMsg = "Product Id: " + productId + " not found in fallback cache!"; LOG.warn(errMsg); throw new NotFoundException(errMsg); } return new Product(productId, "Fallback product" + productId, productId, serviceUtil.getServiceAddress()); } private ProductAggregate createProductAggregate(SecurityContext sc, Product product, List<Recommendation> recommendations, List<Review> reviews, String serviceAddress) { logAuthorizationInfo(sc); // 1. Setup product info int productId = product.getProductId(); String name = product.getName(); int weight = product.getWeight(); // 2. Copy summary recommendation info, if available List<RecommendationSummary> recommendationSummaries = (recommendations == null) ? null : recommendations.stream() .map(r -> new RecommendationSummary(r.getRecommendationId(), r.getAuthor(), r.getRate(), r.getContent())) .collect(Collectors.toList()); // 3. Copy summary review info, if available List<ReviewSummary> reviewSummaries = (reviews == null) ? null : reviews.stream() .map(r -> new ReviewSummary(r.getReviewId(), r.getAuthor(), r.getSubject(), r.getContent())) .collect(Collectors.toList()); // 4. Create info regarding the involved microservices addresses String productAddress = product.getServiceAddress(); String reviewAddress = (reviews != null && reviews.size() > 0) ? reviews.get(0).getServiceAddress() : ""; String recommendationAddress = (recommendations != null && recommendations.size() > 0) ? recommendations.get(0).getServiceAddress() : ""; ServiceAddresses serviceAddresses = new ServiceAddresses(serviceAddress, productAddress, reviewAddress, recommendationAddress); return new ProductAggregate(productId, name, weight, recommendationSummaries, reviewSummaries, serviceAddresses); } private void logAuthorizationInfo(SecurityContext sc) { if (sc != null && sc.getAuthentication() != null && sc.getAuthentication() instanceof JwtAuthenticationToken) { Jwt jwtToken = ((JwtAuthenticationToken)sc.getAuthentication()).getToken(); logAuthorizationInfo(jwtToken); } else { LOG.warn("No JWT based Authentication supplied, running tests are we?"); } } private void logAuthorizationInfo(Jwt jwt) { if (jwt == null) { LOG.warn("No JWT supplied, running tests are we?"); } else { if (LOG.isDebugEnabled()) { URL issuer = jwt.getIssuer(); List<String> audience = jwt.getAudience(); Object subject = jwt.getClaims().get("sub"); Object scopes = jwt.getClaims().get("scope"); Object expires = jwt.getClaims().get("exp"); LOG.debug("Authorization info: Subject: {}, scopes: {}, expires {}: issuer: {}, audience: {}", subject, scopes, expires, issuer, audience); } } } }
8,460
Java
.java
146
48.40411
192
0.690913
AcornPublishing/microservices-spring
8
4
0
GPL-3.0
9/4/2024, 9:22:36 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
8,460
3,596,977
MethodVisitor.java
TANGO-Project_code-profiler-plugin/bundles/org.jvmmonitor.agent/src/org/jvmmonitor/internal/agent/asm/MethodVisitor.java
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2007 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.jvmmonitor.internal.agent.asm; /** * A visitor to visit a Java method. The methods of this interface must be * called in the following order: [ <tt>visitAnnotationDefault</tt> ] ( * <tt>visitAnnotation</tt> | <tt>visitParameterAnnotation</tt> | * <tt>visitAttribute</tt> )* [ <tt>visitCode</tt> ( <tt>visitFrame</tt> | * <tt>visit</tt><i>X</i>Insn</tt> | <tt>visitLabel</tt> | <tt>visitTryCatchBlock</tt> | * <tt>visitLocalVariable</tt> | <tt>visitLineNumber</tt>)* <tt>visitMaxs</tt> ] * <tt>visitEnd</tt>. In addition, the <tt>visit</tt><i>X</i>Insn</tt> * and <tt>visitLabel</tt> methods must be called in the sequential order of * the bytecode instructions of the visited code, <tt>visitTryCatchBlock</tt> * must be called <i>before</i> the labels passed as arguments have been * visited, and the <tt>visitLocalVariable</tt> and <tt>visitLineNumber</tt> * methods must be called <i>after</i> the labels passed as arguments have been * visited. * * @author Eric Bruneton */ public interface MethodVisitor { // ------------------------------------------------------------------------- // Annotations and non standard attributes // ------------------------------------------------------------------------- /** * Visits the default value of this annotation interface method. * * @return a visitor to the visit the actual default value of this * annotation interface method, or <tt>null</tt> if this visitor * is not interested in visiting this default value. The 'name' * parameters passed to the methods of this annotation visitor are * ignored. Moreover, exacly one visit method must be called on this * annotation visitor, followed by visitEnd. */ AnnotationVisitor visitAnnotationDefault(); /** * Visits an annotation of this method. * * @param desc the class descriptor of the annotation class. * @param visible <tt>true</tt> if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or <tt>null</tt> if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitAnnotation(String desc, boolean visible); /** * Visits an annotation of a parameter this method. * * @param parameter the parameter index. * @param desc the class descriptor of the annotation class. * @param visible <tt>true</tt> if the annotation is visible at runtime. * @return a visitor to visit the annotation values, or <tt>null</tt> if * this visitor is not interested in visiting this annotation. */ AnnotationVisitor visitParameterAnnotation( int parameter, String desc, boolean visible); /** * Visits a non standard attribute of this method. * * @param attr an attribute. */ void visitAttribute(Attribute attr); /** * Starts the visit of the method's code, if any (i.e. non abstract method). */ void visitCode(); /** * Visits the current state of the local variables and operand stack * elements. This method must(*) be called <i>just before</i> any * instruction <b>i</b> that follows an unconditionnal branch instruction * such as GOTO or THROW, that is the target of a jump instruction, or that * starts an exception handler block. The visited types must describe the * values of the local variables and of the operand stack elements <i>just * before</i> <b>i</b> is executed. <br> <br> (*) this is mandatory only * for classes whose version is greater than or equal to * {@link Opcodes#V1_6 V1_6}. <br> <br> Packed frames are basically * "deltas" from the state of the previous frame (very first frame is * implicitly defined by the method's parameters and access flags): <ul> * <li>{@link Opcodes#F_SAME} representing frame with exactly the same * locals as the previous frame and with the empty stack.</li> <li>{@link Opcodes#F_SAME1} * representing frame with exactly the same locals as the previous frame and * with single value on the stack (<code>nStack</code> is 1 and * <code>stack[0]</code> contains value for the type of the stack item).</li> * <li>{@link Opcodes#F_APPEND} representing frame with current locals are * the same as the locals in the previous frame, except that additional * locals are defined (<code>nLocal</code> is 1, 2 or 3 and * <code>local</code> elements contains values representing added types).</li> * <li>{@link Opcodes#F_CHOP} representing frame with current locals are * the same as the locals in the previous frame, except that the last 1-3 * locals are absent and with the empty stack (<code>nLocals</code> is 1, * 2 or 3). </li> <li>{@link Opcodes#F_FULL} representing complete frame * data.</li> </li> </ul> * * @param type the type of this stack map frame. Must be * {@link Opcodes#F_NEW} for expanded frames, or * {@link Opcodes#F_FULL}, {@link Opcodes#F_APPEND}, * {@link Opcodes#F_CHOP}, {@link Opcodes#F_SAME} or * {@link Opcodes#F_APPEND}, {@link Opcodes#F_SAME1} for compressed * frames. * @param nLocal the number of local variables in the visited frame. * @param local the local variable types in this frame. This array must not * be modified. Primitive types are represented by * {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, * {@link Opcodes#FLOAT}, {@link Opcodes#LONG}, * {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or * {@link Opcodes#UNINITIALIZED_THIS} (long and double are * represented by a single element). Reference types are represented * by String objects (representing internal names), and uninitialized * types by Label objects (this label designates the NEW instruction * that created this uninitialized value). * @param nStack the number of operand stack elements in the visited frame. * @param stack the operand stack types in this frame. This array must not * be modified. Its content has the same format as the "local" array. */ void visitFrame( int type, int nLocal, Object[] local, int nStack, Object[] stack); // ------------------------------------------------------------------------- // Normal instructions // ------------------------------------------------------------------------- /** * Visits a zero operand instruction. * * @param opcode the opcode of the instruction to be visited. This opcode is * either NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, * ICONST_3, ICONST_4, ICONST_5, LCONST_0, LCONST_1, FCONST_0, * FCONST_1, FCONST_2, DCONST_0, DCONST_1, IALOAD, LALOAD, FALOAD, * DALOAD, AALOAD, BALOAD, CALOAD, SALOAD, IASTORE, LASTORE, FASTORE, * DASTORE, AASTORE, BASTORE, CASTORE, SASTORE, POP, POP2, DUP, * DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2, SWAP, IADD, LADD, FADD, * DADD, ISUB, LSUB, FSUB, DSUB, IMUL, LMUL, FMUL, DMUL, IDIV, LDIV, * FDIV, DDIV, IREM, LREM, FREM, DREM, INEG, LNEG, FNEG, DNEG, ISHL, * LSHL, ISHR, LSHR, IUSHR, LUSHR, IAND, LAND, IOR, LOR, IXOR, LXOR, * I2L, I2F, I2D, L2I, L2F, L2D, F2I, F2L, F2D, D2I, D2L, D2F, I2B, * I2C, I2S, LCMP, FCMPL, FCMPG, DCMPL, DCMPG, IRETURN, LRETURN, * FRETURN, DRETURN, ARETURN, RETURN, ARRAYLENGTH, ATHROW, * MONITORENTER, or MONITOREXIT. */ void visitInsn(int opcode); /** * Visits an instruction with a single int operand. * * @param opcode the opcode of the instruction to be visited. This opcode is * either BIPUSH, SIPUSH or NEWARRAY. * @param operand the operand of the instruction to be visited.<br> When * opcode is BIPUSH, operand value should be between Byte.MIN_VALUE * and Byte.MAX_VALUE.<br> When opcode is SIPUSH, operand value * should be between Short.MIN_VALUE and Short.MAX_VALUE.<br> When * opcode is NEWARRAY, operand value should be one of * {@link Opcodes#T_BOOLEAN}, {@link Opcodes#T_CHAR}, * {@link Opcodes#T_FLOAT}, {@link Opcodes#T_DOUBLE}, * {@link Opcodes#T_BYTE}, {@link Opcodes#T_SHORT}, * {@link Opcodes#T_INT} or {@link Opcodes#T_LONG}. */ void visitIntInsn(int opcode, int operand); /** * Visits a local variable instruction. A local variable instruction is an * instruction that loads or stores the value of a local variable. * * @param opcode the opcode of the local variable instruction to be visited. * This opcode is either ILOAD, LLOAD, FLOAD, DLOAD, ALOAD, ISTORE, * LSTORE, FSTORE, DSTORE, ASTORE or RET. * @param var the operand of the instruction to be visited. This operand is * the index of a local variable. */ void visitVarInsn(int opcode, int var); /** * Visits a type instruction. A type instruction is an instruction that * takes the internal name of a class as parameter. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either NEW, ANEWARRAY, CHECKCAST or INSTANCEOF. * @param type the operand of the instruction to be visited. This operand * must be the internal name of an object or array class (see {@link * Type#getInternalName() getInternalName}). */ void visitTypeInsn(int opcode, String type); /** * Visits a field instruction. A field instruction is an instruction that * loads or stores the value of a field of an object. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either GETSTATIC, PUTSTATIC, GETFIELD or PUTFIELD. * @param owner the internal name of the field's owner class (see {@link * Type#getInternalName() getInternalName}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type Type}). */ void visitFieldInsn(int opcode, String owner, String name, String desc); /** * Visits a method instruction. A method instruction is an instruction that * invokes a method. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC or * INVOKEINTERFACE. * @param owner the internal name of the method's owner class (see {@link * Type#getInternalName() getInternalName}). * @param name the method's name. * @param desc the method's descriptor (see {@link Type Type}). */ void visitMethodInsn(int opcode, String owner, String name, String desc); /** * Visits a jump instruction. A jump instruction is an instruction that may * jump to another instruction. * * @param opcode the opcode of the type instruction to be visited. This * opcode is either IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ, * IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, * IF_ACMPNE, GOTO, JSR, IFNULL or IFNONNULL. * @param label the operand of the instruction to be visited. This operand * is a label that designates the instruction to which the jump * instruction may jump. */ void visitJumpInsn(int opcode, Label label); /** * Visits a label. A label designates the instruction that will be visited * just after it. * * @param label a {@link Label Label} object. */ void visitLabel(Label label); // ------------------------------------------------------------------------- // Special instructions // ------------------------------------------------------------------------- /** * Visits a LDC instruction. * * @param cst the constant to be loaded on the stack. This parameter must be * a non null {@link Integer}, a {@link Float}, a {@link Long}, a * {@link Double} a {@link String} (or a {@link Type} for * <tt>.class</tt> constants, for classes whose version is 49.0 or * more). */ void visitLdcInsn(Object cst); /** * Visits an IINC instruction. * * @param var index of the local variable to be incremented. * @param increment amount to increment the local variable by. */ void visitIincInsn(int var, int increment); /** * Visits a TABLESWITCH instruction. * * @param min the minimum key value. * @param max the maximum key value. * @param dflt beginning of the default handler block. * @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is * the beginning of the handler block for the <tt>min + i</tt> key. */ void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels); /** * Visits a LOOKUPSWITCH instruction. * * @param dflt beginning of the default handler block. * @param keys the values of the keys. * @param labels beginnings of the handler blocks. <tt>labels[i]</tt> is * the beginning of the handler block for the <tt>keys[i]</tt> key. */ void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels); /** * Visits a MULTIANEWARRAY instruction. * * @param desc an array type descriptor (see {@link Type Type}). * @param dims number of dimensions of the array to allocate. */ void visitMultiANewArrayInsn(String desc, int dims); // ------------------------------------------------------------------------- // Exceptions table entries, debug information, max stack and max locals // ------------------------------------------------------------------------- /** * Visits a try catch block. * * @param start beginning of the exception handler's scope (inclusive). * @param end end of the exception handler's scope (exclusive). * @param handler beginning of the exception handler's code. * @param type internal name of the type of exceptions handled by the * handler, or <tt>null</tt> to catch any exceptions (for "finally" * blocks). * @throws IllegalArgumentException if one of the labels has already been * visited by this visitor (by the {@link #visitLabel visitLabel} * method). */ void visitTryCatchBlock(Label start, Label end, Label handler, String type); /** * Visits a local variable declaration. * * @param name the name of a local variable. * @param desc the type descriptor of this local variable. * @param signature the type signature of this local variable. May be * <tt>null</tt> if the local variable type does not use generic * types. * @param start the first instruction corresponding to the scope of this * local variable (inclusive). * @param end the last instruction corresponding to the scope of this local * variable (exclusive). * @param index the local variable's index. * @throws IllegalArgumentException if one of the labels has not already * been visited by this visitor (by the * {@link #visitLabel visitLabel} method). */ void visitLocalVariable( String name, String desc, String signature, Label start, Label end, int index); /** * Visits a line number declaration. * * @param line a line number. This number refers to the source file from * which the class was compiled. * @param start the first instruction corresponding to this line number. * @throws IllegalArgumentException if <tt>start</tt> has not already been * visited by this visitor (by the {@link #visitLabel visitLabel} * method). */ void visitLineNumber(int line, Label start); /** * Visits the maximum stack size and the maximum number of local variables * of the method. * * @param maxStack maximum stack size of the method. * @param maxLocals maximum number of local variables for the method. */ void visitMaxs(int maxStack, int maxLocals); /** * Visits the end of the method. This method, which is the last one to be * called, is used to inform the visitor that all the annotations and * attributes of the method have been visited. */ void visitEnd(); }
18,514
Java
.java
366
45.032787
94
0.642585
TANGO-Project/code-profiler-plugin
3
1
0
EPL-2.0
9/4/2024, 11:34:47 PM (Europe/Amsterdam)
true
true
true
true
false
true
true
true
18,514
1,316,576
A_testVararg04_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testVararg04_in.java
package p; class A { public void use(String... args) { } public void call() { use(); use("one"); use("one", "two"); use(new String[] {"one", "two"}); use(null); use((String[]) null); use((String) null); } }
226
Java
.java
13
14.923077
36
0.56872
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
226
3,354,128
MaterialCardView_OnCheckedChangeListenerImplementor.java
IShiraiKurokoI_DLUTToolBoxMobile/DLUTToolBoxMobile/DLUTToolBoxMobile.Android/obj/Debug/120/android/src/mono/com/google/android/material/card/MaterialCardView_OnCheckedChangeListenerImplementor.java
package mono.com.google.android.material.card; public class MaterialCardView_OnCheckedChangeListenerImplementor extends java.lang.Object implements mono.android.IGCUserPeer, com.google.android.material.card.MaterialCardView.OnCheckedChangeListener { /** @hide */ public static final String __md_methods; static { __md_methods = "n_onCheckedChanged:(Lcom/google/android/material/card/MaterialCardView;Z)V:GetOnCheckedChanged_Lcom_google_android_material_card_MaterialCardView_ZHandler:Google.Android.Material.Card.MaterialCardView/IOnCheckedChangeListenerInvoker, Xamarin.Google.Android.Material\n" + ""; mono.android.Runtime.register ("Google.Android.Material.Card.MaterialCardView+IOnCheckedChangeListenerImplementor, Xamarin.Google.Android.Material", MaterialCardView_OnCheckedChangeListenerImplementor.class, __md_methods); } public MaterialCardView_OnCheckedChangeListenerImplementor () { super (); if (getClass () == MaterialCardView_OnCheckedChangeListenerImplementor.class) mono.android.TypeManager.Activate ("Google.Android.Material.Card.MaterialCardView+IOnCheckedChangeListenerImplementor, Xamarin.Google.Android.Material", "", this, new java.lang.Object[] { }); } public void onCheckedChanged (com.google.android.material.card.MaterialCardView p0, boolean p1) { n_onCheckedChanged (p0, p1); } private native void n_onCheckedChanged (com.google.android.material.card.MaterialCardView p0, boolean p1); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
1,737
Java
.java
39
41.897436
274
0.808171
IShiraiKurokoI/DLUTToolBoxMobile
4
0
0
GPL-2.0
9/4/2024, 11:14:57 PM (Europe/Amsterdam)
false
true
false
true
true
true
true
true
1,737
1,315,745
Constructor1.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceParameter/simple/Constructor1.java
//selection: 25, 33, 25, 41 //name: string -> name package simple; /** * @see Constructor1#create(int num) * @see #create(int) * * @see Constructor1#Constructor1(String) * @see #Constructor1(String name) */ public class Constructor1 { /** * @param name the name */ private Constructor1(String name) { System.out.println(name); } /** * Creator. * @param num the count * @return a Constructor1 */ public Constructor1 create(int num) { return new Constructor1("secret" + " #" + num); } }
514
Java
.java
26
17.653846
49
0.678279
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
514
1,319,633
A_test503.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_out/A_test503.java
package locals_out; public class A_test503 { public void foo() { int x= 10; extracted(x); } protected void extracted(int x) { /*[*/x++;/*]*/ } }
159
Java
.java
10
13.5
34
0.627586
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
159
1,314,796
A_testParametricEmptySelection_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeTypeRefactoring/positive/A_testParametricEmptySelection_in.java
import java.util.Arrays; import java.util.List; import java.util.Vector; public class A_testParametricEmptySelection_in { String fValue2 = "Eclipse"; List<String> fValue = Arrays.asList("Eclipse"); String test(String arg) { return null;} List<String> test2(java.util.List<Object> aList, List<Object> l){ return null; } Vector foo(BBB aaa){ List<String> xx = null; return null; } } class AAA { } class BBB extends AAA { }
478
Java
.java
19
21.157895
69
0.691964
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
478
4,948,027
CustomerCreditMemoDetailReportDataHolder.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/report/util/CustomerCreditMemoDetailReportDataHolder.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.report.util; import java.math.BigDecimal; import org.kuali.kfs.module.ar.businessobject.CustomerCreditMemoDetail; import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceDetail; import org.kuali.rice.core.api.util.type.KualiDecimal; public class CustomerCreditMemoDetailReportDataHolder { private BigDecimal creditMemoItemQuantity; private String creditMemoItemUnitOfMeasureCode; private String creditMemoItemDescription; private String creditMemoItemCode; private KualiDecimal creditMemoItemUnitPrice; private KualiDecimal creditMemoItemTaxAmount; private KualiDecimal creditMemoItemTotalAmount; public CustomerCreditMemoDetailReportDataHolder(CustomerCreditMemoDetail cmDetail, CustomerInvoiceDetail iDetail) { creditMemoItemQuantity = cmDetail.getCreditMemoItemQuantity(); creditMemoItemUnitOfMeasureCode = iDetail.getInvoiceItemUnitOfMeasureCode(); creditMemoItemDescription = iDetail.getInvoiceItemDescription(); creditMemoItemCode = iDetail.getInvoiceItemCode(); creditMemoItemUnitPrice = new KualiDecimal(iDetail.getInvoiceItemUnitPrice()); creditMemoItemTaxAmount = cmDetail.getCreditMemoItemTaxAmount(); creditMemoItemTotalAmount = cmDetail.getCreditMemoLineTotalAmount(); } /** * Gets the creditMemoItemQuantity attribute. * @return Returns the creditMemoItemQuantity. */ public BigDecimal getCreditMemoItemQuantity() { return creditMemoItemQuantity; } /** * Sets the creditMemoItemQuantity attribute value. * @param creditMemoItemQuantity The creditMemoItemQuantity to set. */ public void setCreditMemoItemQuantity(BigDecimal creditMemoItemQuantity) { this.creditMemoItemQuantity = creditMemoItemQuantity; } /** * Gets the creditMemoItemUnitOfMeasureCode attribute. * @return Returns the creditMemoItemUnitOfMeasureCode. */ public String getCreditMemoItemUnitOfMeasureCode() { return creditMemoItemUnitOfMeasureCode; } /** * Sets the creditMemoItemUnitOfMeasureCode attribute value. * @param creditMemoItemUnitOfMeasureCode The creditMemoItemUnitOfMeasureCode to set. */ public void setCreditMemoItemUnitOfMeasureCode(String creditMemoItemUnitOfMeasureCode) { this.creditMemoItemUnitOfMeasureCode = creditMemoItemUnitOfMeasureCode; } /** * Gets the creditMemoItemDescription attribute. * @return Returns the creditMemoItemDescription. */ public String getCreditMemoItemDescription() { return creditMemoItemDescription; } /** * Sets the creditMemoItemDescription attribute value. * @param creditMemoItemDescription The creditMemoItemDescription to set. */ public void setCreditMemoItemDescription(String creditMemoItemDescription) { this.creditMemoItemDescription = creditMemoItemDescription; } /** * Gets the creditMemoItemCode attribute. * @return Returns the creditMemoItemCode. */ public String getCreditMemoItemCode() { return creditMemoItemCode; } /** * Sets the creditMemoItemCode attribute value. * @param creditMemoItemCode The creditMemoItemCode to set. */ public void setCreditMemoItemCode(String creditMemoItemCode) { this.creditMemoItemCode = creditMemoItemCode; } /** * Gets the creditMemoItemUnitPrice attribute. * @return Returns the creditMemoItemUnitPrice. */ public KualiDecimal getCreditMemoItemUnitPrice() { return creditMemoItemUnitPrice; } /** * Sets the creditMemoItemUnitPrice attribute value. * @param creditMemoItemUnitPrice The creditMemoItemUnitPrice to set. */ public void setCreditMemoItemUnitPrice(KualiDecimal creditMemoItemUnitPrice) { this.creditMemoItemUnitPrice = creditMemoItemUnitPrice; } /** * Gets the creditMemoItemTaxAmount attribute. * @return Returns the creditMemoItemTaxAmount. */ public KualiDecimal getCreditMemoItemTaxAmount() { return creditMemoItemTaxAmount; } /** * Sets the creditMemoItemTaxAmount attribute value. * @param creditMemoItemTaxAmount The creditMemoItemTaxAmount to set. */ public void setCreditMemoItemTaxAmount(KualiDecimal creditMemoItemTaxAmount) { this.creditMemoItemTaxAmount = creditMemoItemTaxAmount; } /** * Gets the creditMemoItemTotalAmount attribute. * @return Returns the creditMemoItemTotalAmount. */ public KualiDecimal getCreditMemoItemTotalAmount() { return creditMemoItemTotalAmount; } /** * Sets the creditMemoItemTotalAmount attribute value. * @param creditMemoItemTotalAmount The creditMemoItemTotalAmount to set. */ public void setCreditMemoItemTotalAmount(KualiDecimal creditMemoItemTotalAmount) { this.creditMemoItemTotalAmount = creditMemoItemTotalAmount; } }
5,991
Java
.java
139
36.431655
120
0.748364
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
5,991
1,315,946
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test27/out/A.java
package p; class A { { for (int i = new int[]{}.length; i < new int[]{}.length; new int[]{}[i] = i) ; } }
114
Java
.java
7
14.142857
78
0.509434
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
114
4,492,714
WrapperLoginServerSetCompression.java
TheGreatRambler_AdvancedReplay2/src/main/java/com/comphenix/packetwrapper/WrapperLoginServerSetCompression.java
/** * PacketWrapper - ProtocolLib wrappers for Minecraft packets * Copyright (C) dmulloy2 <http://dmulloy2.net> * Copyright (C) Kristian S. Strangeland * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.comphenix.packetwrapper; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; public class WrapperLoginServerSetCompression extends AbstractPacket { public static final PacketType TYPE = PacketType.Login.Server.SET_COMPRESSION; public WrapperLoginServerSetCompression () { super (new PacketContainer (TYPE), TYPE); handle.getModifier ().writeDefaults (); } public WrapperLoginServerSetCompression (PacketContainer packet) { super (packet, TYPE); } /** * Retrieve Threshold. * <p> * Notes: threshold is the max size of a packet before its compressed * * @return The current Threshold */ public int getThreshold () { return handle.getIntegers ().read (0); } /** * Set Threshold. * * @param value - new value. */ public void setThreshold (int value) { handle.getIntegers ().write (0, value); } }
1,705
Java
.java
49
32.44898
79
0.758788
TheGreatRambler/AdvancedReplay2
2
0
0
GPL-3.0
9/5/2024, 12:14:53 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,705
1,315,522
A_test20_out.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameParameters/canRename/A_test20_out.java
//renaming to: j package p; class A{ Object m(i j){ j.i.i= j.i; i:{ while(true){ break i; } } return j; }; } class i{ i i; }
145
Java
.java
16
6.8125
16
0.538462
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
145
210,880
BenchmarkTest00726.java
OWASP-Benchmark_BenchmarkJava/src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00726.java
/** * OWASP Benchmark Project v1.2 * * <p>This file is part of the Open Web Application Security Project (OWASP) Benchmark Project. For * details, please see <a * href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>. * * <p>The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * <p>The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * @author Nick Sanidas * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value = "/xss-01/BenchmarkTest00726") public class BenchmarkTest00726 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String[] values = request.getParameterValues("BenchmarkTest00726"); String param; if (values != null && values.length > 0) param = values[0]; else param = ""; String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param); response.setHeader("X-XSS-Protection", "0"); response.getWriter().println(bar); } }
1,975
Java
.java
45
39.6
100
0.748699
OWASP-Benchmark/BenchmarkJava
656
1,037
15
GPL-2.0
9/4/2024, 7:05:34 PM (Europe/Amsterdam)
false
true
true
true
false
true
true
true
1,975
1,318,863
BBB.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/BBB.java
public class BBB { public void foo() { int i= 0; BBB b= new BBB(); BBB[] bb= new BBB[10]; if (i == 0 && i == 10 && b instanceof BBB) foo(); while(i++ == 10) { foo(); } i--; while(i++ == 10) foo(); i--; do { } while (i < 10); for (int x= 0, o= 0; x < 10; x++, o++); { foo(); int z;//= x; } try { foo(); } catch (Exception e) { } finally { } switch (i) { case 10: foo(); case 20: foo(); default: foo(); } } public int g() { g(); return 1; } }
546
Java
.java
40
10.025
44
0.442857
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
546
4,948,052
CustomerInvoiceWriteoffLookupSummaryAction.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/web/struts/CustomerInvoiceWriteoffLookupSummaryAction.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.web.struts; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.ar.ArKeyConstants; import org.kuali.kfs.module.ar.ArPropertyConstants; import org.kuali.kfs.module.ar.batch.service.CustomerInvoiceWriteoffBatchService; import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceWriteoffLookupResult; import org.kuali.kfs.module.ar.businessobject.lookup.CustomerInvoiceWriteoffLookupUtil; import org.kuali.kfs.module.ar.document.CustomerInvoiceDocument; import org.kuali.kfs.module.ar.document.service.CustomerInvoiceWriteoffDocumentService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kns.util.KNSGlobalVariables; import org.kuali.rice.kns.web.struts.action.KualiAction; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; public class CustomerInvoiceWriteoffLookupSummaryAction extends KualiAction { public ActionForward viewSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CustomerInvoiceWriteoffLookupSummaryForm customerInvoiceWriteoffLookupSummaryForm = (CustomerInvoiceWriteoffLookupSummaryForm) form; String lookupResultsSequenceNumber = customerInvoiceWriteoffLookupSummaryForm.getLookupResultsSequenceNumber(); if (StringUtils.isNotBlank(lookupResultsSequenceNumber)) { String personId = GlobalVariables.getUserSession().getPerson().getPrincipalId(); Collection<CustomerInvoiceWriteoffLookupResult> customerInvoiceWriteoffLookupResults = CustomerInvoiceWriteoffLookupUtil.getCustomerInvoiceWriteoffResutlsFromLookupResultsSequenceNumber(lookupResultsSequenceNumber,personId); customerInvoiceWriteoffLookupSummaryForm.setCustomerInvoiceWriteoffLookupResults(customerInvoiceWriteoffLookupResults); GlobalVariables.getUserSession().addObject(KRADConstants.LOOKUP_RESULTS_SEQUENCE_NUMBER, lookupResultsSequenceNumber); } return mapping.findForward(KFSConstants.MAPPING_BASIC); } public ActionForward createCustomerInvoiceWriteoffs(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CustomerInvoiceWriteoffLookupSummaryForm customerInvoiceWriteoffLookupSummaryForm = (CustomerInvoiceWriteoffLookupSummaryForm) form; Person person = GlobalVariables.getUserSession().getPerson(); CustomerInvoiceWriteoffDocumentService service = SpringContext.getBean(CustomerInvoiceWriteoffDocumentService.class); Collection<CustomerInvoiceWriteoffLookupResult> lookupResults = customerInvoiceWriteoffLookupSummaryForm.getCustomerInvoiceWriteoffLookupResults(); //TODO Need to check every invoiceNumber submitted and make sure that: // 1. Invoice exists in the system. // 2. Invoice doesnt already have a writeoff in progress, either in route or final. // make sure no null/blank invoiceNumbers get sent boolean anyFound = false; boolean customerNoteMissingOrInvalid = false; int ind = 0; String customerNote; for( CustomerInvoiceWriteoffLookupResult customerInvoiceWriteoffLookupResult : lookupResults ){ customerNote = customerInvoiceWriteoffLookupResult.getCustomerNote(); if (StringUtils.isEmpty(customerNote)) { GlobalVariables.getMessageMap().putError(KFSConstants.CUSTOMER_INVOICE_WRITEOFF_LOOKUP_RESULT_ERRORS + "[" + ind +"]." + ArPropertyConstants.CustomerInvoiceWriteoffLookupResultFields.CUSTOMER_NOTE, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_CUSTOMER_NOTE_REQUIRED); customerNoteMissingOrInvalid = true; } else if (customerNote.trim().length() < 5) { GlobalVariables.getMessageMap().putError(KFSConstants.CUSTOMER_INVOICE_WRITEOFF_LOOKUP_RESULT_ERRORS + "[" + ind +"]." + ArPropertyConstants.CustomerInvoiceWriteoffLookupResultFields.CUSTOMER_NOTE, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_CUSTOMER_NOTE_INVALID); customerNoteMissingOrInvalid = true; } for (CustomerInvoiceDocument invoiceDocument : customerInvoiceWriteoffLookupResult.getCustomerInvoiceDocuments()) { if (StringUtils.isNotBlank(invoiceDocument.getDocumentNumber())) { anyFound = true; } } ind++; } if (customerNoteMissingOrInvalid || !anyFound) { // only submit this if there's at least one invoiceNumber in the stack if (!anyFound) GlobalVariables.getMessageMap().putError(KFSConstants.GLOBAL_ERRORS, ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_NO_INVOICES_SELECTED); return mapping.findForward(KFSConstants.MAPPING_BASIC); } // send the batch file off String filename = service.sendCustomerInvoiceWriteoffDocumentsToBatch(person, lookupResults); // manually fire off the batch job SpringContext.getBean(CustomerInvoiceWriteoffBatchService.class).loadFiles(); customerInvoiceWriteoffLookupSummaryForm.setSentToBatch(true); KNSGlobalVariables.getMessageList().add(ArKeyConstants.ERROR_CUSTOMER_INVOICE_WRITEOFF_BATCH_SENT); return mapping.findForward(KFSConstants.MAPPING_BASIC); } public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(KFSConstants.MAPPING_CANCEL); } }
7,001
Java
.java
99
61.606061
286
0.770318
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
7,001
2,762,330
ClientToolbar.java
zeruth_RuneLitePlus-Injector/RuneLitePlus/src/main/java/net/runelite/client/ui/ClientToolbar.java
/* * Copyright (c) 2017, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.ui; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import net.runelite.client.eventbus.EventBus; import net.runelite.client.events.NavigationButtonAdded; import net.runelite.client.events.NavigationButtonRemoved; /** * Plugin toolbar buttons holder. */ @Singleton public class ClientToolbar { private final EventBus eventBus; private final Set<NavigationButton> buttons = new HashSet<>(); @Inject private ClientToolbar(final EventBus eventBus) { this.eventBus = eventBus; } /** * Add navigation. * * @param button the button */ public void addNavigation(final NavigationButton button) { if (buttons.contains(button)) { return; } if (buttons.add(button)) { eventBus.post(new NavigationButtonAdded(button)); } } /** * Remove navigation. * * @param button the button */ public void removeNavigation(final NavigationButton button) { if (buttons.remove(button)) { eventBus.post(new NavigationButtonRemoved(button)); } } }
2,452
Java
.java
74
30.918919
82
0.776981
zeruth/RuneLitePlus-Injector
6
8
0
AGPL-3.0
9/4/2024, 10:13:45 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
2,452
1,311,888
TypeVariable2.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.corext.refactoring.typeconstraints2; import org.eclipse.core.runtime.Assert; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange; import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType; /** * A TypeVariable is a ConstraintVariable which stands for a * single type reference (in source). */ public final class TypeVariable2 extends ConstraintVariable2 implements ITypeConstraintVariable { private final CompilationUnitRange fRange; public TypeVariable2(TType type, CompilationUnitRange range) { super(type); Assert.isNotNull(range); fRange= range; } @Override public CompilationUnitRange getRange() { return fRange; } /* * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return getRange().hashCode() ^ getType().hashCode(); } /* * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { //TODO: unique per construction? //return this == other; if (this == other) return true; if (other.getClass() != TypeVariable2.class) return false; TypeVariable2 otherTypeVariable= (TypeVariable2) other; return getRange().equals(otherTypeVariable.getRange()) && getType() == otherTypeVariable.getType(); } @Override public void setCompilationUnit(ICompilationUnit unit) { throw new UnsupportedOperationException(); } @Override public ICompilationUnit getCompilationUnit() { return fRange.getCompilationUnit(); } @Override public String toString() { return super.toString() + " [" + fRange.getSourceRange().getOffset() + '+' + fRange.getSourceRange().getLength() + ']'; //$NON-NLS-1$ } }
2,319
Java
.java
67
32.179104
135
0.712243
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
2,319
1,320,668
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/testFail45/in/A.java
package p; interface J{ void m(); } interface I extends J{ void m(); } interface I1 extends J{ void m(); }
106
Java
.java
10
9.7
23
0.721649
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
106
1,318,782
Inner.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test30/out/Inner.java
import static java.lang.Math.E; public class Inner { /** Comment */ private A a; Inner(A a) { this.a= a; int f= this.a.foo(); int g= this.a.bar(); double e= E; } }
177
Java
.java
12
12.666667
31
0.621951
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
177
1,315,672
A1.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/UseSupertypeWherePossible/test57/in/A1.java
package p; public class A1 extends A{ protected A f(){ return this; } void test(){ f().m(); } }
104
Java
.java
9
9.666667
26
0.631579
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
104
4,041,683
RegistryMBean.java
deathspeeder_class-guard/apache-tomcat-7.0.53-src/java/org/apache/tomcat/util/modeler/RegistryMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.modeler; import java.util.List; import javax.management.ObjectName; /** * Interface for modeler MBeans. * * This is the main entry point into modeler. It provides methods to create * and manipulate model mbeans and simplify their use. * * Starting with version 1.1, this is no longer a singleton and the static * methods are strongly deprecated. In a container environment we can expect * different applications to use different registries. * * @author Craig R. McClanahan * @author Costin Manolache * * @since 1.1 */ public interface RegistryMBean { /** * Load an extended mlet file. The source can be an URL, File or * InputStream. * * All mbeans will be instantiated, registered and the attributes will be * set. The result is a list of ObjectNames. * * @param source InputStream or URL of the file * @param cl ClassLoader to be used to load the mbeans, or null to use the * default JMX mechanism ( i.e. all registered loaders ) * @return List of ObjectName for the loaded mbeans * @throws Exception * * @since 1.1 */ public List<ObjectName> loadMBeans( Object source, ClassLoader cl ) throws Exception; /** Invoke an operation on a set of mbeans. * * @param mbeans List of ObjectNames * @param operation Operation to perform. Typically "init" "start" "stop" or "destroy" * @param failFirst Behavior in case of exceptions - if false we'll ignore * errors * @throws Exception */ public void invoke( List<ObjectName> mbeans, String operation, boolean failFirst ) throws Exception; /** Register a bean by creating a modeler mbean and adding it to the * MBeanServer. * * If metadata is not loaded, we'll look up and read a file named * "mbeans-descriptors.ser" or "mbeans-descriptors.xml" in the same package * or parent. * * If the bean is an instance of DynamicMBean. it's metadata will be converted * to a model mbean and we'll wrap it - so modeler services will be supported * * If the metadata is still not found, introspection will be used to extract * it automatically. * * If an mbean is already registered under this name, it'll be first * unregistered. * * If the component implements MBeanRegistration, the methods will be called. * If the method has a method "setRegistry" that takes a RegistryMBean as * parameter, it'll be called with the current registry. * * * @param bean Object to be registered * @param oname Name used for registration * @param type The type of the mbean, as declared in mbeans-descriptors. If * null, the name of the class will be used. This can be used as a hint or * by subclasses. * * @since 1.1 */ public void registerComponent(Object bean, String oname, String type) throws Exception; /** Unregister a component. We'll first check if it is registered, * and mask all errors. This is mostly a helper. * * @param oname * * @since 1.1 */ public void unregisterComponent( String oname ); /** Return an int ID for faster access. Will be used for notifications * and for other operations we want to optimize. * * @param domain Namespace * @param name Type of the notification * @return An unique id for the domain:name combination * @since 1.1 */ public int getId( String domain, String name); /** Reset all metadata cached by this registry. Should be called * to support reloading. Existing mbeans will not be affected or modified. * * It will be called automatically if the Registry is unregistered. * @since 1.1 */ public void stop(); /** Load descriptors. The source can be a File, URL pointing to an * mbeans-descriptors.xml. * * Also ( experimental for now ) a ClassLoader - in which case META-INF/ will * be used. * * @param source */ public void loadMetadata(Object source ) throws Exception; }
5,016
Java
.java
127
34.204724
90
0.689167
deathspeeder/class-guard
2
2
0
GPL-2.0
9/5/2024, 12:00:55 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
5,016
1,317,699
A_test19_out.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test19_out.java
package p; class A{ void m(int i){ int temp= f(); if (temp == 0){ int t= temp; } } int f(){ return 5; } }
120
Java
.java
12
7.833333
17
0.522936
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
120
1,312,599
QualifiedTypeNameHistory.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/QualifiedTypeNameHistory.java
/******************************************************************************* * Copyright (c) 2000, 2015 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.corext.util; import org.w3c.dom.Element; public class QualifiedTypeNameHistory extends History<String, String> { private static final String NODE_ROOT= "qualifiedTypeNameHistroy"; //$NON-NLS-1$ private static final String NODE_TYPE_INFO= "fullyQualifiedTypeName"; //$NON-NLS-1$ private static final String NODE_NAME= "name"; //$NON-NLS-1$ private static QualifiedTypeNameHistory fgInstance; public static QualifiedTypeNameHistory getDefault() { if (fgInstance == null) fgInstance= new QualifiedTypeNameHistory("QualifiedTypeNameHistory.xml"); //$NON-NLS-1$ return fgInstance; } public QualifiedTypeNameHistory(String fileName) { super(fileName, NODE_ROOT, NODE_TYPE_INFO); load(); } @Override protected void setAttributes(Object object, Element element) { element.setAttribute(NODE_NAME, (String)object); } @Override protected String createFromElement(Element element) { return element.getAttribute(NODE_NAME); } @Override protected String getKey(String object) { return object; } public static int getBoost(String fullyQualifiedTypeName, int min, int max) { float position= getDefault().getNormalizedPosition(fullyQualifiedTypeName); int dist= max - min; return Math.round(position * dist) + min; } public static void remember(String fullyQualifiedTypeName) { getDefault().accessed(fullyQualifiedTypeName); } }
1,963
Java
.java
50
36.82
90
0.71722
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
1,963
1,316,314
I.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test7/out/I.java
package p; import java.io.IOException; import java.util.List; import java.util.Set; /** typecomment template*/ interface I { List m(Set set, Set set1) throws IOException; }
177
Java
.java
8
20.625
46
0.783133
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
177
1,315,105
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameNonPrivateField/testGenerics2/out/A.java
package p; class A<T> { T g; public T getG() { return g; } public void setG(T f) { this.g = f; } }
146
Java
.java
10
8.9
27
0.456
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
146
1,310,076
ZGetMessageParams.java
zextras_carbonio-mailbox/client/src/main/java/com/zimbra/client/ZGetMessageParams.java
// SPDX-FileCopyrightText: 2022 Synacor, Inc. // SPDX-FileCopyrightText: 2022 Zextras <https://www.zextras.com> // // SPDX-License-Identifier: GPL-2.0-only package com.zimbra.client; import com.zimbra.common.util.StringUtil; public class ZGetMessageParams { private String mId; private boolean mMarkRead; private boolean mWantHtml; private boolean mNeuterImages; private boolean mRawContent; private String mPart; private Integer mMax; private String mRequestHeaders; public ZGetMessageParams() { } public boolean isWantHtml() { return mWantHtml; } public void setWantHtml(boolean wantHtml) { mWantHtml = wantHtml; } public String getId() { return mId; } public void setId(String id) { mId = id; } public boolean isMarkRead() { return mMarkRead; } public void setMarkRead(boolean markRead) { mMarkRead = markRead; } public boolean isNeuterImages() { return mNeuterImages; } public void setNeuterImages(boolean neuterImages) { this.mNeuterImages = neuterImages; } public boolean isRawContent() { return mRawContent; } public void setRawContent(boolean rawContent) { mRawContent = rawContent; } public String getPart() { return mPart; } public void setPart(String part) { mPart = part; } public Integer getMax() { return mMax; } public void setMax(Integer max) { mMax = max; } public int hashCode() { if (mPart != null) return (mId+mPart).hashCode(); else return mId.hashCode(); } public void setReqHeaders(String reqHeaders) { this.mRequestHeaders = reqHeaders; } public String getReqHeaders() { return this.mRequestHeaders; } /** * * @return true if get message params are equal. */ public boolean equals(Object obj) { if (obj == this) return true; if (! (obj instanceof ZGetMessageParams)) return false; ZGetMessageParams that = (ZGetMessageParams) obj; return this.mNeuterImages == that.mNeuterImages && this.mRawContent == that.mRawContent && this.mWantHtml == that.mWantHtml && this.mMarkRead == that.mMarkRead && StringUtil.equal(this.mId, that.mId) && StringUtil.equal(this.mPart, that.mPart) && this.mMax == that.mMax; } public ZGetMessageParams(ZGetMessageParams that) { this.mId = that.mId; this.mWantHtml = that.mWantHtml; this.mMarkRead = that.mMarkRead; this.mNeuterImages = that.mNeuterImages; this.mRawContent = that.mRawContent; this.mPart = that.mPart; } }
2,862
Java
.java
95
22.926316
65
0.635764
zextras/carbonio-mailbox
32
6
6
GPL-2.0
9/4/2024, 7:33:43 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
2,862
1,319,075
A_test576.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_in/A_test576.java
package locals_in; public class A_test576 { public void foo() { /*[*/int avail= 10;/*]*/ for (;;) { try { } finally { avail= 20; } } } }
160
Java
.java
12
10.416667
26
0.527397
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
160
2,193,111
ItemEmptyMap.java
Cats-Club_Impact-3_0/net/minecraft/item/ItemEmptyMap.java
package net.minecraft.item; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; public class ItemEmptyMap extends ItemMapBase { protected ItemEmptyMap() { this.setCreativeTab(CreativeTabs.MISC); } public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { ItemStack itemstack = new ItemStack(Items.FILLED_MAP, 1, worldIn.getUniqueDataId("map")); String s = "map_" + itemstack.getMetadata(); MapData mapdata = new MapData(s); worldIn.setItemData(s, mapdata); mapdata.scale = 0; mapdata.calculateMapCenter(playerIn.posX, playerIn.posZ, mapdata.scale); mapdata.dimension = (byte)worldIn.provider.getDimensionType().getId(); mapdata.trackingPosition = true; mapdata.markDirty(); --itemStackIn.stackSize; if (itemStackIn.stackSize <= 0) { return new ActionResult(EnumActionResult.SUCCESS, itemstack); } else { if (!playerIn.inventory.addItemStackToInventory(itemstack.copy())) { playerIn.dropItem(itemstack, false); } playerIn.addStat(StatList.getObjectUseStats(this)); return new ActionResult(EnumActionResult.SUCCESS, itemStackIn); } } }
1,667
Java
.java
43
31.883721
127
0.705374
Cats-Club/Impact-3.0
19
1
0
MPL-2.0
9/4/2024, 8:32:05 PM (Europe/Amsterdam)
false
false
true
true
false
true
true
true
1,667
1,316,496
A_test20_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_test20_in.java
package p; class A { void m(int a, int b[]){} }
49
Java
.java
4
11
25
0.6
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
49
4,492,515
ConsumerRepository.java
OpenGlobes_Core/core-commons/src/main/java/com/lmax/disruptor/dsl/ConsumerRepository.java
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.dsl; import com.lmax.disruptor.*; import java.util.*; /** * Provides a repository mechanism to associate {@link EventHandler}s with * {@link EventProcessor}s * * @param <T> the type of the {@link EventHandler} */ class ConsumerRepository<T> implements Iterable<ConsumerInfo> { private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByEventHandler = new IdentityHashMap<>(); private final Map<Sequence, ConsumerInfo> eventProcessorInfoBySequence = new IdentityHashMap<>(); private final Collection<ConsumerInfo> consumerInfos = new ArrayList<>(); public void add( final EventProcessor eventprocessor, final EventHandler<? super T> handler, final SequenceBarrier barrier) { final EventProcessorInfo<T> consumerInfo = new EventProcessorInfo<>(eventprocessor, handler, barrier); eventProcessorInfoByEventHandler.put(handler, consumerInfo); eventProcessorInfoBySequence.put(eventprocessor.getSequence(), consumerInfo); consumerInfos.add(consumerInfo); } public void add(final EventProcessor processor) { final EventProcessorInfo<T> consumerInfo = new EventProcessorInfo<>(processor, null, null); eventProcessorInfoBySequence.put(processor.getSequence(), consumerInfo); consumerInfos.add(consumerInfo); } public void add(final WorkerPool<T> workerPool, final SequenceBarrier sequenceBarrier) { final WorkerPoolInfo<T> workerPoolInfo = new WorkerPoolInfo<>(workerPool, sequenceBarrier); consumerInfos.add(workerPoolInfo); for (Sequence sequence : workerPool.getWorkerSequences()) { eventProcessorInfoBySequence.put(sequence, workerPoolInfo); } } public Sequence[] getLastSequenceInChain(boolean includeStopped) { List<Sequence> lastSequence = new ArrayList<>(); for (ConsumerInfo consumerInfo : consumerInfos) { if ((includeStopped || consumerInfo.isRunning()) && consumerInfo.isEndOfChain()) { final Sequence[] sequences = consumerInfo.getSequences(); Collections.addAll(lastSequence, sequences); } } return lastSequence.toArray(new Sequence[lastSequence.size()]); } public EventProcessor getEventProcessorFor(final EventHandler<T> handler) { final EventProcessorInfo<T> eventprocessorInfo = getEventProcessorInfo(handler); if (eventprocessorInfo == null) { throw new IllegalArgumentException("The event handler " + handler + " is not processing events."); } return eventprocessorInfo.getEventProcessor(); } public Sequence getSequenceFor(final EventHandler<T> handler) { return getEventProcessorFor(handler).getSequence(); } public void unMarkEventProcessorsAsEndOfChain(final Sequence... barrierEventProcessors) { for (Sequence barrierEventProcessor : barrierEventProcessors) { getEventProcessorInfo(barrierEventProcessor).markAsUsedInBarrier(); } } @Override public Iterator<ConsumerInfo> iterator() { return consumerInfos.iterator(); } public SequenceBarrier getBarrierFor(final EventHandler<T> handler) { final ConsumerInfo consumerInfo = getEventProcessorInfo(handler); return consumerInfo != null ? consumerInfo.getBarrier() : null; } private EventProcessorInfo<T> getEventProcessorInfo(final EventHandler<T> handler) { return eventProcessorInfoByEventHandler.get(handler); } private ConsumerInfo getEventProcessorInfo(final Sequence barrierEventProcessor) { return eventProcessorInfoBySequence.get(barrierEventProcessor); } }
4,359
Java
.java
91
41.318681
110
0.730416
OpenGlobes/Core
2
2
0
AGPL-3.0
9/5/2024, 12:14:53 AM (Europe/Amsterdam)
false
true
false
true
true
true
true
true
4,359
1,381,511
PDFDictionary.java
alex73_mmscomputing/src/uk/co/mmscomputing/imageio/pdf/PDFDictionary.java
package uk.co.mmscomputing.imageio.pdf; import java.io.*; import java.util.*; public class PDFDictionary extends PDFObject{ private Vector list = new Vector(); public void put(String key,PDFObject obj){ if(obj instanceof PDFIndirectObject){ obj=new PDFIndirectReference((PDFIndirectObject)obj); } Enumeration e = list.elements(); while(e.hasMoreElements()){ PDFDictionaryEntry entry=(PDFDictionaryEntry)e.nextElement(); if(key.equals(entry.getKey())){ entry.obj=obj;return; } } list.add(new PDFDictionaryEntry(key,obj)); } public PDFObject get(String key){ Enumeration e = list.elements(); while(e.hasMoreElements()){ PDFDictionaryEntry entry=(PDFDictionaryEntry)e.nextElement(); if(key.equals(entry.getKey())){ return entry.getValue(); } } return null; } public PDFObject getObject(String key){ PDFObject obj = get(key); while(obj instanceof PDFIndirectReference){ obj = ((PDFIndirectReference)obj).getIndirectObject().getDirectObject(); } return obj; } public boolean checkNameEntry(String name, String value){ PDFObject obj = get(name); if(obj==null){return false;} if(!(obj instanceof PDFObject.PDFName)){return false;} return ((PDFObject.PDFName)obj).getName().equals(value); } public void read(PDFScanner s)throws IOException{ if(s.symbol==T_DICTIONARY_START){ // should have just scanned << T_DICTIONARY_START PDFObject key,obj; s.scan(); while(s.symbol!=T_DICTIONARY_END){ key = readObject(s); // System.err.println("key = "+key); if(!(key instanceof PDFName)){ throw new IOException(getClass().getName()+".read\n\tDictionary key must be of type NAME.\nSYMBOL = "+s.symbol+" "+key); } obj = readObject(s); if(obj==null){ throw new IOException(getClass().getName()+".read\n\tDictionary obj is missing.");} put(((PDFName)key).getName(),obj); // System.err.println("obj = "+obj); } if(s.symbol!=T_DICTIONARY_END){ throw new IOException(getClass().getName()+".read\n\tDictionary: Missing start >> ."); } }else{ throw new IOException(getClass().getName()+".read\n\tDictionary: Missing start << ."); } } public void write(PDFFile out)throws IOException{ out.writeln("<<"); Enumeration e = list.elements(); while(e.hasMoreElements()){ ((PDFDictionaryEntry)e.nextElement()).write(out); } out.writeln(">>"); } public String toString(){ String s="<<\n"; Enumeration e = list.elements(); while(e.hasMoreElements()){ s+=e.nextElement(); } s+=">>\n"; return s; } static public class PDFDictionaryEntry{ private PDFName key; private PDFObject obj; public PDFDictionaryEntry(String k,PDFObject o){ key=new PDFName(k);obj=o; } public String getKey(){ return key.getName();} public PDFObject getValue(){ return obj;} /* public void read(PDFScanner s)throws IOException{ key = readObject(s); if(!(key instanceof PDFName)){ throw new IllegalArgumentException(getClass().getName()+".read\n\tDictionary key must be of type NAME."); } obj = readObject(s); if(obj==null){ throw new IllegalArgumentException(getClass().getName()+".read\n\tDictionary obj is missing."); } } */ public void write(PDFFile out)throws IOException{ key.write(out); obj.write(out); if(!(obj instanceof PDFDictionary)){out.write("\n");} } public String toString(){ return key.toString()+obj.toString()+((obj instanceof PDFDictionary)?"":"\n"); } } }
3,782
Java
.java
108
29.462963
130
0.644341
alex73/mmscomputing
21
31
2
LGPL-3.0
9/4/2024, 7:47:27 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
3,782
1,319,496
A_test130.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/invalidSelection/A_test130.java
package invalidSelection; public class A_test130 { public void foo() { class Inner { } /*]*/Inner inner= new Inner(); foo();/*[*/ } }
147
Java
.java
9
13.888889
32
0.637037
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
147
1,316,245
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test24/in/A.java
package p; class A { public void m() {} public void m1() {} void g() { A a= (A)new A(); ((A)this).m1(); ((A)this).m(); (((A)this)).m(); } }
152
Java
.java
11
11.727273
20
0.48227
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
152
3,299,482
StatisticsFlowServiceImpl.java
chenbo19867758_jeecmsX1_2/jeecms-component/src/main/java/com/jeecms/statistics/service/impl/StatisticsFlowServiceImpl.java
/* * @Copyright: 江西金磊科技发展有限公司 All rights reserved.Notice 仅限于授权后使用,禁止非授权传阅以及私自用于商业目的。 */ package com.jeecms.statistics.service.impl; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_IP; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_JUMP; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_PV; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_TIME; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_UV; import static com.jeecms.statistics.domain.dto.StatisticsDto.ORDER_TYPE_PAGE; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jeecms.common.base.service.BaseServiceImpl; import com.jeecms.common.exception.GlobalException; import com.jeecms.common.util.MathUtil; import com.jeecms.common.util.MyDateUtils; import com.jeecms.statistics.constants.StatisticsConstant; import com.jeecms.statistics.dao.StatisticsFlowDao; import com.jeecms.statistics.domain.StatisticsFlow; import com.jeecms.statistics.domain.dto.StatisticsDto; import com.jeecms.statistics.domain.dto.StatisticsFlowDto; import com.jeecms.statistics.domain.dto.StatisticsFlowRealTimeItemDto; import com.jeecms.statistics.domain.vo.AccessAreaVo; import com.jeecms.statistics.domain.vo.AccessDeviceVo; import com.jeecms.statistics.domain.vo.AccessDeviceVo.DeviceVo; import com.jeecms.statistics.domain.vo.AccessUserVo; import com.jeecms.statistics.domain.vo.BaseAccessVo; import com.jeecms.statistics.domain.vo.StatisitcsOverviewVo; import com.jeecms.statistics.domain.vo.StatisitcsOverviewVos; import com.jeecms.statistics.domain.vo.StatisticsFlowImageVo; import com.jeecms.statistics.domain.vo.StatisticsFlowListVo; import com.jeecms.statistics.domain.vo.StatisticsFlowRealTimeItemVo; import com.jeecms.statistics.domain.vo.StatisticsFlowRealTimeVo; import com.jeecms.statistics.domain.vo.StatisticsFlowVo; import com.jeecms.statistics.domain.vo.StatisticsVisitorVo; import com.jeecms.statistics.service.StatisticsFlowService; import com.jeecms.statistics.service.TimeCuttingService; import com.jeecms.system.domain.SysAccessRecord; import com.jeecms.system.service.SysAccessRecordService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.LongAdder; import java.util.stream.Collectors; /** * 趋势分析service实体类 * * @author: chenming * @date: 2019年6月25日 下午2:12:28 */ @Service @Transactional(rollbackFor = Exception.class) public class StatisticsFlowServiceImpl extends BaseServiceImpl<StatisticsFlow, StatisticsFlowDao, Integer> implements StatisticsFlowService { @Autowired private SysAccessRecordService sysAccessRecordService; @Autowired private TimeCuttingService timeCuttingService; @Override public List<StatisticsFlowRealTimeVo> getRealTimeVo(Integer siteId) { /** * 底下如此记录uv(可能按照某个大维度而言uv计算重复了,但是按照小维度(4分钟之内),而言这种计算才是合理的) */ Date endTime = new Date(); Date startTime = MyDateUtils.getMinuteBeforeTime(endTime, 30); // 根据4分钟进行时间切割 List<Date> dates = timeCuttingService.getIntervalTimeList(startTime, endTime, 4); // 时间和操作记录集合 Map<Date, List<SysAccessRecord>> dateMap = new LinkedHashMap<Date, List<SysAccessRecord>>(); List<SysAccessRecord> accessRecords = sysAccessRecordService.findByDate(startTime, endTime, siteId); // 遍历时间取出该时间段内的记录list集合 for (Date date : dates) { Long time = startTime.getTime(); List<SysAccessRecord> records = accessRecords.stream() .filter( accessRecord -> accessRecord.getCreateTime().getTime() >= time && accessRecord.getCreateTime().getTime() <= date.getTime()) .collect(Collectors.toList()); startTime = date; dateMap.put(date, records); } List<String> dateList = new ArrayList<String>(); List<Integer> pvs = new ArrayList<Integer>(); List<Integer> uvs = new ArrayList<Integer>(); // 遍历map将其放到list集合中 for (Date date : dateMap.keySet()) { dateList.add(MyDateUtils.formatDate(date, MyDateUtils.COM_H_M_PATTERN)); List<SysAccessRecord> records = dateMap.get(date); if (records != null && records.size() > 0) { pvs.add(records.size()); uvs.add(this.receiveUv(records)); } else { pvs.add(0); uvs.add(0); } } List<StatisticsFlowRealTimeVo> vos = new ArrayList<StatisticsFlowRealTimeVo>(); for (int i = 0; i < dateList.size(); i++) { StatisticsFlowRealTimeVo vo = new StatisticsFlowRealTimeVo(dateList.get(i), pvs.get(i), uvs.get(i)); vos.add(vo); } return vos; } @Override public Integer getRealTimeUvNum(Integer siteId) { Date endTime = new Date(); Date startTime = MyDateUtils.getMinuteBeforeTime(endTime, 30); List<SysAccessRecord> accessRecords = sysAccessRecordService.findByDate(startTime, endTime, siteId); Integer uvNum = 0; if (accessRecords != null && accessRecords.size() > 0) { uvNum = this.receiveUv(accessRecords); } return uvNum; } @Override public List<StatisticsFlow> flowList(Date start, Date end, Integer siteId, Integer sourceType, Boolean visit, String province) throws GlobalException { return dao.getFlowList(start, end, siteId, sourceType, visit, province); } @Override public AccessAreaVo timeArea(StatisticsDto dto) throws Exception { AccessAreaVo vo = new AccessAreaVo(); List<StatisticsVisitorVo> pvList = new ArrayList<StatisticsVisitorVo>(34); List<StatisticsVisitorVo> uvList = new ArrayList<StatisticsVisitorVo>(34); List<StatisticsVisitorVo> ipsList = new ArrayList<StatisticsVisitorVo>(34); Date start = MyDateUtils.getStartDate(new Date()); //查询列表记录 List<SysAccessRecord> records = sysAccessRecordService .haveList(start, new Date(), dto.getSiteId(), dto.getSourceType(), null, dto.getVisitor()); //得到总的PV数 Integer pv = records.size(); vo.setPv(pv); //总的访客数 Integer uv = records.stream() .filter(x -> StringUtils.isNotBlank(x.getCookieId())) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); vo.setUv(uv); //总的IP数 Integer ips = records.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessIp())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); vo.setIps(ips); //跳出率计算:只出现一个的Session次数/PV总数 //平均访问时长计算:总的访问时间/session次数 List<BigDecimal> jumpAndTime = jumpAndTime(records); vo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); vo.setVisitTime(jumpAndTime.get(1)); vo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); //省份PV数据 Map<String, List<SysAccessRecord>> province = records.stream() .collect(Collectors.groupingBy(SysAccessRecord::getAccessProvince)); for (String key : province.keySet()) { List<SysAccessRecord> sysRecords = province.get(key); StatisticsVisitorVo vi = new StatisticsVisitorVo(); vi.setType(key); vi.setValue(sysRecords.size()); BigDecimal sum = MathUtil.div(new BigDecimal(sysRecords.size()), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(sum.multiply(new BigDecimal(100))); pvList.add(vi); } vo.setPvList(pvList); //省份访客数据 for (String key : province.keySet()) { List<SysAccessRecord> sysRecords = province.get(key); Integer visit = sysRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getCookieId())) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)) .size(); StatisticsVisitorVo vi = new StatisticsVisitorVo(); vi.setType(key); vi.setValue(visit); BigDecimal sum = MathUtil.div(new BigDecimal(visit), new BigDecimal(uv), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(sum.multiply(new BigDecimal(100))); uvList.add(vi); } vo.setUvList(uvList); //IPS 访客数据 for (String key : province.keySet()) { List<SysAccessRecord> sysRecords = province.get(key); Integer ip = sysRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessIp())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)) .size(); StatisticsVisitorVo vi = new StatisticsVisitorVo(); vi.setType(key); vi.setValue(ip); BigDecimal sum = MathUtil.div(new BigDecimal(ip), new BigDecimal(ips), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(sum); ipsList.add(vi); } vo.setIpsList(ipsList); return vo; } @Override public JSONObject timeArea(StatisticsDto dto, Pageable pageable) throws Exception { List<AccessAreaVo> vos = new ArrayList<AccessAreaVo>(10); Date start = MyDateUtils.getStartDate(new Date()); //查询列表记录 List<SysAccessRecord> records = sysAccessRecordService .haveList(start, new Date(), dto.getSiteId(), dto.getSourceType(), null, dto.getVisitor()); //省份PV数据 Map<String, List<SysAccessRecord>> province = records.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessProvince())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessProvince)); for (String key : province.keySet()) { List<BaseAccessVo> cityList = new ArrayList<BaseAccessVo>(10); List<SysAccessRecord> sysRecords = province.get(key); Map<String, List<SysAccessRecord>> city = sysRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessCity())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessCity)); for (String citykey : city.keySet()) { BaseAccessVo cityvo = new BaseAccessVo(); List<SysAccessRecord> cityRecords = city.get(citykey); // pv数 Integer pv = cityRecords.size(); cityvo.setName(citykey); cityvo.setPv(pv); // 总的访客数 Integer uv = cityRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getCookieId())) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); cityvo.setUv(uv); // 总的IP数 Integer ips = cityRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessIp())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); cityvo.setIps(ips); List<BigDecimal> jumpAndTime = jumpAndTime(cityRecords); cityvo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); cityvo.setVisitTime(jumpAndTime.get(1)); cityvo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); cityList.add(cityvo); } AccessAreaVo vo = new AccessAreaVo(); vo.setName(key); //pv数 Integer pv = sysRecords.size(); vo.setPv(pv); //总的访客数 Integer uv = sysRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getCookieId())) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); vo.setUv(uv); //总的IP数 Integer ips = sysRecords.stream() .filter(x -> StringUtils.isNotBlank(x.getAccessIp())) .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); vo.setIps(ips); List<BigDecimal> jumpAndTime = jumpAndTime(sysRecords); vo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); vo.setVisitTime(jumpAndTime.get(1)); vo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); vo.setCityList(cityList); vos.add(vo); } List<AccessAreaVo> areaVo = new ArrayList<AccessAreaVo>(10); //排序 if (!vos.isEmpty()) { vos = sort(dto.getOrderType(), dto.getOrder(), vos); areaVo = vos.stream() .skip(pageable.getPageSize() * (pageable.getPageNumber())) .limit(pageable.getPageSize()).collect(Collectors.toList()); } PageImpl<AccessAreaVo> page = new PageImpl<AccessAreaVo>(areaVo, pageable, vos.size()); JSONObject object = new JSONObject(); object.put("page", page); object.put("collect", collect(areaVo)); return object; } /** * 区域排序 * * @param orderType 类型 * @param order 方式 * @param vos 数据 * @return * @Title: sort */ public List<AccessAreaVo> sort(Integer orderType, Boolean order, List<AccessAreaVo> vos) { if (orderType == null || order == null) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getPv)) .collect(Collectors.toList()); return vos; } if (orderType.equals(ORDER_TYPE_PV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getPv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getPv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_UV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getUv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getUv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_IP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getIps)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getIps).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_JUMP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getJump)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getJump).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_TIME)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getVisitTime)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getVisitTime).reversed()) .collect(Collectors.toList()); } } else { vos = vos.stream().sorted(Comparator.comparing(AccessAreaVo::getPv)) .collect(Collectors.toList()); } return vos; } /** * 汇总 * * @param areaVo 区域VO * @return * @Title: collect */ public BaseAccessVo collect(List<AccessAreaVo> areaVo) { BaseAccessVo vo = new BaseAccessVo(); vo.setName("当前列表汇总"); vo.setPv(areaVo.stream().map(AccessAreaVo::getPv).reduce(0, Integer::sum)); vo.setUv(areaVo.stream().map(AccessAreaVo::getUv).reduce(0, Integer::sum)); vo.setIps(areaVo.stream().map(AccessAreaVo::getIps).reduce(0, Integer::sum)); vo.setJump(areaVo.stream().map(AccessAreaVo::getJump).reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTime(areaVo.stream().map(AccessAreaVo::getVisitTime) .reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTimes(MyDateUtils.secToTime(vo.getVisitTime().intValue())); return vo; } /** * 汇总 * * @param deviceVo 设备VO * @return * @Title: collectDevice */ public BaseAccessVo collectDevice(List<AccessDeviceVo> deviceVo) { BaseAccessVo vo = new BaseAccessVo(); vo.setName("当前列表汇总"); vo.setPv(deviceVo.stream().map(AccessDeviceVo::getPv).reduce(0, Integer::sum)); vo.setUv(deviceVo.stream().map(AccessDeviceVo::getUv).reduce(0, Integer::sum)); vo.setIps(deviceVo.stream().map(AccessDeviceVo::getIps).reduce(0, Integer::sum)); vo.setJump(deviceVo.stream().map(AccessDeviceVo::getJump).reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTime(deviceVo.stream().map(AccessDeviceVo::getVisitTime) .reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTimes(MyDateUtils.secToTime(vo.getVisitTime().intValue())); return vo; } /** * 汇总 * * @param userVo 客户VO * @return * @Title: collectUser */ public AccessUserVo collectUser(List<AccessUserVo> userVo) { AccessUserVo vo = new AccessUserVo(); vo.setName("当前列表汇总"); vo.setPv(userVo.stream().map(AccessUserVo::getPv).reduce(0, Integer::sum)); vo.setUv(userVo.stream().map(AccessUserVo::getUv).reduce(0, Integer::sum)); vo.setIps(userVo.stream().map(AccessUserVo::getIps).reduce(0, Integer::sum)); vo.setJump(userVo.stream().map(AccessUserVo::getJump).reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitPage(userVo.stream().map(AccessUserVo::getVisitPage) .reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTime(userVo.stream().map(AccessUserVo::getVisitTime) .reduce(BigDecimal.ZERO, BigDecimal::add)); vo.setVisitTimes(MyDateUtils.secToTime(vo.getVisitTime().intValue())); return vo; } /** * 计算跳出率和平均访问时长 * * @param records 记录列表 * @throws IllegalAccessException 转换异常 * @Title: jumpAndTime */ public List<BigDecimal> jumpAndTime(List<SysAccessRecord> records) throws IllegalAccessException { //过滤session为空 records = records.stream() .filter(x -> StringUtils.isNotBlank(x.getSessionId())) .collect(Collectors.toList()); LongAdder adder = new LongAdder(); LongAdder timer = new LongAdder(); Map<String, List<SysAccessRecord>> map = records.stream() .collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); for (List<SysAccessRecord> list : map.values()) { //只出现一次的Session if (list.size() == 1) { adder.increment(); } else { //统计总时长 //按照创建时间排序 list = list.stream().sorted(Comparator.comparing(SysAccessRecord::getCreateTime)) .collect(Collectors.toList()); Long sum = list.get(list.size() - 1).getCreateTime().getTime() - list.get(0).getCreateTime().getTime(); sum = Math.abs(sum) / 1000; timer.add(sum); } } BigDecimal jump = MathUtil.div(new BigDecimal(adder.sumThenReset()), new BigDecimal(records.size()), MathUtil.SCALE_LEN_COMMON); //平均访问时长计算:总的访问时间/ 次数 BigDecimal visitTime = MathUtil.div(new BigDecimal(timer.sumThenReset()), new BigDecimal(map.size()), MathUtil.SCALE_LEN_COMMON); return Arrays.asList(jump, visitTime); } @Override public AccessAreaVo area(StatisticsDto dto) throws Exception { List<StatisticsVisitorVo> pvList = new ArrayList<StatisticsVisitorVo>(34); List<StatisticsVisitorVo> uvList = new ArrayList<StatisticsVisitorVo>(34); List<StatisticsVisitorVo> ipsList = new ArrayList<StatisticsVisitorVo>(34); AccessAreaVo vo = new AccessAreaVo(); List<StatisticsFlow> folws = flowList(new Date(dto.getStartTime()), new Date(dto.getEndTime()), dto.getSiteId(), dto.getSourceType(), dto.getVisitor(), null); //得到PV,结果累加 Integer pv = folws.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vo.setPv(pv); //得到uv Integer uv = folws.stream().map(StatisticsFlow::getUvs).reduce(0, Integer::sum); vo.setUv(uv); //得到IPS Integer ips = folws.stream().map(StatisticsFlow::getIps).reduce(0, Integer::sum); vo.setIps(ips); //跳出率 Integer only = folws.stream().map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vo.setJump(jump.multiply(new BigDecimal(100))); //得到访问时长 Integer time = folws.stream().map(StatisticsFlow::getAccessHoureLong).reduce(0, Integer::sum); Integer session = folws.stream().map(StatisticsFlow::getSession).reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitTime(hour); vo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); //省份PV数据 Map<String, List<StatisticsFlow>> province = folws.stream() .filter(x -> StringUtils.isNotBlank(x.getVisitorProvince())) .collect(Collectors.groupingBy(StatisticsFlow::getVisitorProvince)); for (String key : province.keySet()) { List<StatisticsFlow> pvValue = province.get(key); StatisticsVisitorVo vi = new StatisticsVisitorVo(); Integer sum = pvValue.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vi.setType(key); vi.setValue(sum); BigDecimal dec = MathUtil.div(new BigDecimal(sum), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(dec.multiply(new BigDecimal(100))); pvList.add(vi); } vo.setPvList(pvList); // 省份访客数据 for (String key : province.keySet()) { List<StatisticsFlow> uvValue = province.get(key); Integer sum = uvValue.stream().map(StatisticsFlow::getUvs).reduce(0, Integer::sum); StatisticsVisitorVo vi = new StatisticsVisitorVo(); vi.setType(key); vi.setValue(sum); BigDecimal dec = MathUtil.div(new BigDecimal(sum), new BigDecimal(uv), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(dec.multiply(new BigDecimal(100))); uvList.add(vi); } vo.setUvList(uvList); // IPS 访客数据 for (String key : province.keySet()) { List<StatisticsFlow> ipsValue = province.get(key); Integer sum = ipsValue.stream().map(StatisticsFlow::getIps).reduce(0, Integer::sum); StatisticsVisitorVo vi = new StatisticsVisitorVo(); vi.setType(key); vi.setValue(sum); BigDecimal dec = MathUtil.div(new BigDecimal(sum), new BigDecimal(ips), MathUtil.SCALE_LEN_COMMON); vi.setDecimal(dec); ipsList.add(vi); } vo.setIpsList(ipsList); return vo; } @Override public JSONObject timePage(StatisticsDto dto, Pageable pageable) throws Exception { List<AccessAreaVo> vos = new ArrayList<AccessAreaVo>(10); List<StatisticsFlow> folws = flowList(new Date(dto.getStartTime()), new Date(dto.getEndTime()), dto.getSiteId(), dto.getSourceType(), dto.getVisitor(), null); //省份数据 Map<String, List<StatisticsFlow>> province = folws.stream() .filter(x -> StringUtils.isNotBlank(x.getVisitorProvince())) .collect(Collectors.groupingBy(StatisticsFlow::getVisitorProvince)); for (String key : province.keySet()) { List<BaseAccessVo> cityList = new ArrayList<BaseAccessVo>(10); List<StatisticsFlow> provinceList = province.get(key); Map<String, List<StatisticsFlow>> city = provinceList.stream() .collect(Collectors.groupingBy(StatisticsFlow::getVisitorCity)); for (String citykey : city.keySet()) { BaseAccessVo cityvo = new BaseAccessVo(); List<StatisticsFlow> cityFlow = city.get(citykey); cityvo.setName(citykey); //pv数 Integer pv = cityFlow.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); cityvo.setPv(pv); //总的访客数 Integer uv = cityFlow.stream() .map(StatisticsFlow::getUvs).reduce(0, Integer::sum); cityvo.setUv(uv); //总的IP数 Integer ips = cityFlow.stream() .map(StatisticsFlow::getIps).reduce(0, Integer::sum); cityvo.setIps(ips); //计算跳出率 Integer only = cityFlow.stream() .map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); cityvo.setJump(jump.multiply(new BigDecimal(100))); // 得到访问时长 Integer time = cityFlow.stream().map(StatisticsFlow::getAccessHoureLong) .reduce(0, Integer::sum); Integer session = cityFlow.stream().map(StatisticsFlow::getSession) .reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); cityvo.setVisitTime(hour); cityvo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); cityList.add(cityvo); } AccessAreaVo vo = new AccessAreaVo(); vo.setName(key); //pv数 Integer pv = provinceList.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vo.setPv(pv); //总的访客数 Integer uv = provinceList.stream() .map(StatisticsFlow::getUvs).reduce(0, Integer::sum); vo.setUv(uv); //总的IP数 Integer ips = provinceList.stream() .map(StatisticsFlow::getIps).reduce(0, Integer::sum); vo.setIps(ips); //计算跳出率 Integer only = provinceList.stream() .map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vo.setJump(jump.multiply(new BigDecimal(100))); // 得到访问时长 Integer time = provinceList.stream().map(StatisticsFlow::getAccessHoureLong) .reduce(0, Integer::sum); Integer session = provinceList.stream().map(StatisticsFlow::getSession).reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitTime(hour); vo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); vo.setCityList(cityList); vos.add(vo); } List<AccessAreaVo> areaVo = new ArrayList<AccessAreaVo>(10); //排序 if (!vos.isEmpty()) { vos = sort(dto.getOrderType(), dto.getOrder(), vos); areaVo = vos.stream() .skip(pageable.getPageSize() * (pageable.getPageNumber())) .limit(pageable.getPageSize()).collect(Collectors.toList()); } PageImpl<AccessAreaVo> page = new PageImpl<AccessAreaVo>(areaVo, pageable, vos.size()); JSONObject object = new JSONObject(); object.put("page", page); object.put("collect", collect(areaVo)); return object; } @Override public AccessDeviceVo timeDevice(Integer siteID) throws Exception { AccessDeviceVo vo = new AccessDeviceVo(); List<DeviceVo> pvList = new ArrayList<AccessDeviceVo.DeviceVo>(10); List<DeviceVo> uvList = new ArrayList<AccessDeviceVo.DeviceVo>(10); List<DeviceVo> ipsList = new ArrayList<AccessDeviceVo.DeviceVo>(10); Date start = MyDateUtils.getStartDate(new Date()); //查询列表记录 List<SysAccessRecord> records = sysAccessRecordService .haveList(start, new Date(), siteID, null, null, null); //得到总的PV数 Integer pv = records.size(); vo.setPv(pv); //总的访客数 Integer uv = records.stream() .filter(x -> x.getCookieId() != null) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); vo.setUv(uv); //总的IP数 Integer ips = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); vo.setIps(ips); //跳出率计算:只出现一个的Session次数/PV总数 //平均访问时长计算:总的访问时间/session次数 List<BigDecimal> jumpAndTime = jumpAndTime(records); vo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); vo.setVisitTime(jumpAndTime.get(1)); vo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); //设备类型数据 Map<Short, List<SysAccessRecord>> device = records.stream() .collect(Collectors.groupingBy(SysAccessRecord::getDeviceType)); for (Short key : device.keySet()) { List<SysAccessRecord> sysRecords = device.get(key); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == SysAccessRecord.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(sysRecords.size()); pvList.add(vi); } vo.setPvList(pvList); //uv数据 for (Short key : device.keySet()) { List<SysAccessRecord> sysRecords = device.get(key); Integer visit = sysRecords.stream() .filter(x -> x.getCookieId() != null) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)) .size(); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == SysAccessRecord.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(visit); uvList.add(vi); } vo.setUvList(uvList); //IPS数据 for (Short key : device.keySet()) { List<SysAccessRecord> sysRecords = device.get(key); Integer ip = sysRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)) .size(); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == SysAccessRecord.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(ip); ipsList.add(vi); } vo.setIpsList(ipsList); return vo; } @Override public JSONObject timeDeviceList(Integer siteID, Integer orderType, Boolean order) throws Exception { List<AccessDeviceVo> vos = new ArrayList<AccessDeviceVo>(10); Date start = MyDateUtils.getStartDate(new Date()); //查询列表记录 List<SysAccessRecord> records = sysAccessRecordService .haveList(start, new Date(), siteID, null, null, null); //设备数据 Map<Short, List<SysAccessRecord>> deviceType = records.stream() .collect(Collectors.groupingBy(SysAccessRecord::getDeviceType)); for (Short key : deviceType.keySet()) { List<BaseAccessVo> deviceList = new ArrayList<BaseAccessVo>(10); List<SysAccessRecord> sysRecords = deviceType.get(key); Map<String, List<SysAccessRecord>> device = sysRecords.stream() .collect(Collectors.groupingBy(SysAccessRecord::getAccessDevice)); for (String devicekey : device.keySet()) { BaseAccessVo devicevo = new BaseAccessVo(); List<SysAccessRecord> deviceRecords = device.get(devicekey); // pv数 Integer pv = deviceRecords.size(); devicevo.setName(devicekey); devicevo.setPv(pv); // 总的访客数 Integer uv = deviceRecords.stream() .filter(x -> x.getCookieId() != null) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); devicevo.setUv(uv); // 总的IP数 Integer ips = deviceRecords.stream() .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); devicevo.setIps(ips); List<BigDecimal> jumpAndTime = jumpAndTime(deviceRecords); devicevo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); devicevo.setVisitTime(jumpAndTime.get(1)); devicevo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); deviceList.add(devicevo); } AccessDeviceVo vo = new AccessDeviceVo(); if (key == SysAccessRecord.COMPUTER) { vo.setName("计算机"); } else { vo.setName("移动设备"); } //pv数 Integer pv = sysRecords.size(); vo.setPv(pv); //总的访客数 Integer uv = sysRecords.stream() .filter(x -> x.getCookieId() != null) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); vo.setUv(uv); //总的IP数 Integer ips = sysRecords.stream() .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); vo.setIps(ips); List<BigDecimal> jumpAndTime = jumpAndTime(sysRecords); vo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); vo.setVisitTime(jumpAndTime.get(1)); vo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); vo.setDeviceList(deviceList); vos.add(vo); } //排序 if (!vos.isEmpty()) { vos = sortDevice(orderType, order, vos); } JSONObject object = new JSONObject(); object.put("list", vos); object.put("collect", collectDevice(vos)); return object; } /** * 区域排序 * * @param orderType 类型 * @param order 方式 * @param vos 数据 * @return * @Title: sort */ public List<AccessDeviceVo> sortDevice(Integer orderType, Boolean order, List<AccessDeviceVo> vos) { if (orderType == null || order == null) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getPv)) .collect(Collectors.toList()); return vos; } if (orderType.equals(ORDER_TYPE_PV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getPv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getPv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_UV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getUv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getUv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_IP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getIps)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getIps).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_JUMP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getJump)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getJump).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_TIME)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getVisitTime)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getVisitTime).reversed()) .collect(Collectors.toList()); } } else { vos = vos.stream().sorted(Comparator.comparing(AccessDeviceVo::getPv)) .collect(Collectors.toList()); } return vos; } @Override public AccessDeviceVo device(StatisticsDto dto) throws Exception { AccessDeviceVo vo = new AccessDeviceVo(); List<DeviceVo> pvList = new ArrayList<AccessDeviceVo.DeviceVo>(10); List<DeviceVo> uvList = new ArrayList<AccessDeviceVo.DeviceVo>(10); List<DeviceVo> ipsList = new ArrayList<AccessDeviceVo.DeviceVo>(10); List<StatisticsFlow> folws = flowList(new Date(dto.getStartTime()), new Date(dto.getEndTime()), dto.getSiteId(), null, null, null); //得到PV,结果累加 Integer pv = folws.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vo.setPv(pv); //得到uv Integer uv = folws.stream().map(StatisticsFlow::getUvs).reduce(0, Integer::sum); vo.setUv(uv); //得到IPS Integer ips = folws.stream().map(StatisticsFlow::getIps).reduce(0, Integer::sum); vo.setIps(ips); //跳出率 Integer only = folws.stream().map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vo.setJump(jump.multiply(new BigDecimal(100))); //得到访问时长 Integer time = folws.stream().map(StatisticsFlow::getAccessHoureLong).reduce(0, Integer::sum); Integer session = folws.stream().map(StatisticsFlow::getSession).reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitTime(hour); vo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); //设备PV数据 Map<Integer, List<StatisticsFlow>> device = folws.stream() .collect(Collectors.groupingBy(StatisticsFlow::getVisitorDeviceType)); for (Integer key : device.keySet()) { List<StatisticsFlow> pvValue = device.get(key); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == StatisticsFlow.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(pvValue.size()); pvList.add(vi); } vo.setPvList(pvList); // 设备UV数据 for (Integer key : device.keySet()) { List<StatisticsFlow> uvValue = device.get(key); Integer sum = uvValue.stream().map(StatisticsFlow::getUvs).reduce(0, Integer::sum); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == StatisticsFlow.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(sum); uvList.add(vi); } vo.setUvList(uvList); // 设备IPS数据 for (Integer key : device.keySet()) { List<StatisticsFlow> ipsValue = device.get(key); Integer sum = ipsValue.stream().map(StatisticsFlow::getIps).reduce(0, Integer::sum); DeviceVo vi = new AccessDeviceVo().new DeviceVo(); if (key == StatisticsFlow.COMPUTER) { vi.setType("计算机"); } else { vi.setType("移动设备"); } vi.setValue(sum); ipsList.add(vi); } vo.setIpsList(ipsList); return vo; } @Override public JSONObject deviceList(StatisticsDto dto) throws Exception { List<AccessDeviceVo> vos = new ArrayList<AccessDeviceVo>(10); List<StatisticsFlow> folws = flowList(new Date(dto.getStartTime()), new Date(dto.getEndTime()), null, null, null, null); //设备数据 Map<Integer, List<StatisticsFlow>> deviceType = folws.stream() .collect(Collectors.groupingBy(StatisticsFlow::getVisitorDeviceType)); for (Integer key : deviceType.keySet()) { List<BaseAccessVo> devices = new ArrayList<BaseAccessVo>(10); List<StatisticsFlow> deviceList = deviceType.get(key); Map<String, List<StatisticsFlow>> device = deviceList.stream() .filter(x -> StringUtils.isNotBlank(x.getVisitorDeviceOs())) .collect(Collectors.groupingBy(StatisticsFlow::getVisitorDeviceOs)); for (String devicekey : device.keySet()) { BaseAccessVo deviceVo = new BaseAccessVo(); List<StatisticsFlow> cityFlow = device.get(devicekey); deviceVo.setName(devicekey); //pv数 Integer pv = cityFlow.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); deviceVo.setPv(pv); //总的访客数 Integer uv = cityFlow.stream() .map(StatisticsFlow::getUvs).reduce(0, Integer::sum); deviceVo.setUv(uv); //总的IP数 Integer ips = cityFlow.stream() .map(StatisticsFlow::getIps).reduce(0, Integer::sum); deviceVo.setIps(ips); //计算跳出率 Integer only = cityFlow.stream() .map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); deviceVo.setJump(jump.multiply(new BigDecimal(100))); // 得到访问时长 Integer time = cityFlow.stream().map(StatisticsFlow::getAccessHoureLong) .reduce(0, Integer::sum); Integer session = cityFlow.stream().map(StatisticsFlow::getSession) .reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); deviceVo.setVisitTime(hour); deviceVo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); devices.add(deviceVo); } AccessDeviceVo vo = new AccessDeviceVo(); if (key == StatisticsFlow.COMPUTER) { vo.setName("计算机"); } else { vo.setName("移动设备"); } //pv数 Integer pv = deviceList.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vo.setPv(pv); //总的访客数 Integer uv = deviceList.stream() .map(StatisticsFlow::getUvs).reduce(0, Integer::sum); vo.setUv(uv); //总的IP数 Integer ips = deviceList.stream() .map(StatisticsFlow::getIps).reduce(0, Integer::sum); vo.setIps(ips); //计算跳出率 Integer only = deviceList.stream() .map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vo.setJump(jump.multiply(new BigDecimal(100))); // 得到访问时长 Integer time = deviceList.stream().map(StatisticsFlow::getAccessHoureLong) .reduce(0, Integer::sum); Integer session = deviceList.stream().map(StatisticsFlow::getSession).reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitTime(hour); vo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); vo.setDeviceList(devices); vos.add(vo); } JSONObject object = new JSONObject(); object.put("list", vos); object.put("collect", collectDevice(vos)); return object; } @Override public JSONObject timeUsers(StatisticsDto dto) throws Exception { List<AccessUserVo> vos = new ArrayList<AccessUserVo>(10); Date start = MyDateUtils.getStartDate(new Date()); Date end = MyDateUtils.getFinallyDate(new Date()); //查询列表记录 List<SysAccessRecord> records = sysAccessRecordService .haveList(start, end, dto.getSiteId(), dto.getSourceType(), dto.getProvince(), null); if (records.isEmpty()) { AccessUserVo vo = new AccessUserVo(); vo.setName("新客户"); vo.setIsNew(true); vo.setPv(0); vo.setUv(0); vo.setIps(0); vo.setJump(BigDecimal.ZERO); vo.setVisitTime(BigDecimal.ZERO); vo.setVisitPage(BigDecimal.ZERO); AccessUserVo voo = new AccessUserVo(); voo.setName("老客户"); vo.setIsNew(false); voo.setPv(0); voo.setUv(0); voo.setIps(0); voo.setJump(BigDecimal.ZERO); voo.setVisitTime(BigDecimal.ZERO); voo.setVisitPage(BigDecimal.ZERO); vos.add(vo); vos.add(voo); JSONObject object = new JSONObject(); object.put("list", vos); object.put("collect", collectUser(vos)); return object; } //session分组 Map<String, List<SysAccessRecord>> session = records.stream() .filter(x -> StringUtils.isNotBlank(x.getSessionId())) .collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); //新老客户数据 Map<Boolean, List<SysAccessRecord>> deviceType = records.stream() .filter(x -> x.getNewVisitor() != null) .collect(Collectors.groupingBy(SysAccessRecord::getNewVisitor)); for (Boolean key : deviceType.keySet()) { List<SysAccessRecord> sysRecords = deviceType.get(key); AccessUserVo vo = new AccessUserVo(); if (key) { vo.setName("新客户"); vo.setIsNew(true); } else { vo.setName("老客户"); vo.setIsNew(false); } //pv数 Integer pv = sysRecords.size(); vo.setPv(pv); //总的访客数 Integer uv = uvNumber(sysRecords); vo.setUv(uv); //总的IP数 Integer ips = sysRecords.stream() .filter(x -> x.getAccessIp() != null) .collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).size(); vo.setIps(ips); List<BigDecimal> jumpAndTime = jumpAndTime(sysRecords); vo.setJump(jumpAndTime.get(0).multiply(new BigDecimal(100))); vo.setVisitTime(jumpAndTime.get(1)); vo.setVisitTimes(MyDateUtils.secToTime(jumpAndTime.get(1).intValue())); //平均访问页数:PV/session个数 BigDecimal page = MathUtil.div(new BigDecimal(pv), new BigDecimal(session.size()), MathUtil.SCALE_LEN_COMMON); vo.setVisitPage(page); vos.add(vo); } //排序 if (!vos.isEmpty()) { vos = sortUser(dto.getOrderType(), dto.getOrder(), vos); } JSONObject object = new JSONObject(); object.put("list", vos); object.put("collect", collectUser(vos)); return object; } @Override public JSONObject users(StatisticsDto dto) throws Exception { List<AccessUserVo> vos = new ArrayList<AccessUserVo>(10); List<StatisticsFlow> folws = flowList(new Date(dto.getStartTime()), new Date(dto.getEndTime()), dto.getSiteId(), dto.getSourceType(), null, dto.getProvince()); //新老客户 Map<Boolean, List<StatisticsFlow>> user = folws.stream() .collect(Collectors.groupingBy(StatisticsFlow::getIsNewVisitor)); for (Boolean key : user.keySet()) { List<StatisticsFlow> userList = user.get(key); AccessUserVo vo = new AccessUserVo(); if (key) { vo.setName("新客户"); vo.setIsNew(true); } else { vo.setName("老客户"); vo.setIsNew(false); } //pv数 Integer pv = userList.stream().map(StatisticsFlow::getPvs).reduce(0, Integer::sum); vo.setPv(pv); //总的访客数 Integer uv = userList.stream() .map(StatisticsFlow::getUvs).reduce(0, Integer::sum); vo.setUv(uv); //总的IP数 Integer ips = userList.stream() .map(StatisticsFlow::getIps).reduce(0, Integer::sum); vo.setIps(ips); //计算跳出率 Integer only = userList.stream() .map(StatisticsFlow::getOnlyOnePv).reduce(0, Integer::sum); BigDecimal jump = MathUtil.div(new BigDecimal(only), new BigDecimal(pv), MathUtil.SCALE_LEN_COMMON); vo.setJump(jump.multiply(new BigDecimal(100))); // 得到访问时长 Integer time = userList.stream().map(StatisticsFlow::getAccessHoureLong) .reduce(0, Integer::sum); // 得到session个数 Integer session = userList.stream().map(StatisticsFlow::getSession).reduce(0, Integer::sum); BigDecimal hour = MathUtil.div(new BigDecimal(time), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitTime(hour); vo.setVisitTimes(MyDateUtils.secToTime(hour.intValue())); //平均访问页数:PV/session个数 BigDecimal page = MathUtil.div(new BigDecimal(pv), new BigDecimal(session), MathUtil.SCALE_LEN_COMMON); vo.setVisitPage(page); vos.add(vo); } //排序 if (!vos.isEmpty()) { vos = sortUser(dto.getOrderType(), dto.getOrder(), vos); } JSONObject object = new JSONObject(); object.put("list", vos); object.put("collect", collectUser(vos)); return object; } /** * 新老客户排序 * * @param orderType 类型 * @param order 方式 * @param vos 数据 * @return * @Title: sortUser */ public List<AccessUserVo> sortUser(Integer orderType, Boolean order, List<AccessUserVo> vos) { if (orderType == null || order == null) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getPv)) .collect(Collectors.toList()); return vos; } if (orderType.equals(ORDER_TYPE_PV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getPv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getPv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_UV)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getUv)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getUv).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_IP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getIps)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getIps).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_JUMP)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getJump)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getJump).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_TIME)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getVisitTime)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getVisitTime).reversed()) .collect(Collectors.toList()); } } else if (orderType.equals(ORDER_TYPE_PAGE)) { if (order) { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getVisitPage)) .collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getVisitPage).reversed()) .collect(Collectors.toList()); } } else { vos = vos.stream().sorted(Comparator.comparing(AccessUserVo::getPv)) .collect(Collectors.toList()); } return vos; } /** * 通过List<SysAccessRecord>集合计算出uv数 */ private int receiveUv(List<SysAccessRecord> records) { // 方法进行此records一定不为空,至少存在一个值 List<SysAccessRecord> logRecords = records.stream() .filter(record -> record.getLoginUserId() != null).collect(Collectors.toList()); List<SysAccessRecord> notLogRecords = records.stream() .filter(record -> record.getLoginUserId() == null && record.getCookieId() != null) .collect(Collectors.toList()); Integer logUv = 0; if (logRecords != null && logRecords.size() > 0) { // 集合过滤掉userId不为空的(登录的),而后通过userId分组,再取出userId的个数 logUv = logRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getLoginUserId)) .keySet().size(); } Integer notLogUv = 0; if (notLogRecords != null && notLogRecords.size() > 0) { // 集合过滤掉userId为空的(游客访问),而后通过cookieId分组,再取出cookieId的个数 notLogUv = notLogRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getCookieId)) .keySet().size(); } return logUv + notLogUv; } public Map<Date, Date> groupByWeek(Date startTime, Date endTime) { Map<Date, Date> dateMap = new LinkedHashMap<Date, Date>(); Calendar cl1 = Calendar.getInstance(); cl1.setTime(startTime); Calendar cl2 = Calendar.getInstance(); cl2.setTime(endTime); Calendar cl3 = Calendar.getInstance(); if (cl1.get(Calendar.DAY_OF_WEEK) - 1 == 1) { cl1.add(Calendar.DAY_OF_MONTH, 6); } else { cl1.add(Calendar.DAY_OF_MONTH, 8 - cl1.get(Calendar.DAY_OF_WEEK)); } dateMap.put(MyDateUtils.getStartDate(startTime), MyDateUtils.getStartDate(cl1.getTime())); while (cl3.getTime().getTime() < cl2.getTime().getTime()) { cl1.add(Calendar.DAY_OF_MONTH, 1); Date s = cl1.getTime(); cl1.add(Calendar.DAY_OF_MONTH, 6); dateMap.put(MyDateUtils.getStartDate(s), MyDateUtils.getFinallyDate(cl1.getTime())); cl3.setTime(cl1.getTime()); cl3.add(Calendar.DAY_OF_MONTH, 7); } // do { // cl1.add(Calendar.DAY_OF_MONTH, 1); // Date s = cl1.getTime(); // cl1.add(Calendar.DAY_OF_MONTH, 6); // dateMap.put(MyDateUtils.getStartDate(s), MyDateUtils.getFinallyDate(cl1.getTime())); // cl3.setTime(cl1.getTime()); // cl3.add(Calendar.DAY_OF_MONTH, 7); // } while (cl3.getTime().getTime() < cl2.getTime().getTime()); cl1.add(Calendar.DAY_OF_MONTH, 1); Date s = cl1.getTime(); if (cl1.getTime().equals(endTime)) { dateMap.put(MyDateUtils.getStartDate(s), MyDateUtils.getFinallyDate(s)); } else { dateMap.put(MyDateUtils.getStartDate(s), MyDateUtils.getFinallyDate(endTime)); } return dateMap; } @Override public List<StatisticsFlowRealTimeItemVo> getRealTimeItemVo(StatisticsFlowRealTimeItemDto dto) { // 默认时间为当前时间 Date endTime = new Date(); Date startTime = MyDateUtils.getStartDate(endTime); Date time = dto.getTime(); if (time != null) { startTime = MyDateUtils.getStartDate(time); endTime = MyDateUtils.getFinallyDate(time); } // 根据筛选条件筛选出数据 List<SysAccessRecord> records = sysAccessRecordService.getRealTimeItem(dto, startTime, endTime); if (records != null && records.size() > 0) { Integer minFrequency = dto.getMinFrequency(); // 全局储存放置数据 List<SysAccessRecord> accessRecords = new ArrayList<SysAccessRecord>(); // 全局储存放置map Map<Integer, SysAccessRecord> accessRecordMap = new HashMap<Integer, SysAccessRecord>(); if (minFrequency != null) { Map<Integer, List<SysAccessRecord>> frequencyMap = this.receiveFrequency(records); Map<Integer, List<SysAccessRecord>> minFrequencyMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); for (Integer num : frequencyMap.keySet()) { if (num >= minFrequency) { minFrequencyMap.put(num, frequencyMap.get(num)); } } Map<Integer, List<SysAccessRecord>> maxFrequencyMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); Integer maxFrequency = dto.getMaxFrequency(); if (maxFrequency != null) { for (Integer num : minFrequencyMap.keySet()) { if (num <= maxFrequency) { maxFrequencyMap.put(num, frequencyMap.get(num)); } } } accessRecords.addAll(this.toIntegerList(maxFrequencyMap)); accessRecordMap = accessRecords.stream() .collect(Collectors.toMap(SysAccessRecord::getId, s -> s)); } Integer minDepth = dto.getMinDepth(); Map<Integer, List<SysAccessRecord>> depthMap = this.receiveDepth(records); if (minDepth != null) { Map<Integer, List<SysAccessRecord>> minDepthMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); for (Integer depthNum : depthMap.keySet()) { if (depthNum >= minDepth) { minDepthMap.put(depthNum, depthMap.get(depthNum)); } } Map<Integer, List<SysAccessRecord>> maxDepthMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); Integer maxDepth = dto.getMaxDepth(); if (maxDepth != null) { for (Integer depthNum : minDepthMap.keySet()) { if (depthNum <= maxDepth) { maxDepthMap.put(depthNum, depthMap.get(depthNum)); } } } depthMap = maxDepthMap; } accessRecords.clear(); for (Integer num : depthMap.keySet()) { // 此处相当于将上面两个筛选条件的数据取一个交集 for (SysAccessRecord sysAccessRecord : depthMap.get(num)) { sysAccessRecord.setPageSize(num); if (dto.getIsFrequency()) { if (accessRecordMap.size() > 0) { if (accessRecordMap.get(sysAccessRecord.getId()) != null) { accessRecords.add(sysAccessRecord); } } } else { accessRecords.add(sysAccessRecord); } } } if (accessRecordMap.size() == 0) { accessRecordMap = accessRecords.stream() .collect(Collectors.toMap(SysAccessRecord::getId, s -> s)); } else { for (SysAccessRecord sysAccessRecord : accessRecords) { Integer id = sysAccessRecord.getId(); if (accessRecordMap.get(id) != null) { accessRecordMap.put(id, sysAccessRecord); } } } Integer duration = dto.getDuration(); Map<Integer, List<SysAccessRecord>> durationMap = this.receiveDuration(accessRecords, true,false); if (duration != null) { // 处理访问时长 durationMap = this.spliceDurationMap(durationMap, duration); } List<String> sessions = new ArrayList<String>(); List<SysAccessRecord> durations = new ArrayList<SysAccessRecord>(); for (Integer i : durationMap.keySet()) { // 底下通过session进行分组因为在之前为了过滤掉筛选条件访问时长,所以在处理的时候我将相同的访问时长的list集合放到同一个Map的key中,所以到达此处必须再次通过session分组取出对应的集合 List<SysAccessRecord> snapRecords = durationMap.get(i); Map<String, List<SysAccessRecord>> snapRecordMap = snapRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); for (String session : snapRecordMap.keySet()) { // 此处排序时因为,使用stream进行分组,其中的list会乱掉,所以再次排序,排序后再取第一个页面才是入口页面 List<SysAccessRecord> newSnapRecords = snapRecordMap.get(session).stream().sorted(Comparator.comparing(SysAccessRecord::getId)) .collect(Collectors.toList()); // 此处去只取集合第一个是因为需要显示入口页面 SysAccessRecord snapDuration = newSnapRecords.get(0); String sessionId = snapDuration.getSessionId(); if (!sessions.contains(sessionId)) { snapDuration.setAccessTime(i); durations.add(snapDuration); sessions.add(sessionId); } } } List<StatisticsFlowRealTimeItemVo> vos = new ArrayList<StatisticsFlowRealTimeItemVo>(); for (int i = 0; i < durations.size(); i++) { SysAccessRecord record = durations.get(i); SysAccessRecord newRecord = accessRecordMap.get(record.getId()); if (newRecord != null) { StatisticsFlowRealTimeItemVo vo = new StatisticsFlowRealTimeItemVo(); vo.setId(i + 1); vo.setCreateTime(record.getCreateTime()); vo.setAreaName(record.getAccessCity()); vo.setSourceUrl(record.getSourceUrl()); vo.setEntranceUrl(record.getAccessUrl()); vo.setUserName(record.getLoginUserName()); vo.setAccessIp(record.getAccessIp()); vo.setAccessTime(record.getAccessTime()); vo.setAccessPage(newRecord.getPageSize()); vos.add(vo); } } vos = this.sortFlowRealTimeItemVo(vos, dto.getSortTerm(), dto.getOrder()); return vos; } return null; } private List<StatisticsFlowRealTimeItemVo> sortFlowRealTimeItemVo(List<StatisticsFlowRealTimeItemVo> vos, Short sortTerm, Boolean order) { switch (sortTerm) { case StatisticsFlow.SORT_TIME: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getCreateTime)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getCreateTime).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_DURATION: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getAccessTime)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getAccessTime).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_PAGE_NUM: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getAccessPage)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowRealTimeItemVo::getAccessPage).reversed()).collect(Collectors.toList()); } break; default: break; } return vos; } private Map<Integer, List<SysAccessRecord>> spliceDurationMap(Map<Integer, List<SysAccessRecord>> durationMap, Integer duration) { Map<Integer, List<SysAccessRecord>> numDurationMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); switch (duration) { case 1: this.treatDurationMap(durationMap, numDurationMap, 0, 30); break; case 2: this.treatDurationMap(durationMap, numDurationMap, 31, 60); break; case 3: this.treatDurationMap(durationMap, numDurationMap, 61, 90); break; case 4: this.treatDurationMap(durationMap, numDurationMap, 91, 180); break; case 5: this.treatDurationMap(durationMap, numDurationMap, 181, 300); break; case 6: this.treatDurationMap(durationMap, numDurationMap, 301, 600); break; case 7: this.treatDurationMap(durationMap, numDurationMap, 600, null); break; default: break; } return numDurationMap; } private void treatDurationMap(Map<Integer, List<SysAccessRecord>> durationMap, Map<Integer, List<SysAccessRecord>> newDurationMap, Integer minTime, Integer maxTime) { for (Integer i : durationMap.keySet()) { if (i == 0) { newDurationMap.put(i, durationMap.get(i)); } if (maxTime != null) { if (minTime != null ) { if (i >= minTime && i<= maxTime) { newDurationMap.put(i, durationMap.get(i)); } } } else { if (i >= minTime) { newDurationMap.put(i, durationMap.get(i)); } } } } /** * 计算访问时间 * filter -> 过滤,过滤session为1的情况(计算时长,需要过滤掉session为1的情况,但是在实时访客中此值又不需要过滤) */ private Map<Integer, List<SysAccessRecord>> receiveDuration(List<SysAccessRecord> records, boolean isInitMap,boolean filter) { records = records.stream().filter(record -> record.getSessionId() != null).collect(Collectors.toList()); Map<Integer, List<SysAccessRecord>> newDurationMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); // 过滤掉session为空的,并且根据session分组 Map<String, List<SysAccessRecord>> durationMap = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); for (String session : durationMap.keySet()) { List<SysAccessRecord> accessRecords = durationMap.get(session); // 此处过滤掉访问session只为1的情况 if (filter) { if (accessRecords.size() == 1) { continue; } } // 根据时间排序,防止出现list数据乱的情况 accessRecords = accessRecords.stream().sorted(Comparator.comparing(SysAccessRecord::getCreateTime)).collect(Collectors.toList()); Long minTime = accessRecords.get(0).getCreateTime().getTime(); Long maxTime = accessRecords.get(accessRecords.size() - 1).getCreateTime().getTime(); Long time = (maxTime - minTime) / 1000; Integer timeValue = time.intValue(); // 是否需要初始化Map if (isInitMap) { this.initDurationMap(newDurationMap, timeValue, accessRecords); } else { if (newDurationMap.get(timeValue) != null) { newDurationMap.remove(timeValue); timeValue = timeValue * 2; } newDurationMap.put(timeValue, accessRecords); } } return newDurationMap; } private void initDurationMap(Map<Integer, List<SysAccessRecord>> durationMap, Integer num, List<SysAccessRecord> records) { List<SysAccessRecord> duration = durationMap.get(num); if (duration != null && duration.size() > 0) { duration.addAll(records); durationMap.put(num, duration); } else { durationMap.put(num, records); } } private Map<Integer, List<SysAccessRecord>> receiveDepth(List<SysAccessRecord> records) { if (records != null && records.size() > 0) { records = records.stream().filter(record -> record.getAccessUrl() != null && record.getSessionId() != null).collect(Collectors.toList()); Map<Integer, List<SysAccessRecord>> newDepthMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); Map<String, Map<String, List<SysAccessRecord>>> depthMap = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessUrl, Collectors.groupingBy(SysAccessRecord::getSessionId))); for (String str : depthMap.keySet()) { Integer num = depthMap.get(str).size(); List<SysAccessRecord> value = this.toStringList(depthMap.get(str)); newDepthMap.put(num, value); } return newDepthMap; } return null; } /** * 计算访问频次 */ private Map<Integer, List<SysAccessRecord>> receiveFrequency(List<SysAccessRecord> records) { // 方法进行此records一定不为空,至少存在一个值 List<SysAccessRecord> logRecords = records.stream().filter(record -> record.getLoginUserId() != null && record.getSessionId() != null) .collect(Collectors.toList()); // 根据userId+sessionId分组计算已登录用户的访问频次 Map<String, Map<Integer, List<SysAccessRecord>>> logRecordMap = logRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId, Collectors.groupingBy(SysAccessRecord::getLoginUserId))); Map<Integer, List<SysAccessRecord>> frequency = new LinkedHashMap<Integer, List<SysAccessRecord>>(); for (String session : logRecordMap.keySet()) { Integer num = logRecordMap.get(session).size(); List<SysAccessRecord> value = this.toIntegerList(logRecordMap.get(session)); frequency.put(num, value); } List<SysAccessRecord> notLogRecords = records.stream() .filter(record -> record.getLoginUserId() == null && record.getCookieId() != null && record.getSessionId() != null) .collect(Collectors.toList()); // 根据cookieId+session分组计算未登录用户的访问频次 Map<String, Map<String, List<SysAccessRecord>>> notLogRecordMap = notLogRecords.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId, Collectors.groupingBy(SysAccessRecord::getCookieId))); for (String cookieId : notLogRecordMap.keySet()) { Integer num = notLogRecordMap.get(cookieId).size(); List<SysAccessRecord> newValue = this.toStringList(notLogRecordMap.get(cookieId)); List<SysAccessRecord> value = frequency.get(num); if (value != null) { value.addAll(newValue); } else { frequency.put(num, newValue); } } return frequency; } /** * 将key为string的map转化成list */ private List<SysAccessRecord> toStringList(Map<String, List<SysAccessRecord>> recordMap) { List<SysAccessRecord> records = new ArrayList<SysAccessRecord>(); for (String str : recordMap.keySet()) { records.addAll(recordMap.get(str)); } return records; } /** * 将key为Integer的map转化成list */ private List<SysAccessRecord> toIntegerList(Map<Integer, List<SysAccessRecord>> recordMap) { List<SysAccessRecord> records = new ArrayList<SysAccessRecord>(); for (Integer i : recordMap.keySet()) { records.addAll(recordMap.get(i)); } return records; } private int receiveIp(List<SysAccessRecord> records) { records = records.stream().filter(record -> record.getAccessIp() != null).collect(Collectors.toList()); int size = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessIp)).keySet().size(); return size; } @Override public StatisticsFlowVo getFlow(StatisticsFlowDto dto) { List<String> dates = new ArrayList<String>(); List<Integer> pvs = new ArrayList<Integer>(); List<Integer> uvs = new ArrayList<Integer>(); List<Integer> ips = new ArrayList<Integer>(); List<BigDecimal> depths = new ArrayList<BigDecimal>(); List<Integer> times = new ArrayList<Integer>(); List<StatisticsFlowListVo> flowListVos = new ArrayList<StatisticsFlowListVo>(); StatisitcsOverviewVo vo = null; Long startTime = MyDateUtils.getStartDate(new Date()).getTime(); Long endTime = MyDateUtils.getFinallyDate(new Date()).getTime(); Long minTime = dto.getMinTime().getTime(); if (minTime >= startTime && minTime <= endTime) { dto.setMinTime(MyDateUtils.getStartDate(new Date())); dto.setMaxTime(new Date()); List<SysAccessRecord> records = sysAccessRecordService.getFlow(dto); // 大于小时分组说明使用day天数分组 if (dto.getShowStyle() > StatisticsFlow.SHOW_HOUR) { dates.add(MyDateUtils.formatDate(new Date())); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(1, MyDateUtils.formatDate(new Date())); this.splicRealTimeFlowImage(records, dates, pvs, uvs, ips, depths, times, false); this.splicRealTimeFlowList(records, flowListVo, flowListVos, false); } else { @SuppressWarnings("deprecation") Map<Integer, List<SysAccessRecord>> snapRecordMap = records.parallelStream() .collect(Collectors.groupingBy(o -> o.getCreateTime().getHours())); Map<Integer, List<SysAccessRecord>> recordMap = new LinkedHashMap<Integer, List<SysAccessRecord>>(); snapRecordMap.entrySet().stream().sorted(Map.Entry.<Integer, List<SysAccessRecord>>comparingByKey()) .forEachOrdered(e -> recordMap.put(e.getKey(), e.getValue())); Integer hourNum = MyDateUtils.getDiffIntHourTwoDate(MyDateUtils.getSpecficDateStart(new Date(), 0), new Date()); for (int i = 0; i <= hourNum; i++) { List<SysAccessRecord> snapRecords = recordMap.get(i); dates.add(String.valueOf(i)); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(i, this.hourToString(i)); boolean isEnd = i == hourNum ? true : false; this.splicRealTimeFlowImage(snapRecords, dates, pvs, uvs, ips, depths, times, isEnd); this.splicRealTimeFlowList(snapRecords, flowListVo, flowListVos, isEnd); } } } else { /** 这里就是通过中间表取数据了,中间表中的规则是今天统计昨天的数据*/ dto.setMinTime(MyDateUtils.getSpecficDateStart(dto.getMinTime(), 1)); dto.setMaxTime(MyDateUtils.getSpecficDateEnd(dto.getMaxTime(), 1)); List<StatisticsFlow> flows = dao.getFlow(dto); if (flows != null && flows.size() > 0) { Map<String, List<StatisticsFlow>> flowMap = new LinkedHashMap<String, List<StatisticsFlow>>(); Map<Date, Date> dateMap = null; int i = 1; switch (dto.getShowStyle()) { case StatisticsFlow.SHOW_HOUR: Map<Integer, List<StatisticsFlow>> snapflowHourMap = flows.parallelStream() .collect(Collectors.groupingBy(o -> o.getStatisticsHour())); snapflowHourMap.entrySet().stream().sorted(Map.Entry.<Integer, List<StatisticsFlow>>comparingByKey()).forEachOrdered(e -> flowMap.put(String.valueOf(e.getKey()), e.getValue())); for (String str : flowMap.keySet()) { dates.add(str); List<StatisticsFlow> snapflows = flowMap.get(str); this.splicFlowImage(snapflows, dates, pvs, uvs, ips, depths, times); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(i, this.hourToString(Integer.valueOf(str))); this.splicFlowList(snapflows, flowListVo, flowListVos); i++; } break; case StatisticsFlow.SHOW_DAY: Map<String, List<StatisticsFlow>> snapflowDayMap = flows.parallelStream() .collect(Collectors.groupingBy(o -> o.getStatisticsDay())); snapflowDayMap.entrySet().stream().sorted(Map.Entry.<String, List<StatisticsFlow>>comparingByKey()).forEachOrdered(e -> flowMap.put(e.getKey(), e.getValue())); i = 1; for (String str : flowMap.keySet()) { dates.add(str); List<StatisticsFlow> snapflows = flowMap.get(str); this.splicFlowImage(snapflows, dates, pvs, uvs, ips, depths, times); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(i, str); this.splicFlowList(snapflows, flowListVo, flowListVos); i++; } break; case StatisticsFlow.SHOW_WEEK: dateMap = this.groupByWeek(dto.getMinTime(), dto.getMaxTime()); for (Date date : dateMap.keySet()) { Date value = dateMap.get(date); List<StatisticsFlow> snapflows = flows.stream().filter(s -> s.getCreateTime().getTime() <= value.getTime() && s.getCreateTime().getTime() >= date.getTime()).collect(Collectors.toList()); String key1 = MyDateUtils.formatDate(date); String key2 = MyDateUtils.formatDate(value); flowMap.put(key1 + " " + key2, snapflows); } for (String str : flowMap.keySet()) { dates.add(str); List<StatisticsFlow> snapflows = flowMap.get(str); this.splicFlowImage(snapflows, dates, pvs, uvs, ips, depths, times); } Map<String, List<StatisticsFlow>> newSnapflowDayMap = flows.parallelStream() .collect(Collectors.groupingBy(o -> o.getStatisticsDay())); Map<String, List<StatisticsFlow>> newFlowMap = new LinkedHashMap<String, List<StatisticsFlow>>(); newSnapflowDayMap.entrySet().stream().sorted(Map.Entry.<String, List<StatisticsFlow>>comparingByKey()).forEachOrdered(e -> newFlowMap.put(e.getKey(), e.getValue())); i = 1; for (String str : newFlowMap.keySet()) { List<StatisticsFlow> snapflows = newFlowMap.get(str); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(i, str); this.splicFlowList(snapflows, flowListVo, flowListVos); i++; } break; case StatisticsFlow.SHOW_MONTH: dateMap = this.groupByMonth(dto.getMinTime(), dto.getMaxTime()); for (Date date : dateMap.keySet()) { Date value = dateMap.get(date); List<StatisticsFlow> snapflows = flows.stream().filter(s -> s.getCreateTime().getTime() <= value.getTime() && s.getCreateTime().getTime() >= date.getTime()).collect(Collectors.toList()); String key1 = MyDateUtils.formatDate(date); String key2 = MyDateUtils.formatDate(value); flowMap.put(key1 + " " + key2, snapflows); } for (String str : flowMap.keySet()) { dates.add(str); List<StatisticsFlow> snapflows = flowMap.get(str); this.splicFlowImage(snapflows, dates, pvs, uvs, ips, depths, times); } Map<String, List<StatisticsFlow>> resetSnapflowDayMap = flows.parallelStream() .collect(Collectors.groupingBy(o -> o.getStatisticsDay())); Map<String, List<StatisticsFlow>> resetNewFlowMap = new LinkedHashMap<String, List<StatisticsFlow>>(); resetSnapflowDayMap.entrySet().stream().sorted(Map.Entry.<String, List<StatisticsFlow>>comparingByKey()).forEachOrdered(e -> resetNewFlowMap.put(e.getKey(), e.getValue())); i = 1; for (String str : resetNewFlowMap.keySet()) { List<StatisticsFlow> snapflows = resetNewFlowMap.get(str); StatisticsFlowListVo flowListVo = new StatisticsFlowListVo(i, str); this.splicFlowList(snapflows, flowListVo, flowListVos); i++; } break; default: break; } } else { // this.initImageVo(dates, pvs, uvs, ips, depths, times, dto.getShowStyle(), dto.getMinTime(), dto.getMaxTime()); } } if (dto.getSortTerm() != null && dto.getOrder() != null) { flowListVos = this.sort(flowListVos, dto.getSortTerm(), dto.getOrder()); } else { flowListVos = this.sort(flowListVos, StatisticsFlow.SORT_DATE, false); } vo = this.initTotal(pvs, uvs, ips, depths, times); JSONArray array = new JSONArray(); for (int j = 0; j < dates.size(); j++) { JSONObject object = new JSONObject(); object.put(StatisticsConstant.FIELD_NAME_DATE, dates.get(j)); if (dto.getShowStyle() == StatisticsFlow.SHOW_HOUR) { object.put(StatisticsConstant.FIELD_NAME_SHOW_TIME, String.valueOf(j)); } else { object.put(StatisticsConstant.FIELD_NAME_SHOW_TIME, dates.get(j)); } switch (dto.getShowType()) { case StatisticsConstant.SHOW_FILE_PV: object.put(StatisticsConstant.FIELD_NAME_PV, pvs.get(j)); break; case StatisticsConstant.SHOW_FILE_UV: object.put(StatisticsConstant.FIELD_NAME_UV, uvs.get(j)); break; case StatisticsConstant.SHOW_FILE_IP: object.put(StatisticsConstant.FIELD_NAME_IP, ips.get(j)); break; case StatisticsConstant.SHOW_FILE_DEPTH: object.put(StatisticsConstant.FIELD_NAME_DEPTH, depths.get(j)); break; case StatisticsConstant.SHOW_FILE_TIMES: object.put(StatisticsConstant.FIELD_NAME_TIMES, times.get(j)); break; default: break; } array.add(object); } StatisticsFlowImageVo imageVo = new StatisticsFlowImageVo(array, vo); return new StatisticsFlowVo(flowListVos, imageVo); } private StatisitcsOverviewVo initTotal(List<Integer> pvs, List<Integer> uvs, List<Integer> ips, List<BigDecimal> depths, List<Integer> times) { Integer pv = pvs.stream().collect(Collectors.summingInt(s -> s)); Integer uv = uvs.stream().collect(Collectors.summingInt(s -> s)); Integer ip = ips.stream().collect(Collectors.summingInt(s -> s)); BigDecimal decimal = new BigDecimal(0); for (BigDecimal depth : depths) { decimal = decimal.add(depth); } if (decimal.intValue() > 0) { decimal = decimal.divide(new BigDecimal(depths.size()), BigDecimal.ROUND_HALF_UP); } Integer time = times.stream().collect(Collectors.summingInt(s -> s)); if (time > 0) { time = time / times.size(); } StatisitcsOverviewVo vo = new StatisitcsOverviewVo(pv, uv, ip, MathUtil.formatScaleCast(decimal, 4), time); return vo; } private void initImageVo(List<String> dates, List<Integer> pvs, List<Integer> uvs, List<Integer> ips, List<BigDecimal> depths, List<Integer> times, Short showStyle, Date minTime, Date maxTime) { minTime = MyDateUtils.getSpecficDateStart(minTime, -1); maxTime = MyDateUtils.getSpecficDateEnd(maxTime, -1); Map<Date, Date> dateMap = null; String dateTime = null; switch (showStyle) { case StatisticsFlow.SHOW_HOUR: for (int i = 0; i < 24; i++) { dates.add(this.hourToString(i)); } break; case StatisticsFlow.SHOW_DAY: dateMap = this.groupByDay(minTime, maxTime); for (Date date : dateMap.keySet()) { dates.add(MyDateUtils.formatDate(date)); } break; case StatisticsFlow.SHOW_WEEK: dateMap = this.groupByWeek(minTime, maxTime); for (Date date : dateMap.keySet()) { dateTime = MyDateUtils.formatDate(date) + " - " + MyDateUtils.formatDate(dateMap.get(date)); dates.add(dateTime); } break; case StatisticsFlow.SHOW_MONTH: dateMap = this.groupByMonth(minTime, maxTime); for (Date date : dateMap.keySet()) { dateTime = MyDateUtils.formatDate(date) + " - " + MyDateUtils.formatDate(dateMap.get(date)); dates.add(dateTime); } break; default: break; } for (int i = 0; i < dates.size(); i++) { pvs.add(0); uvs.add(0); ips.add(0); depths.add(new BigDecimal(0)); times.add(0); } } public Map<Date, Date> groupByDay(Date startDate, Date endDate) { Map<Date, Date> dateMap = new LinkedHashMap<Date, Date>(); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); while (true) { cal.add(Calendar.DATE, 0); if (cal.getTime().getTime() < endDate.getTime()) { dateMap.put(startDate, null); } else { break; } cal.add(Calendar.DATE, 1); startDate = cal.getTime(); } return dateMap; } private List<StatisticsFlowListVo> sort(List<StatisticsFlowListVo> vos, Short sortTerm, Boolean order) { switch (sortTerm) { case StatisticsFlow.SORT_DATE: if (!order) { Collections.reverse(vos); } break; case StatisticsFlow.SORT_PV: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getPvNum)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getPvNum).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_UV: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getUvNum)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getUvNum).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_IP: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getIpNum)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getIpNum).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_DEPTH: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getDepthNum)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getDepthNum).reversed()).collect(Collectors.toList()); } break; case StatisticsFlow.SORT_TIME_NUM: if (order) { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getTimeNum)).collect(Collectors.toList()); } else { vos = vos.stream().sorted(Comparator.comparing(StatisticsFlowListVo::getTimeNum).reversed()).collect(Collectors.toList()); } break; default: break; } return vos; } private void splicFlowImage(List<StatisticsFlow> snapflows, List<String> dates, List<Integer> pvs, List<Integer> uvs, List<Integer> ips, List<BigDecimal> depths, List<Integer> times) { Integer pv = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getPvs)); pvs.add(pv); Integer uv = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getUvs)); uvs.add(uv); Integer ip = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getIps)); ips.add(ip); Double depthNum = Double.valueOf(snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getOnlyOnePv)) + ""); BigDecimal depth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(depthNum / Double.valueOf(pv + "")), 4); depths.add(depth); Integer timeNum = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getAccessHoureLong)); ; Integer sissionNum = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getSession)); times.add(sissionNum == 0 ? 0 : timeNum / sissionNum); } private void splicFlowList(List<StatisticsFlow> snapflows, StatisticsFlowListVo flowListVo, List<StatisticsFlowListVo> flowListVos) { Integer pv = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getPvs)); Integer uv = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getUvs)); Integer ip = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getIps)); Double depthNum = Double.valueOf(snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getOnlyOnePv)) + ""); // 如果ip不为0,pv为0,这是不可能的 BigDecimal depth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(depthNum / Double.valueOf(pv + "")), 4); Integer timeNum = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getAccessHoureLong)); flowListVo.setPvNum(pv); flowListVo.setUvNum(uv); flowListVo.setIpNum(ip); flowListVo.setDepthNum(depth); Integer sissionNum = snapflows.stream().collect(Collectors.summingInt(StatisticsFlow::getSession)); flowListVo.setTimeNum(sissionNum == 0 ? 0 : timeNum / sissionNum); flowListVos.add(flowListVo); } private void splicRealTimeFlowList(List<SysAccessRecord> records, StatisticsFlowListVo flowListVo, List<StatisticsFlowListVo> flowListVos, boolean isEnd) { Integer pv = records == null ? 0 : records.size(); Integer uv = records == null ? 0 : this.receiveUv(records); BigDecimal depth = null; Map<Integer, List<SysAccessRecord>> durationMap = null; Integer timeNum = 0; Integer ip = records == null ? 0 : this.receiveIp(records); String depthMapValue = null; if (records != null && records.size() > 0 && this.receiveDepth(records).get(0) != null) { depthMapValue = this.receiveDepth(records).get(0).size() + ""; } Double depthNum = depthMapValue == null ? 0 : Double.valueOf(depthMapValue); depth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(depthNum / Double.valueOf(pv + "")), 4); durationMap = records == null ? new LinkedHashMap<Integer, List<SysAccessRecord>>() : this.receiveDuration(records, false,true); for (Integer time : durationMap.keySet()) { timeNum += time; } flowListVo.setPvNum(pv); flowListVo.setUvNum(uv); flowListVo.setIpNum(ip); if (isEnd) { flowListVo.setDepthNum(new BigDecimal(0)); flowListVo.setTimeNum(0); } else { flowListVo.setDepthNum(depth); Integer sessionNum = this.receiveSessionNum(records); flowListVo.setTimeNum(sessionNum == 0 ? 0 : timeNum / sessionNum); } flowListVos.add(flowListVo); } private int receiveSessionNum(List<SysAccessRecord> records) { int sessionNum = 0; if (records != null && records.size() > 0) { // TODO 计算出正确的session的数量,方便处理平均时长 records = records.stream().filter(record -> record.getSessionId() != null).collect(Collectors.toList()); if (records != null && records.size() > 0) { Map<String,List<SysAccessRecord>> recordMap = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); List<String> deleteSession = new ArrayList<String>(); for (String session : recordMap.keySet()) { if (recordMap.get(session).size() == 1) { deleteSession.add(session); } } for (String session : deleteSession) { recordMap.remove(session); } sessionNum = recordMap.keySet().size(); } } return sessionNum; } private void splicRealTimeFlowImage(List<SysAccessRecord> records, List<String> dates, List<Integer> pvs, List<Integer> uvs, List<Integer> ips, List<BigDecimal> depths, List<Integer> times, boolean isEnd) { Integer pv = 0; Integer uv = 0; BigDecimal depth = null; Map<Integer, List<SysAccessRecord>> durationMap = null; Integer timeNum = 0; Integer ip = 0; pv = records == null ? 0 : records.size(); pvs.add(pv); uv = records == null ? 0 : this.receiveUv(records); uvs.add(uv); ip = records == null ? 0 : this.receiveIp(records); ips.add(ip); String depthMapValue = null; if (records != null && records.size() > 0 && this.receiveDepth(records).get(1) != null) { depthMapValue = this.receiveDepth(records).get(1).size() + ""; } Double depthNum = depthMapValue == null ? 0 : Double.valueOf(depthMapValue); depth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(depthNum / Double.valueOf(pv + "")), 4); depths.add(depth); durationMap = records == null ? new LinkedHashMap<Integer, List<SysAccessRecord>>() : this.receiveDuration(records, false,true); for (Integer time : durationMap.keySet()) { timeNum += time; } Integer sessionNum = this.receiveSessionNum(records); times.add(sessionNum == 0 ? 0 : timeNum / sessionNum); } @SuppressWarnings("deprecation") private Map<Date, Date> groupByMonth(Date startDate, Date endDate) { Map<Date, Date> dateMap = new LinkedHashMap<Date, Date>(); Date firstDay = null; Date lastDay = null; Calendar dd = Calendar.getInstance();// 定义日期实例 dd.setTime(startDate);// 设置日期起始时间 Calendar cale = Calendar.getInstance(); Calendar c = Calendar.getInstance(); c.setTime(endDate); int startDay = startDate.getDate(); int endDay = endDate.getDate(); while (dd.getTime().before(endDate)) {// 判断是否到结束日期 cale.setTime(dd.getTime()); if (dd.getTime().equals(startDate)) { cale.set(Calendar.DAY_OF_MONTH, dd.getActualMaximum(Calendar.DAY_OF_MONTH)); lastDay = cale.getTime(); dateMap.put(startDate, lastDay); } else if (dd.get(Calendar.MONTH) == endDate.getMonth() && dd.get(Calendar.YEAR) == c.get(Calendar.YEAR)) { cale.set(Calendar.DAY_OF_MONTH, 1);// 取第一天 firstDay = cale.getTime(); dateMap.put(firstDay, endDate); } else { cale.set(Calendar.DAY_OF_MONTH, 1);// 取第一天 firstDay = cale.getTime(); cale.set(Calendar.DAY_OF_MONTH, dd.getActualMaximum(Calendar.DAY_OF_MONTH)); lastDay = cale.getTime(); dateMap.put(firstDay, lastDay); } dd.add(Calendar.MONTH, 1);// 进行当前日期月份加1 } if (endDay < startDay) { cale.setTime(endDate); cale.set(Calendar.DAY_OF_MONTH, 1);// 取第一天 firstDay = cale.getTime(); dateMap.put(firstDay, endDate); } return dateMap; } private String hourToString(Integer hour) { return hour + ":00 - " + hour + ":59:59"; } @Override public StatisitcsOverviewVos getOverviewVos(Integer siteId) { Date endTime = new Date(); Date startTime = MyDateUtils.getSpecficDateStart(endTime, 0); List<SysAccessRecord> records = sysAccessRecordService.findByDate(startTime, endTime, siteId); Integer pv = records == null ? 0 : records.size(); Integer uv = records == null ? 0 : this.receiveUv(records); Integer ip = records == null ? 0 : this.receiveIp(records); String depthMapValue = null; if (records != null && records.size() > 0 && this.receiveDepth(records).get(0) != null) { depthMapValue = this.receiveDepth(records).get(0).size() + ""; } Double depthNum = depthMapValue == null ? 0 : Double.valueOf(depthMapValue); BigDecimal depth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(depthNum / Double.valueOf(pv + "")), 4); Map<Integer, List<SysAccessRecord>> durationMap = null; Integer timeNum = 0; durationMap = records == null ? new LinkedHashMap<Integer, List<SysAccessRecord>>() : this.receiveDuration(records, false,true); for (Integer time : durationMap.keySet()) { timeNum += time; } Integer sessionNum = this.receiveSessionNum(records); StatisitcsOverviewVo now = new StatisitcsOverviewVo(pv, uv, ip, depth, sessionNum == 0 ? 0 : timeNum / sessionNum); List<StatisticsFlow> flows = dao.findBySiteId(siteId); List<StatisticsFlow> yesterdayFlows = null; // 如果昨天的数据还没有产生那么直接返回null StatisitcsOverviewVo yesterday = null; StatisitcsOverviewVo highest = null; if (flows != null && flows.size() > 0) { yesterdayFlows = flows.stream().filter(flow -> flow.getCreateTime().getTime() >= startTime.getTime() && flow.getCreateTime().getTime() <= endTime.getTime()).collect(Collectors.toList()); if (yesterdayFlows != null && yesterdayFlows.size() > 0) { pv = yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getPvs)); uv = yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getUvs)); ip = yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getIps)); Double yesterDepthNum = Double.valueOf(yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getOnlyOnePv)) + ""); BigDecimal yesterDepth = pv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(yesterDepthNum / Double.valueOf(pv + "")), 4); Integer yesterTimeNum = yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getAccessHoureLong)); ; sessionNum = yesterdayFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getSession)); yesterday = new StatisitcsOverviewVo(pv, uv, ip, yesterDepth, sessionNum == 0 ? 0 : yesterTimeNum / sessionNum); } else { yesterday = new StatisitcsOverviewVo(0, 0, 0, new BigDecimal(0), 0); } Map<String, List<StatisticsFlow>> flowMap = flows.stream().collect(Collectors.groupingBy(StatisticsFlow::getStatisticsDay)); List<Integer> pvs = new ArrayList<Integer>(); List<Integer> uvs = new ArrayList<Integer>(); List<Integer> ips = new ArrayList<Integer>(); List<BigDecimal> depths = new ArrayList<BigDecimal>(); List<Integer> times = new ArrayList<Integer>(); for (String str : flowMap.keySet()) { List<StatisticsFlow> snapFlows = flowMap.get(str); Integer snapPv = snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getPvs)); pvs.add(snapPv); uvs.add(snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getUvs))); ips.add(snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getIps))); Integer snapDepth = snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getOnlyOnePv)); depths.add(snapPv == 0 ? new BigDecimal(0) : MathUtil.formatScaleCast(new BigDecimal(snapDepth / Double.valueOf(snapPv + "")), 6)); sessionNum = snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getSession)); times.add(sessionNum == 0 ? 0 : snapFlows.stream().collect(Collectors.summingInt(StatisticsFlow::getAccessHoureLong)) / sessionNum); } highest = new StatisitcsOverviewVo(this.receiveMaxList(pvs), this.receiveMaxList(uvs), this.receiveMaxList(ips), this.receiveMaxBigDecimals(depths), this.receiveMaxList(times)); } else { yesterday = new StatisitcsOverviewVo(0, 0, 0, new BigDecimal(0), 0); highest = new StatisitcsOverviewVo(0, 0, 0, new BigDecimal(0), 0); } StatisitcsOverviewVos vos = new StatisitcsOverviewVos(now, yesterday, highest); return vos; } private BigDecimal receiveMaxBigDecimals(List<BigDecimal> bigs) { BigDecimal max = bigs.stream().max(new Comparator<BigDecimal>() { @Override public int compare(BigDecimal o1, BigDecimal o2) { return o1.compareTo(o2); } }).get(); return max; } private int receiveMaxList(List<Integer> list) { int max = list.stream().max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }).get(); return max; } @Override public void save() throws GlobalException { Date beginTime = MyDateUtils.getSpecficDateStart(new Date(), -1); Date endTime = MyDateUtils.getFinallyDate(beginTime); List<StatisticsFlow> flows = new ArrayList<StatisticsFlow>(); List<SysAccessRecord> records = sysAccessRecordService.getSource(beginTime, endTime, null, null, null, null); String statisticsDay = MyDateUtils.formatDate(beginTime); if (records != null && records.size() > 0) { // 对siteId进行分组 records = records.stream().filter(record -> record.getSiteId() != null).collect(Collectors.toList()); Map<Integer, List<SysAccessRecord>> siteMap = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getSiteId)); for (Integer siteId : siteMap.keySet()) { // 对来源网站类型分组 List<SysAccessRecord> siteList = siteMap.get(siteId); siteList = siteList.stream().filter(record -> record.getSorceUrlType() != null).collect(Collectors.toList()); Map<Integer, List<SysAccessRecord>> sourceUrlTypeMap = siteList.stream().collect(Collectors.groupingBy(SysAccessRecord::getSorceUrlType)); for (Integer sourceUrlTypeRecord : sourceUrlTypeMap.keySet()) { if (SysAccessRecord.RESOURCE_SEARCHER.equals(sourceUrlTypeRecord)) { List<SysAccessRecord> sourceUrlTypeRecordList = sourceUrlTypeMap.get(sourceUrlTypeRecord); sourceUrlTypeRecordList = sourceUrlTypeRecordList.stream().filter(record -> record.getEngineName() != null).collect(Collectors.toList()); Map<String,List<SysAccessRecord>> engineNameMap = sourceUrlTypeRecordList.stream().collect(Collectors.groupingBy(SysAccessRecord::getEngineName)); for (String engineName : engineNameMap.keySet()) { List<SysAccessRecord> engineNameList = engineNameMap.get(engineName); flows = this.initFlow(engineNameList, flows, sourceUrlTypeRecord, siteId, statisticsDay,engineName); } } else { flows = this.initFlow(sourceUrlTypeMap.get(sourceUrlTypeRecord), flows, sourceUrlTypeRecord, siteId, statisticsDay,null); } } } } if (flows.size() > 0) { Map<Integer, List<StatisticsFlow>> flowMap = flows.stream().collect(Collectors.groupingBy(StatisticsFlow::getSiteId)); for (Integer siteId : flowMap.keySet()) { List<Integer> hours = flowMap.get(siteId).stream().map(StatisticsFlow::getStatisticsHour).collect(Collectors.toList()); for (int i = 0; i < 24; i++) { if (!hours.contains(i)) { StatisticsFlow flow = new StatisticsFlow(siteId, statisticsDay, 0, false, 1, null, null, null, i, 0, 0, 0, 0, 0, 0,null); flows.add(flow); } } } super.saveAll(flows); } } private List<StatisticsFlow> initFlow(List<SysAccessRecord> sourceUrlTypeList,List<StatisticsFlow> flows,Integer sourceUrlTypeRecord,Integer siteId,String statisticsDay,String engineName) { // 对是否新用户分组 sourceUrlTypeList = sourceUrlTypeList.stream().filter(record -> record.getNewVisitor() != null).collect(Collectors.toList()); Map<Boolean, List<SysAccessRecord>> newVisitorMap = sourceUrlTypeList.stream().collect(Collectors.groupingBy(SysAccessRecord::getNewVisitor)); for (Boolean newVisitor : newVisitorMap.keySet()) { // 对设备类型(1.计算机、2.移动设备)分组 List<SysAccessRecord> newVisitorList = newVisitorMap.get(newVisitor); newVisitorList = newVisitorList.stream().filter(record -> record.getDeviceType() != null).collect(Collectors.toList()); Map<Short, List<SysAccessRecord>> deviceTypeMap = newVisitorList.stream().collect(Collectors.groupingBy(SysAccessRecord::getDeviceType)); for (Short deviceType : deviceTypeMap.keySet()) { // 对访客设备系统进行分组 List<SysAccessRecord> deviceTypeList = deviceTypeMap.get(deviceType); deviceTypeList = deviceTypeList.stream().filter(record -> record.getAccessDevice() != null).collect(Collectors.toList()); Map<String, List<SysAccessRecord>> accessDeviceTypeMap = deviceTypeList.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessDevice)); for (String accessDevice : accessDeviceTypeMap.keySet()) { // 对城市分组(相当于同时对省份进行了分组) List<SysAccessRecord> accessDeviceList = accessDeviceTypeMap.get(accessDevice); accessDeviceList = accessDeviceList.stream().filter(record -> record.getAccessCity() != null).collect(Collectors.toList()); Map<String, List<SysAccessRecord>> accessCityMap = accessDeviceList.stream().collect(Collectors.groupingBy(SysAccessRecord::getAccessCity)); for (String city : accessCityMap.keySet()) { List<SysAccessRecord> accessCityList = accessCityMap.get(city); @SuppressWarnings("deprecation") Map<Integer, List<SysAccessRecord>> hourMap = accessCityList.parallelStream() .collect(Collectors.groupingBy(o -> o.getCreateTime().getHours())); for (Integer hour : hourMap.keySet()) { List<SysAccessRecord> hourList = hourMap.get(hour); Integer pvs = hourList.size(); Integer uvs = this.receiveUv(hourList); Integer ips = this.receiveIp(hourList); Integer accessHoureLong = this.receiveHoureLong(hourList); Map<Integer, List<SysAccessRecord>> onePvMap = this.receiveDepth(hourList); Integer onlyOnePv = 0; if (onePvMap != null && onePvMap.get(0) != null) { onlyOnePv = onePvMap.get(0).size(); } StatisticsFlow flow = new StatisticsFlow(siteId, statisticsDay, sourceUrlTypeRecord, newVisitor, Integer.valueOf(deviceType), accessDevice, hourList.get(0).getAccessProvince(), city, hour, pvs, uvs, ips, accessHoureLong, onlyOnePv, this.receiveSessionNum(hourList),engineName); flows.add(flow); } } } } } return flows; } private int receiveHoureLong(List<SysAccessRecord> records) { Integer houreLong = 0; records = records.stream().filter(record -> record.getSessionId() != null).collect(Collectors.toList()); if (records != null && records.size() > 0) { Map<String, List<SysAccessRecord>> recordMap = records.stream().collect(Collectors.groupingBy(SysAccessRecord::getSessionId)); for (String session : recordMap.keySet()) { List<SysAccessRecord> snapRecords = recordMap.get(session); snapRecords = snapRecords.stream().sorted(Comparator.comparing(SysAccessRecord::getCreateTime)).collect(Collectors.toList()); Long minTime = snapRecords.get(0).getCreateTime().getTime(); Long maxTime = snapRecords.get(snapRecords.size() - 1).getCreateTime().getTime(); Long time = (maxTime - minTime) / 1000; Integer timeValue = time.intValue(); houreLong += timeValue; } } return houreLong; } /** 访客数(UV):当前站点下, 有user_id,以user_id分组,统计user_id数量,记为:C1; 无user_id,以cookie分组,统计cookie数量,记为:C2; 访客数(UV)= C1+C2。**/ @Override public Integer uvNumber(List<SysAccessRecord> records) throws GlobalException { Integer c1 = 0; Integer c2 = 0; if (records.isEmpty()) { return 0; } c1 = records.stream().filter(o -> o.getLoginUserId() != null) .collect(Collectors.groupingBy(SysAccessRecord::getLoginUserId)).size(); c2 = records.stream().filter(o -> o.getLoginUserId() == null) .filter(o -> StringUtils.isNotBlank(o.getCookieId())) .collect(Collectors.groupingBy(SysAccessRecord::getCookieId)).size(); return c1 + c2; } }
98,074
Java
.java
2,252
38.129218
284
0.721889
chenbo19867758/jeecmsX1.2
4
7
11
GPL-3.0
9/4/2024, 11:11:18 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
95,182
3,081,546
PlayerInfoSerializer.java
hungnguyennaz_ZCord/proxy/src/main/java/net/md_5/bungee/PlayerInfoSerializer.java
package net.md_5.bungee; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.UUID; import net.md_5.bungee.api.ServerPing; public class PlayerInfoSerializer implements JsonSerializer<ServerPing.PlayerInfo>, JsonDeserializer<ServerPing.PlayerInfo> { @Override public ServerPing.PlayerInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject js = json.getAsJsonObject(); ServerPing.PlayerInfo info = new ServerPing.PlayerInfo( js.get( "name" ).getAsString(), (UUID) null ); String id = js.get( "id" ).getAsString(); if ( !id.contains( "-" ) ) { info.setId( id ); } else { info.setUniqueId( UUID.fromString( id ) ); } return info; } @Override public JsonElement serialize(ServerPing.PlayerInfo src, Type typeOfSrc, JsonSerializationContext context) { JsonObject out = new JsonObject(); out.addProperty( "name", src.getName() ); out.addProperty( "id", src.getUniqueId().toString() ); return out; } }
1,416
Java
.java
37
32.837838
138
0.717091
hungnguyennaz/ZCord
5
1
0
GPL-3.0
9/4/2024, 10:46:59 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
1,416
1,001,707
OptionHandler.java
cacheonix_cacheonix-core/3rdparty/apache-log4j-1.2.15/src/main/java/org/apache/log4j/spi/OptionHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.log4j.spi; /** A string based interface to configure package components. @author Ceki G&uuml;lc&uuml; @author Anders Kristensen @since 0.8.1 */ public interface OptionHandler { /** Activate the options that were previously set with calls to option setters. <p>This allows to defer activiation of the options until all options have been set. This is required for components which have related options that remain ambigous until all are set. <p>For example, the FileAppender has the {@link org.apache.log4j.FileAppender#setFile File} and {@link org.apache.log4j.FileAppender#setAppend Append} options both of which are ambigous until the other is also set. */ void activateOptions(); /** Return list of strings that the OptionHandler instance recognizes. @deprecated We now use JavaBeans style getters/setters. */ // String[] getOptionStrings(); /** Set <code>option</code> to <code>value</code>. <p>The handling of each option depends on the OptionHandler instance. Some options may become active immediately whereas other may be activated only when {@link #activateOptions} is called. @deprecated We now use JavaBeans style getters/setters. */ //void setOption(String option, String value); }
2,146
Java
.java
50
39.04
75
0.746641
cacheonix/cacheonix-core
52
19
9
LGPL-2.1
9/4/2024, 7:10:22 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
2,146
1,318,366
A_test311.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/SelectionAnalyzerWorkSpace/SelectionAnalyzerTests/validSelection/A_test311.java
package validSelection; public class A_test311 { public void foo() { /*]*/foo();/*[*/ try { foo(); } catch (Exception e) { foo(); } } }
152
Java
.java
11
11.363636
25
0.567376
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
152
4,948,023
CustomerStatementResultHolder.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/report/util/CustomerStatementResultHolder.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.ar.report.util; import java.io.File; import java.util.ArrayList; import java.util.List; import org.kuali.rice.core.api.util.type.KualiDecimal; public class CustomerStatementResultHolder { private String customerNumber; private File file; private KualiDecimal currentBilledAmount; private List<String> invoiceNumbers; public CustomerStatementResultHolder() { customerNumber = null; file = null; currentBilledAmount = KualiDecimal.ZERO; invoiceNumbers = new ArrayList<String>(); } /** * @return the currentBilledAmount */ public KualiDecimal getCurrentBilledAmount() { return currentBilledAmount; } /** * @param currentBilledAmount the currentBilledAmount to set */ public void setCurrentBilledAmount(KualiDecimal currentBilledAmount) { this.currentBilledAmount = currentBilledAmount; } /** * @return the invoiceNumbers */ public List<String> getInvoiceNumbers() { return invoiceNumbers; } /** * @param invoiceNumbers the invoiceNumbers to set */ public void setInvoiceNumbers(List<String> invoiceNumbers) { this.invoiceNumbers = invoiceNumbers; } /** * @return the file */ public File getFile() { return file; } /** * @param file the file to set */ public void setFile(File file) { this.file = file; } /** * @return the customerNumber */ public String getCustomerNumber() { return customerNumber; } /** * @param customerNumber the customerNumber to set */ public void setCustomerNumber(String customerNumber) { this.customerNumber = customerNumber; } }
2,725
Java
.java
83
26.53012
97
0.68112
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
true
true
true
true
false
true
false
true
2,725
1,314,510
MockPluginView.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/model/MockPluginView.java
/******************************************************************************* * Copyright (c) 2005, 2015 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.tests.model; import java.io.ByteArrayInputStream; import java.io.InputStream; import org.eclipse.team.core.diff.IDiff; import org.eclipse.team.core.diff.provider.ThreeWayDiff; import org.eclipse.team.core.history.IFileRevision; import org.eclipse.team.core.history.provider.FileRevision; import org.eclipse.team.core.mapping.ISynchronizationContext; import org.eclipse.team.core.mapping.provider.ResourceDiff; import org.eclipse.team.core.mapping.provider.ResourceDiffTree; import org.eclipse.team.core.mapping.provider.SynchronizationContext; import org.eclipse.team.core.mapping.provider.SynchronizationScopeManager; import org.eclipse.team.ui.mapping.ITeamContentProviderManager; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IStorage; import org.eclipse.core.resources.mapping.ResourceMapping; import org.eclipse.core.resources.mapping.ResourceMappingContext; import org.eclipse.core.resources.mapping.ResourceTraversal; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.ui.navigator.CommonViewer; import org.eclipse.ui.navigator.INavigatorContentExtension; import org.eclipse.ui.navigator.INavigatorContentServiceListener; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IJavaProject; public class MockPluginView extends ViewPart implements INavigatorContentServiceListener { private static final String VIEWER_ID = "org.eclipse.jdt.tests.ui.model.mockViewer"; private static final String JAVA_CONTENT_PROVIDER_ID = "org.eclipse.jdt.ui.javaModelContent"; private CommonViewer fViewer; private INavigatorContentExtension fExtension; private ISynchronizationContext fContext; public MockPluginView() { // Nothing to do } @Override public void createPartControl(Composite parent) { fViewer = new CommonViewer(VIEWER_ID, parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); // Only enable the Java model content fViewer.getNavigatorContentService().bindExtensions(new String[] { JAVA_CONTENT_PROVIDER_ID }, true); fViewer.getNavigatorContentService().getActivationService().activateExtensions(new String[] { JAVA_CONTENT_PROVIDER_ID }, true); fViewer.getNavigatorContentService().addListener(this); if (fContext != null) setInput(fContext); } @Override public void setFocus() { // Nothing to do } public void setInput(Object input) { fViewer.setInput(input); } public ITreeContentProvider getContentProvider() { return (ITreeContentProvider)fViewer.getContentProvider(); } @Override public void onLoad(INavigatorContentExtension anExtension) { this.fExtension = anExtension; setContext(fContext); } public void setProject(IJavaProject project) throws CoreException { ISynchronizationContext context = createContext(project); setContext(context); } private void setContext(ISynchronizationContext context) { if (fContext != context) { if (fContext != null) { fContext.dispose(); } fContext = context; } if (fExtension != null) { fExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_SCOPE, context.getScope()); fExtension.getStateModel().setProperty(ITeamContentProviderManager.P_SYNCHRONIZATION_CONTEXT, context); } setInput(fContext); } @Override public void dispose() { super.dispose(); if (fContext != null) { fContext.dispose(); } } private ISynchronizationContext createContext(IJavaProject project) throws CoreException { ResourceDiffTree tree = new ResourceDiffTree(); SynchronizationScopeManager manager = new SynchronizationScopeManager("Java Model Tests", getResourceMappings(project), ResourceMappingContext.LOCAL_CONTEXT, true); manager.initialize(new NullProgressMonitor()); SynchronizationContext context = new SynchronizationContext(manager, ISynchronizationContext.THREE_WAY, tree) { @Override public void refresh(ResourceTraversal[] traversals, int flags, IProgressMonitor monitor) throws CoreException { // Nothing to do } }; return context; } private ResourceMapping[] getResourceMappings(IJavaProject project) { ResourceMapping mapping = project.getResource().getAdapter(ResourceMapping.class); return new ResourceMapping[] { mapping }; } private IResource getResource(IProject project, String path) { if (path.endsWith("/")) return project.getFolder(path); return project.getFile(path); } private ResourceDiff createResourceDiff(IProject project, String path, int kind) { final IResource resource = getResource(project, path); ResourceDiff diff = new ResourceDiff(resource, kind, 0, new FileRevision() { @Override public String getName() { return resource.getName(); } @Override public IStorage getStorage(IProgressMonitor monitor) throws CoreException { return new IStorage() { @Override public <T> T getAdapter(Class<T> adapter) { return null; } @Override public boolean isReadOnly() { return true; } @Override public String getName() { return resource.getName(); } @Override public IPath getFullPath() { return resource.getFullPath(); } @Override public InputStream getContents() throws CoreException { return new ByteArrayInputStream("".getBytes()); } }; } @Override public boolean isPropertyMissing() { return false; } @Override public IFileRevision withAllProperties(IProgressMonitor monitor) throws CoreException { return this; }}, null); return diff; } public void addOutgoingDeletion(IProject project, String path) { IDiff diff = createOutgoingDeletion(project, path); add(diff); } private IDiff createOutgoingDeletion(IProject project, String path) { ResourceDiff diff= createResourceDiff(project, path, IDiff.REMOVE); return new ThreeWayDiff(diff, null); } public void addIncomingAddition(IProject project, String path){ IDiff diff = createIncomingAddition(project,path); add(diff); } private IDiff createIncomingAddition(IProject project, String path) { ResourceDiff diff= createResourceDiff(project, path, IDiff.ADD); return new ThreeWayDiff(null, diff); } public void addOutgoingChange(IProject project, String path){ IDiff diff= createOutgoingChange(project,path); add(diff); } private IDiff createOutgoingChange(IProject project, String path) { ResourceDiff diff= createResourceDiff(project, path, IDiff.CHANGE); return new ThreeWayDiff(diff, null); } private void add(IDiff diff) { ((ResourceDiffTree)fContext.getDiffTree()).add(diff); } }
7,460
Java
.java
196
35.005102
130
0.771847
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
false
true
true
true
true
true
7,460
3,799,414
CalculatorKeysPanel.java
openjump-gis_sextante-extension/sextante-algorithm/src/main/java/es/unex/sextante/nonSpatial/calculator/CalculatorKeysPanel.java
package es.unex.sextante.nonSpatial.calculator; import info.clearthought.layout.TableLayout; import info.clearthought.layout.TableLayoutConstants; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextArea; public class CalculatorKeysPanel extends JPanel { private JTextArea m_TextExpression = null; private JButton jButtonMinus; private JButton jButtonDivide; private JButton jButton2; private JButton jButtonDot; private JButton jButtonBrackets; private JButton jButton0; private JButton jButton9; private JButton jButton8; private JButton jButton7; private JButton jButton6; private JButton jButton5; private JButton jButton4; private JButton jButton3; private JButton jButton1; private JButton jButtonMultiply; private JButton jButtonPlus; public CalculatorKeysPanel(final JTextArea textExpression) { super(); m_TextExpression = textExpression; initialize(); } private void initialize() { final ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent evt) { addText(evt.getSource()); } }; final ActionListener listenerBrackets = new ActionListener() { public void actionPerformed(ActionEvent evt) { m_TextExpression.insert(" ()", m_TextExpression.getCaretPosition()); m_TextExpression.setCaretPosition(m_TextExpression.getCaretPosition() - 1); } }; final TableLayout thisLayout = new TableLayout( new double[][] { { TableLayoutConstants.FILL, 10.0, TableLayoutConstants.FILL, TableLayoutConstants.FILL, TableLayoutConstants.FILL }, { TableLayoutConstants.FILL, TableLayoutConstants.FILL, TableLayoutConstants.FILL, TableLayoutConstants.FILL } }); thisLayout.setHGap(5); thisLayout.setVGap(5); this.setLayout(thisLayout); this.setPreferredSize(new java.awt.Dimension(284, 239)); { jButtonPlus = new JButton(); this.add(jButtonPlus, "0, 0"); jButtonPlus.setText("+"); jButtonPlus.addActionListener(listener); } { jButtonMinus = new JButton(); this.add(jButtonMinus, "0, 1"); jButtonMinus.setText("-"); jButtonMinus.addActionListener(listener); } { jButtonMultiply = new JButton(); this.add(jButtonMultiply, "0, 2"); jButtonMultiply.setText("*"); jButtonMultiply.addActionListener(listener); } { jButtonDivide = new JButton(); this.add(jButtonDivide, "0, 3"); jButtonDivide.setText("/"); jButtonDivide.addActionListener(listener); } { jButton1 = new JButton(); this.add(jButton1, "2, 2"); jButton1.setText("1"); jButton1.addActionListener(listener); } { jButton2 = new JButton(); this.add(jButton2, "3, 2"); jButton2.setText("2"); jButton2.addActionListener(listener); } { jButton3 = new JButton(); this.add(jButton3, "4, 2"); jButton3.setText("3"); jButton3.addActionListener(listener); } { jButton4 = new JButton(); this.add(jButton4, "2, 1"); jButton4.setText("4"); jButton4.addActionListener(listener); } { jButton5 = new JButton(); this.add(jButton5, "3, 1"); jButton5.setText("5"); jButton5.addActionListener(listener); } { jButton6 = new JButton(); this.add(jButton6, "4, 1"); jButton6.setText("6"); jButton6.addActionListener(listener); } { jButton7 = new JButton(); this.add(jButton7, "2, 0"); jButton7.setText("7"); jButton7.addActionListener(listener); } { jButton8 = new JButton(); this.add(jButton8, "3, 0"); jButton8.setText("8"); jButton8.addActionListener(listener); } { jButton9 = new JButton(); this.add(jButton9, "4, 0"); jButton9.setText("9"); jButton9.addActionListener(listener); } { jButton0 = new JButton(); this.add(jButton0, "2, 3"); jButton0.setText("0"); jButton0.addActionListener(listener); } { jButtonDot = new JButton(); this.add(jButtonDot, "4, 3"); jButtonDot.setText("."); jButtonDot.addActionListener(listener); } { jButtonBrackets = new JButton(); this.add(jButtonBrackets, "3, 3"); jButtonBrackets.setText("( )"); jButtonBrackets.addActionListener(listenerBrackets); } } private void addText(final Object source) { if (source instanceof JButton) { String s = ((JButton) source).getText(); try { final int i = Integer.parseInt(s); } catch (final NumberFormatException e) { s = " " + s + " "; } m_TextExpression.insert(s, m_TextExpression.getCaretPosition()); } } }
5,408
Java
.java
165
24.248485
112
0.603409
openjump-gis/sextante-extension
3
2
1
GPL-3.0
9/4/2024, 11:42:59 PM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
5,408
1,320,590
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/testDelegate01/out/A.java
package p; public interface I { /** * @deprecated Use {@link #k()} instead */ public void m(); public void k(); }
126
Java
.java
8
13.25
40
0.628319
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
126
1,317,161
SomeClass.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testSimilarElements22/in/SomeClass.java
package p; public class SomeClass { { class InInitializer { SomeClass someClassInInitializer; } } }
115
Java
.java
8
11.5
36
0.762376
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
115
1,316,632
Foo.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test33/out/Foo.java
package p; public class Foo { private Bar _bar; private void foo() { _bar.foo(); } }
92
Java
.java
7
11.142857
21
0.662651
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
92
1,316,142
C.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test75/out/C.java
package p; public class C { I fA; void f(){ B b= new B(2, fA); } }
73
Java
.java
7
8.571429
20
0.569231
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
73
1,316,520
A_testAdd33_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAdd33_in.java
package p; class A{ private void m(){ m(); } }
50
Java
.java
6
6.833333
18
0.6
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
50
1,317,216
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test60/in/A.java
package p; /** * p.A * AA A */ public class A{ A a;//A String aa= "C:\\A.java"; };
89
Java
.java
9
8.222222
25
0.525
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
89
1,314,844
Foo.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test04/out/Foo.java
package p; public class Foo { /** * @param foo */ public static void bar(Foo foo) { foo.foo(); } // Test qualification with outer type void foo() { Bar bar= new Bar() { { Foo.bar(Foo.this); // <--- invoke here } }; } } class Bar { }
271
Java
.java
19
11.263158
42
0.5875
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
271
1,314,947
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/Delete/testDeleteWithinCu17/in/A.java
package p; class A { void f(){} /** * */ void fs(){} }
67
Java
.java
8
5.875
12
0.454545
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
67
4,948,603
ProposalInquirable.java
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/cg/businessobject/inquiry/ProposalInquirable.java
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.cg.businessobject.inquiry; import org.kuali.kfs.sys.businessobject.inquiry.KfsInquirableImpl; /** * Used for wiring up {@link Proposal} for inquiries. */ public class ProposalInquirable extends KfsInquirableImpl { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ProposalInquirable.class); }
1,220
Java
.java
26
43.653846
116
0.765152
ua-eas/ua-kfs-5.3
1
0
0
AGPL-3.0
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
true
true
true
true
false
true
true
true
1,220
963,242
Video.java
ajscape_PixaToon/libraries/opencv/src/org/opencv/video/Video.java
// // This file is auto-generated. Please don't modify it! // package org.opencv.video; import java.util.ArrayList; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfFloat; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Rect; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.core.TermCriteria; import org.opencv.utils.Converters; public class Video { private static final int CV_LKFLOW_INITIAL_GUESSES = 4, CV_LKFLOW_GET_MIN_EIGENVALS = 8; public static final int OPTFLOW_USE_INITIAL_FLOW = 4, OPTFLOW_LK_GET_MIN_EIGENVALS = 8, OPTFLOW_FARNEBACK_GAUSSIAN = 256, MOTION_TRANSLATION = 0, MOTION_EUCLIDEAN = 1, MOTION_AFFINE = 2, MOTION_HOMOGRAPHY = 3; // // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) // //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_0(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_1(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } // // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) // //javadoc: createBackgroundSubtractorMOG2(history, varThreshold, detectShadows) public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history, double varThreshold, boolean detectShadows) { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_0(history, varThreshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorMOG2() public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2() { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_1()); return retVal; } // // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) // //javadoc: createBackgroundSubtractorKNN(history, dist2Threshold, detectShadows) public static BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history, double dist2Threshold, boolean detectShadows) { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_0(history, dist2Threshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorKNN() public static BackgroundSubtractorKNN createBackgroundSubtractorKNN() { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_1()); return retVal; } // // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() // //javadoc: createOptFlow_DualTVL1() public static DualTVL1OpticalFlow createOptFlow_DualTVL1() { DualTVL1OpticalFlow retVal = new DualTVL1OpticalFlow(createOptFlow_DualTVL1_0()); return retVal; } // // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) // //javadoc: calcOpticalFlowFarneback(prev, next, flow, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) public static void calcOpticalFlowFarneback(Mat prev, Mat next, Mat flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) { calcOpticalFlowFarneback_0(prev.nativeObj, next.nativeObj, flow.nativeObj, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags); return; } // // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size(21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) // //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel, criteria, flags, minEigThreshold) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel, TermCriteria criteria, int flags, double minEigThreshold) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_0(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel, criteria.type, criteria.maxCount, criteria.epsilon, flags, minEigThreshold); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_1(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_2(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj); return; } // // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) // //javadoc: estimateRigidTransform(src, dst, fullAffine) public static Mat estimateRigidTransform(Mat src, Mat dst, boolean fullAffine) { Mat retVal = new Mat(estimateRigidTransform_0(src.nativeObj, dst.nativeObj, fullAffine)); return retVal; } // // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) // //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType, criteria, inputMask) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType, TermCriteria criteria, Mat inputMask) { double retVal = findTransformECC_0(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType, criteria.type, criteria.maxCount, criteria.epsilon, inputMask.nativeObj); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType) { double retVal = findTransformECC_1(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix) { double retVal = findTransformECC_2(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj); return retVal; } // // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: meanShift(probImage, window, criteria) public static int meanShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; int retVal = meanShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon); if(window!=null){ window.x = (int)window_out[0]; window.y = (int)window_out[1]; window.width = (int)window_out[2]; window.height = (int)window_out[3]; } return retVal; } // // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: CamShift(probImage, window, criteria) public static RotatedRect CamShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; RotatedRect retVal = new RotatedRect(CamShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon)); if(window!=null){ window.x = (int)window_out[0]; window.y = (int)window_out[1]; window.width = (int)window_out[2]; window.height = (int)window_out[3]; } return retVal; } // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) private static native int buildOpticalFlowPyramid_0(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage); private static native int buildOpticalFlowPyramid_1(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) private static native long createBackgroundSubtractorMOG2_0(int history, double varThreshold, boolean detectShadows); private static native long createBackgroundSubtractorMOG2_1(); // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) private static native long createBackgroundSubtractorKNN_0(int history, double dist2Threshold, boolean detectShadows); private static native long createBackgroundSubtractorKNN_1(); // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() private static native long createOptFlow_DualTVL1_0(); // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) private static native void calcOpticalFlowFarneback_0(long prev_nativeObj, long next_nativeObj, long flow_nativeObj, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags); // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size(21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) private static native void calcOpticalFlowPyrLK_0(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, int criteria_type, int criteria_maxCount, double criteria_epsilon, int flags, double minEigThreshold); private static native void calcOpticalFlowPyrLK_1(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); private static native void calcOpticalFlowPyrLK_2(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj); // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) private static native long estimateRigidTransform_0(long src_nativeObj, long dst_nativeObj, boolean fullAffine); // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) private static native double findTransformECC_0(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType, int criteria_type, int criteria_maxCount, double criteria_epsilon, long inputMask_nativeObj); private static native double findTransformECC_1(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType); private static native double findTransformECC_2(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj); // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) private static native int meanShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) private static native double[] CamShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); }
15,138
Java
.java
209
65.066986
370
0.750972
ajscape/PixaToon
56
15
3
GPL-3.0
9/4/2024, 7:10:21 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
15,138
1,311,239
SortedSet.java
TheLogicMaster_clearwing-vm/runtime/src/java/util/SortedSet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util; /** * SortedSet is a Set which iterates over its elements in a sorted order. The * order is determined either by the elements natural ordering, or by a * {@link Comparator} which is passed into a concrete implementation at * construction time. All elements in this set must be mutually comparable. The * ordering in this set must be consistent with {@code equals} of its elements. * * @see Comparator * @see Comparable */ public interface SortedSet<E> extends Set<E> { /** * Returns the comparator used to compare elements in this {@code SortedSet}. * * @return a comparator or null if the natural ordering is used. */ public Comparator<? super E> comparator(); /** * Returns the first element in this {@code SortedSet}. The first element * is the lowest element. * * @return the first element. * @throws NoSuchElementException * when this {@code SortedSet} is empty. */ public E first(); /** * Returns a {@code SortedSet} of the specified portion of this * {@code SortedSet} which contains elements less than the end element. The * returned {@code SortedSet} is backed by this {@code SortedSet} so changes * to one set are reflected by the other. * * @param end * the end element. * @return a subset where the elements are less than {@code end}. * @throws ClassCastException * when the class of the end element is inappropriate for this * SubSet. * @throws NullPointerException * when the end element is null and this {@code SortedSet} does * not support null elements. */ public SortedSet<E> headSet(E end); /** * Returns the last element in this {@code SortedSet}. The last element is * the highest element. * * @return the last element. * @throws NoSuchElementException * when this {@code SortedSet} is empty. */ public E last(); /** * Returns a {@code SortedSet} of the specified portion of this * {@code SortedSet} which contains elements greater or equal to the start * element but less than the end element. The returned {@code SortedSet} is * backed by this SortedMap so changes to one set are reflected by the * other. * * @param start * the start element. * @param end * the end element. * @return a subset where the elements are greater or equal to {@code start} * and less than {@code end}. * @throws ClassCastException * when the class of the start or end element is inappropriate * for this SubSet. * @throws NullPointerException * when the start or end element is null and this * {@code SortedSet} does not support null elements. * @throws IllegalArgumentException * when the start element is greater than the end element. */ public SortedSet<E> subSet(E start, E end); /** * Returns a {@code SortedSet} of the specified portion of this * {@code SortedSet} which contains elements greater or equal to the start * element. The returned {@code SortedSet} is backed by this * {@code SortedSet} so changes to one set are reflected by the other. * * @param start * the start element. * @return a subset where the elements are greater or equal to {@code start} . * @throws ClassCastException * when the class of the start element is inappropriate for this * SubSet. * @throws NullPointerException * when the start element is null and this {@code SortedSet} * does not support null elements. */ public SortedSet<E> tailSet(E start); }
4,730
Java
.java
110
38.027273
82
0.658997
TheLogicMaster/clearwing-vm
38
3
1
GPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
4,730
3,190,928
LongMap.java
Lux-Vacuos_LightEngine/lightengine-utils/src/main/java/com/badlogic/gdx/utils/LongMap.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.utils; import java.util.Iterator; import java.util.NoSuchElementException; import com.badlogic.gdx.math.MathUtils; /** An unordered map that uses long keys. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small * stash for problematic keys. Null values are allowed. No allocation is done except when growing the table size. <br> * <br> * This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower, * depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the * next higher POT size. * @author Nathan Sweet */ public class LongMap<V> implements Iterable<LongMap.Entry<V>> { private static final int PRIME1 = 0xbe1f14b1; private static final int PRIME2 = 0xb4b82e39; private static final int PRIME3 = 0xced1c241; private static final int EMPTY = 0; public int size; long[] keyTable; V[] valueTable; int capacity, stashSize; V zeroValue; boolean hasZeroValue; private float loadFactor; private int hashShift, mask, threshold; private int stashCapacity; private int pushIterations; private Entries entries1, entries2; private Values values1, values2; private Keys keys1, keys2; /** Creates a new map with an initial capacity of 51 and a load factor of 0.8. */ public LongMap () { this(51, 0.8f); } /** Creates a new map with a load factor of 0.8. * @param initialCapacity If not a power of two, it is increased to the next nearest power of two. */ public LongMap (int initialCapacity) { this(initialCapacity, 0.8f); } /** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity items before * growing the backing table. * @param initialCapacity If not a power of two, it is increased to the next nearest power of two. */ public LongMap (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity); initialCapacity = MathUtils.nextPowerOfTwo((int)Math.ceil(initialCapacity / loadFactor)); if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity); capacity = initialCapacity; if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor); this.loadFactor = loadFactor; threshold = (int)(capacity * loadFactor); mask = capacity - 1; hashShift = 63 - Long.numberOfTrailingZeros(capacity); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2); pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8); keyTable = new long[capacity + stashCapacity]; valueTable = (V[])new Object[keyTable.length]; } /** Creates a new map identical to the specified map. */ public LongMap (LongMap<? extends V> map) { this((int)Math.floor(map.capacity * map.loadFactor), map.loadFactor); stashSize = map.stashSize; System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length); System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length); size = map.size; zeroValue = map.zeroValue; hasZeroValue = map.hasZeroValue; } public V put (long key, V value) { if (key == 0) { V oldValue = zeroValue; zeroValue = value; if (!hasZeroValue) { hasZeroValue = true; size++; } return oldValue; } long[] keyTable = this.keyTable; // Check for existing keys. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == key) { V oldValue = valueTable[index1]; valueTable[index1] = value; return oldValue; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == key) { V oldValue = valueTable[index2]; valueTable[index2] = value; return oldValue; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == key) { V oldValue = valueTable[index3]; valueTable[index3] = value; return oldValue; } // Update key in the stash. for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; valueTable[i] = value; return oldValue; } } // Check for empty buckets. if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return null; } if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return null; } push(key, value, index1, key1, index2, key2, index3, key3); return null; } public void putAll (LongMap<V> map) { for (Entry<V> entry : map.entries()) put(entry.key, entry.value); } /** Skips checks for existing keys. */ private void putResize (long key, V value) { if (key == 0) { zeroValue = value; hasZeroValue = true; return; } // Check for empty buckets. int index1 = (int)(key & mask); long key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = key; valueTable[index1] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index2 = hash2(key); long key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = key; valueTable[index2] = value; if (size++ >= threshold) resize(capacity << 1); return; } int index3 = hash3(key); long key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = key; valueTable[index3] = value; if (size++ >= threshold) resize(capacity << 1); return; } push(key, value, index1, key1, index2, key2, index3, key3); } private void push (long insertKey, V insertValue, int index1, long key1, int index2, long key2, int index3, long key3) { long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int mask = this.mask; // Push keys until an empty bucket is found. long evictedKey; V evictedValue; int i = 0, pushIterations = this.pushIterations; do { // Replace the key and value for one of the hashes. switch (MathUtils.random(2)) { case 0: evictedKey = key1; evictedValue = valueTable[index1]; keyTable[index1] = insertKey; valueTable[index1] = insertValue; break; case 1: evictedKey = key2; evictedValue = valueTable[index2]; keyTable[index2] = insertKey; valueTable[index2] = insertValue; break; default: evictedKey = key3; evictedValue = valueTable[index3]; keyTable[index3] = insertKey; valueTable[index3] = insertValue; break; } // If the evicted key hashes to an empty bucket, put it there and stop. index1 = (int)(evictedKey & mask); key1 = keyTable[index1]; if (key1 == EMPTY) { keyTable[index1] = evictedKey; valueTable[index1] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index2 = hash2(evictedKey); key2 = keyTable[index2]; if (key2 == EMPTY) { keyTable[index2] = evictedKey; valueTable[index2] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } index3 = hash3(evictedKey); key3 = keyTable[index3]; if (key3 == EMPTY) { keyTable[index3] = evictedKey; valueTable[index3] = evictedValue; if (size++ >= threshold) resize(capacity << 1); return; } if (++i == pushIterations) break; insertKey = evictedKey; insertValue = evictedValue; } while (true); putStash(evictedKey, evictedValue); } private void putStash (long key, V value) { if (stashSize == stashCapacity) { // Too many pushes occurred and the stash is full, increase the table size. resize(capacity << 1); put(key, value); return; } // Store key in the stash. int index = capacity + stashSize; keyTable[index] = key; valueTable[index] = value; stashSize++; size++; } public V get (long key) { if (key == 0) { if (!hasZeroValue) return null; return zeroValue; } int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, null); } } return valueTable[index]; } public V get (long key, V defaultValue) { if (key == 0) { if (!hasZeroValue) return defaultValue; return zeroValue; } int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return getStash(key, defaultValue); } } return valueTable[index]; } private V getStash (long key, V defaultValue) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return valueTable[i]; return defaultValue; } public V remove (long key) { if (key == 0) { if (!hasZeroValue) return null; V oldValue = zeroValue; zeroValue = null; hasZeroValue = false; size--; return oldValue; } int index = (int)(key & mask); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash2(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } index = hash3(key); if (keyTable[index] == key) { keyTable[index] = EMPTY; V oldValue = valueTable[index]; valueTable[index] = null; size--; return oldValue; } return removeStash(key); } V removeStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) { if (keyTable[i] == key) { V oldValue = valueTable[i]; removeStashIndex(i); size--; return oldValue; } } return null; } void removeStashIndex (int index) { // If the removed location was not last, move the last tuple to the removed location. stashSize--; int lastIndex = capacity + stashSize; if (index < lastIndex) { keyTable[index] = keyTable[lastIndex]; valueTable[index] = valueTable[lastIndex]; valueTable[lastIndex] = null; } else valueTable[index] = null; } /** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is * done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */ public void shrink (int maximumCapacity) { if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity); if (size > maximumCapacity) maximumCapacity = size; if (capacity <= maximumCapacity) return; maximumCapacity = MathUtils.nextPowerOfTwo(maximumCapacity); resize(maximumCapacity); } /** Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger. */ public void clear (int maximumCapacity) { if (capacity <= maximumCapacity) { clear(); return; } zeroValue = null; hasZeroValue = false; size = 0; resize(maximumCapacity); } public void clear () { if (size == 0) return; long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = capacity + stashSize; i-- > 0;) { keyTable[i] = EMPTY; valueTable[i] = null; } size = 0; stashSize = 0; zeroValue = null; hasZeroValue = false; } /** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be * an expensive operation. */ public boolean containsValue (Object value, boolean identity) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return true; long[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return true; } else if (identity) { if (value == zeroValue) return true; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return true; } else { if (hasZeroValue && value.equals(zeroValue)) return true; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return true; } return false; } public boolean containsKey (long key) { if (key == 0) return hasZeroValue; int index = (int)(key & mask); if (keyTable[index] != key) { index = hash2(key); if (keyTable[index] != key) { index = hash3(key); if (keyTable[index] != key) return containsKeyStash(key); } } return true; } private boolean containsKeyStash (long key) { long[] keyTable = this.keyTable; for (int i = capacity, n = i + stashSize; i < n; i++) if (keyTable[i] == key) return true; return false; } /** Returns the key for the specified value, or <tt>notFound</tt> if it is not in the map. Note this traverses the entire map * and compares every value, which may be an expensive operation. * @param identity If true, uses == to compare the specified value with values in the map. If false, uses * {@link #equals(Object)}. */ public long findKey (Object value, boolean identity, long notFound) { V[] valueTable = this.valueTable; if (value == null) { if (hasZeroValue && zeroValue == null) return 0; long[] keyTable = this.keyTable; for (int i = capacity + stashSize; i-- > 0;) if (keyTable[i] != EMPTY && valueTable[i] == null) return keyTable[i]; } else if (identity) { if (value == zeroValue) return 0; for (int i = capacity + stashSize; i-- > 0;) if (valueTable[i] == value) return keyTable[i]; } else { if (hasZeroValue && value.equals(zeroValue)) return 0; for (int i = capacity + stashSize; i-- > 0;) if (value.equals(valueTable[i])) return keyTable[i]; } return notFound; } /** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many * items to avoid multiple backing array resizes. */ public void ensureCapacity (int additionalCapacity) { int sizeNeeded = size + additionalCapacity; if (sizeNeeded >= threshold) resize(MathUtils.nextPowerOfTwo((int)Math.ceil(sizeNeeded / loadFactor))); } private void resize (int newSize) { int oldEndIndex = capacity + stashSize; capacity = newSize; threshold = (int)(newSize * loadFactor); mask = newSize - 1; hashShift = 63 - Long.numberOfTrailingZeros(newSize); stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize)) * 2); pushIterations = Math.max(Math.min(newSize, 8), (int)Math.sqrt(newSize) / 8); long[] oldKeyTable = keyTable; V[] oldValueTable = valueTable; keyTable = new long[newSize + stashCapacity]; valueTable = (V[])new Object[newSize + stashCapacity]; int oldSize = size; size = hasZeroValue ? 1 : 0; stashSize = 0; if (oldSize > 0) { for (int i = 0; i < oldEndIndex; i++) { long key = oldKeyTable[i]; if (key != EMPTY) putResize(key, oldValueTable[i]); } } } private int hash2 (long h) { h *= PRIME2; return (int)((h ^ h >>> hashShift) & mask); } private int hash3 (long h) { h *= PRIME3; return (int)((h ^ h >>> hashShift) & mask); } public int hashCode () { int h = 0; if (hasZeroValue && zeroValue != null) { h += zeroValue.hashCode(); } long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = 0, n = capacity + stashSize; i < n; i++) { long key = keyTable[i]; if (key != EMPTY) { h += (int)(key ^ (key >>> 32)) * 31; V value = valueTable[i]; if (value != null) { h += value.hashCode(); } } } return h; } public boolean equals (Object obj) { if (obj == this) return true; if (!(obj instanceof LongMap)) return false; LongMap<V> other = (LongMap)obj; if (other.size != size) return false; if (other.hasZeroValue != hasZeroValue) return false; if (hasZeroValue) { if (other.zeroValue == null) { if (zeroValue != null) return false; } else { if (!other.zeroValue.equals(zeroValue)) return false; } } long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; for (int i = 0, n = capacity + stashSize; i < n; i++) { long key = keyTable[i]; if (key != EMPTY) { V value = valueTable[i]; if (value == null) { if (!other.containsKey(key) || other.get(key) != null) { return false; } } else { if (!value.equals(other.get(key))) { return false; } } } } return true; } public String toString () { if (size == 0) return "[]"; StringBuilder buffer = new StringBuilder(32); buffer.append('['); long[] keyTable = this.keyTable; V[] valueTable = this.valueTable; int i = keyTable.length; while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); break; } while (i-- > 0) { long key = keyTable[i]; if (key == EMPTY) continue; buffer.append(", "); buffer.append(key); buffer.append('='); buffer.append(valueTable[i]); } buffer.append(']'); return buffer.toString(); } public Iterator<Entry<V>> iterator () { return entries(); } /** Returns an iterator for the entries in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Entries<V> entries () { if (entries1 == null) { entries1 = new Entries(this); entries2 = new Entries(this); } if (!entries1.valid) { entries1.reset(); entries1.valid = true; entries2.valid = false; return entries1; } entries2.reset(); entries2.valid = true; entries1.valid = false; return entries2; } /** Returns an iterator for the values in the map. Remove is supported. Note that the same iterator instance is returned each * time this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Values<V> values () { if (values1 == null) { values1 = new Values(this); values2 = new Values(this); } if (!values1.valid) { values1.reset(); values1.valid = true; values2.valid = false; return values1; } values2.reset(); values2.valid = true; values1.valid = false; return values2; } /** Returns an iterator for the keys in the map. Remove is supported. Note that the same iterator instance is returned each time * this method is called. Use the {@link Entries} constructor for nested or multithreaded iteration. */ public Keys keys () { if (keys1 == null) { keys1 = new Keys(this); keys2 = new Keys(this); } if (!keys1.valid) { keys1.reset(); keys1.valid = true; keys2.valid = false; return keys1; } keys2.reset(); keys2.valid = true; keys1.valid = false; return keys2; } static public class Entry<V> { public long key; public V value; public String toString () { return key + "=" + value; } } static private class MapIterator<V> { static final int INDEX_ILLEGAL = -2; static final int INDEX_ZERO = -1; public boolean hasNext; final LongMap<V> map; int nextIndex, currentIndex; boolean valid = true; public MapIterator (LongMap<V> map) { this.map = map; reset(); } public void reset () { currentIndex = INDEX_ILLEGAL; nextIndex = INDEX_ZERO; if (map.hasZeroValue) hasNext = true; else findNextIndex(); } void findNextIndex () { hasNext = false; long[] keyTable = map.keyTable; for (int n = map.capacity + map.stashSize; ++nextIndex < n;) { if (keyTable[nextIndex] != EMPTY) { hasNext = true; break; } } } public void remove () { if (currentIndex == INDEX_ZERO && map.hasZeroValue) { map.zeroValue = null; map.hasZeroValue = false; } else if (currentIndex < 0) { throw new IllegalStateException("next must be called before remove."); } else if (currentIndex >= map.capacity) { map.removeStashIndex(currentIndex); nextIndex = currentIndex - 1; findNextIndex(); } else { map.keyTable[currentIndex] = EMPTY; map.valueTable[currentIndex] = null; } currentIndex = INDEX_ILLEGAL; map.size--; } } static public class Entries<V> extends MapIterator<V> implements Iterable<Entry<V>>, Iterator<Entry<V>> { private Entry<V> entry = new Entry(); public Entries (LongMap map) { super(map); } /** Note the same entry instance is returned each time this method is called. */ public Entry<V> next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); long[] keyTable = map.keyTable; if (nextIndex == INDEX_ZERO) { entry.key = 0; entry.value = map.zeroValue; } else { entry.key = keyTable[nextIndex]; entry.value = map.valueTable[nextIndex]; } currentIndex = nextIndex; findNextIndex(); return entry; } public boolean hasNext () { if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); return hasNext; } public Iterator<Entry<V>> iterator () { return this; } public void remove () { super.remove(); } } static public class Values<V> extends MapIterator<V> implements Iterable<V>, Iterator<V> { public Values (LongMap<V> map) { super(map); } public boolean hasNext () { if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); return hasNext; } public V next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); V value; if (nextIndex == INDEX_ZERO) value = map.zeroValue; else value = map.valueTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return value; } public Iterator<V> iterator () { return this; } /** Returns a new array containing the remaining values. */ public Array<V> toArray () { Array array = new Array(true, map.size); while (hasNext) array.add(next()); return array; } public void remove () { super.remove(); } } static public class Keys extends MapIterator { public Keys (LongMap map) { super(map); } public long next () { if (!hasNext) throw new NoSuchElementException(); if (!valid) throw new GdxRuntimeException("#iterator() cannot be used nested."); long key = nextIndex == INDEX_ZERO ? 0 : map.keyTable[nextIndex]; currentIndex = nextIndex; findNextIndex(); return key; } /** Returns a new array containing the remaining values. */ public LongArray toArray () { LongArray array = new LongArray(true, map.size); while (hasNext) array.add(next()); return array; } } }
23,770
Java
.java
755
27.984106
129
0.672834
Lux-Vacuos/LightEngine
4
0
5
GPL-3.0
9/4/2024, 11:03:47 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
23,770
61,697
SkeletonHorse.java
Luohuayu_CatServer/src/main/java/org/bukkit/entity/SkeletonHorse.java
package org.bukkit.entity; /** * Represents a SkeletonHorse - variant of {@link AbstractHorse}. */ public interface SkeletonHorse extends AbstractHorse { }
159
Java
.java
5
30.2
65
0.784314
Luohuayu/CatServer
1,967
211
97
LGPL-3.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
159
1,319,446
A_test733.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/return_out/A_test733.java
package return_in; public class A_test733 { public int foo() { return extracted(); } protected int extracted() { /*[*/ int x = 1; if (x > 0) { throw new IllegalArgumentException(); } return x; /*]*/ } }
227
Java
.java
15
12.533333
40
0.62201
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
227
1,317,243
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testFail82/in/A.java
package p; class A{} class X{ class B extends A{} }
52
Java
.java
5
9.4
20
0.708333
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
52
1,319,515
A_test121.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/invalidSelection/A_test121.java
package invalidSelection; public class A_test121 { public void foo() { int x= 1; int y= 2; /*]*/x= y + x; y= x + y;/*[*/ x++; y++; } }
155
Java
.java
11
11.272727
25
0.528986
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
155
1,315,990
B.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test10/in/B.java
// 9, 28 -> 9, 37 replaceAll == false package p2; import p1.A; class B { public static void main(String[] args) { System.out.println(A.ELYSIUM); } }
158
Java
.java
8
17.75
41
0.668919
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
158
1,316,368
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenamePrivateMethod/test10/in/A.java
package p; //renaming A.m to k class A { private void m(){} } class B { void m(){} }
86
Java
.java
8
9.625
19
0.632911
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
86
3,068,768
SFTPFileSystemPolicyXMLHandler.java
Tostis_areca/src/main/java/com/application/areca/adapters/SFTPFileSystemPolicyXMLHandler.java
package com.application.areca.adapters; import org.w3c.dom.Node; import com.application.areca.AbstractTarget; import com.application.areca.adapters.read.TargetXMLReader; import com.application.areca.impl.policy.FileSystemPolicy; import com.application.areca.impl.policy.SFTPFileSystemPolicy; import com.myJava.util.xml.AdapterException; import com.myJava.util.xml.XMLTool; /** * Serializer/Deserializer for SFTPFileSystemPolicy instances. * <BR> * @author Olivier PETRUCCI * <BR> * */ /* Copyright 2005-2015, Olivier PETRUCCI. This file is part of Areca. Areca is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Areca is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Areca; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class SFTPFileSystemPolicyXMLHandler extends AbstractFileSystemPolicyXMLHandler { public static final String POLICY_SFTP = "sftp"; public static final String XML_MEDIUM_SFTP_LOGIN = "sftp_login"; public static final String XML_MEDIUM_SFTP_PASSWORD = "sftp_password"; public static final String XML_MEDIUM_SFTP_HOST = "sftp_host"; public static final String XML_MEDIUM_SFTP_PORT = "sftp_port"; public static final String XML_MEDIUM_SFTP_REMOTEDIR= "sftp_remotedir"; public static final String XML_MEDIUM_SFTP_HOSTKEY= "sftp_hostkey"; public static final String XML_MEDIUM_SFTP_CHECK_HOSTKEY= "sftp_check_hostkey"; public static final String XML_MEDIUM_SFTP_USE_CERT= "sftp_use_certificate"; public static final String XML_MEDIUM_SFTP_CERT= "sftp_certificate_path"; public static final String XML_MEDIUM_SFTP_ENC_CERT= "sftp_encrypted_cert"; public FileSystemPolicy read( Node mediumNode, AbstractTarget target, TargetXMLReader reader ) throws AdapterException { Node serverNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_HOST); Node portNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_PORT); Node loginNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_LOGIN); Node dirNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_REMOTEDIR); Node nameNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_ARCHIVENAME); Node hkNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_HOSTKEY); Node checkhkNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_CHECK_HOSTKEY); Node encryptedCertNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_ENC_CERT); Node useCertNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_USE_CERT); Node certNode = mediumNode.getAttributes().getNamedItem(XML_MEDIUM_SFTP_CERT); // No storage policy found if (serverNode == null && portNode == null && loginNode == null && dirNode == null) { throw new AdapterException("Medium storage policy not found : your medium must have either a '" + XML_MEDIUM_PATH + "' attribute or SFTP attributes (" + XML_MEDIUM_FTP_HOST + ", " + XML_MEDIUM_FTP_LOGIN + ", " + XML_MEDIUM_FTP_PASSWORD + " ...)"); } // SFTP policy initialization if (serverNode == null) { throw new AdapterException("SFTP host not found : your medium must have a '" + XML_MEDIUM_SFTP_HOST + "' attribute."); } if (portNode == null) { throw new AdapterException("SFTP remote port not found : your medium must have a '" + XML_MEDIUM_SFTP_PORT + "' attribute."); } boolean encryptedCert = encryptedCertNode != null && encryptedCertNode.getNodeValue().equalsIgnoreCase("true"); boolean checkHostKey = checkhkNode != null && checkhkNode.getNodeValue().equalsIgnoreCase("true"); if (checkHostKey && hkNode == null) { throw new AdapterException("SFTP hostkey not found : your medium must have a '" + XML_MEDIUM_SFTP_HOSTKEY + "' attribute."); } if (loginNode == null) { throw new AdapterException("SFTP login not found : your medium must have a '" + XML_MEDIUM_SFTP_LOGIN + "' attribute."); } if (dirNode == null) { throw new AdapterException("SFTP remote directory not found : your medium must have a '" + XML_MEDIUM_SFTP_REMOTEDIR + "' attribute."); } boolean useCert = useCertNode != null && useCertNode.getNodeValue().equalsIgnoreCase("true"); if (useCert && certNode == null) { throw new AdapterException("SFTP certificate path not found : your medium must have a '" + XML_MEDIUM_SFTP_CERT + "' attribute."); } SFTPFileSystemPolicy policy = new SFTPFileSystemPolicy(); policy.setUseCertificateAuth(useCert); policy.setCertificateFileName(certNode == null ? null : certNode.getNodeValue()); policy.setRemoteServer(serverNode.getNodeValue()); policy.setRemotePort(Integer.parseInt(portNode.getNodeValue())); policy.setLogin(loginNode.getNodeValue()); policy.setCheckHostKey(checkHostKey); policy.setEncryptedCert(encryptedCert); if (hkNode != null) { policy.setHostKey(hkNode.getNodeValue()); } String password = XMLTool.extractPassword(XML_MEDIUM_SFTP_PASSWORD, mediumNode); if (password != null) { // Standard case policy.setPassword(password); } else if ((! useCert) || encryptedCert ) { // SFTP Password missing if (reader.getMissingDataListener() != null) { Object[] sftpData = (Object[])reader.getMissingDataListener().missingFTPDataDetected(target, reader.getSource()); if (sftpData != null) { policy.setPassword((String)sftpData[0]); } } if (policy.getPassword() == null || policy.getPassword().trim().length() == 0) { // Second check .... after missingDataListener invocation. throw new AdapterException("No SFTP password found : your medium must have a '" + XML_MEDIUM_SFTP_PASSWORD + "' attribute."); } } policy.setRemoteDirectory(dirNode.getNodeValue()); policy.setId(POLICY_SFTP); policy.setArchiveName(nameNode.getNodeValue()); return policy; } public void write( FileSystemPolicy source, boolean removeSensitiveData, StringBuffer sb) { SFTPFileSystemPolicy policy = (SFTPFileSystemPolicy)source; sb.append(XMLTool.encodeProperty(XML_MEDIUM_ARCHIVENAME, policy.getArchiveName())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_HOST, policy.getRemoteServer())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_PORT, policy.getRemotePort())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_HOSTKEY, policy.getHostKey())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_CHECK_HOSTKEY, policy.isCheckHostKey())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_LOGIN, policy.getLogin())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_USE_CERT, policy.isUseCertificateAuth())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_CERT, policy.getCertificateFileName())); sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_ENC_CERT, policy.isEncryptedCert())); if (! removeSensitiveData) { sb.append(XMLTool.encodePassword(XML_MEDIUM_SFTP_PASSWORD, policy.getPassword())); } sb.append(XMLTool.encodeProperty(XML_MEDIUM_SFTP_REMOTEDIR, policy.getRemoteDirectory())); } }
8,171
Java
.java
136
51.397059
271
0.700355
Tostis/areca
5
0
3
GPL-2.0
9/4/2024, 10:46:08 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
8,171
1,317,070
B.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testFail96/in/B.java
package p1; import p2.*; public class B extends C { }
54
Java
.java
4
12.5
26
0.74
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
54
2,044,641
CursorValue.java
AstroImageJ_astroimagej/Nom_Fits/src/main/java/nom/tam/util/CursorValue.java
package nom.tam.util; /* * #%L * nom.tam FITS library * %% * Copyright (C) 1996 - 2024 nom-tam-fits * %% * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * 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 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. * #L% */ /** * Interface for cursor-based access to keys * * @param <T> The generic type of key that this cursor uses */ public interface CursorValue<T> { /** * Returns the key at the current cursor position * * @return the key at the current cursor position */ T getKey(); }
1,635
Java
.java
44
34.681818
74
0.741814
AstroImageJ/astroimagej
13
10
36
GPL-3.0
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,635
1,320,594
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/test11/in/A.java
//renaming I.m to k package p; interface I{ void m(); } interface I2{ void m(); } interface I3 extends I, I2{ }
111
Java
.java
10
10.2
27
0.715686
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
111
1,314,938
Foo.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test05/in/Foo.java
package p; public class Foo extends Bar { // Test correct "thisification". void foo() { X x= new X() { { getDisplay(); // <- invoke here } }; } } class X { }
189
Java
.java
13
11.153846
35
0.58642
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
189
1,317,251
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testFail61/in/A.java
package p; class A{ } class X{ class B{ } boolean m(Object o){ return o instanceof A; } }
96
Java
.java
10
8
24
0.686047
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
96
1,317,784
A_test115_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test115_in.java
package p; //7, 17, 7, 22 public class A { void m() { int x = 9; int y = 10; int j = x + y + (x + y); } }
139
Java
.java
8
12.25
32
0.384615
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
139
1,710,781
ICommand.java
andrew-nguyen_ucanaccess/src/main/java/net/ucanaccess/commands/ICommand.java
/* Copyright (c) 2012 Marco Amadei. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA You can contact Marco Amadei at amadei.mar@gmail.com. */ package net.ucanaccess.commands; import java.sql.SQLException; public interface ICommand { public enum TYPES { COMPOSITE, DDL, DELETE, INSERT, UPDATE }; public String getExecId(); public String getTableName(); public TYPES getType(); public IFeedbackAction persist() throws SQLException; public IFeedbackAction rollback() throws SQLException; }
1,162
Java
.java
28
39.5
68
0.808969
andrew-nguyen/ucanaccess
13
10
1
LGPL-2.1
9/4/2024, 8:15:43 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,162
4,906,161
DefaultStartExi.java
aryantaheri_controller/opendaylight/netconf/netconf-impl/src/main/java/org/opendaylight/controller/netconf/impl/mapping/operations/DefaultStartExi.java
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.netconf.impl.mapping.operations; import org.opendaylight.controller.netconf.api.NetconfDocumentedException; import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity; import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag; import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType; import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants; import org.opendaylight.controller.netconf.api.NetconfMessage; import org.opendaylight.controller.netconf.impl.NetconfServerSession; import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution; import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation; import org.opendaylight.controller.netconf.util.xml.XmlElement; import org.opendaylight.controller.netconf.util.xml.XmlUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; public class DefaultStartExi extends AbstractSingletonNetconfOperation implements DefaultNetconfOperation { public static final String START_EXI = "start-exi"; private static final Logger logger = LoggerFactory.getLogger(DefaultStartExi.class); private NetconfServerSession netconfSession; public DefaultStartExi(String netconfSessionIdForReporting) { super(netconfSessionIdForReporting); } @Override public Document handle(Document message, NetconfOperationChainedExecution subsequentOperation) throws NetconfDocumentedException { logger.debug("Received start-exi message {} ", XmlUtil.toString(message)); try { netconfSession.startExiCommunication(new NetconfMessage(message)); } catch (IllegalArgumentException e) { throw new NetconfDocumentedException("Failed to parse EXI parameters", ErrorType.protocol, ErrorTag.operation_failed, ErrorSeverity.error); } return super.handle(message, subsequentOperation); } @Override protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws NetconfDocumentedException { Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK); logger.trace("{} operation successful", START_EXI); return getSchemaResult; } @Override protected String getOperationName() { return START_EXI; } @Override protected String getOperationNamespace() { return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0; } @Override public void setNetconfSession(NetconfServerSession s) { netconfSession = s; } }
3,217
Java
.java
61
46.262295
146
0.775191
aryantaheri/controller
1
0
0
EPL-1.0
9/5/2024, 12:35:26 AM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
3,217
4,474,759
GetMine.java
GeoscienceAustralia_FSDF-Metadata-Tool/services/src/main/java/org/fao/geonet/guiservices/groups/GetMine.java
//============================================================================= //=== Copyright (C) 2001-2007 Food and Agriculture Organization of the //=== United Nations (FAO-UN), United Nations World Food Programme (WFP) //=== and United Nations Environment Programme (UNEP) //=== //=== This program is free software; you can redistribute it and/or modify //=== it under the terms of the GNU General Public License as published by //=== the Free Software Foundation; either version 2 of the License, or (at //=== your option) any later version. //=== //=== This program is distributed in the hope that it will be useful, but //=== WITHOUT ANY WARRANTY; without even the implied warranty of //=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //=== General Public License for more details. //=== //=== You should have received a copy of the GNU General Public License //=== along with this program; if not, write to the Free Software //=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA //=== //=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, //=== Rome - Italy. email: geonetwork@osgeo.org //============================================================================== package org.fao.geonet.guiservices.groups; import jeeves.interfaces.Service; import jeeves.server.ServiceConfig; import jeeves.server.UserSession; import jeeves.server.context.ServiceContext; import org.fao.geonet.constants.Geonet; import org.fao.geonet.domain.Group_; import org.fao.geonet.domain.Profile; import org.fao.geonet.domain.UserGroup; import org.fao.geonet.lib.Lib; import org.fao.geonet.repository.GroupRepository; import org.fao.geonet.repository.SortUtils; import org.fao.geonet.repository.UserGroupRepository; import org.fao.geonet.repository.specification.GroupSpecs; import org.fao.geonet.repository.specification.UserGroupSpecs; import org.jdom.Element; import org.springframework.data.jpa.domain.Specifications; import java.nio.file.Path; import java.util.HashSet; import java.util.List; import static org.springframework.data.jpa.domain.Specifications.not; import static org.springframework.data.jpa.domain.Specifications.where; //============================================================================= /** * Service used to return all groups in the system */ public class GetMine implements Service { String profile; public void init(Path appPath, ServiceConfig params) throws Exception { profile = params.getValue("profile"); } //-------------------------------------------------------------------------- //--- //--- Service //--- //-------------------------------------------------------------------------- public Element exec(Element params, ServiceContext context) throws Exception { UserSession session = context.getUserSession(); if (!session.isAuthenticated()) { return new Element(Geonet.Elem.GROUPS); } //--- retrieve user groups if (Profile.Administrator == session.getProfile()) { return context.getBean(GroupRepository.class).findAllAsXml(not(GroupSpecs.isReserved())); } else { final UserGroupRepository userGroupRepository = context.getBean(UserGroupRepository.class); int userId = session.getUserIdAsInt(); Specifications<UserGroup> spec = where(UserGroupSpecs.isReservedGroup(false)).and(UserGroupSpecs.hasUserId(userId)); if (profile != null) { spec = spec.and(UserGroupSpecs.hasProfile(Profile.findProfileIgnoreCase(profile))); } List<Integer> ids = userGroupRepository.findGroupIds(spec); Element groups = context.getBean(GroupRepository.class).findAllAsXml(SortUtils.createSort(Group_.id)); return Lib.element.pruneChildren(groups, new HashSet<Integer>(ids)); } } } //=============================================================================
3,999
Java
.java
80
45.7125
128
0.647858
GeoscienceAustralia/FSDF-Metadata-Tool
2
0
0
GPL-2.0
9/5/2024, 12:14:28 AM (Europe/Amsterdam)
false
false
false
true
false
false
false
true
3,999
4,324,598
TelegraphButtonAction.java
bfetter1234_Mars-Sim-Alpha/mars-sim-ui/src/main/java/org/mars_sim/msp/ui/swing/notification/TelegraphButtonAction.java
/* * JTelegraph -- a Java message notification library * Copyright (c) 2012, Paulo Roberto Massa Cereda * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.mars_sim.msp.ui.swing.notification; /** * This interface allows to define an action to execute while clicking on the * button of a {@link Telegraph} object. It consists in a simple way to ask * JTelegraph to process something while clicking on the button... * * Please take in consideration that your action is blocking for the other * notifications, so if you'd like to execute something which takes time, please * use threads... * * @author Antoine Neveux * @version 2.1 * @since 2.1 * */ public interface TelegraphButtonAction { /** * - Captain Obvious! Please help us understand! * * - Quite easy to solve this one! Just implement something that does * something! */ public void doSomething(); }
2,436
Java
.java
57
40.649123
80
0.754836
bfetter1234/Mars-Sim-Alpha
2
0
0
GPL-3.0
9/5/2024, 12:09:08 AM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
2,436
1,317,307
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test63/in/anotherp/A.java
package another.p; /** * See also another.p.A {@link another.p.A} and p.A, and A. * @see another.p.A */ public class A { String a= "A"; String pA= "p.A"; String anotherpA= "another.p.A"; }
196
Java
.java
10
17.9
59
0.643243
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
196
1,314,898
Bar.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test27/out/Bar.java
package p1; import p0.Foo; public class Bar { /** * @param foo */ public static void bar(Foo foo) { foo.foo(); } }
128
Java
.java
10
10.5
34
0.640351
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
128
4,537,345
SplashScreen.java
SergioFLS_lampiro-fork/src/it/yup/screens/SplashScreen.java
// #condition !UI //@/* Copyright (c) 2008-2009-2010 Bluendo S.r.L. //@ * See about.html for details about license. //@ * //@ * $Id: SplashScreen.java 2310 2010-11-04 12:18:13Z luca $ //@*/ //@ //@package it.yup.screens; //@ //@import java.util.TimerTask; //@ //@import it.yup.util.Utils; //@ //@import javax.microedition.lcdui.Canvas; //@import javax.microedition.lcdui.Font; //@import javax.microedition.lcdui.Graphics; //@import javax.microedition.lcdui.Image; //@ //@import lampiro.LampiroMidlet; //@ //@public class SplashScreen extends Canvas { //@ //@ private Image logo; //@ // private String message = null; //@ //@ private boolean first_time = true; //@ //@ public SplashScreen() { //@ try { //@ logo = Image.createImage("/icons/lampiro_icon.png"); //@ } catch(Exception ex) { } //@ } //@ //@ protected void paint(Graphics g) { //@ //@ //@ int w = g.getClipWidth(); //@ int h = g.getClipHeight(); //@ //@ setTitle("Lampiro"); //@ //@ Font f = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE); //@ g.setColor(0xCBDBE3); //@ g.fillRect(0, 0, w, h); //@ g.setFont(f); //@ //@// if(message != null) { //@// g.setColor(0x00FC9A13); //@// g.drawString(message, 0, 0, Graphics.TOP | Graphics.LEFT); //@// } //@ //@ // compute text heigth //@ int text_height = f.getHeight(); //@ int hspacing = (h - text_height - logo.getHeight()) / 3; //@ //@ if(text_height + logo.getHeight() <= h) { //@ g.setColor(0x00FC9A13); //@ g.drawImage(logo, w/2, hspacing, Graphics.TOP | Graphics.HCENTER); //@ g.drawString("Loading Lampiro...", w/2, hspacing *2 + logo.getHeight(), Graphics.TOP | Graphics.HCENTER); //@ } else { //@ g.drawImage(logo, w/2, h/2, Graphics.VCENTER | Graphics.HCENTER); //@ } //@ //@ if(first_time) { //@ first_time = false; //@ Utils.tasks.schedule(new TimerTask() { //@ public void run() { //@ RegisterScreen rgs = RegisterScreen.getInstance(); //@ LampiroMidlet.disp.setCurrent(rgs); //@ } //@ //@ }, 3000); //@ } //@ } //@ //@ protected void keyPressed(int kc) { //@ // message = getKeyName(kc); //@ repaint(); //@ } //@}
2,251
Java
.java
80
26.525
115
0.584523
SergioFLS/lampiro-fork
2
0
0
GPL-2.0
9/5/2024, 12:16:26 AM (Europe/Amsterdam)
true
true
true
true
true
true
true
true
2,251
1,487,035
ArrayAccessNode.java
stg-tud_MUDetect/aug/src/main/java/de/tu_darmstadt/stg/mudetect/aug/model/actions/ArrayAccessNode.java
package de.tu_darmstadt.stg.mudetect.aug.model.actions; import de.tu_darmstadt.stg.mudetect.aug.visitors.NodeVisitor; public class ArrayAccessNode extends MethodCallNode { public ArrayAccessNode(String arrayTypeName) { super(arrayTypeName, "arrayget()"); } public ArrayAccessNode(String arrayTypeName, int sourceLineNumber) { super(arrayTypeName, "arrayget()", sourceLineNumber); } @Override public boolean isCoreAction() { return false; } @Override public <R> R apply(NodeVisitor<R> visitor) { return visitor.visit(this); } }
604
Java
.java
18
28.277778
72
0.719449
stg-tud/MUDetect
24
8
16
MPL-2.0
9/4/2024, 7:53:45 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
604
3,199,156
ConcatenationTest.java
aitoralmeida_c4a_data_repository/LinkedDataInterface/src/ruleEngine/test/de/fuberlin/wiwiss/d2rq/expr/ConcatenationTest.java
package de.fuberlin.wiwiss.d2rq.expr; import java.util.Arrays; import java.util.Collections; import junit.framework.TestCase; import de.fuberlin.wiwiss.d2rq.algebra.Attribute; public class ConcatenationTest extends TestCase { public void testCreateEmpty() { assertEquals(new Constant(""), Concatenation.create(Collections.<Expression>emptyList())); } public void testCreateOnePart() { Expression expr = new AttributeExpr(new Attribute(null, "table", "col")); assertEquals(expr, Concatenation.create(Collections.singletonList(expr))); } public void testTwoParts() { Expression expr1 = new Constant("mailto:"); Expression expr2 = new AttributeExpr(new Attribute(null, "user", "email")); Expression concat = Concatenation.create(Arrays.asList(new Expression[]{expr1, expr2})); assertEquals("Concatenation(Constant(mailto:), AttributeExpr(@@user.email@@))", concat.toString()); } public void testFilterEmptyParts() { Expression empty = new Constant(""); Expression expr1 = new Constant("aaa"); assertEquals(expr1, Concatenation.create(Arrays.asList( new Expression[]{empty, empty, expr1, empty}))); } }
1,145
Java
.java
27
39.703704
92
0.768051
aitoralmeida/c4a_data_repository
4
2
7
GPL-3.0
9/4/2024, 11:04:39 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
1,145
285,900
UPCEReader.java
iluhcm_QrCodeScanner/zxing/src/main/java/com/google/zxing/oned/UPCEReader.java
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * <p>Implements decoding of the UPC-E format.</p> * <p><a href="http://www.barcodeisland.com/upce.phtml">This</a> is a great reference for * UPC-E information.</p> * * @author Sean Owen */ public final class UPCEReader extends UPCEANReader { /** * The pattern that marks the middle, and end, of a UPC-E pattern. * There is no "second half" to a UPC-E barcode. */ private static final int[] MIDDLE_END_PATTERN = {1, 1, 1, 1, 1, 1}; // For an UPC-E barcode, the final digit is represented by the parities used // to encode the middle six digits, according to the table below. // // Parity of next 6 digits // Digit 0 1 2 3 4 5 // 0 Even Even Even Odd Odd Odd // 1 Even Even Odd Even Odd Odd // 2 Even Even Odd Odd Even Odd // 3 Even Even Odd Odd Odd Even // 4 Even Odd Even Even Odd Odd // 5 Even Odd Odd Even Even Odd // 6 Even Odd Odd Odd Even Even // 7 Even Odd Even Odd Even Odd // 8 Even Odd Even Odd Odd Even // 9 Even Odd Odd Even Odd Even // // The encoding is represented by the following array, which is a bit pattern // using Odd = 0 and Even = 1. For example, 5 is represented by: // // Odd Even Even Odd Odd Even // in binary: // 0 1 1 0 0 1 == 0x19 // /** * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of * even-odd parity encodings of digits that imply both the number system (0 or 1) * used, and the check digit. */ static final int[][] NUMSYS_AND_CHECK_DIGIT_PATTERNS = { {0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25}, {0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A} }; private final int[] decodeMiddleCounters; public UPCEReader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); result.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (5 - x); } } determineNumSysAndCheckDigit(result, lgPatternFound); return rowOffset; } @Override protected int[] decodeEnd(BitArray row, int endStart) throws NotFoundException { return findGuardPattern(row, endStart, true, MIDDLE_END_PATTERN); } @Override protected boolean checkChecksum(String s) throws FormatException { return super.checkChecksum(convertUPCEtoUPCA(s)); } private static void determineNumSysAndCheckDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException { for (int numSys = 0; numSys <= 1; numSys++) { for (int d = 0; d < 10; d++) { if (lgPatternFound == NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) { resultString.insert(0, (char) ('0' + numSys)); resultString.append((char) ('0' + d)); return; } } } throw NotFoundException.getNotFoundInstance(); } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.UPC_E; } /** * Expands a UPC-E value back into its full, equivalent UPC-A code value. * * @param upce UPC-E code as string of digits * @return equivalent UPC-A code as string of digits */ public static String convertUPCEtoUPCA(String upce) { char[] upceChars = new char[6]; upce.getChars(1, 7, upceChars, 0); StringBuilder result = new StringBuilder(12); result.append(upce.charAt(0)); char lastChar = upceChars[5]; switch (lastChar) { case '0': case '1': case '2': result.append(upceChars, 0, 2); result.append(lastChar); result.append("0000"); result.append(upceChars, 2, 3); break; case '3': result.append(upceChars, 0, 3); result.append("00000"); result.append(upceChars, 3, 2); break; case '4': result.append(upceChars, 0, 4); result.append("00000"); result.append(upceChars[4]); break; default: result.append(upceChars, 0, 5); result.append("0000"); result.append(lastChar); break; } // Only append check digit in conversion if supplied if (upce.length() >= 8) { result.append(upce.charAt(7)); } return result.toString(); } }
5,732
Java
.java
162
30.654321
98
0.636036
iluhcm/QrCodeScanner
445
126
5
GPL-3.0
9/4/2024, 7:06:16 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
5,732
4,490,935
BlockStateProvider.java
PatchworkMC_crabwork/src/main/forge/net/minecraftforge/client/model/generators/BlockStateProvider.java
/* * Minecraft Forge, Patchwork Project * Copyright (c) 2016-2020, 2019-2020 * * 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 version 2.1 * of the License. * * 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 net.minecraftforge.client.model.generators; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import javax.annotation.Nonnull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.DoorBlock; import net.minecraft.block.FenceBlock; import net.minecraft.block.FenceGateBlock; import net.minecraft.block.FourWayBlock; import net.minecraft.block.PaneBlock; import net.minecraft.block.RotatedPillarBlock; import net.minecraft.block.SixWayBlock; import net.minecraft.block.SlabBlock; import net.minecraft.block.StairsBlock; import net.minecraft.block.TrapDoorBlock; import net.minecraft.block.WallBlock; import net.minecraft.block.WallHeight; import net.minecraft.data.DataGenerator; import net.minecraft.data.DirectoryCache; import net.minecraft.data.IDataProvider; import net.minecraft.state.Property; import net.minecraft.state.properties.AttachFace; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.state.properties.DoorHingeSide; import net.minecraft.state.properties.DoubleBlockHalf; import net.minecraft.state.properties.Half; import net.minecraft.state.properties.SlabType; import net.minecraft.state.properties.StairsShape; import net.minecraft.util.Direction; import net.minecraft.util.Direction.Axis; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraft.util.ResourceLocation; /** * Data provider for blockstate files. Extends {@link BlockModelProvider} so that * blockstates and their referenced models can be provided in tandem. */ public abstract class BlockStateProvider implements IDataProvider { private static final Logger LOGGER = LogManager.getLogger(); private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); @VisibleForTesting protected final Map<Block, IGeneratedBlockstate> registeredBlocks = new LinkedHashMap<>(); private final DataGenerator generator; private final String modid; private final BlockModelProvider blockModels; private final ItemModelProvider itemModels; public BlockStateProvider(DataGenerator gen, String modid, ExistingFileHelper exFileHelper) { this.generator = gen; this.modid = modid; this.blockModels = new BlockModelProvider(gen, modid, exFileHelper) { @Override protected void registerModels() {} }; this.itemModels = new ItemModelProvider(gen, modid, this.blockModels.existingFileHelper) { @Override protected void registerModels() {} }; } @Override public void act(DirectoryCache cache) throws IOException { models().clear(); itemModels().clear(); registeredBlocks.clear(); registerStatesAndModels(); models().generateAll(cache); itemModels().generateAll(cache); for (Map.Entry<Block, IGeneratedBlockstate> entry : registeredBlocks.entrySet()) { saveBlockState(cache, entry.getValue().toJson(), entry.getKey()); } } protected abstract void registerStatesAndModels(); public VariantBlockStateBuilder getVariantBuilder(Block b) { if (registeredBlocks.containsKey(b)) { IGeneratedBlockstate old = registeredBlocks.get(b); Preconditions.checkState(old instanceof VariantBlockStateBuilder); return (VariantBlockStateBuilder) old; } else { VariantBlockStateBuilder ret = new VariantBlockStateBuilder(b); registeredBlocks.put(b, ret); return ret; } } public MultiPartBlockStateBuilder getMultipartBuilder(Block b) { if (registeredBlocks.containsKey(b)) { IGeneratedBlockstate old = registeredBlocks.get(b); Preconditions.checkState(old instanceof MultiPartBlockStateBuilder); return (MultiPartBlockStateBuilder) old; } else { MultiPartBlockStateBuilder ret = new MultiPartBlockStateBuilder(b); registeredBlocks.put(b, ret); return ret; } } public BlockModelProvider models() { return blockModels; } public ItemModelProvider itemModels() { return itemModels; } public ResourceLocation modLoc(String name) { return new ResourceLocation(modid, name); } public ResourceLocation mcLoc(String name) { return new ResourceLocation(name); } private String name(Block block) { return block.getRegistryName().getPath(); } public ResourceLocation blockTexture(Block block) { ResourceLocation name = block.getRegistryName(); return new ResourceLocation(name.getNamespace(), ModelProvider.BLOCK_FOLDER + "/" + name.getPath()); } private ResourceLocation extend(ResourceLocation rl, String suffix) { return new ResourceLocation(rl.getNamespace(), rl.getPath() + suffix); } public ModelFile cubeAll(Block block) { return models().cubeAll(name(block), blockTexture(block)); } public void simpleBlock(Block block) { simpleBlock(block, cubeAll(block)); } public void simpleBlock(Block block, Function<ModelFile, ConfiguredModel[]> expander) { simpleBlock(block, expander.apply(cubeAll(block))); } public void simpleBlock(Block block, ModelFile model) { simpleBlock(block, new ConfiguredModel(model)); } public void simpleBlockItem(Block block, ModelFile model) { itemModels().getBuilder(block.getRegistryName().getPath()).parent(model); } public void simpleBlock(Block block, ConfiguredModel... models) { getVariantBuilder(block) .partialState().setModels(models); } public void axisBlock(RotatedPillarBlock block) { axisBlock(block, blockTexture(block)); } public void logBlock(RotatedPillarBlock block) { axisBlock(block, blockTexture(block), extend(blockTexture(block), "_top")); } public void axisBlock(RotatedPillarBlock block, ResourceLocation baseName) { axisBlock(block, extend(baseName, "_side"), extend(baseName, "_end")); } public void axisBlock(RotatedPillarBlock block, ResourceLocation side, ResourceLocation end) { axisBlock(block, models().cubeColumn(name(block), side, end), models().cubeColumnHorizontal(name(block) + "_horizontal", side, end)); } public void axisBlock(RotatedPillarBlock block, ModelFile vertical, ModelFile horizontal) { getVariantBuilder(block) .partialState().with(RotatedPillarBlock.AXIS, Axis.Y) .modelForState().modelFile(vertical).addModel() .partialState().with(RotatedPillarBlock.AXIS, Axis.Z) .modelForState().modelFile(horizontal).rotationX(90).addModel() .partialState().with(RotatedPillarBlock.AXIS, Axis.X) .modelForState().modelFile(horizontal).rotationX(90).rotationY(90).addModel(); } private static final int DEFAULT_ANGLE_OFFSET = 180; public void horizontalBlock(Block block, ResourceLocation side, ResourceLocation front, ResourceLocation top) { horizontalBlock(block, models().orientable(name(block), side, front, top)); } public void horizontalBlock(Block block, ModelFile model) { horizontalBlock(block, model, DEFAULT_ANGLE_OFFSET); } public void horizontalBlock(Block block, ModelFile model, int angleOffset) { horizontalBlock(block, $ -> model, angleOffset); } public void horizontalBlock(Block block, Function<BlockState, ModelFile> modelFunc) { horizontalBlock(block, modelFunc, DEFAULT_ANGLE_OFFSET); } public void horizontalBlock(Block block, Function<BlockState, ModelFile> modelFunc, int angleOffset) { getVariantBuilder(block) .forAllStates(state -> ConfiguredModel.builder() .modelFile(modelFunc.apply(state)) .rotationY(((int) state.get(BlockStateProperties.HORIZONTAL_FACING).getHorizontalAngle() + angleOffset) % 360) .build() ); } public void horizontalFaceBlock(Block block, ModelFile model) { horizontalFaceBlock(block, model, DEFAULT_ANGLE_OFFSET); } public void horizontalFaceBlock(Block block, ModelFile model, int angleOffset) { horizontalFaceBlock(block, $ -> model, angleOffset); } public void horizontalFaceBlock(Block block, Function<BlockState, ModelFile> modelFunc) { horizontalFaceBlock(block, modelFunc, DEFAULT_ANGLE_OFFSET); } public void horizontalFaceBlock(Block block, Function<BlockState, ModelFile> modelFunc, int angleOffset) { getVariantBuilder(block) .forAllStates(state -> ConfiguredModel.builder() .modelFile(modelFunc.apply(state)) .rotationX(state.get(BlockStateProperties.FACE).ordinal() * 90) .rotationY((((int) state.get(BlockStateProperties.HORIZONTAL_FACING).getHorizontalAngle() + angleOffset) + (state.get(BlockStateProperties.FACE) == AttachFace.CEILING ? 180 : 0)) % 360) .build() ); } public void directionalBlock(Block block, ModelFile model) { directionalBlock(block, model, DEFAULT_ANGLE_OFFSET); } public void directionalBlock(Block block, ModelFile model, int angleOffset) { directionalBlock(block, $ -> model, angleOffset); } public void directionalBlock(Block block, Function<BlockState, ModelFile> modelFunc) { directionalBlock(block, modelFunc, DEFAULT_ANGLE_OFFSET); } public void directionalBlock(Block block, Function<BlockState, ModelFile> modelFunc, int angleOffset) { getVariantBuilder(block) .forAllStates(state -> { Direction dir = state.get(BlockStateProperties.FACING); return ConfiguredModel.builder() .modelFile(modelFunc.apply(state)) .rotationX(dir == Direction.DOWN ? 180 : dir.getAxis().isHorizontal() ? 90 : 0) .rotationY(dir.getAxis().isVertical() ? 0 : (((int) dir.getHorizontalAngle()) + angleOffset) % 360) .build(); }); } public void stairsBlock(StairsBlock block, ResourceLocation texture) { stairsBlock(block, texture, texture, texture); } public void stairsBlock(StairsBlock block, String name, ResourceLocation texture) { stairsBlock(block, name, texture, texture, texture); } public void stairsBlock(StairsBlock block, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) { stairsBlockInternal(block, block.getRegistryName().toString(), side, bottom, top); } public void stairsBlock(StairsBlock block, String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) { stairsBlockInternal(block, name + "_stairs", side, bottom, top); } private void stairsBlockInternal(StairsBlock block, String baseName, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) { ModelFile stairs = models().stairs(baseName, side, bottom, top); ModelFile stairsInner = models().stairsInner(baseName + "_inner", side, bottom, top); ModelFile stairsOuter = models().stairsOuter(baseName + "_outer", side, bottom, top); stairsBlock(block, stairs, stairsInner, stairsOuter); } public void stairsBlock(StairsBlock block, ModelFile stairs, ModelFile stairsInner, ModelFile stairsOuter) { getVariantBuilder(block) .forAllStatesExcept(state -> { Direction facing = state.get(StairsBlock.FACING); Half half = state.get(StairsBlock.HALF); StairsShape shape = state.get(StairsBlock.SHAPE); int yRot = (int) facing.rotateY().getHorizontalAngle(); // Stairs model is rotated 90 degrees clockwise for some reason if (shape == StairsShape.INNER_LEFT || shape == StairsShape.OUTER_LEFT) { yRot += 270; // Left facing stairs are rotated 90 degrees clockwise } if (shape != StairsShape.STRAIGHT && half == Half.TOP) { yRot += 90; // Top stairs are rotated 90 degrees clockwise } yRot %= 360; boolean uvlock = yRot != 0 || half == Half.TOP; // Don't set uvlock for states that have no rotation return ConfiguredModel.builder() .modelFile(shape == StairsShape.STRAIGHT ? stairs : shape == StairsShape.INNER_LEFT || shape == StairsShape.INNER_RIGHT ? stairsInner : stairsOuter) .rotationX(half == Half.BOTTOM ? 0 : 180) .rotationY(yRot) .uvLock(uvlock) .build(); }, StairsBlock.WATERLOGGED); } public void slabBlock(SlabBlock block, ResourceLocation doubleslab, ResourceLocation texture) { slabBlock(block, doubleslab, texture, texture, texture); } public void slabBlock(SlabBlock block, ResourceLocation doubleslab, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) { slabBlock(block, models().slab(name(block), side, bottom, top), models().slabTop(name(block) + "_top", side, bottom, top), models().getExistingFile(doubleslab)); } public void slabBlock(SlabBlock block, ModelFile bottom, ModelFile top, ModelFile doubleslab) { getVariantBuilder(block) .partialState().with(SlabBlock.TYPE, SlabType.BOTTOM).addModels(new ConfiguredModel(bottom)) .partialState().with(SlabBlock.TYPE, SlabType.TOP).addModels(new ConfiguredModel(top)) .partialState().with(SlabBlock.TYPE, SlabType.DOUBLE).addModels(new ConfiguredModel(doubleslab)); } public void fourWayBlock(FourWayBlock block, ModelFile post, ModelFile side) { MultiPartBlockStateBuilder builder = getMultipartBuilder(block) .part().modelFile(post).addModel().end(); fourWayMultipart(builder, side); } public void fourWayMultipart(MultiPartBlockStateBuilder builder, ModelFile side) { SixWayBlock.FACING_TO_PROPERTY_MAP.entrySet().forEach(e -> { Direction dir = e.getKey(); if (dir.getAxis().isHorizontal()) { builder.part().modelFile(side).rotationY((((int) dir.getHorizontalAngle()) + 180) % 360).uvLock(true).addModel() .condition(e.getValue(), true); } }); } public void fenceBlock(FenceBlock block, ResourceLocation texture) { String baseName = block.getRegistryName().toString(); fourWayBlock(block, models().fencePost(baseName + "_post", texture), models().fenceSide(baseName + "_side", texture)); } public void fenceBlock(FenceBlock block, String name, ResourceLocation texture) { fourWayBlock(block, models().fencePost(name + "_fence_post", texture), models().fenceSide(name + "_fence_side", texture)); } public void fenceGateBlock(FenceGateBlock block, ResourceLocation texture) { fenceGateBlockInternal(block, block.getRegistryName().toString(), texture); } public void fenceGateBlock(FenceGateBlock block, String name, ResourceLocation texture) { fenceGateBlockInternal(block, name + "_fence_gate", texture); } private void fenceGateBlockInternal(FenceGateBlock block, String baseName, ResourceLocation texture) { ModelFile gate = models().fenceGate(baseName, texture); ModelFile gateOpen = models().fenceGateOpen(baseName + "_open", texture); ModelFile gateWall = models().fenceGateWall(baseName + "_wall", texture); ModelFile gateWallOpen = models().fenceGateWallOpen(baseName + "_wall_open", texture); fenceGateBlock(block, gate, gateOpen, gateWall, gateWallOpen); } public void fenceGateBlock(FenceGateBlock block, ModelFile gate, ModelFile gateOpen, ModelFile gateWall, ModelFile gateWallOpen) { getVariantBuilder(block).forAllStatesExcept(state -> { ModelFile model = gate; if (state.get(FenceGateBlock.IN_WALL)) { model = gateWall; } if (state.get(FenceGateBlock.OPEN)) { model = model == gateWall ? gateWallOpen : gateOpen; } return ConfiguredModel.builder() .modelFile(model) .rotationY((int) state.get(FenceGateBlock.HORIZONTAL_FACING).getHorizontalAngle()) .uvLock(true) .build(); }, FenceGateBlock.POWERED); } public void wallBlock(WallBlock block, ResourceLocation texture) { wallBlockInternal(block, block.getRegistryName().toString(), texture); } public void wallBlock(WallBlock block, String name, ResourceLocation texture) { wallBlockInternal(block, name + "_wall", texture); } private void wallBlockInternal(WallBlock block, String baseName, ResourceLocation texture) { wallBlock(block, models().wallPost(baseName + "_post", texture), models().wallSide(baseName + "_side", texture), models().wallSideTall(baseName + "_side_tall", texture)); } public static final ImmutableMap<Direction, Property<WallHeight>> WALL_PROPS = ImmutableMap.<Direction, Property<WallHeight>>builder() .put(Direction.EAST, BlockStateProperties.WALL_HEIGHT_EAST) .put(Direction.NORTH, BlockStateProperties.WALL_HEIGHT_NORTH) .put(Direction.SOUTH, BlockStateProperties.WALL_HEIGHT_SOUTH) .put(Direction.WEST, BlockStateProperties.WALL_HEIGHT_WEST) .build(); public void wallBlock(WallBlock block, ModelFile post, ModelFile side, ModelFile sideTall) { MultiPartBlockStateBuilder builder = getMultipartBuilder(block) .part().modelFile(post).addModel() .condition(WallBlock.UP, true).end(); WALL_PROPS.entrySet().stream() .filter(e -> e.getKey().getAxis().isHorizontal()) .forEach(e -> { wallSidePart(builder, side, e, WallHeight.LOW); wallSidePart(builder, sideTall, e, WallHeight.TALL); }); } private void wallSidePart(MultiPartBlockStateBuilder builder, ModelFile model, Map.Entry<Direction, Property<WallHeight>> entry, WallHeight height) { builder.part() .modelFile(model) .rotationY((((int) entry.getKey().getHorizontalAngle()) + 180) % 360) .uvLock(true) .addModel() .condition(entry.getValue(), height); } public void paneBlock(PaneBlock block, ResourceLocation pane, ResourceLocation edge) { paneBlockInternal(block, block.getRegistryName().toString(), pane, edge); } public void paneBlock(PaneBlock block, String name, ResourceLocation pane, ResourceLocation edge) { paneBlockInternal(block, name + "_pane", pane, edge); } private void paneBlockInternal(PaneBlock block, String baseName, ResourceLocation pane, ResourceLocation edge) { ModelFile post = models().panePost(baseName + "_post", pane, edge); ModelFile side = models().paneSide(baseName + "_side", pane, edge); ModelFile sideAlt = models().paneSideAlt(baseName + "_side_alt", pane, edge); ModelFile noSide = models().paneNoSide(baseName + "_noside", pane); ModelFile noSideAlt = models().paneNoSideAlt(baseName + "_noside_alt", pane); paneBlock(block, post, side, sideAlt, noSide, noSideAlt); } public void paneBlock(PaneBlock block, ModelFile post, ModelFile side, ModelFile sideAlt, ModelFile noSide, ModelFile noSideAlt) { MultiPartBlockStateBuilder builder = getMultipartBuilder(block) .part().modelFile(post).addModel().end(); SixWayBlock.FACING_TO_PROPERTY_MAP.entrySet().forEach(e -> { Direction dir = e.getKey(); if (dir.getAxis().isHorizontal()) { boolean alt = dir == Direction.SOUTH; builder.part().modelFile(alt || dir == Direction.WEST ? sideAlt : side).rotationY(dir.getAxis() == Axis.X ? 90 : 0).addModel() .condition(e.getValue(), true).end() .part().modelFile(alt || dir == Direction.EAST ? noSideAlt : noSide).rotationY(dir == Direction.WEST ? 270 : dir == Direction.SOUTH ? 90 : 0).addModel() .condition(e.getValue(), false); } }); } public void doorBlock(DoorBlock block, ResourceLocation bottom, ResourceLocation top) { doorBlockInternal(block, block.getRegistryName().toString(), bottom, top); } public void doorBlock(DoorBlock block, String name, ResourceLocation bottom, ResourceLocation top) { doorBlockInternal(block, name + "_door", bottom, top); } private void doorBlockInternal(DoorBlock block, String baseName, ResourceLocation bottom, ResourceLocation top) { ModelFile bottomLeft = models().doorBottomLeft(baseName + "_bottom", bottom, top); ModelFile bottomRight = models().doorBottomRight(baseName + "_bottom_hinge", bottom, top); ModelFile topLeft = models().doorTopLeft(baseName + "_top", bottom, top); ModelFile topRight = models().doorTopRight(baseName + "_top_hinge", bottom, top); doorBlock(block, bottomLeft, bottomRight, topLeft, topRight); } public void doorBlock(DoorBlock block, ModelFile bottomLeft, ModelFile bottomRight, ModelFile topLeft, ModelFile topRight) { getVariantBuilder(block).forAllStatesExcept(state -> { int yRot = ((int) state.get(DoorBlock.FACING).getHorizontalAngle()) + 90; boolean rh = state.get(DoorBlock.HINGE) == DoorHingeSide.RIGHT; boolean open = state.get(DoorBlock.OPEN); boolean right = rh ^ open; if (open) { yRot += 90; } if (rh && open) { yRot += 180; } yRot %= 360; return ConfiguredModel.builder().modelFile(state.get(DoorBlock.HALF) == DoubleBlockHalf.LOWER ? (right ? bottomRight : bottomLeft) : (right ? topRight : topLeft)) .rotationY(yRot) .build(); }, DoorBlock.POWERED); } public void trapdoorBlock(TrapDoorBlock block, ResourceLocation texture, boolean orientable) { trapdoorBlockInternal(block, block.getRegistryName().toString(), texture, orientable); } public void trapdoorBlock(TrapDoorBlock block, String name, ResourceLocation texture, boolean orientable) { trapdoorBlockInternal(block, name + "_trapdoor", texture, orientable); } private void trapdoorBlockInternal(TrapDoorBlock block, String baseName, ResourceLocation texture, boolean orientable) { ModelFile bottom = orientable ? models().trapdoorOrientableBottom(baseName + "_bottom", texture) : models().trapdoorBottom(baseName + "_bottom", texture); ModelFile top = orientable ? models().trapdoorOrientableTop(baseName + "_top", texture) : models().trapdoorTop(baseName + "_top", texture); ModelFile open = orientable ? models().trapdoorOrientableOpen(baseName + "_open", texture) : models().trapdoorOpen(baseName + "_open", texture); trapdoorBlock(block, bottom, top, open, orientable); } public void trapdoorBlock(TrapDoorBlock block, ModelFile bottom, ModelFile top, ModelFile open, boolean orientable) { getVariantBuilder(block).forAllStatesExcept(state -> { int xRot = 0; int yRot = ((int) state.get(TrapDoorBlock.HORIZONTAL_FACING).getHorizontalAngle()) + 180; boolean isOpen = state.get(TrapDoorBlock.OPEN); if (orientable && isOpen && state.get(TrapDoorBlock.HALF) == Half.TOP) { xRot += 180; yRot += 180; } if (!orientable && !isOpen) { yRot = 0; } yRot %= 360; return ConfiguredModel.builder().modelFile(isOpen ? open : state.get(TrapDoorBlock.HALF) == Half.TOP ? top : bottom) .rotationX(xRot) .rotationY(yRot) .build(); }, TrapDoorBlock.POWERED, TrapDoorBlock.WATERLOGGED); } private void saveBlockState(DirectoryCache cache, JsonObject stateJson, Block owner) { ResourceLocation blockName = Preconditions.checkNotNull(owner.getRegistryName()); Path mainOutput = generator.getOutputFolder(); String pathSuffix = "assets/" + blockName.getNamespace() + "/blockstates/" + blockName.getPath() + ".json"; Path outputPath = mainOutput.resolve(pathSuffix); try { IDataProvider.save(GSON, cache, stateJson, outputPath); } catch (IOException e) { LOGGER.error("Couldn't save blockstate to {}", outputPath, e); } } @Nonnull @Override public String getName() { return "Block States: " + modid; } public static class ConfiguredModelList { private final List<ConfiguredModel> models; private ConfiguredModelList(List<ConfiguredModel> models) { Preconditions.checkArgument(!models.isEmpty()); this.models = models; } public ConfiguredModelList(ConfiguredModel model) { this(ImmutableList.of(model)); } public ConfiguredModelList(ConfiguredModel... models) { this(Arrays.asList(models)); } public JsonElement toJSON() { if (models.size()==1) { return models.get(0).toJSON(false); } else { JsonArray ret = new JsonArray(); for (ConfiguredModel m:models) { ret.add(m.toJSON(true)); } return ret; } } public ConfiguredModelList append(ConfiguredModel... models) { return new ConfiguredModelList(ImmutableList.<ConfiguredModel>builder().addAll(this.models).add(models).build()); } } }
27,461
Java
.java
517
44.398453
205
0.68405
PatchworkMC/crabwork
2
0
0
LGPL-2.1
9/5/2024, 12:14:53 AM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
27,461
1,381,558
SFFImageReader.java
alex73_mmscomputing/src/uk/co/mmscomputing/imageio/sff/SFFImageReader.java
package uk.co.mmscomputing.imageio.sff; import java.io.*; import java.util.*; import java.awt.image.*; import javax.imageio.*; import javax.imageio.spi.*; import javax.imageio.stream.*; import javax.imageio.metadata.*; import uk.co.mmscomputing.io.*; public class SFFImageReader extends ImageReader{ static private class IFD{ int width=0; int height=0; byte[] data=null; } private Vector ifds = null; protected SFFImageReader(ImageReaderSpi originatingProvider){ super(originatingProvider); } public BufferedImage read(int imageIndex, ImageReadParam param)throws IOException{ readIFDs(); checkIndex(imageIndex); return readImage((IFD)ifds.elementAt(imageIndex)); } public int getHeight(int imageIndex)throws IOException{ readIFDs(); checkIndex(imageIndex); return ((IFD)ifds.elementAt(imageIndex)).height; } public int getWidth(int imageIndex)throws IOException{ readIFDs(); checkIndex(imageIndex); return ((IFD)ifds.elementAt(imageIndex)).width; } public Iterator getImageTypes(int imageIndex)throws IOException{ readIFDs(); checkIndex(imageIndex); ImageTypeSpecifier imageType = null; java.util.List l = new ArrayList(); imageType=ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); l.add(imageType); return l.iterator(); } public int getNumImages(boolean allowSearch)throws IOException{ readIFDs(); return ifds.size(); } public IIOMetadata getImageMetadata(int imageIndex)throws IOException{ readIFDs(); checkIndex(imageIndex); return null; } public IIOMetadata getStreamMetadata() throws IOException{ return null; } private void checkIndex(int imageIndex) { if (imageIndex >= ifds.size()) { throw new IndexOutOfBoundsException(getClass().getName()+".checkIndex:\n\tBad index in sff image reader"); } } private byte[] readImageData()throws IOException{ // read whole sff stream into memory ImageInputStream iis=(ImageInputStream)getInput(); int len=(int)iis.length(); byte[] data; if(len==-1){ // don't know length yet ByteArrayOutputStream baos=new ByteArrayOutputStream(); data=new byte[1<<13]; while((len=iis.read(data))!=-1){ baos.write(data,0,len); } data=baos.toByteArray(); }else{ data=new byte[len]; iis.readFully(data,0,len); } return data; } private IFD readIFD(SFFInputStream in)throws IOException{ try{ /* 1. get page data (modified huffman) evaluate height */ ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] data=new byte[2048<<2];int len; while(!in.isEndOfPage()&&(len=in.read(data))!=-1){ // read modified Huffman codes of page baos.write(data,0,len); } IFD ifd=new IFD(); ifd.width =in.getWidth(); ifd.height =in.getHeight(); ifd.data =baos.toByteArray(); return ifd; }catch(Exception e){ e.printStackTrace(); throw new IOException(getClass().getName()+".readIFD:\n\t"+e.getMessage()); } } private void readIFDs()throws IOException{ if(ifds==null){ ifds=new Vector(); byte[] data=readImageData(); SFFInputStream sffis = new SFFInputStream(new ByteArrayInputStream(data)); while(sffis.hasImage()){ ifds.add(readIFD(sffis)); } } } /* private BufferedImage readImage(IFD ifd)throws IOException{ try{ // 2. evaluate runlength // convert into runs // copy to image buffer ByteArrayInputStream bais=new ByteArrayInputStream(ifd.data); ModHuffmanInputStream mhis=new ModHuffmanInputStream(bais); RLEInputStream rlis=new RLEInputStream(mhis); BufferedImage image=new BufferedImage(ifd.width,ifd.height,BufferedImage.TYPE_BYTE_GRAY); WritableRaster raster=image.getRaster(); DataBufferByte buffer=(DataBufferByte)raster.getDataBuffer(); byte[] imgdata=(byte[])buffer.getData(); byte[] buf=new byte[ifd.width];int off=0,len=0; while(true){ try{ len=rlis.read(buf); // read one image line if(len==-1){break;} // end of page System.arraycopy(buf,0,imgdata,off,len); // copy line to image buffer }catch(ModHuffmanInputStream.ModHuffmanCodingException mhce){ System.err.println(getClass().getName()+".readImage\n\t"+mhce.getMessage()); } mhis.syncWithEOL(); // skip to eol synchronization bytes rlis.resetToStartCodeWord(); // start next line with white off+=ifd.width; } return image; }catch(Exception e){ e.printStackTrace(); throw new IOException(getClass().getName()+".readImage:\n\t"+e.getMessage()); } } */ private BufferedImage readImage(IFD ifd)throws IOException{ try{ // 2. evaluate runlength // convert into runs // copy to image buffer ByteArrayInputStream bais=new ByteArrayInputStream(ifd.data); ModHuffmanInputStream mhis=new ModHuffmanInputStream(bais); RLEBitInputStream rlis=new RLEBitInputStream(mhis); BufferedImage image=new BufferedImage(ifd.width,ifd.height,BufferedImage.TYPE_BYTE_BINARY); WritableRaster raster=image.getRaster(); DataBufferByte buffer=(DataBufferByte)raster.getDataBuffer(); byte[] imgdata=(byte[])buffer.getData(); if((ifd.width%8)==0){ byte[] buf=new byte[ifd.width>>3];int off=0,len=0; while(true){ try{ len=rlis.read(buf); // read one image line if(len==-1){break;} // end of page System.arraycopy(buf,0,imgdata,off,len); // copy line to image buffer }catch(ModHuffmanInputStream.ModHuffmanCodingException mhce){ System.err.println(getClass().getName()+".readImage\n\t"+mhce.getMessage()); } mhis.syncWithEOL(); // skip to eol synchronization bytes rlis.resetToStartCodeWord(); // start next line with white off+=len; } return image; }else{ byte[] buf=new byte[(ifd.width+7)>>3];int off=0,len=0,ecw=8-(ifd.width&0x0007),bits; while(true){ try{ len=rlis.read(buf,0,buf.length-1); // read one image line if(len==-1){break;} // end of page bits=rlis.readBits(7,ecw); buf[len]=(byte)bits; System.arraycopy(buf,0,imgdata,off,len+1); // copy line to image buffer }catch(ModHuffmanInputStream.ModHuffmanCodingException mhce){ System.err.println(getClass().getName()+".readImage\n\t"+mhce.getMessage()); } mhis.syncWithEOL(); // skip to eol synchronization bytes rlis.resetToStartCodeWord(); // start next line with white off+=len+1; } return image; } }catch(Exception e){ e.printStackTrace(); throw new IOException(getClass().getName()+".readImage:\n\t"+e.getMessage()); } } }
7,477
Java
.java
192
32.375
112
0.628186
alex73/mmscomputing
21
31
2
LGPL-3.0
9/4/2024, 7:47:27 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
7,477
1,662,497
Deserializer.java
mdaniel_svn-caucho-com-resin/modules/hessian/src/com/caucho/hessian/io/Deserializer.java
/* * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. * * The Apache Software License, Version 1.1 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Caucho Technology (http://www.caucho.com/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Burlap", "Resin", and "Caucho" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * info@caucho.com. * * 5. Products derived from this software may not be called "Resin" * nor may "Resin" appear in their names without prior written * permission of Caucho Technology. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Scott Ferguson */ package com.caucho.hessian.io; import java.io.IOException; /** * Deserializing an object. Custom deserializers should extend * from AbstractDeserializer to avoid issues with signature * changes. */ public interface Deserializer { public Class<?> getType(); public boolean isReadResolve(); public Object readObject(AbstractHessianInput in) throws IOException; public Object readList(AbstractHessianInput in, int length) throws IOException; public Object readLengthList(AbstractHessianInput in, int length) throws IOException; public Object readMap(AbstractHessianInput in) throws IOException; /** * Creates an empty array for the deserializers field * entries. * * @param len number of fields to be read * @return empty array of the proper field type. */ public Object []createFields(int len); /** * Returns the deserializer's field reader for the given name. * * @param name the field name * @return the deserializer's internal field reader */ public Object createField(String name); /** * Reads the object from the input stream, given the field * definition. * * @param in the input stream * @param fields the deserializer's own field marshal * @return the new object * @throws IOException */ public Object readObject(AbstractHessianInput in, Object []fields) throws IOException; public Object readObject(AbstractHessianInput in, String []fieldNames) throws IOException; }
3,801
Java
.java
96
36.09375
74
0.745039
mdaniel/svn-caucho-com-resin
18
17
0
GPL-2.0
9/4/2024, 8:12:19 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
3,801
1,314,759
A_testParametricTypeWithNonParametricSuperType_in.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeTypeRefactoring/positive/A_testParametricTypeWithNonParametricSuperType_in.java
import java.util.List; public class A_testParametricTypeWithNonParametricSuperType_in { void foo(){ List<String> x = null; } }
132
Java
.java
6
20.166667
64
0.784
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
132
1,315,184
TestClass.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceFactory/Bugzilla/46189/TestClass.java
package p; public class TestClass { public TestClass() { } } class UseTestClass { public void foo() { /*[*/new TestClass()/*]*/; } }
141
Java
.java
10
12.3
28
0.658915
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
141
1,381,614
ImageTypeConvertOpPanel.java
alex73_mmscomputing/src/uk/co/mmscomputing/image/operators/ImageTypeConvertOpPanel.java
package uk.co.mmscomputing.image.operators; import java.util.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.imageio.*; import uk.co.mmscomputing.concurrent.Semaphore; public class ImageTypeConvertOpPanel extends JPanel implements ActionListener,ChangeListener{ static private Properties params=new Properties(); private JDialog dialog; private boolean cancelled; private JRadioButton buttonByteBinary; private JRadioButton buttonByteIndexed; private JRadioButton buttonByteGrayScaled; private JRadioButton buttonBPP1,buttonBPP2,buttonBPP4,buttonBPP8,buttonBPP16,buttonBPP24,buttonBPP32; private JSlider sliderThreshold; private Semaphore blocker=new Semaphore(0,true); public ImageTypeConvertOpPanel(){ super(new BorderLayout()); cancelled=false; add(getMainCentralPanel(),BorderLayout.CENTER); JPanel bp=new JPanel(); bp.setLayout(new GridLayout(1,2)); JButton button = new JButton("ok"); button.setActionCommand("ok"); button.addActionListener(this); bp.add(button); button = new JButton("cancel"); button.setActionCommand("cancel"); button.addActionListener(this); bp.add(button); add(bp,BorderLayout.SOUTH); } private JPanel getMainCentralPanel(){ JPanel p = new JPanel(new GridLayout(0,1)); p.setBorder(new EtchedBorder()); p.add(getImageTypePanel()); p.add(getBPPPanel()); p.add(getQualityPanel()); return p; } private JPanel getImageTypePanel(){ buttonByteBinary = new JRadioButton("Byte Binary"); buttonByteBinary.setActionCommand("ByteBinary"); buttonByteBinary.addActionListener(this); buttonByteBinary.setSelected(true); params.setProperty("type",Integer.toString(BufferedImage.TYPE_BYTE_BINARY)); buttonByteIndexed = new JRadioButton("Byte Indexed"); buttonByteIndexed.setActionCommand("ByteIndexed"); buttonByteIndexed.addActionListener(this); buttonByteGrayScaled = new JRadioButton("Byte Gray Scale"); buttonByteGrayScaled.setActionCommand("ByteGrayScale"); buttonByteGrayScaled.addActionListener(this); ButtonGroup group = new ButtonGroup(); group.add(buttonByteBinary); group.add(buttonByteIndexed); group.add(buttonByteGrayScaled); JPanel p = new JPanel(new GridLayout(1,0)); p.setBorder(new TitledBorder(new EtchedBorder(),"Image Type")); p.add(buttonByteBinary); p.add(buttonByteIndexed); p.add(buttonByteGrayScaled); return p; } private JPanel getBPPPanel(){ buttonBPP1 = new JRadioButton("1"); buttonBPP1.setActionCommand("bpp1"); buttonBPP1.addActionListener(this); buttonBPP1.setSelected(true); params.setProperty("bpp","1"); buttonBPP2 = new JRadioButton("2"); buttonBPP2.setActionCommand("bpp2"); buttonBPP2.addActionListener(this); buttonBPP4 = new JRadioButton("4"); buttonBPP4.setActionCommand("bpp4"); buttonBPP4.addActionListener(this); buttonBPP8 = new JRadioButton("8"); buttonBPP8.setActionCommand("bpp8"); buttonBPP8.addActionListener(this); buttonBPP8.setEnabled(false); ButtonGroup group = new ButtonGroup(); group.add(buttonBPP1); group.add(buttonBPP2); group.add(buttonBPP4); group.add(buttonBPP8); JPanel p = new JPanel(new GridLayout(1,0)); p.setBorder(new TitledBorder(new EtchedBorder(),"Bits Per Pixel")); p.add(buttonBPP1); p.add(buttonBPP2); p.add(buttonBPP4); p.add(buttonBPP8); return p; } private boolean setType(String action){ if(action.equals("ByteBinary")){ params.setProperty("type",Integer.toString(BufferedImage.TYPE_BYTE_BINARY)); buttonByteBinary.setSelected(true); buttonBPP1.setEnabled(true); buttonBPP2.setEnabled(true); buttonBPP4.setEnabled(true); buttonBPP8.setEnabled(false); if(buttonBPP8.isSelected()){setBPP("bpp4");} }else if(action.equals("ByteIndexed")){ params.setProperty("type",Integer.toString(BufferedImage.TYPE_BYTE_INDEXED)); buttonByteIndexed.setSelected(true); buttonBPP1.setEnabled(false); buttonBPP2.setEnabled(false); buttonBPP4.setEnabled(false); buttonBPP8.setEnabled(true); setBPP("bpp8"); }else if(action.equals("ByteGrayScale")){ params.setProperty("type",Integer.toString(BufferedImage.TYPE_BYTE_GRAY)); buttonByteGrayScaled.setSelected(true); buttonBPP1.setEnabled(false); buttonBPP2.setEnabled(false); buttonBPP4.setEnabled(false); buttonBPP8.setEnabled(true); setBPP("bpp8"); }else{ return false; } return true; } private boolean setBPP(String action){ if(action.equals("bpp1")){ params.setProperty("bpp","1"); buttonBPP1.setSelected(true); sliderThreshold.setEnabled(true); }else if(action.equals("bpp2")){ params.setProperty("bpp","2"); buttonBPP2.setSelected(true); sliderThreshold.setEnabled(false); }else if(action.equals("bpp4")){ params.setProperty("bpp","4"); buttonBPP4.setSelected(true); sliderThreshold.setEnabled(false); }else if(action.equals("bpp8")){ params.setProperty("bpp","8"); buttonBPP8.setSelected(true); sliderThreshold.setEnabled(false); }else{ return false; } return true; } public void actionPerformed(ActionEvent ev) { String action=ev.getActionCommand(); if(action.equals("ok")){ cancelled=false; if(dialog!=null){dialog.dispose();} blocker.release(); }else if(action.equals("cancel")){ cancelled=true; if(dialog!=null){dialog.dispose();} blocker.release(); }else if(setType(action)){ }else if(setBPP(action)){ }else{ } } private JPanel getQualityPanel(){ int threshold=50; params.setProperty("threshold",Integer.toString(threshold)); sliderThreshold=new JSlider(JSlider.HORIZONTAL,0,100,threshold); sliderThreshold.addChangeListener(this); sliderThreshold.setEnabled(true); sliderThreshold.setMinorTickSpacing(2); sliderThreshold.setMajorTickSpacing(10); sliderThreshold.setPaintTicks(true); Dictionary dict=new Hashtable(); for(int i=0;i<=100;i+=10){ dict.put(new Integer(i), new JLabel(Integer.toString(i))); } sliderThreshold.setLabelTable(dict); sliderThreshold.setPaintLabels(true); JPanel p=new JPanel(); p.setLayout(new BorderLayout()); p.setBorder(new TitledBorder(new EtchedBorder(),"Threshold")); p.add(sliderThreshold,BorderLayout.CENTER); return p; } public void stateChanged(ChangeEvent e){ JSlider slider=(JSlider)e.getSource(); if(!slider.getValueIsAdjusting()){ if(slider==sliderThreshold){ int threshold=slider.getValue(); if(threshold<=0){threshold=1;slider.setValue(1);} params.setProperty("threshold",Integer.toString(threshold)); } } } public void display(){ try{ dialog=new JDialog((Frame)null,"Image Type Converter Settings",false); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setContentPane(this); GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setVisible(true); }catch(Exception e){ System.out.println("9\b"+getClass().getName()+".display:\n\t"+e); e.printStackTrace(); } } public ImageTypeConvertOp activate(){ display(); try{ blocker.acquire(); }catch(InterruptedException ie){ return null; } if(cancelled){return null;} return new ImageTypeConvertOp(params); } }
7,850
Java
.java
219
30.557078
109
0.713815
alex73/mmscomputing
21
31
2
LGPL-3.0
9/4/2024, 7:47:27 PM (Europe/Amsterdam)
false
false
true
true
false
true
true
true
7,850
4,739,410
ExGetBossRecord.java
ichiro101_l2adena-l2j-core/java/com/l2jserver/gameserver/network/serverpackets/ExGetBossRecord.java
/* * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.gameserver.network.serverpackets; import java.util.Map; /** * Format: ch ddd [ddd] * @author KenM */ public class ExGetBossRecord extends L2GameServerPacket { private static final String _S__FE_33_EXGETBOSSRECORD = "[S] FE:34 ExGetBossRecord"; private Map<Integer, Integer> _bossRecordInfo; private int _ranking; private int _totalPoints; public ExGetBossRecord(int ranking, int totalScore, Map<Integer, Integer> list) { _ranking = ranking; _totalPoints = totalScore; _bossRecordInfo = list; } /** * @see com.l2jserver.util.network.BaseSendablePacket.ServerBasePacket#writeImpl() */ @Override protected void writeImpl() { writeC(0xfe); writeH(0x34); writeD(_ranking); writeD(_totalPoints); if (_bossRecordInfo == null) { writeD(0x00); writeD(0x00); writeD(0x00); writeD(0x00); } else { writeD(_bossRecordInfo.size()); //list size for (int bossId : _bossRecordInfo.keySet()) { writeD(bossId); writeD(_bossRecordInfo.get(bossId)); writeD(0x00); //?? } } } /** * @see com.l2jserver.gameserver.BasePacket#getType() */ @Override public String getType() { return _S__FE_33_EXGETBOSSRECORD; } }
1,938
Java
.java
69
24.347826
86
0.704741
ichiro101/l2adena-l2j-core
1
2
0
GPL-3.0
9/5/2024, 12:29:04 AM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
1,938
3,032,108
FlatGeneratorInfo.java
SelfMadeSystem_PasteL/src/main/java/net/minecraft/world/gen/FlatGeneratorInfo.java
package net.minecraft.world.gen; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import net.minecraft.world.biome.BiomeGenBase; public class FlatGeneratorInfo { /** List of layers on this preset. */ private final List flatLayers = Lists.newArrayList(); /** List of world features enabled on this preset. */ private final Map worldFeatures = Maps.newHashMap(); private int biomeToUse; private static final String __OBFID = "CL_00000440"; /** * Return the biome used on this preset. */ public int getBiome() { return this.biomeToUse; } /** * Set the biome used on this preset. */ public void setBiome(int p_82647_1_) { this.biomeToUse = p_82647_1_; } /** * Return the list of world features enabled on this preset. */ public Map getWorldFeatures() { return this.worldFeatures; } /** * Return the list of layers on this preset. */ public List getFlatLayers() { return this.flatLayers; } public void func_82645_d() { int var1 = 0; FlatLayerInfo var3; for (Iterator var2 = this.flatLayers.iterator(); var2.hasNext(); var1 += var3.getLayerCount()) { var3 = (FlatLayerInfo)var2.next(); var3.setMinY(var1); } } public String toString() { StringBuilder var1 = new StringBuilder(); var1.append(3); var1.append(";"); int var2; for (var2 = 0; var2 < this.flatLayers.size(); ++var2) { if (var2 > 0) { var1.append(","); } var1.append(((FlatLayerInfo)this.flatLayers.get(var2)).toString()); } var1.append(";"); var1.append(this.biomeToUse); if (!this.worldFeatures.isEmpty()) { var1.append(";"); var2 = 0; Iterator var3 = this.worldFeatures.entrySet().iterator(); while (var3.hasNext()) { Entry var4 = (Entry)var3.next(); if (var2++ > 0) { var1.append(","); } var1.append(((String)var4.getKey()).toLowerCase()); Map var5 = (Map)var4.getValue(); if (!var5.isEmpty()) { var1.append("("); int var6 = 0; Iterator var7 = var5.entrySet().iterator(); while (var7.hasNext()) { Entry var8 = (Entry)var7.next(); if (var6++ > 0) { var1.append(" "); } var1.append((String)var8.getKey()); var1.append("="); var1.append((String)var8.getValue()); } var1.append(")"); } } } else { var1.append(";"); } return var1.toString(); } private static FlatLayerInfo func_180715_a(int p_180715_0_, String p_180715_1_, int p_180715_2_) { String[] var3 = p_180715_0_ >= 3 ? p_180715_1_.split("\\*", 2) : p_180715_1_.split("x", 2); int var4 = 1; int var5 = 0; if (var3.length == 2) { try { var4 = Integer.parseInt(var3[0]); if (p_180715_2_ + var4 >= 256) { var4 = 256 - p_180715_2_; } if (var4 < 0) { var4 = 0; } } catch (Throwable var8) { return null; } } Block var6 = null; try { String var7 = var3[var3.length - 1]; if (p_180715_0_ < 3) { var3 = var7.split(":", 2); if (var3.length > 1) { var5 = Integer.parseInt(var3[1]); } var6 = Block.getBlockById(Integer.parseInt(var3[0])); } else { var3 = var7.split(":", 3); var6 = var3.length > 1 ? Block.getBlockFromName(var3[0] + ":" + var3[1]) : null; if (var6 != null) { var5 = var3.length > 2 ? Integer.parseInt(var3[2]) : 0; } else { var6 = Block.getBlockFromName(var3[0]); if (var6 != null) { var5 = var3.length > 1 ? Integer.parseInt(var3[1]) : 0; } } if (var6 == null) { return null; } } if (var6 == Blocks.air) { var5 = 0; } if (var5 < 0 || var5 > 15) { var5 = 0; } } catch (Throwable var9) { return null; } FlatLayerInfo var10 = new FlatLayerInfo(p_180715_0_, var4, var6, var5); var10.setMinY(p_180715_2_); return var10; } private static List func_180716_a(int p_180716_0_, String p_180716_1_) { if (p_180716_1_ != null && p_180716_1_.length() >= 1) { ArrayList var2 = Lists.newArrayList(); String[] var3 = p_180716_1_.split(","); int var4 = 0; String[] var5 = var3; int var6 = var3.length; for (int var7 = 0; var7 < var6; ++var7) { String var8 = var5[var7]; FlatLayerInfo var9 = func_180715_a(p_180716_0_, var8, var4); if (var9 == null) { return null; } var2.add(var9); var4 += var9.getLayerCount(); } return var2; } else { return null; } } public static FlatGeneratorInfo createFlatGeneratorFromString(String p_82651_0_) { if (p_82651_0_ == null) { return getDefaultFlatGenerator(); } else { String[] var1 = p_82651_0_.split(";", -1); int var2 = var1.length == 1 ? 0 : MathHelper.parseIntWithDefault(var1[0], 0); if (var2 >= 0 && var2 <= 3) { FlatGeneratorInfo var3 = new FlatGeneratorInfo(); int var4 = var1.length == 1 ? 0 : 1; List var5 = func_180716_a(var2, var1[var4++]); if (var5 != null && !var5.isEmpty()) { var3.getFlatLayers().addAll(var5); var3.func_82645_d(); int var6 = BiomeGenBase.plains.biomeID; if (var2 > 0 && var1.length > var4) { var6 = MathHelper.parseIntWithDefault(var1[var4++], var6); } var3.setBiome(var6); if (var2 > 0 && var1.length > var4) { String[] var7 = var1[var4++].toLowerCase().split(","); String[] var8 = var7; int var9 = var7.length; for (int var10 = 0; var10 < var9; ++var10) { String var11 = var8[var10]; String[] var12 = var11.split("\\(", 2); HashMap var13 = Maps.newHashMap(); if (var12[0].length() > 0) { var3.getWorldFeatures().put(var12[0], var13); if (var12.length > 1 && var12[1].endsWith(")") && var12[1].length() > 1) { String[] var14 = var12[1].substring(0, var12[1].length() - 1).split(" "); for (int var15 = 0; var15 < var14.length; ++var15) { String[] var16 = var14[var15].split("=", 2); if (var16.length == 2) { var13.put(var16[0], var16[1]); } } } } } } else { var3.getWorldFeatures().put("village", Maps.newHashMap()); } return var3; } else { return getDefaultFlatGenerator(); } } else { return getDefaultFlatGenerator(); } } } public static FlatGeneratorInfo getDefaultFlatGenerator() { FlatGeneratorInfo var0 = new FlatGeneratorInfo(); var0.setBiome(BiomeGenBase.plains.biomeID); var0.getFlatLayers().add(new FlatLayerInfo(1, Blocks.bedrock)); var0.getFlatLayers().add(new FlatLayerInfo(2, Blocks.dirt)); var0.getFlatLayers().add(new FlatLayerInfo(1, Blocks.grass)); var0.func_82645_d(); var0.getWorldFeatures().put("village", Maps.newHashMap()); return var0; } }
10,057
Java
.java
299
19.48495
109
0.425685
SelfMadeSystem/PasteL
5
0
0
GPL-3.0
9/4/2024, 10:43:25 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
10,057
1,797,458
AbstractSVGPathSegList.java
git-moss_Push2Display/lib/batik-1.8/sources/org/apache/batik/dom/svg/AbstractSVGPathSegList.java
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.dom.svg; import org.apache.batik.parser.DefaultPathHandler; import org.apache.batik.parser.ParseException; import org.apache.batik.parser.PathParser; import org.w3c.dom.DOMException; import org.w3c.dom.svg.SVGException; import org.w3c.dom.svg.SVGPathSeg; import org.w3c.dom.svg.SVGPathSegArcAbs; import org.w3c.dom.svg.SVGPathSegArcRel; import org.w3c.dom.svg.SVGPathSegCurvetoCubicAbs; import org.w3c.dom.svg.SVGPathSegCurvetoCubicRel; import org.w3c.dom.svg.SVGPathSegCurvetoCubicSmoothAbs; import org.w3c.dom.svg.SVGPathSegCurvetoCubicSmoothRel; import org.w3c.dom.svg.SVGPathSegCurvetoQuadraticAbs; import org.w3c.dom.svg.SVGPathSegCurvetoQuadraticRel; import org.w3c.dom.svg.SVGPathSegCurvetoQuadraticSmoothAbs; import org.w3c.dom.svg.SVGPathSegCurvetoQuadraticSmoothRel; import org.w3c.dom.svg.SVGPathSegLinetoAbs; import org.w3c.dom.svg.SVGPathSegLinetoHorizontalAbs; import org.w3c.dom.svg.SVGPathSegLinetoHorizontalRel; import org.w3c.dom.svg.SVGPathSegLinetoRel; import org.w3c.dom.svg.SVGPathSegLinetoVerticalAbs; import org.w3c.dom.svg.SVGPathSegLinetoVerticalRel; import org.w3c.dom.svg.SVGPathSegList; import org.w3c.dom.svg.SVGPathSegMovetoAbs; import org.w3c.dom.svg.SVGPathSegMovetoRel; /** * This class is the implementation of * <code>SVGPathSegList</code>. * * @author nicolas.socheleau@bitflash.com * @version $Id: AbstractSVGPathSegList.java 1664314 2015-03-05 11:45:15Z lbernardo $ */ public abstract class AbstractSVGPathSegList extends AbstractSVGList implements SVGPathSegList, SVGPathSegConstants { /** * Separator for a point list. */ public static final String SVG_PATHSEG_LIST_SEPARATOR =" "; /** * Creates a new SVGPathSegList. */ protected AbstractSVGPathSegList() { super(); } /** * Return the separator between segments in the list. */ protected String getItemSeparator(){ return SVG_PATHSEG_LIST_SEPARATOR; } /** * Create an SVGException when the checkItemType fails. * * @return SVGException */ protected abstract SVGException createSVGException(short type, String key, Object[] args); /** */ public SVGPathSeg initialize ( SVGPathSeg newItem ) throws DOMException, SVGException { return (SVGPathSeg)initializeImpl(newItem); } /** */ public SVGPathSeg getItem ( int index ) throws DOMException { return (SVGPathSeg)getItemImpl(index); } /** */ public SVGPathSeg insertItemBefore ( SVGPathSeg newItem, int index ) throws DOMException, SVGException { return (SVGPathSeg)insertItemBeforeImpl(newItem,index); } /** */ public SVGPathSeg replaceItem ( SVGPathSeg newItem, int index ) throws DOMException, SVGException { return (SVGPathSeg)replaceItemImpl(newItem,index); } /** */ public SVGPathSeg removeItem ( int index ) throws DOMException { return (SVGPathSeg)removeItemImpl(index); } /** */ public SVGPathSeg appendItem ( SVGPathSeg newItem ) throws DOMException, SVGException { return (SVGPathSeg) appendItemImpl(newItem); } /** */ protected SVGItem createSVGItem(Object newItem){ SVGPathSeg pathSeg = (SVGPathSeg)newItem; return createPathSegItem(pathSeg); } /** * Parse the 'd' attribute. * * @param value 'd' attribute value * @param handler : list handler */ protected void doParse(String value, ListHandler handler) throws ParseException{ PathParser pathParser = new PathParser(); PathSegListBuilder builder = new PathSegListBuilder(handler); pathParser.setPathHandler(builder); pathParser.parse(value); } /** * Check if the item is an SVGPathSeg. */ protected void checkItemType(Object newItem){ if ( !( newItem instanceof SVGPathSeg ) ){ createSVGException(SVGException.SVG_WRONG_TYPE_ERR, "expected SVGPathSeg", null); } } /** * create an SVGItem representing this SVGPathSeg. */ protected SVGPathSegItem createPathSegItem(SVGPathSeg pathSeg){ SVGPathSegItem pathSegItem = null; short type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_ARC_ABS: case SVGPathSeg.PATHSEG_ARC_REL: pathSegItem = new SVGPathSegArcItem(pathSeg); break; case SVGPathSeg.PATHSEG_CLOSEPATH: pathSegItem = new SVGPathSegItem(pathSeg); break; case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: pathSegItem = new SVGPathSegCurvetoCubicItem(pathSeg); break; case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: pathSegItem = new SVGPathSegCurvetoCubicSmoothItem(pathSeg); break; case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: pathSegItem = new SVGPathSegCurvetoQuadraticItem(pathSeg); break; case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: pathSegItem = new SVGPathSegCurvetoQuadraticSmoothItem(pathSeg); break; case SVGPathSeg.PATHSEG_LINETO_ABS: case SVGPathSeg.PATHSEG_LINETO_REL: case SVGPathSeg.PATHSEG_MOVETO_ABS: case SVGPathSeg.PATHSEG_MOVETO_REL: pathSegItem = new SVGPathSegMovetoLinetoItem(pathSeg); break; case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: pathSegItem = new SVGPathSegLinetoHorizontalItem(pathSeg); break; case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: pathSegItem = new SVGPathSegLinetoVerticalItem(pathSeg); break; default: } return pathSegItem; } public class SVGPathSegMovetoLinetoItem extends SVGPathSegItem implements SVGPathSegMovetoAbs, SVGPathSegMovetoRel, SVGPathSegLinetoAbs, SVGPathSegLinetoRel { public SVGPathSegMovetoLinetoItem(short type, String letter, float x, float y){ super(type,letter); this.setX(x); this.setY(y); } public SVGPathSegMovetoLinetoItem(SVGPathSeg pathSeg){ type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_LINETO_REL: letter = PATHSEG_LINETO_REL_LETTER; setX(((SVGPathSegLinetoRel)pathSeg).getX()); setY(((SVGPathSegLinetoRel)pathSeg).getY()); break; case SVGPathSeg.PATHSEG_LINETO_ABS: letter = PATHSEG_LINETO_ABS_LETTER; setX(((SVGPathSegLinetoAbs)pathSeg).getX()); setY(((SVGPathSegLinetoAbs)pathSeg).getY()); break; case SVGPathSeg.PATHSEG_MOVETO_REL: letter = PATHSEG_MOVETO_REL_LETTER; setX(((SVGPathSegMovetoRel)pathSeg).getX()); setY(((SVGPathSegMovetoRel)pathSeg).getY()); break; case SVGPathSeg.PATHSEG_MOVETO_ABS: letter = PATHSEG_MOVETO_ABS_LETTER; setX(((SVGPathSegMovetoAbs)pathSeg).getX()); setY(((SVGPathSegMovetoAbs)pathSeg).getY()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX()) + ' ' + Float.toString(getY()); } } public class SVGPathSegCurvetoCubicItem extends SVGPathSegItem implements SVGPathSegCurvetoCubicAbs, SVGPathSegCurvetoCubicRel { public SVGPathSegCurvetoCubicItem(short type,String letter, float x1,float y1,float x2, float y2, float x, float y){ super(type,letter); this.setX(x); this.setY(y); this.setX1(x1); this.setY1(y1); this.setX2(x2); this.setY2(y2); } public SVGPathSegCurvetoCubicItem(SVGPathSeg pathSeg){ this.type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS: letter = PATHSEG_CURVETO_CUBIC_ABS_LETTER; setX(((SVGPathSegCurvetoCubicAbs)pathSeg).getX()); setY(((SVGPathSegCurvetoCubicAbs)pathSeg).getY()); setX1(((SVGPathSegCurvetoCubicAbs)pathSeg).getX1()); setY1(((SVGPathSegCurvetoCubicAbs)pathSeg).getY1()); setX2(((SVGPathSegCurvetoCubicAbs)pathSeg).getX2()); setY2(((SVGPathSegCurvetoCubicAbs)pathSeg).getY2()); break; case SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL: letter = PATHSEG_CURVETO_CUBIC_REL_LETTER; setX(((SVGPathSegCurvetoCubicRel)pathSeg).getX()); setY(((SVGPathSegCurvetoCubicRel)pathSeg).getY()); setX1(((SVGPathSegCurvetoCubicRel)pathSeg).getX1()); setY1(((SVGPathSegCurvetoCubicRel)pathSeg).getY1()); setX2(((SVGPathSegCurvetoCubicRel)pathSeg).getX2()); setY2(((SVGPathSegCurvetoCubicRel)pathSeg).getY2()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } public void setX1(float x1){ super.setX1(x1); resetAttribute(); } public void setY1(float y1){ super.setY1(y1); resetAttribute(); } public void setX2(float x2){ super.setX2(x2); resetAttribute(); } public void setY2(float y2){ super.setY2(y2); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX1()) + ' ' + Float.toString(getY1()) + ' ' + Float.toString(getX2()) + ' ' + Float.toString(getY2()) + ' ' + Float.toString(getX()) + ' ' + Float.toString(getY()); } } public class SVGPathSegCurvetoQuadraticItem extends SVGPathSegItem implements SVGPathSegCurvetoQuadraticAbs, SVGPathSegCurvetoQuadraticRel { public SVGPathSegCurvetoQuadraticItem(short type,String letter, float x1,float y1,float x, float y ){ super(type,letter); this.setX(x); this.setY(y); this.setX1(x1); this.setY1(y1); } public SVGPathSegCurvetoQuadraticItem(SVGPathSeg pathSeg){ this.type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS: letter = PATHSEG_CURVETO_QUADRATIC_ABS_LETTER; setX(((SVGPathSegCurvetoQuadraticAbs)pathSeg).getX()); setY(((SVGPathSegCurvetoQuadraticAbs)pathSeg).getY()); setX1(((SVGPathSegCurvetoQuadraticAbs)pathSeg).getX1()); setY1(((SVGPathSegCurvetoQuadraticAbs)pathSeg).getY1()); break; case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL: letter = PATHSEG_CURVETO_QUADRATIC_REL_LETTER; setX(((SVGPathSegCurvetoQuadraticRel)pathSeg).getX()); setY(((SVGPathSegCurvetoQuadraticRel)pathSeg).getY()); setX1(((SVGPathSegCurvetoQuadraticRel)pathSeg).getX1()); setY1(((SVGPathSegCurvetoQuadraticRel)pathSeg).getY1()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } public void setX1(float x1){ super.setX1(x1); resetAttribute(); } public void setY1(float y1){ super.setY1(y1); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX1()) + ' ' + Float.toString(getY1()) + ' ' + Float.toString(getX()) + ' ' + Float.toString(getY()); } } public class SVGPathSegArcItem extends SVGPathSegItem implements SVGPathSegArcAbs, SVGPathSegArcRel { public SVGPathSegArcItem(short type,String letter, float r1,float r2,float angle, boolean largeArcFlag, boolean sweepFlag, float x, float y ){ super(type,letter); this.setX(x); this.setY(y); this.setR1(r1); this.setR2(r2); this.setAngle(angle); this.setLargeArcFlag(largeArcFlag); this.setSweepFlag(sweepFlag); } public SVGPathSegArcItem(SVGPathSeg pathSeg){ type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_ARC_ABS: letter = PATHSEG_ARC_ABS_LETTER; setX(((SVGPathSegArcAbs)pathSeg).getX()); setY(((SVGPathSegArcAbs)pathSeg).getY()); setR1(((SVGPathSegArcAbs)pathSeg).getR1()); setR2(((SVGPathSegArcAbs)pathSeg).getR2()); setAngle(((SVGPathSegArcAbs)pathSeg).getAngle()); setLargeArcFlag(((SVGPathSegArcAbs)pathSeg).getLargeArcFlag()); setSweepFlag(((SVGPathSegArcAbs)pathSeg).getSweepFlag()); break; case SVGPathSeg.PATHSEG_ARC_REL: letter = PATHSEG_ARC_REL_LETTER; setX(((SVGPathSegArcRel)pathSeg).getX()); setY(((SVGPathSegArcRel)pathSeg).getY()); setR1(((SVGPathSegArcRel)pathSeg).getR1()); setR2(((SVGPathSegArcRel)pathSeg).getR2()); setAngle(((SVGPathSegArcRel)pathSeg).getAngle()); setLargeArcFlag(((SVGPathSegArcRel)pathSeg).getLargeArcFlag()); setSweepFlag(((SVGPathSegArcRel)pathSeg).getSweepFlag()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } public void setR1(float r1){ super.setR1(r1); resetAttribute(); } public void setR2(float r2){ super.setR2(r2); resetAttribute(); } public void setAngle(float angle){ super.setAngle(angle); resetAttribute(); } public boolean getSweepFlag(){ return isSweepFlag(); } public void setSweepFlag(boolean sweepFlag){ super.setSweepFlag(sweepFlag); resetAttribute(); } public boolean getLargeArcFlag(){ return isLargeArcFlag(); } public void setLargeArcFlag(boolean largeArcFlag){ super.setLargeArcFlag(largeArcFlag); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getR1()) + ' ' + Float.toString(getR2()) + ' ' + Float.toString(getAngle()) + ' ' + ((isLargeArcFlag()?"1":"0")) + ' ' + ((isSweepFlag()?"1":"0")) + (' ') + Float.toString(getX()) + ' ' + Float.toString(getY()); } } public class SVGPathSegLinetoHorizontalItem extends SVGPathSegItem implements SVGPathSegLinetoHorizontalAbs, SVGPathSegLinetoHorizontalRel { public SVGPathSegLinetoHorizontalItem(short type, String letter, float value){ super(type,letter); this.setX(value); } public SVGPathSegLinetoHorizontalItem(SVGPathSeg pathSeg){ this.type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS: letter = PATHSEG_LINETO_HORIZONTAL_ABS_LETTER; setX(((SVGPathSegLinetoHorizontalAbs)pathSeg).getX()); break; case SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL: letter = PATHSEG_LINETO_HORIZONTAL_REL_LETTER; setX(((SVGPathSegLinetoHorizontalRel)pathSeg).getX()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX()); } } public class SVGPathSegLinetoVerticalItem extends SVGPathSegItem implements SVGPathSegLinetoVerticalAbs, SVGPathSegLinetoVerticalRel { public SVGPathSegLinetoVerticalItem(short type, String letter, float value){ super(type,letter); this.setY(value); } public SVGPathSegLinetoVerticalItem(SVGPathSeg pathSeg){ type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS: letter = PATHSEG_LINETO_VERTICAL_ABS_LETTER; setY(((SVGPathSegLinetoVerticalAbs)pathSeg).getY()); break; case SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL: letter = PATHSEG_LINETO_VERTICAL_REL_LETTER; setY(((SVGPathSegLinetoVerticalRel)pathSeg).getY()); break; default: } } public void setY(float y){ super.setY(y); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getY()); } } public class SVGPathSegCurvetoCubicSmoothItem extends SVGPathSegItem implements SVGPathSegCurvetoCubicSmoothAbs, SVGPathSegCurvetoCubicSmoothRel { public SVGPathSegCurvetoCubicSmoothItem(short type,String letter, float x2,float y2,float x, float y ){ super(type,letter); this.setX(x); this.setY(y); this.setX2(x2); this.setY2(y2); } public SVGPathSegCurvetoCubicSmoothItem(SVGPathSeg pathSeg){ type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS: letter = PATHSEG_CURVETO_CUBIC_SMOOTH_ABS_LETTER; setX(((SVGPathSegCurvetoCubicSmoothAbs)pathSeg).getX()); setY(((SVGPathSegCurvetoCubicSmoothAbs)pathSeg).getY()); setX2(((SVGPathSegCurvetoCubicSmoothAbs)pathSeg).getX2()); setY2(((SVGPathSegCurvetoCubicSmoothAbs)pathSeg).getY2()); break; case SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL: letter = PATHSEG_CURVETO_CUBIC_SMOOTH_REL_LETTER; setX(((SVGPathSegCurvetoCubicSmoothRel)pathSeg).getX()); setY(((SVGPathSegCurvetoCubicSmoothRel)pathSeg).getY()); setX2(((SVGPathSegCurvetoCubicSmoothRel)pathSeg).getX2()); setY2(((SVGPathSegCurvetoCubicSmoothRel)pathSeg).getY2()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } public void setX2(float x2){ super.setX2(x2); resetAttribute(); } public void setY2(float y2){ super.setY2(y2); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX2()) + ' ' + Float.toString(getY2()) + ' ' + Float.toString(getX()) + ' ' + Float.toString(getY()); } } public class SVGPathSegCurvetoQuadraticSmoothItem extends SVGPathSegItem implements SVGPathSegCurvetoQuadraticSmoothAbs , SVGPathSegCurvetoQuadraticSmoothRel { public SVGPathSegCurvetoQuadraticSmoothItem(short type, String letter, float x, float y){ super(type,letter); this.setX(x); this.setY(y); } public SVGPathSegCurvetoQuadraticSmoothItem(SVGPathSeg pathSeg){ type = pathSeg.getPathSegType(); switch(type){ case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS: letter = PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS_LETTER; setX(((SVGPathSegCurvetoQuadraticSmoothAbs)pathSeg).getX()); setY(((SVGPathSegCurvetoQuadraticSmoothAbs)pathSeg).getY()); break; case SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL: letter = PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL_LETTER; setX(((SVGPathSegCurvetoQuadraticSmoothRel)pathSeg).getX()); setY(((SVGPathSegCurvetoQuadraticSmoothRel)pathSeg).getY()); break; default: } } public void setX(float x){ super.setX(x); resetAttribute(); } public void setY(float y){ super.setY(y); resetAttribute(); } protected String getStringValue(){ return letter + ' ' + Float.toString(getX()) + ' ' + Float.toString(getY()); } } protected class PathSegListBuilder extends DefaultPathHandler { protected ListHandler listHandler; public PathSegListBuilder(ListHandler listHandler){ this.listHandler = listHandler; } /** * Implements {@link org.apache.batik.parser.PathHandler#startPath()}. */ public void startPath() throws ParseException { listHandler.startList(); } /** * Implements {@link org.apache.batik.parser.PathHandler#endPath()}. */ public void endPath() throws ParseException { listHandler.endList(); } /** * Implements {@link org.apache.batik.parser.PathHandler#movetoRel(float,float)}. */ public void movetoRel(float x, float y) throws ParseException { listHandler.item(new SVGPathSegMovetoLinetoItem (SVGPathSeg.PATHSEG_MOVETO_REL,PATHSEG_MOVETO_REL_LETTER, x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#movetoAbs(float,float)}. */ public void movetoAbs(float x, float y) throws ParseException { listHandler.item(new SVGPathSegMovetoLinetoItem (SVGPathSeg.PATHSEG_MOVETO_ABS,PATHSEG_MOVETO_ABS_LETTER, x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#closePath()}. */ public void closePath() throws ParseException { listHandler.item(new SVGPathSegItem (SVGPathSeg.PATHSEG_CLOSEPATH,PATHSEG_CLOSEPATH_LETTER)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoRel(float,float)}. */ public void linetoRel(float x, float y) throws ParseException { listHandler.item(new SVGPathSegMovetoLinetoItem (SVGPathSeg.PATHSEG_LINETO_REL,PATHSEG_LINETO_REL_LETTER, x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoAbs(float,float)}. */ public void linetoAbs(float x, float y) throws ParseException { listHandler.item(new SVGPathSegMovetoLinetoItem (SVGPathSeg.PATHSEG_LINETO_ABS,PATHSEG_LINETO_ABS_LETTER, x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoHorizontalRel(float)}. */ public void linetoHorizontalRel(float x) throws ParseException { listHandler.item(new SVGPathSegLinetoHorizontalItem (SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL,PATHSEG_LINETO_HORIZONTAL_REL_LETTER, x)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoHorizontalAbs(float)}. */ public void linetoHorizontalAbs(float x) throws ParseException { listHandler.item(new SVGPathSegLinetoHorizontalItem (SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS,PATHSEG_LINETO_HORIZONTAL_ABS_LETTER, x)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoVerticalRel(float)}. */ public void linetoVerticalRel(float y) throws ParseException { listHandler.item(new SVGPathSegLinetoVerticalItem (SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL,PATHSEG_LINETO_VERTICAL_REL_LETTER, y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#linetoVerticalAbs(float)}. */ public void linetoVerticalAbs(float y) throws ParseException { listHandler.item(new SVGPathSegLinetoVerticalItem (SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS,PATHSEG_LINETO_VERTICAL_ABS_LETTER, y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoCubicRel(float,float,float,float,float,float)}. */ public void curvetoCubicRel(float x1, float y1, float x2, float y2, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoCubicItem (SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL,PATHSEG_CURVETO_CUBIC_REL_LETTER, x1,y1,x2,y2,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoCubicAbs(float,float,float,float,float,float)}. */ public void curvetoCubicAbs(float x1, float y1, float x2, float y2, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoCubicItem (SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS,PATHSEG_CURVETO_CUBIC_ABS_LETTER, x1,y1,x2,y2,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoCubicSmoothRel(float,float,float,float)}. */ public void curvetoCubicSmoothRel(float x2, float y2, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoCubicSmoothItem (SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL,PATHSEG_CURVETO_CUBIC_SMOOTH_REL_LETTER, x2,y2,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoCubicSmoothAbs(float,float,float,float)}. */ public void curvetoCubicSmoothAbs(float x2, float y2, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoCubicSmoothItem (SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS,PATHSEG_CURVETO_CUBIC_SMOOTH_ABS_LETTER, x2,y2,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoQuadraticRel(float,float,float,float)}. */ public void curvetoQuadraticRel(float x1, float y1, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoQuadraticItem (SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL,PATHSEG_CURVETO_QUADRATIC_REL_LETTER, x1,y1,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#curvetoQuadraticAbs(float,float,float,float)}. */ public void curvetoQuadraticAbs(float x1, float y1, float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoQuadraticItem (SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS,PATHSEG_CURVETO_QUADRATIC_ABS_LETTER, x1,y1,x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#curvetoQuadraticSmoothRel(float,float)}. */ public void curvetoQuadraticSmoothRel(float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoQuadraticSmoothItem (SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL,PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL_LETTER, x,y)); } /** * Implements {@link org.apache.batik.parser.PathHandler#curvetoQuadraticSmoothAbs(float,float)}. */ public void curvetoQuadraticSmoothAbs(float x, float y) throws ParseException { listHandler.item(new SVGPathSegCurvetoQuadraticSmoothItem (SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS,PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS_LETTER, x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#arcRel(float,float,float,boolean,boolean,float,float)}. */ public void arcRel(float rx, float ry, float xAxisRotation, boolean largeArcFlag, boolean sweepFlag, float x, float y) throws ParseException { listHandler.item(new SVGPathSegArcItem (SVGPathSeg.PATHSEG_ARC_REL,PATHSEG_ARC_REL_LETTER, rx,ry,xAxisRotation,largeArcFlag,sweepFlag,x,y)); } /** * Implements {@link * org.apache.batik.parser.PathHandler#arcAbs(float,float,float,boolean,boolean,float,float)}. */ public void arcAbs(float rx, float ry, float xAxisRotation, boolean largeArcFlag, boolean sweepFlag, float x, float y) throws ParseException { listHandler.item(new SVGPathSegArcItem (SVGPathSeg.PATHSEG_ARC_ABS,PATHSEG_ARC_ABS_LETTER, rx,ry,xAxisRotation,largeArcFlag,sweepFlag,x,y)); } } }
33,621
Java
.java
833
27.854742
109
0.579613
git-moss/Push2Display
16
3
0
LGPL-3.0
9/4/2024, 8:19:01 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
33,621
3,990,796
AbstractDataset.java
pablopatarca_proyecto-teoria-control-utn-frro/jfreechart-1.0.16/source/org/jfree/data/general/AbstractDataset.java
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------------- * AbstractDataset.java * -------------------- * (C)opyright 2000-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): Nicolas Brodu (for Astrium and EADS Corporate Research * Center); * * Changes (from 21-Aug-2001) * -------------------------- * 21-Aug-2001 : Added standard header. Fixed DOS encoding problem (DG); * 18-Sep-2001 : Updated e-mail address in header (DG); * 15-Oct-2001 : Moved to new package (com.jrefinery.data.*) (DG); * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG); * 17-Nov-2001 : Changed constructor from public to protected, created new * AbstractSeriesDataset class and transferred series-related * methods, updated Javadoc comments (DG); * 04-Mar-2002 : Updated import statements (DG); * 11-Jun-2002 : Updated for change in the event constructor (DG); * 07-Aug-2002 : Changed listener list to use * javax.swing.event.EventListenerList (DG); * 04-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 27-Mar-2003 : Implemented Serializable (DG); * 18-Aug-2003 : Implemented Cloneable (DG); * 08-Sep-2003 : Serialization fixes (NB); * 11-Sep-2003 : Cloning Fixes (NB); * 01-Jun-2005 : Added hasListener() method for unit testing (DG); * 03-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.data.general; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util.EventListener; import java.util.List; import javax.swing.event.EventListenerList; import org.jfree.chart.util.ParamChecks; /** * An abstract implementation of the {@link Dataset} interface, containing a * mechanism for registering change listeners. */ public abstract class AbstractDataset implements Dataset, Cloneable, Serializable, ObjectInputValidation { /** For serialization. */ private static final long serialVersionUID = 1918768939869230744L; /** The group that the dataset belongs to. */ private DatasetGroup group; /** Storage for registered change listeners. */ private transient EventListenerList listenerList; /** * Constructs a dataset. By default, the dataset is assigned to its own * group. */ protected AbstractDataset() { this.group = new DatasetGroup(); this.listenerList = new EventListenerList(); } /** * Returns the dataset group for the dataset. * * @return The group (never <code>null</code>). * * @see #setGroup(DatasetGroup) */ public DatasetGroup getGroup() { return this.group; } /** * Sets the dataset group for the dataset. * * @param group the group (<code>null</code> not permitted). * * @see #getGroup() */ public void setGroup(DatasetGroup group) { ParamChecks.nullNotPermitted(group, "group"); this.group = group; } /** * Registers an object to receive notification of changes to the dataset. * * @param listener the object to register. * * @see #removeChangeListener(DatasetChangeListener) */ public void addChangeListener(DatasetChangeListener listener) { this.listenerList.add(DatasetChangeListener.class, listener); } /** * Deregisters an object so that it no longer receives notification of * changes to the dataset. * * @param listener the object to deregister. * * @see #addChangeListener(DatasetChangeListener) */ public void removeChangeListener(DatasetChangeListener listener) { this.listenerList.remove(DatasetChangeListener.class, listener); } /** * Returns <code>true</code> if the specified object is registered with * the dataset as a listener. Most applications won't need to call this * method, it exists mainly for use by unit testing code. * * @param listener the listener. * * @return A boolean. * * @see #addChangeListener(DatasetChangeListener) * @see #removeChangeListener(DatasetChangeListener) */ public boolean hasListener(EventListener listener) { List list = Arrays.asList(this.listenerList.getListenerList()); return list.contains(listener); } /** * Notifies all registered listeners that the dataset has changed. * * @see #addChangeListener(DatasetChangeListener) */ protected void fireDatasetChanged() { notifyListeners(new DatasetChangeEvent(this, this)); } /** * Notifies all registered listeners that the dataset has changed. * * @param event contains information about the event that triggered the * notification. * * @see #addChangeListener(DatasetChangeListener) * @see #removeChangeListener(DatasetChangeListener) */ protected void notifyListeners(DatasetChangeEvent event) { Object[] listeners = this.listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == DatasetChangeListener.class) { ((DatasetChangeListener) listeners[i + 1]).datasetChanged( event); } } } /** * Returns a clone of the dataset. The cloned dataset will NOT include the * {@link DatasetChangeListener} references that have been registered with * this dataset. * * @return A clone. * * @throws CloneNotSupportedException if the dataset does not support * cloning. */ public Object clone() throws CloneNotSupportedException { AbstractDataset clone = (AbstractDataset) super.clone(); clone.listenerList = new EventListenerList(); return clone; } /** * Handles serialization. * * @param stream the output stream. * * @throws IOException if there is an I/O problem. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); } /** * Restores a serialized object. * * @param stream the input stream. * * @throws IOException if there is an I/O problem. * @throws ClassNotFoundException if there is a problem loading a class. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.listenerList = new EventListenerList(); stream.registerValidation(this, 10); // see comments about priority of // 10 in validateObject() } /** * Validates the object. We use this opportunity to call listeners who have * registered during the deserialization process, as listeners are not * serialized. This method is called by the serialization system after the * entire graph is read. * * This object has registered itself to the system with a priority of 10. * Other callbacks may register with a higher priority number to be called * before this object, or with a lower priority number to be called after * the listeners were notified. * * All listeners are supposed to have register by now, either in their * readObject or validateObject methods. Notify them that this dataset has * changed. * * @exception InvalidObjectException If the object cannot validate itself. */ public void validateObject() throws InvalidObjectException { fireDatasetChanged(); } }
9,302
Java
.java
234
33.431624
80
0.656582
pablopatarca/proyecto-teoria-control-utn-frro
2
0
0
GPL-2.0
9/4/2024, 11:59:28 PM (Europe/Amsterdam)
false
true
true
true
true
true
true
true
9,302
1,316,833
A.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test68/in/A.java
public class A extends C { public A() { i= 1; } public int m(D d) { B b= new B() { public int n() { return i; } }; return b.n(); } public static void main(String[] args) { System.out.println(new A().m(new D())); } } class B extends C { public int n() { return -1; } } class C { public int i= 0; } class D { }
347
Java
.java
26
10.884615
41
0.576433
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
false
true
true
false
true
true
347
1,820,085
FAtribuicao.java
cams7_erp/freedom/src/main/java/org/freedom/modulos/atd/view/frame/crud/plain/FAtribuicao.java
/** * @version 02/11/2003 <BR> * @author Setpoint Informática Ltda./Fernando Oliveira da Silva <BR> * * Projeto: Freedom <BR> * * Pacote: org.freedom.modulos.atd <BR> * Classe: @(#)FAtribuicao.java <BR> * * Este arquivo é parte do sistema Freedom-ERP, o Freedom-ERP é um software livre; você pode redistribui-lo e/ou <BR> * modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); <BR> * na versão 2 da Licença, ou (na sua opnião) qualquer versão. <BR> * Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; <BR> * sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. <BR> * Veja a Licença Pública Geral GNU para maiores detalhes. <BR> * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa, se não, <BR> * escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA <BR> * <BR> * * Comentários sobre a classe... * */ package org.freedom.modulos.atd.view.frame.crud.plain; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.freedom.infra.functions.StringFunctions; import org.freedom.library.component.ImprimeOS; import org.freedom.library.functions.Funcoes; import org.freedom.library.persistence.ListaCampos; import org.freedom.library.swing.component.JTextAreaPad; import org.freedom.library.swing.component.JTextFieldPad; import org.freedom.library.swing.frame.FDados; import org.freedom.library.type.TYPE_PRINT; import org.freedom.modulos.atd.view.dialog.report.DLRTipoConv; public class FAtribuicao extends FDados implements ActionListener { private static final long serialVersionUID = 1L; private JTextFieldPad txtCodAtrib = new JTextFieldPad( JTextFieldPad.TP_STRING, 15, 0 ); private JTextFieldPad txtDescAtrib = new JTextFieldPad( JTextFieldPad.TP_STRING, 50, 0 ); private JTextAreaPad txaObsAtrib = new JTextAreaPad(); public FAtribuicao() { super(); setTitulo( "Cadastro de Atribuições" ); setAtribos( 20, 20, 370, 225 ); adicCampo( txtCodAtrib, 7, 20, 80, 20, "CodAtrib", "Cód.atrib.", ListaCampos.DB_PK, true ); adicCampo( txtDescAtrib, 90, 20, 250, 20, "DescAtrib", "Descrição da atribuição", ListaCampos.DB_SI, true ); adicDB( txaObsAtrib, 7, 60, 333, 80, "ObsAtrib", "Observação", true ); setListaCampos( true, "ATRIBUICAO", "AT" ); btImp.addActionListener( this ); btPrevimp.addActionListener( this ); lcCampos.setQueryInsert( false ); setImprimir( true ); } public void actionPerformed( ActionEvent evt ) { if ( evt.getSource() == btPrevimp ) { // Funcoes.mensageInforma(this, "Teste"); imprimir( TYPE_PRINT.VIEW ); } else if ( evt.getSource() == btImp ) imprimir( TYPE_PRINT.PRINT); super.actionPerformed( evt ); } private void imprimir( TYPE_PRINT bVisualizar ) { ImprimeOS imp = new ImprimeOS( "", con ); int linPag = imp.verifLinPag() - 1; imp.montaCab(); imp.setTitulo( "Relatório de Atribuições" ); DLRTipoConv dl = new DLRTipoConv(); dl.setVisible( true ); if ( dl.OK == false ) { dl.dispose(); return; } String sSQL = "SELECT CODATRIB,DESCATRIB FROM ATATRIBUICAO ORDER BY " + dl.getValor(); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement( sSQL ); rs = ps.executeQuery(); imp.limpaPags(); while ( rs.next() ) { if ( imp.pRow() == 0 ) { imp.impCab( 80, false ); imp.say( imp.pRow() + 0, 0, "" + imp.normal() ); imp.say( imp.pRow() + 0, 0, "" ); imp.say( imp.pRow() + 0, 2, "Cód.atrib." ); imp.say( imp.pRow() + 0, 25, "Descrição" ); imp.say( imp.pRow() + 1, 0, "" + imp.normal() ); imp.say( imp.pRow() + 0, 0, StringFunctions.replicate( "-", 79 ) ); } imp.say( imp.pRow() + 1, 0, "" + imp.normal() ); imp.say( imp.pRow() + 0, 2, rs.getString( "CodAtrib" ) ); imp.say( imp.pRow() + 0, 25, rs.getString( "DescAtrib" ) ); if ( imp.pRow() >= linPag ) { imp.incPags(); imp.eject(); } } imp.say( imp.pRow() + 1, 0, "" + imp.normal() ); imp.say( imp.pRow() + 0, 0, StringFunctions.replicate( "=", 79 ) ); imp.eject(); imp.fechaGravacao(); // rs.close(); // ps.close(); con.commit(); dl.dispose(); } catch ( SQLException err ) { Funcoes.mensagemErro( this, "Erro consulta tabela de atribuições!" + err.getMessage(), true, con, err ); } if ( bVisualizar==TYPE_PRINT.VIEW ) { imp.preview( this ); } else { imp.print(); } } }
4,803
Java
.java
119
36.831933
128
0.679074
cams7/erp
12
13
0
GPL-3.0
9/4/2024, 8:19:45 PM (Europe/Amsterdam)
false
false
true
true
false
true
false
true
4,758
1,316,593
A_testAll39_out.java
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll39_out.java
package p; //to public class A{ public int m(boolean jj, Object x, int i){ return m(false, x, m(jj, x, i)); } } class B extends A{ public int m(boolean jj, Object x, int i){ return m(false, x, m(jj, x, i)); } }
218
Java
.java
12
16.583333
43
0.637681
eclipse-jdt/eclipse.jdt.ui
35
86
242
EPL-2.0
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
false
false
true
true
true
true
true
true
218