blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9c1155c37294c4b39629e8783c56df6a4ece7c02 | b8360bb6c3140031159b3cc73c1d6b5d88ffdad3 | /src/main/java/com/endava/appium/framework/util/HttpDeleteWithBody.java | 59ca3aa609a2613b7fdc5c5ad041bb769eea64d1 | []
| no_license | tod00RS/EndavaGoTestFramework | f8c4608e172047757eca8e16ab126966ec0d5bb5 | 589b2a7b7c826e6eba2adf3ae1ea34f067378395 | refs/heads/master | 2023-05-31T17:22:54.065263 | 2020-05-21T10:53:52 | 2020-05-21T10:53:52 | 265,824,937 | 0 | 0 | null | 2021-06-07T18:47:05 | 2020-05-21T10:55:20 | Java | UTF-8 | Java | false | false | 682 | java | package com.endava.appium.framework.util;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
/**
* Added since appache does not support sending DELETE request with a BODY attached
*/
@NotThreadSafe
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() {
super();
}
public String getMethod() {
return METHOD_NAME;
}
} | [
"Ludisamuraj@007"
]
| Ludisamuraj@007 |
239d29e9e1150cf3035cb86ef6c4bb2d2da9f544 | d7dfbdabcbc95ce559b501708e4330a8f298eb6d | /src/main/java/hudson/plugins/pxe/ZipTree.java | 54cf97da99aa4f027d7838f4cd730eac1959bf8c | []
| no_license | jenkinsci/pxe-plugin | 5aebc299784caf1a13a20d5884a2a11d21baa570 | 201b0c4a99a12856054159a5118cdfa336d557a1 | refs/heads/master | 2023-05-30T22:33:38.422510 | 2012-04-06T16:11:05 | 2012-04-06T16:11:05 | 1,163,712 | 1 | 5 | null | null | null | null | UTF-8 | Java | false | false | 2,629 | java | package hudson.plugins.pxe;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Binding {@link ZipFile} to an HTTP URL space.
*
* <p>
* Not designed for great performance.
*
* @author Kohsuke Kawaguchi
*/
public class ZipTree implements HttpResponse {
private final File zip;
public ZipTree(File zip) {
this.zip = zip;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
ZipFile zf = new ZipFile(zip);
try {
String rest = req.getRestOfPath().substring(1); // trim off the head '/'
if(!rest.endsWith("/")) rest+="/";
// because of the idiosyncrasy in zf.getEntry, it may match "foo" when it should only match "foo/",
// so be defensive
ZipEntry e = zf.getEntry(rest);
if(e==null) e=zf.getEntry(rest.substring(0,rest.length()-1));
if(e==null) {
rsp.sendError(SC_NOT_FOUND);
return;
}
if(e.isDirectory()) {
// if the target page to be displayed is a directory and the path doesn't end with '/', redirect
StringBuffer reqUrl = req.getRequestURL();
if(reqUrl.charAt(reqUrl.length()-1)!='/') {
rsp.sendRedirect2(reqUrl.append('/').toString());
return;
}
rsp.setContentType("text/html");
PrintWriter w = new PrintWriter(rsp.getWriter());
w.println("<html><body>");
Enumeration<? extends ZipEntry> list = zf.entries();
while (list.hasMoreElements()) {
ZipEntry f = list.nextElement();
if(f.getName().startsWith(e.getName()))
w.printf("<LI><A HREF='%1$s'>%1$s</A></LI>",f.getName().substring(rest.length()));
}
w.println("</body></html>");
} else {
InputStream in = zf.getInputStream(e);
rsp.serveFile(req, in, e.getTime(), 1000L*1000*1000, (int)e.getSize(), e.getName());
}
} finally {
zf.close();
}
}
}
| [
"[email protected]"
]
| |
acef780e58cb2d11279174fec247fe473e456869 | 1e9786c55589caa60c46a45f77a50fb6131e7be4 | /src/main/ee/tlu/springrestfulws/service/impl/SchoolRepository.java | df549c45730c113add6a3f092da15f81a62f6b90 | []
| no_license | madis121/SpringRestfulWSReactiveFunctional | 3050b7822a3dcb46cb8dd52352eb97eedb090fa9 | 768bd72a21d5f22cebc798e5cb9c4612d8b6e5d7 | refs/heads/master | 2021-01-24T16:19:15.477495 | 2018-03-04T13:17:33 | 2018-03-04T13:17:34 | 123,181,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,009 | java | package ee.tlu.springrestfulws.service.impl;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import ee.tlu.springrestfulws.dto.School;
import ee.tlu.springrestfulws.dto.Student;
import ee.tlu.springrestfulws.exception.ResourceNotFoundException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class SchoolRepository {
private static Map<Long, School> schools = new HashMap<>();
static {
Map<Long, Student> s1 = new HashMap<>();
s1.put((long) (s1.size() + 1), new Student(s1.size() + 1, "Juku", "Juurikas"));
s1.put((long) (s1.size() + 1), new Student(s1.size() + 1, "Mari", "Maasikas"));
Map<Long, Student> s2 = new HashMap<>();
s2.put((long) (s2.size() + 1), new Student(s2.size() + 1, "Mart", "Murakas"));
s2.put((long) (s2.size() + 1), new Student(s2.size() + 1, "Teele", "Tamme"));
schools.put((long) (schools.size() + 1), new School(schools.size() + 1, "Gustav Adolfi Gümnaasium", s1));
schools.put((long) (schools.size() + 1), new School(schools.size() + 1, "Kadrioru Saksa Gümnaasium", s2));
}
public Flux<School> all() {
return Flux.fromIterable(schools.values());
}
public Mono<School> findById(Long id) {
return Mono.justOrEmpty(schools.get(id));
}
public Mono<Void> save(Mono<School> school) {
return school.doOnNext(value -> {
long id = schools.size() + 1;
value.setId(id);
schools.put(id, value);
}).thenEmpty(Mono.empty());
}
public Mono<School> update(Long id, Mono<School> school) {
Mono<School> existing = Mono.justOrEmpty(schools.get(id));
return existing.doOnNext(e -> {
school.doOnNext(s -> {
e.setName(s.getName());
e.setStudents(s.getStudents());
});
}).switchIfEmpty(Mono.error(new ResourceNotFoundException("School with the id of " + id + " does not exist")));
}
public Mono<Void> delete(Long id) {
schools.remove(id);
return Mono.empty();
}
public Map<Long, School> getSchools() {
return schools;
}
}
| [
"[email protected]"
]
| |
3941dfedaeaa8af24126788c0e0a9cceb4d94674 | c6992ce8db7e5aab6fd959c0c448659ab91b16ce | /sdk/batch/azure-resourcemanager-batch/src/main/java/com/azure/resourcemanager/batch/models/DiffDiskPlacement.java | 9c9ba3e41e9a2657ed9bb9089d8e795a41f44e4f | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
]
| permissive | g2vinay/azure-sdk-for-java | ae6d94d583cc2983a5088ec8f6146744ee82cb55 | b88918a2ba0c3b3e88a36c985e6f83fc2bae2af2 | refs/heads/master | 2023-09-01T17:46:08.256214 | 2021-09-23T22:20:20 | 2021-09-23T22:20:20 | 161,234,198 | 3 | 1 | MIT | 2020-01-16T20:22:43 | 2018-12-10T20:44:41 | Java | UTF-8 | Java | false | false | 1,276 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.batch.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/** Defines values for DiffDiskPlacement. */
public enum DiffDiskPlacement {
/** Enum value CacheDisk. */
CACHE_DISK("CacheDisk");
/** The actual serialized value for a DiffDiskPlacement instance. */
private final String value;
DiffDiskPlacement(String value) {
this.value = value;
}
/**
* Parses a serialized value to a DiffDiskPlacement instance.
*
* @param value the serialized value to parse.
* @return the parsed DiffDiskPlacement object, or null if unable to parse.
*/
@JsonCreator
public static DiffDiskPlacement fromString(String value) {
DiffDiskPlacement[] items = DiffDiskPlacement.values();
for (DiffDiskPlacement item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
| [
"[email protected]"
]
| |
747efc179b369c77e919eedd9d125900506a669d | 1d7463a35762da0558448969cff3ce66e04d8cca | /modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v201711/TechnologyTargetingErrorReason.java | 57ca45b3ed0147b71756e9cfa7db0ce488e2f94f | [
"Apache-2.0"
]
| permissive | jcavalcante/googleads-java-lib | 9694ccd19642d380731db34c63beb406ed2bc170 | 9cb9782edf43ae1280ababbc0f89f945a1cd677c | refs/heads/master | 2020-04-01T21:53:33.161012 | 2018-09-27T14:56:18 | 2018-09-27T14:56:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,914 | java | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v201711;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TechnologyTargetingError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="TechnologyTargetingError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="MOBILE_LINE_ITEM_CONTAINS_WEB_TECH_CRITERIA"/>
* <enumeration value="WEB_LINE_ITEM_CONTAINS_MOBILE_TECH_CRITERIA"/>
* <enumeration value="MOBILE_CARRIER_TARGETING_FEATURE_NOT_ENABLED"/>
* <enumeration value="DEVICE_CAPABILITY_TARGETING_FEATURE_NOT_ENABLED"/>
* <enumeration value="DEVICE_CATEGORY_TARGETING_FEATURE_NOT_ENABLED"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "TechnologyTargetingError.Reason")
@XmlEnum
public enum TechnologyTargetingErrorReason {
/**
*
* Mobile line item cannot target web-only targeting criteria.
*
*
*/
MOBILE_LINE_ITEM_CONTAINS_WEB_TECH_CRITERIA,
/**
*
* Web line item cannot target mobile-only targeting criteria.
*
*
*/
WEB_LINE_ITEM_CONTAINS_MOBILE_TECH_CRITERIA,
/**
*
* The mobile carrier targeting feature is not enabled.
*
*
*/
MOBILE_CARRIER_TARGETING_FEATURE_NOT_ENABLED,
/**
*
* The device capability targeting feature is not enabled.
*
*
*/
DEVICE_CAPABILITY_TARGETING_FEATURE_NOT_ENABLED,
/**
*
* The device category targeting feature is not enabled.
*
*
*/
DEVICE_CATEGORY_TARGETING_FEATURE_NOT_ENABLED,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static TechnologyTargetingErrorReason fromValue(String v) {
return valueOf(v);
}
}
| [
"[email protected]"
]
| |
e6b07a88ece50384520c7c0543200ee597326f58 | 9aed2d8c3b9ef7b3d95cdb6f0d7772c41275d05d | /src/test/java/HeyIAlreadyDidThatTests.java | 2bb7452943d83d5f20c5db760c847cabbd06d1cc | []
| no_license | knufire/Google-Foobar | c92ab51a1b5376c1571b926e7e61aa50c7630399 | a09a36b6dcffe0036fadfc1af7615b6b8ea2a134 | refs/heads/develop | 2022-09-04T23:48:40.228233 | 2020-06-01T08:54:49 | 2020-06-01T08:54:49 | 266,907,976 | 0 | 0 | null | 2020-06-01T08:57:02 | 2020-05-26T00:32:00 | Java | UTF-8 | Java | false | false | 488 | java | import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HeyIAlreadyDidThatTests {
@Test
public void testExampleOne() {
int expected = 3;
int actual = HeyIAlreadyDidThat.Solution.solution("210022", 3);
assertEquals(expected, actual);
}
@Test
public void testExampleTwo() {
int expected = 1;
int actual = HeyIAlreadyDidThat.Solution.solution("1211", 10);
assertEquals(expected, actual);
}
} | [
"[email protected]"
]
| |
e10a54735a6a29dff3b855bc45b74f099f108e90 | d97bd8cdd623d4a66e8bda51ad86c08221e87f14 | /examples/demo/domain/src/main/java/demoapp/dom/types/javalang/strings/jdo/JavaLangStringJdo.java | b91192468d0630aeaf4bc3efa632ae96e92a5acd | [
"Apache-2.0"
]
| permissive | PakhomovAlexander/isis | 24d6c238b2238c7c5bd64aee0d743851358dc50a | 71e48c7302df7ab32f3c4f99ad14e979584b15ef | refs/heads/master | 2023-03-21T03:35:38.432719 | 2021-03-16T08:27:27 | 2021-03-16T08:27:27 | 348,267,542 | 0 | 0 | NOASSERTION | 2021-03-16T08:27:28 | 2021-03-16T08:24:27 | null | UTF-8 | Java | false | false | 3,218 | 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 demoapp.dom.types.javalang.strings.jdo;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.DatastoreIdentity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Editing;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.Optionality;
import org.apache.isis.applib.annotation.Property;
import org.apache.isis.applib.annotation.Title;
import lombok.Getter;
import lombok.Setter;
import demoapp.dom._infra.asciidocdesc.HasAsciiDocDescription;
import demoapp.dom.types.javalang.strings.holder.JavaLangStringHolder2;
//tag::class[]
@PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "demo")
@DatastoreIdentity(strategy = IdGeneratorStrategy.IDENTITY, column = "id")
@DomainObject(
objectType = "demo.JavaLangStringJdo"
)
public class JavaLangStringJdo // <.>
implements HasAsciiDocDescription, JavaLangStringHolder2 {
//end::class[]
public JavaLangStringJdo(String initialValue) {
this.readOnlyProperty = initialValue;
this.readWriteProperty = initialValue;
}
//tag::class[]
@Title(prepend = "StringJDO entity: ")
@MemberOrder(name = "read-only-properties", sequence = "1")
@Column(allowsNull = "false") // <.>
@Getter @Setter
private String readOnlyProperty;
@Property(editing = Editing.ENABLED) // <.>
@MemberOrder(name = "editable-properties", sequence = "1")
@Column(allowsNull = "false")
@Getter @Setter
private String readWriteProperty;
@Property(optionality = Optionality.OPTIONAL) // <.>
@MemberOrder(name = "optional-properties", sequence = "1")
@Column(allowsNull = "true") // <.>
@Getter @Setter
private String readOnlyOptionalProperty;
@Property(editing = Editing.ENABLED, optionality = Optionality.OPTIONAL)
@MemberOrder(name = "optional-properties", sequence = "2")
@Column(allowsNull = "true")
@Getter @Setter
private String readWriteOptionalProperty;
}
//end::class[]
| [
"[email protected]"
]
| |
672ee54be8386a2f5ec3116446b3c1280713920b | 72b0ed6cee028d5793049288596a3b62978cefcb | /SOFTENG_325_Architecture/Assignments/1/se325-assignment-01/se325-concert-service/src/main/java/se325/assignment01/concert/service/mapper/SeatMapper.java | fbc3d32f93bc635b8bd250ddb84ec005aaf14f51 | []
| no_license | AidenBurgess/2020-Semester-Two | eb1900b7656070e83e833bbf0720cd6a23ad4f35 | d3f99196d71e826805878fad142dc60f098ffaaa | refs/heads/master | 2023-02-09T20:27:18.354307 | 2020-11-30T02:04:45 | 2020-11-30T02:04:45 | 282,807,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 303 | java | package se325.assignment01.concert.service.mapper;
import se325.assignment01.concert.common.dto.SeatDTO;
import se325.assignment01.concert.service.domain.Seat;
public class SeatMapper {
public static SeatDTO toDTO(Seat seat) {
return new SeatDTO(seat.getLabel(), seat.getPrice());
}
}
| [
"[email protected]"
]
| |
62c0be06912df5365d0bfd85e0975b46ae80ee3e | ed5550b09efda5189b57ef16c215b303f0cea2aa | /src/main/java/leetcode/UniquePathsII.java | d6ba47a8dd00757d09b3219c895b244318a6d133 | []
| no_license | swastik100/JavaProgramming | 39af790637c3578956713a868abe0d7f62188be8 | 15e54c459b6eb71fcacbc60f8ae4d04063b1c29a | refs/heads/master | 2023-05-14T23:45:46.221763 | 2021-06-03T19:50:00 | 2021-06-03T19:50:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,272 | java | package leetcode;
/**
* @author shivanidwivedi on 26/09/20
* @project JavaProgramming
*/
public class UniquePathsII {
public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
int rowLen = obstacleGrid.length;
int colLen = obstacleGrid[0].length;
if(obstacleGrid[0][0] == 1){
return 0;
}
obstacleGrid[0][0] = 1;
for(int i = 1; i < colLen; i++){
obstacleGrid[0][i] = (obstacleGrid[0][i] == 0 && obstacleGrid[0][i - 1] == 1) ? 1 : 0;
}
for(int i = 1; i < rowLen; i++){
obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) ? 1 : 0;
}
for(int i = 1; i < rowLen; i++){
for(int j = 1; j < colLen; j++){
if(obstacleGrid[i][j] == 0){
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
}else{
obstacleGrid[i][j] = 0;
}
}
}
return obstacleGrid[rowLen-1][colLen-1];
}
public static void main(String[] s){
System.out.println(uniquePathsWithObstacles(new int[][]{
{0,0,0},
{0,1,0},
{0,0,0}
}));
}
}
| [
"[email protected]"
]
| |
9db98f94fcf926ec5ad452181fc90256892cf63b | 22dd611f3454f6fa151f7bb0cc300fe1dfc54783 | /src/main/java/br/com/campingfire/exception/RestExceptionHandler.java | d1c28b699a2dd1a15e9ab1189f6faab020333849 | [
"MIT"
]
| permissive | pablo-matheus/camping-fire-api | 65dbe555e68079bb605cecf65f58679aec1aa28f | 02d7dd42dc560c96d15c71fa2d38e867a9883c47 | refs/heads/master | 2022-12-11T11:11:46.943502 | 2020-09-09T13:38:55 | 2020-09-09T13:38:55 | 288,516,312 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,483 | java | package br.com.campingfire.exception;
import br.com.campingfire.response.ErrorResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestControllerAdvice
public class RestExceptionHandler {
private final MessageSource messageSource;
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public List<ErrorResponse> handle(MethodArgumentNotValidException exception) {
List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
List<ErrorResponse> errorResponses = new ArrayList();
fieldErrors.forEach(e -> {
String message = messageSource.getMessage(e, Locale.ENGLISH);
ErrorResponse errorResponse = new ErrorResponse(e.getField(), message);
errorResponses.add(errorResponse);
});
return errorResponses;
}
}
| [
"[email protected]"
]
| |
f5eb1ca6cb4835f932a85ce83ad2cff83e4943e9 | fdf67de1115bd16d68899af9a224002898feb000 | /Streams_examples/src/com/nishthasoft/streams/StreamReduce.java | 16a0ff5bb00fea74b0543e745efb3e875b454b42 | []
| no_license | NishthaBhardwaj/java-8 | 850609f6f9b1f3804b05a7f87ddffac44ea7321d | 367fd95d59ca59dd7838574f5b3cc64a89accd0d | refs/heads/main | 2023-06-17T16:16:50.360675 | 2021-07-17T09:51:35 | 2021-07-17T09:51:35 | 386,899,054 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,501 | java | package com.nishthasoft.streams;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import com.nishthasoft.data.Student;
import com.nishthasoft.data.StudentDataBase;
public class StreamReduce {
public static int performMultiplication(List<Integer> list) {
int t = list.stream()
// a=1,b=1(from stream) => result 1 is return
// a=1,b=3 => from stream) => result 3 is return
// a=3,b=5 => from stream) => result 15 is return
// a=15,b=7 => result 105 is return
.peek(System.out::println) //
.reduce(1, (a, b) -> a * b);
return t;
}
public static Optional<Integer> performMultiplicationwithoutIdentity(List<Integer> list) {
Optional<Integer> t = list.stream()
// a=1,b=1(from stream) => result 1 is return
// a=1,b=3 => from stream) => result 3 is return
// a=3,b=5 => from stream) => result 15 is return
// a=15,b=7 => result 105 is return
.peek(System.out::println) //
.reduce((a, b) -> a * b);
return t;
}
public static Optional<Student> getHigherGpaStudent(){
List<Student> students = StudentDataBase.getAllStudents();
return students.stream()
.reduce((s1,s2) -> (s1.getGpa() > s2.getGpa()) ? s1 : s2 );
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 3, 5, 7);
System.out.println(performMultiplication(list));
System.out.println(performMultiplicationwithoutIdentity(list).get());
System.out.println(getHigherGpaStudent().get().getGpa());
}
}
| [
"[email protected]"
]
| |
897c16f1486ad62d2bede3ff27a7d77cc506266f | ad460988aa05f26c6a3a811ab3e07b581da9cd20 | /src/main/java/com/japan/JapanService.java | c1663e94cdb0afa1fe1c1293c0d1f13c6e9ee628 | []
| no_license | criskalesh/GitTest | e1eec99af3635aafbb1e4446f313b47e014c1b56 | 668c3f04d8921030f77285f64e2651f44b89be6c | refs/heads/master | 2021-01-23T07:59:28.720891 | 2014-08-08T13:00:52 | 2014-08-08T13:00:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 522 | java | package com.japan;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.springframework.beans.factory.annotation.Autowired;
import com.japan.dao.UserDao;
import com.japan.model.UsersGroup;
@Path("rest")
public class JapanService {
@Autowired
private UserDao userDao;
@GET
public String helloworld() {
UsersGroup ug = new UsersGroup();
ug.setName("Jinkan");
ug.setDescription("Jumpan");
try{
userDao.saveUserGroup(ug);
}catch(Exception e){
e.printStackTrace();
}
return "OK!";
}
}
| [
"[email protected]"
]
| |
f80fb9fc2644da538b343f488f32fbfe7ff687f1 | 089c10afe9d64b603093305c579c92e52470a230 | /wechat/src/main/java/com/hm/carService/controller/SubdivisionController.java | 7398efc49d9d2039abacd5978ec489b35f09b78b | []
| no_license | w133312203/wechat | 7ef950c5baac663fc17fe6cbc756f418cba50b9b | ab2be5a329995ceec9b0e676f023aa26e007495d | refs/heads/master | 2020-03-14T16:21:47.569943 | 2018-10-15T16:20:41 | 2018-10-15T16:20:41 | 131,696,854 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,441 | java | package com.hm.carService.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.hm.base.controller.BaseCotroller;
import com.hm.carService.domain.Subdivision;
import com.hm.carService.service.CarService;
import com.hm.carService.service.SubdivisionService;
import com.hm.utils.StringUtil;
@Controller
@RequestMapping("/carService")
public class SubdivisionController extends BaseCotroller{
@Autowired
CarService carService;
@Autowired
SubdivisionService subdivisionService;
//车辆细分列表页
@RequestMapping("/subdivisionList")
public ModelAndView list(Integer carId) {
ModelAndView mv = new ModelAndView("/carService/subdivision");
mv.addObject("carId",carId);
return mv;
}
//获取车辆细分列表json数据
@ResponseBody
@RequestMapping("/showSubdivisionListJson")
public Map<String,Object> showListJson(Integer carId) {
String maxresult = request.getParameter("limit");
String offset = request.getParameter("offset");
String search = request.getParameter("search");
if(StringUtil.isEmpty(search)) {
search="";
}else{
search="%"+search+"%";
}
List<Map> carList = subdivisionService.findList(carId, search,Integer.parseInt(offset), Integer.parseInt(maxresult));
Integer count = subdivisionService.findCount(carId, search);
Map<String,Object> map = new HashMap<String,Object>();
map.put("rows", carList);
map.put("total", count);
return map;
}
//编辑售卖车辆
@RequestMapping("/editSubdivision")
public ModelAndView edit(Subdivision subdivision) {
ModelAndView mv = new ModelAndView("redirect:/carService/subdivisionList?carId="+subdivision.getCarId());
if(subdivision.getId()==null) {
subdivisionService.save(subdivision);
}else {
subdivisionService.update(subdivision);
}
return mv;
}
//删除分组信息
@RequestMapping("/deleteSubdivision")
public ModelAndView delete(Integer carId, Integer id) {
ModelAndView mv = new ModelAndView("redirect:/carService/subdivisionList?carId="+carId);
subdivisionService.deleteById(id);
return mv;
}
} | [
"[email protected]"
]
| |
6f36207e6f8c3326c5e627e9e5e603589bf52787 | 0deec6666feaf9bc16c12855587d1908af524694 | /com.mobond.mindicator/com.mobond.mindicator/src/java/com/mobond/mindicator/ui/train/SourceSelectUI.java | ee670b970fcc0a8d3e1f0a4887e1b4285092100a | []
| no_license | SecretCoder404/big-data | 12927ef495a86650a25d653abf1979c0d875d3ca | 9827e9ba3c5a7aaa3b8dde1f909722378b81aa5d | refs/heads/master | 2023-02-28T00:17:17.791965 | 2021-02-06T04:35:27 | 2021-02-06T04:35:27 | 332,377,709 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,948 | java | /*
* Decompiled with CFR 0.0.
*
* Could not load the following classes:
* android.app.Activity
* android.content.Context
* android.content.Intent
* android.content.SharedPreferences
* android.os.Bundle
* android.util.Log
* android.view.View
* java.lang.Object
* java.lang.String
* java.lang.StringBuilder
* java.util.Vector
*/
package com.mobond.mindicator.ui.train;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.mobond.mindicator.ConfigurationManager;
import com.mobond.mindicator.ui.l;
import com.mulo.a.d.b;
import com.mulo.a.d.g;
import com.mulo.util.e;
import java.util.Vector;
public class SourceSelectUI
extends l {
String[] A;
SharedPreferences B;
String C;
@Override
public void a() {
}
@Override
public void a(View view, String string, int n2) {
String[] arrstring;
for (int i2 = 0; i2 < (arrstring = this.A).length && !arrstring[i2].equals((Object)string); ++i2) {
}
Intent intent = new Intent();
intent.putExtra("source_stn", string);
this.setResult(-1, intent);
this.finish();
}
@Override
public void onCreate(Bundle bundle) {
this.a("ca-app-pub-5449278086868932/1618940842", "167101606757479_1239839079483721", "ca-app-pub-5449278086868932/4916953830", "167101606757479_1235757683225194", 0);
super.onCreate(bundle);
this.B = this.getSharedPreferences("m-indicator", 0);
this.C = this.B.getString("city", "mumbai");
Vector<String> vector = this.getIntent().getExtras().getBoolean("type_fastest_route", false) ? b.a(this, "local/sdr") : g.a((Activity)this, this.C, ConfigurationManager.a((Context)this));
String string = this.getIntent().getExtras().getString("last_station_1");
String string2 = this.getIntent().getExtras().getString("last_station_2");
String string3 = this.getIntent().getExtras().getString("last_station_3");
String string4 = this.getIntent().getExtras().getString("last_station_4");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("ddd laststation1:");
stringBuilder.append(string);
Log.d((String)"ddd", (String)stringBuilder.toString());
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("ddd laststation2:");
stringBuilder2.append(string2);
Log.d((String)"ddd", (String)stringBuilder2.toString());
StringBuilder stringBuilder3 = new StringBuilder();
stringBuilder3.append("ddd laststation2:");
stringBuilder3.append(string3);
Log.d((String)"ddd", (String)stringBuilder3.toString());
StringBuilder stringBuilder4 = new StringBuilder();
stringBuilder4.append("ddd laststation2:");
stringBuilder4.append(string4);
Log.d((String)"ddd", (String)stringBuilder4.toString());
Vector vector2 = (Vector)vector.clone();
if (string4 != null) {
vector2.add(0, (Object)string4);
this.j = 1 + this.j;
}
if (string3 != null) {
vector2.add(0, (Object)string3);
this.j = 1 + this.j;
}
if (string2 != null) {
vector2.add(0, (Object)string2);
this.j = 1 + this.j;
}
int n2 = 0;
if (string != null) {
vector2.add(0, (Object)string);
this.j = 1 + this.j;
}
while (n2 < vector2.size()) {
String string5 = (String)vector2.elementAt(n2);
vector2.removeElementAt(n2);
vector2.add(n2, (Object)e.a(string5, null));
++n2;
}
this.A = new String[vector2.size()];
vector2.toArray((Object[])this.A);
this.a(this.A);
}
}
| [
"[email protected]"
]
| |
d32fe84eddb60c7ff466816c271bda25e6832dca | e21fdb9ba013d19dd58bd9219ef563c62310bc94 | /BO/src/main/java/com/grupo38/tiendagenerica/DAO/Conexion.java | 54e6acf1b324d0cd473ab1f4528b991cc6e32d3f | []
| no_license | AlejandroGonzalezRincon/G38Equipo11Ciclo3 | 8c72910d6eede7bb35363645e0552e420c178d80 | 91840e1523c77c94b36a71fef4c7b39ff58657c1 | refs/heads/main | 2023-08-15T10:28:23.891515 | 2021-09-26T04:00:26 | 2021-09-26T04:00:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,230 | java | package com.grupo38.tiendagenerica.DAO;
import java.sql.*;
public class Conexion {
//Parametros de conexión
static String nombre_base_datos = "tienda";
static String usuariodb = "root";
static String clavebd = "mintic";
static String url ="jdbc:mysql://127.0.0.1/" + nombre_base_datos;
//Objeto sin inicializar de la conexion
Connection connection = null;
//constructor
public Conexion() {
try {
//Obtenemos el driver de para mysql
Class.forName("com.mysql.cj.jdbc.Driver");
//obtenemos la conexión
connection = DriverManager.getConnection(url, usuariodb, clavebd);
//Si hay conexión correcta mostrar la información en consola
if(connection != null) {
System.out.println("Conexión a base de datos " + nombre_base_datos + " OK\n");
}
} catch (SQLException e) {
//Error de la base de datos
System.out.println(e);
} catch (ClassNotFoundException e) {
//Error en carga de clases
System.out.println(e);
} catch (Exception e) {
//Cualquier otro error
System.out.println(e);
}
}
//Permite retornar la conexión
public Connection getConnection() {
return connection;
}
//Cerrando la conexión
public void desconectar() {
connection = null;
}
}
| [
"[email protected]"
]
| |
c71b1a447bb6ba836e2984044fe73b687f136840 | 1683fe322e34fd28cd10015033bb149e7a7ee7a7 | /app/src/main/java/com/atguigu/mobileplayer1020/view/LyricShowView.java | 8928637e5eab7a1a0e45269dcaed3768823239b4 | []
| no_license | hejian65644955/shoujiyingyin | 8eb4c2287adaaed293327252cd62a74b51c7cad1 | ce4eedf085f6e93c13015823eb845e08f9d42d8b | refs/heads/master | 2021-01-11T19:10:15.181929 | 2017-01-18T10:41:05 | 2017-01-18T10:41:05 | 79,330,282 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,436 | java | package com.atguigu.mobileplayer1020.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
import com.atguigu.mobileplayer1020.bean.LyricBean;
import java.util.ArrayList;
/**
* Created by lenovo on 2017/1/13.
*/
public class LyricShowView extends TextView {
private int width;
private int height;
private ArrayList<LyricBean> lyricBeen;
private Paint paint;
private Paint nopaint;
//歌词的索引
private int index = 0;
private float textHeight = 20;
private int currentPosition;
private float timePoint;
private float sleepTime;
public LyricShowView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
private void initView() {
//创建画笔
paint = new Paint();
paint.setTextSize(20);
paint.setColor(Color.GREEN);
paint.setTextAlign(Paint.Align.CENTER);
paint.setAntiAlias(true);
nopaint = new Paint();
nopaint.setTextSize(20);
nopaint.setColor(Color.WHITE);
nopaint.setTextAlign(Paint.Align.CENTER);
nopaint.setAntiAlias(true);
// lyricBeen = new ArrayList<>();
// LyricBean lyricBean = new LyricBean();
// for (int i = 0; i < 1000; i++) {
// lyricBean.setContent("aaaaaaaaaaa" + i);
// lyricBean.setSleepTime(i + 1000);
// lyricBean.setTimePoint(i * 1000);
// //添加到集合中
// lyricBeen.add(lyricBean);
// //重新创建
// lyricBean = new LyricBean();
// }
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
width =w;
height =h;
}
//绘制歌词
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (lyricBeen != null && lyricBeen.size() > 0) {
if(index !=lyricBeen.size()-1){
float plush;
if(sleepTime ==0){
plush=0;
}else{
plush =((currentPosition-timePoint)/sleepTime)*textHeight;
canvas.translate(0,-plush);//平移动画
}
}
//绘制歌词
//当前句-绿色
String content = lyricBeen.get(index).getContent();
canvas.drawText(content, width / 2, height / 2, paint);
//绘制前面部分
float tempY = height / 2;
for (int i = index - 1; i >= 0; i--) {
tempY = tempY - textHeight;
if (tempY < 0) {
break;
}
String preContent = lyricBeen.get(i).getContent();
canvas.drawText(preContent, width / 2, tempY, nopaint);
}
//绘制后面部分
tempY = height / 2;
for (int i = index + 1; i < lyricBeen.size(); i++) {
tempY = tempY + textHeight;
if (tempY >height) {
break;
}
String nextContent = lyricBeen.get(i).getContent();
canvas.drawText(nextContent, width / 2, tempY, nopaint);
}
} else {
//没有歌词
canvas.drawText("没有找到歌词...", width / 2, height / 2, paint);
}
}
public void setNextShowLyric(int currentPosition) {
this.currentPosition = currentPosition;
if(lyricBeen ==null || lyricBeen.size()==0)
return;
for (int i=1;i<lyricBeen.size();i++){
if(currentPosition <lyricBeen.get(i).getTimePoint()){
int indexTemp = i - 1;
if(currentPosition >= lyricBeen.get(indexTemp).getTimePoint()){
//就我们要找的高亮的哪句
index = indexTemp;
sleepTime =lyricBeen.get(indexTemp).getSleepTime();
timePoint =lyricBeen.get(indexTemp).getTimePoint();
}
}else{
index =i;
}
}
invalidate();//强制绘制
}
public void setLyrics(ArrayList<LyricBean> lyricBeens) {
this.lyricBeen = lyricBeens;
}
}
| [
"[email protected]"
]
| |
c2bc353a132cc5d782f3c982c4f5fccec0134325 | 04d815ec844925c8af59702e14299aeadb8b2e91 | /src/gadget/insurance/policy/Policy.java | af5e1b48becb5cb6f6a6306a74d202ea2c23c536 | []
| no_license | Aleks-P-97/PolicyManager | 28856f0baf94e3bb3bf85b55e42228a2ca3cee45 | 72521eae56479400caea3e4312008a302489ef02 | refs/heads/master | 2021-01-25T07:11:38.324848 | 2017-11-07T09:56:12 | 2017-11-07T09:56:12 | 80,723,338 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,307 | java | package gadget.insurance.policy;
/**
*
* @author Aleksandra Petkova
*/
public class Policy
{
private String name;
private String refNum;
private double excess;
private double discount;
private double numItems;
private double bPremium;
private double limit;
private String term;
private double mExpensiveIt;
Policy()
{
}
public double[] calcPremium()
{
double extraDiscount; //If the user pays annualy they get additional discount.
double annualDiscount;
double monthlyDiscount;
double annualPremium = 0;
double monthlyPremium = 0;
//Calculates the premium depending on the chosen terms.
if (term.equalsIgnoreCase("Annual"))
{
extraDiscount = 0.1;
annualDiscount = (bPremium *12 ) * (extraDiscount + discount);
annualPremium = bPremium *12;
annualPremium -= annualDiscount;
} else if(term.equalsIgnoreCase("Monthly")){
monthlyDiscount = bPremium * discount;
monthlyPremium = bPremium;
monthlyPremium -= monthlyDiscount;
}
double[] premium = {
monthlyPremium, annualPremium
};
return premium;
}
public String toString(String date)
{
double mPrem;
double aPrem;
double[] prem = calcPremium();
mPrem = prem[0];
aPrem = prem[1];
String fTerm;
char cTerm;
fTerm = term.toUpperCase();
cTerm = fTerm.charAt(0);
String aPolicy = "";
//Adds all the date of a policy to a String called aPolicy.
if(term.equalsIgnoreCase("monthly"))
{
if((numItems < 1 || numItems > 5) || (mExpensiveIt > 1000) ){
mPrem = -1;
cTerm = 'R';
}
aPolicy = date +"\t"+ refNum +"\t"+ Math.round(numItems) +"\t"+ Math.round(mExpensiveIt*100.0)/100.0 +"\t"+ Math.round(excess) +"\t"
+ Math.round(mPrem*100.0)/100.0 +"\t"+ cTerm +"\t"+ name +" \n";
} else if(term.equalsIgnoreCase("annual")){
if((numItems < 1 || numItems > 5) || (mExpensiveIt > 1000) ){
aPrem = -1;
cTerm = 'R';
}
aPolicy = date +"\t"+ refNum +"\t"+ Math.round(numItems) +"\t"+ Math.round(mExpensiveIt*100.0)/100.0 +"\t"+ Math.round(excess) +"\t"
+ Math.round(aPrem*100.0)/100.0 +"\t"+ cTerm +"\t"+ name +" \n";
}
return aPolicy;
}
//Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRefNum() {
return refNum;
}
public void setRefNum(String refNum) {
this.refNum = refNum;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public double getExcess() {
return excess;
}
public void setExcess(double excess) {
this.excess = excess;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getNumItems() {
return numItems;
}
public void setNumItems(double numItems) {
this.numItems = numItems;
}
public double getbPremium() {
return bPremium;
}
public void setbPremium(double bPremium) {
this.bPremium = bPremium;
}
public double getLimit() {
return limit;
}
public void setLimit(double limit) {
this.limit = limit;
}
public double getMExpensiveIt() {
return mExpensiveIt;
}
public void setMExpensiveIt(double mExpensiveIt) {
this.mExpensiveIt = mExpensiveIt;
}
} | [
"[email protected]"
]
| |
288be9c84c19c432a37e8f4986e074add3514e98 | 7e67559eac979a1dad7f29fd7532444b11df6b84 | /app/src/main/java/com/creditease/checkcars/net/oper/bean/UserDataBean.java | 32b0609be9c09775cbab2cbf47ab9a11ac60c9b9 | []
| no_license | ChinaAndroidMaster/testgit | 75ee3e4ff074f33944dd549ffcbb6ebdefd1811f | 6b2785e1e8b9cd7bc28685d69f980918a284fa8c | refs/heads/master | 2021-01-17T18:53:15.689636 | 2016-04-25T06:52:08 | 2016-04-25T06:52:08 | 62,482,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 975 | java | package com.creditease.checkcars.net.oper.bean;
import java.io.Serializable;
import com.creditease.checkcars.data.bean.Appraiser;
public class UserDataBean
{
public static class UserDataObj implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 5517170003958884193L;
public UserDataObj()
{
}
public UserDataObj(String uuid, int isProvideService, String declaration)
{
super();
this.uuid = uuid;
this.isProvideService = isProvideService;
this.declaration = declaration;
}
public String uuid;
public int isProvideService;
public String declaration;
}
public static class UserDataResult implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -821461850977177462L;
public Appraiser Appraiser;
}
}
| [
"[email protected]"
]
| |
595ebb82e91747fe378bbb2cfbcafe991832610a | 1eadd590e96f6fffb8cca2661cd3705770853fa6 | /jiujiucms/src/com/jiujiucms/modules/cms/entity/News.java | 3c1babcbe25e53aff8a7afab2bf43e6bcf3ef297 | []
| no_license | v512345/jiujiucms | 6d15da3a7a3430486eddb0474258b58883075904 | 8b73fec8c04aacfc90cad7cc237e7745c34fe278 | refs/heads/master | 2021-01-10T20:43:37.838665 | 2015-08-29T14:18:41 | 2015-08-29T14:18:41 | 40,774,506 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 71 | java | package com.jiujiucms.modules.cms.entity;
public class News {
}
| [
"[email protected]"
]
| |
d63c61dfdbf7e63fc347cc96540825e656d323d0 | 409c991b9f38faa56487d79e6a9c05fd5d10cd30 | /Test22.java | 81ec27635d65d09aa96847f86daed10bbb2d6932 | []
| no_license | sbolcoder/test2 | a1b8b99bfa322d78a93b4c3b6e0cf6eb5d358e63 | 1a637599e285c9954fa33914ba653126daa82a31 | refs/heads/master | 2020-04-01T14:32:29.159618 | 2018-10-16T15:35:38 | 2018-10-16T15:35:38 | 153,298,523 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,227 | java | package Pack1;
import org.junit.*;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.interactions.internal.Locatable;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.sql.Driver;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Test22 {
private static WebDriver driver;
WebDriverWait wait = new WebDriverWait(driver, 10);
@BeforeClass
public static void setup() throws Exception {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://www.chase.com");
}
@Test
public void test01_pagetitle() throws Exception {
Assert.assertEquals("Credit Card, Mortgage, Banking, Auto | Chase Online | Chase.com", driver.getTitle());
}
@Test
public void test02_pageloaded() throws Exception {
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState"
).equals("complete");
}
});
}
@Test
public void test03_pagescroll() throws Exception {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
@Test
public void test04_pagecheck() throws Exception {
Assert.assertEquals("© 2018 JPMorgan Chase & Co.", driver.findElement(By.xpath("/html/body/div/footer/div/div[3]/div/div/div/div[2]/p[2]")).getText());
}
@Test
public void test05_clickOB() throws Exception {
driver.findElement(By.xpath("/html/body/div/footer/div/div[2]/div/div/div[2]/div[2]/ul/li[1]/a")).click();
}
@Test
public void test06_clickEN() throws Exception {
WebElement element = driver.findElement(By.xpath("//*[@id=\"started\"]/div[1]/div/div/div/div[3]/div/a")); // прокрутка к элементу
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(1000);
driver.findElement(By.xpath("//*[@id=\"started\"]/div[1]/div/div/div/div[3]/div/a")).click();
}
@Test
public void test07_usernameinput() throws Exception {
WebElement element = driver.findElement(By.xpath("//*[@id=\"userId-text-input-field\"]")); // прокрутка к элементу
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(1000);
driver.findElement(By.xpath("//*[@id=\"userId-text-input-field\"]")).sendKeys("bmametyarov1");
}
@Test
public void test08_usernamecheck1() throws Exception {
Assert.assertEquals(" Green Check. Meets requirement:Must be 8-32 characters long", driver.findElement(By.xpath("//*[@id=\"userIdRequirementsArea\"]/div[1]")).getAttribute("innerText"));
Assert.assertEquals(" Green Check. Meets requirement:Must contain at least 1 letter and 1 number", driver.findElement(By.xpath("//*[@id=\"userIdRequirementsArea\"]/div[2]")).getAttribute("innerText"));
Assert.assertEquals(" Green Check. Meets requirement:Must not contain special characters (&, %, *, etc.)", driver.findElement(By.xpath("//*[@id=\"userIdRequirementsArea\"]/div[3]")).getAttribute("innerText"));
WebElement chk1 = driver.findElement(By.xpath("//*[@id=\"userId-text-input-field\"]"));
}
@AfterClass
public static void test99_quit() throws Exception {
Thread.sleep(5000);
driver.quit();
}
}
| [
"[email protected]"
]
| |
6f97e02b3ba6191dcc966cf7456e077fee80bbd2 | 8c0b94a5bd3c6509ec7edab9aec2eeb829b28285 | /src/main/java/ca/ubc/bps/state/MutableObject.java | 81a0b3fa892de5929772ad51eb5d23e09d81ccc8 | []
| no_license | UBC-Stat-ML/rejectfree | 5c7262d08fd20c6364dfdbfabb557b0bcfd9cac4 | a95d6cae9d22600bbdb4348dd83ab6af5bd92310 | refs/heads/master | 2023-03-30T16:48:35.833900 | 2018-02-23T00:23:05 | 2018-02-23T00:23:05 | 78,441,108 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java | package ca.ubc.bps.state;
public interface MutableObject<T>
{
public void set(T value);
public T get();
} | [
"[email protected]"
]
| |
26325f404569479322f93c66a8972976c6121ea8 | 92a59fec855a05d3c3cb8060cf1c9c45239657c1 | /29_11/src/zad5/app.java | 47437410597d68175cd6a97e9dd3af2d789d9537 | []
| no_license | rejnowskimikolaj/Backup | a10523fb06ce7cc6c66910882640aeb710ac0f71 | 408d704f8fa6eb16096289afa305e1a1ae2a841b | refs/heads/master | 2021-01-20T10:46:34.837574 | 2017-04-04T12:53:03 | 2017-04-04T12:53:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 194 | java | package zad5;
public class app {
public static void main(String[] args) {
// TODO Auto-generated method stub
LengthChecker lc = new LengthChecker();
lc.make("src\\zad5\\words.txt", 7);
}
}
| [
"[email protected]"
]
| |
9cea46a4ba195ce8d30f4a8a385a596696886d46 | 87b2adc3fe8e566cad9268b8dbdf20733428879b | /src/main/java/example/prototypeVSsingleton/Main.java | 4ed2d9fb9a3f42eab8e7b5f8eb1dff9448b4b451 | []
| no_license | dstoianov/spring-dev-tools | 592df0e70edbdfc10d65c46b50cf62a1214e3956 | 040b8ae801f388283b6a5474ebf2ce7106f83e57 | refs/heads/master | 2023-01-14T01:05:28.433117 | 2020-11-13T19:26:54 | 2020-11-13T19:26:54 | 297,302,007 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 315 | java | package example.prototypeVSsingleton;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext("example.prototypeVSsingleton");
context.close();
}
}
| [
"[email protected]"
]
| |
fef5e026d8a937482f2b614c55532b90624e3b34 | 143089f3d485c8b3ddb0aadbd818801dee93806e | /edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations/src/edu/kit/ipd/sdq/kamp4is/model/fieldofactivityannotations/ISTestCase.java | dba2a36c6a5329273b56a2b85e2d19d63d7d3e9e | [
"Apache-2.0"
]
| permissive | SebastianWeberKamp/KAMP4IS | a58155d504562132a3b124934adf086f6e51aa4d | 3ce896786cf24fd6d03f376c7127920866259666 | refs/heads/master | 2020-09-20T08:14:00.135860 | 2019-12-15T09:22:53 | 2019-12-15T09:22:53 | 224,419,717 | 0 | 0 | Apache-2.0 | 2019-11-27T11:54:15 | 2019-11-27T11:54:14 | null | UTF-8 | Java | false | false | 1,644 | java | /**
*/
package edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>IS Test Case</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations.ISTestCase#getNameOfTest <em>Name Of Test</em>}</li>
* </ul>
*
* @see edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations.ISFieldOfActivityAnnotationsPackage#getISTestCase()
* @model abstract="true"
* @generated
*/
public interface ISTestCase extends EObject {
/**
* Returns the value of the '<em><b>Name Of Test</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name Of Test</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name Of Test</em>' attribute.
* @see #setNameOfTest(String)
* @see edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations.ISFieldOfActivityAnnotationsPackage#getISTestCase_NameOfTest()
* @model
* @generated
*/
String getNameOfTest();
/**
* Sets the value of the '{@link edu.kit.ipd.sdq.kamp4is.model.fieldofactivityannotations.ISTestCase#getNameOfTest <em>Name Of Test</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name Of Test</em>' attribute.
* @see #getNameOfTest()
* @generated
*/
void setNameOfTest(String value);
} // ISTestCase
| [
"[email protected]"
]
| |
10ff94e71150e9f19e41c96b7ed152af66292d76 | e57d2970e1f0112393a81a611ab257aaf054322a | /src/test/java/com/app/tacoLoco/TacoLocoApplicationTests.java | 4c0143cebbbd6b044786bbd1711e22c393e84cf5 | []
| no_license | adamdepollo/TacoLoco | 50c4eadfab39a2c1d384678cf058fade9b05d1b5 | 878bcff610a46e38801a4fce177fca6a416c2547 | refs/heads/main | 2023-06-07T15:08:20.671602 | 2021-07-02T19:18:52 | 2021-07-02T19:18:52 | 382,219,901 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 210 | java | package com.app.tacoLoco;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TacoLocoApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
]
| |
8152d3ca0eebe8b832e84d6335c9f337ae51ab6f | ba44489676470bd4f05185ed33b7cc80f4ce64c9 | /src/com/microchip/mplab/nbide/embedded/chipkit/importer/GCCToolFinder.java | 66074460fa40621f93a208010c95cfa97a41f0c5 | [
"Apache-2.0"
]
| permissive | gholdys/chipKIT-importer-2.0 | 97a9755082ddb006193188e46d03b8190d9354f4 | b1d157655eec74fe917d7129856a493ced6ca30d | refs/heads/master | 2021-06-21T22:52:02.463448 | 2017-08-04T17:34:54 | 2017-08-04T17:34:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,210 | java | /*
* Copyright (c) 2017 Microchip Technology Inc. and its subsidiaries (Microchip). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.microchip.mplab.nbide.embedded.chipkit.importer;
import com.microchip.mplab.nbide.embedded.api.LanguageTool;
import com.microchip.mplab.nbide.embedded.api.LanguageToolchain;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.openide.util.Utilities;
public class GCCToolFinder {
private LanguageToolchain toolchain;
private Path rootToolsPath;
public GCCToolFinder(LanguageToolchain toolchain) {
this.toolchain = toolchain;
}
public GCCToolFinder(Path rootToolsPath) {
this.rootToolsPath = rootToolsPath;
}
public Path findTool( int toolId ) {
if ( toolchain != null ) {
String pathStrnig = ( toolId == LanguageTool.MakeTool && Utilities.isWindows() ) ? "make" : toolchain.getTool(toolId).getPath();
return Paths.get(pathStrnig);
} else {
String suffix;
switch ( toolId ) {
case LanguageTool.Archiver:
suffix = "-ar";
break;
case LanguageTool.CCCompiler:
suffix = "-g++";
break;
case LanguageTool.CCompiler:
suffix = "-gcc";
break;
case LanguageTool.Assembler:
suffix = "-as";
break;
case LanguageTool.MakeTool: // Special case for Make
return Paths.get("make");
default:
throw new RuntimeException("Unsupported Tool ID: " + toolId);
}
try {
return Files.list(rootToolsPath)
.filter( file -> !Files.isDirectory(file) )
.filter( file -> {
String filename = file.getFileName().toString();
// Remove the extension if there is one:
int extensionIndex = filename.indexOf('.');
if ( extensionIndex != -1 ) {
filename = filename.substring(0, extensionIndex);
}
return filename.endsWith(suffix);
})
.findAny()
.get();
} catch (IOException ex) {
throw new RuntimeException("Failed to locate tool: " + toolId, ex);
}
}
}
}
| [
"[email protected]"
]
| |
8a3e1ef58a03b4447f51b2298f6cd9c7a7917d4d | d0b11707c895c9133a558110145a19a2739a05ef | /src/day26/SwappingValues.java | e95a99f47227401c6a0b3bb450279608deaa2e7a | []
| no_license | Ronny2025/git-curso-inicial | 54624fd545e1785fd907ec9de51697c9b6fad098 | 8c7fa5060c7282a6b52f1a2f01803b92a612143b | refs/heads/master | 2022-04-16T04:53:48.050770 | 2020-04-12T23:37:34 | 2020-04-12T23:37:34 | 255,073,491 | 0 | 0 | null | 2020-04-12T23:53:23 | 2020-04-12T12:03:48 | Java | UTF-8 | Java | false | false | 1,371 | java | package day26;
import java.util.*;
public class SwappingValues {
public static void main(String[] args) {
String name1 = "Emma";
String name2 = "Jason";
// name2 should have Emma , name1 should have Jason
//name1 = name2 ;
//name2 = name1 ;
String tempContainer = name1; // emma
name1 = name2; //name1 -->> Jason
name2 = tempContainer; // name -->> Emma
System.out.println("name1 = " + name1);
System.out.println("name2 = " + name2);
// swap the value of first item and last item
int[] myNumbers = new int[]{10, 40, 30, 7};
System.out.println("myNumbers = " + Arrays.toString(myNumbers));
int temp = myNumbers[0]; // temp now has 10
myNumbers[0] = myNumbers[3]; // first item value become 7
myNumbers[3] = temp; // last item now become 10
System.out.println("first item = " + myNumbers[0]);
System.out.println("last item = " + myNumbers[3]);
System.out.println("myNumbers = " + Arrays.toString(myNumbers));
// swap the value of first item and last item
// int[] myNumbers = new int[]{10, 40, 30, 7};
int temp2 = myNumbers[1];
myNumbers[1] = myNumbers[2];
myNumbers[2] = temp2;
System.out.println("myNumbers = " + Arrays.toString(myNumbers));
}
}
| [
"[email protected]"
]
| |
0d0672cc9a1b2572e65b6ff2cba793072ede5f26 | cd4c34d857cac2aaba1cfdf976b90b3fc949908b | /src/test/java/com/example/demo/Week7ChallengeApplicationTests.java | b413301e9d26604511b76fd05ac9e0b1039f0989 | []
| no_license | ri144/Week7Challenge | 104a82003aa3c3b7ae3528fa22fe1ad7fda99805 | 4e3ab6ec2ab54e417d2ac2df43cece689747b958 | refs/heads/master | 2020-12-02T19:34:19.128101 | 2017-07-10T14:20:01 | 2017-07-10T14:20:01 | 96,361,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.example.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Week7ChallengeApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"[email protected]"
]
| |
d6256aa74f67c595a10c90ca53edede38545ef6b | 51bbfe334213ccbd1a96528a48156cb9e21e9898 | /Esame/src/model/Sessione.java | f85e35e75ee5205393e66d2b9ef12256f1ca390e | []
| no_license | carlopigna95/Esame_PPS | bff30a1fa75d14a1eb179544ee559d367b8f539d | 6d38c5a12c54663211ce2d4ba5be3a1adbfc4cbd | refs/heads/master | 2021-01-20T19:34:42.181287 | 2016-06-16T09:23:53 | 2016-06-16T09:23:53 | 60,016,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 326 | java | package model;
import java.util.HashMap;
public class Sessione {
private static Sessione instance;
public HashMap<String, UtenteRegistrato> session = new HashMap<String,UtenteRegistrato>();
public static synchronized Sessione getInstance() {
if(instance == null)
instance = new Sessione();
return instance;
}
}
| [
"[email protected]"
]
| |
0b6c08c2943bce53e304a804d5862c7d02a459e4 | 232809980743d39816d67e58be52e83684f3f905 | /Atividades/src/Generics/ComGenerics/CaixaTeste.java | 3eaa93e945c94b8f84394cf4852b66ec48c9d6b8 | [
"MIT"
]
| permissive | israelmessias/Atividades_Java | 8fa76b59365208c573f479563ee0c7c388605d8b | 8dda9fe69022a216ea372f2a4909d47a5b5400cf | refs/heads/main | 2023-06-14T06:38:25.730643 | 2021-06-30T00:00:08 | 2021-06-30T00:00:08 | 316,617,504 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 424 | java | package Generics.ComGenerics;
public class CaixaTeste {
public static void main(String[] args) {
Caixa<String> caixaA = new Caixa<>();
caixaA.guardar("Segredo!");
String coisaA = caixaA.abrir();
System.out.println(coisaA);
Caixa<Double> caixaB = new Caixa<>();
caixaB.guardar(2.3);
Double coisaB = caixaB.abrir();
System.out.println(coisaB);
}
}
| [
"[email protected]"
]
| |
50a067d97ab90d258e9265f522c3f92100d2dd22 | 472615ab267659d735a3bc40da947a6a736a5c93 | /lab8/src/main/java/cs545/bank/dao/AccountDAO.java | 44293dd7474035c215c502eaf0bd3cba15aff8c6 | []
| no_license | chauky/WAA | 3cdda605bcf48e1de0a577b1882117ea05c0169c | 67b10de6c52374a1546571decdc5e399c550d01a | refs/heads/master | 2021-01-24T16:40:08.887575 | 2018-03-16T03:38:48 | 2018-03-16T03:38:48 | 123,207,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,123 | java | package cs545.bank.dao;
import java.util.*;
import cs545.bank.domain.Account;
public class AccountDAO implements IAccountDAO {
Collection<Account> accountlist = new ArrayList<Account>();
public void saveAccount(Account account) {
// System.out.println("AccountDAO: saving account with accountnr ="+account.getAccountnumber());
accountlist.add(account); // add the new
}
public void updateAccount(Account account) {
// System.out.println("AccountDAO: update account with accountnr ="+account.getAccountnumber());
Account accountexist = loadAccount(account.getAccountnumber());
if (accountexist != null) {
accountlist.remove(accountexist); // remove the old
accountlist.add(account); // add the new
}
}
public Account loadAccount(long accountnumber) {
// System.out.println("AccountDAO: loading account with accountnr ="+accountnumber);
for (Account account : accountlist) {
if (account.getAccountnumber() == accountnumber) {
return account;
}
}
return null;
}
public Collection<Account> getAccounts() {
return accountlist;
}
}
| [
"[email protected]"
]
| |
f85f28f2739c151e2b077a54a796a2c830872e96 | a01e4e575d09503e114d4497cd0e1265f05e1e3e | /gen/nl/bertkamphuis/mijnfrequentie/BuildConfig.java | 2d75a6b10ed63115741d72813e72a2084b576ef7 | []
| no_license | kamphuisbert/MijnFrequentie | 2385271ecb6bd46bb3dfca549e2f404fab2079ec | 16368e8783e8c6f43ab4cdddddb22c3fdb30e1cb | refs/heads/master | 2016-09-03T07:16:16.719582 | 2013-02-18T20:24:49 | 2013-02-18T20:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 172 | java | /** Automatically generated file. DO NOT MODIFY */
package nl.bertkamphuis.mijnfrequentie;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | [
"[email protected]"
]
| |
f5bd09f63bcb6a968a05345860dace3501a9d36f | c03c6767d79ec30b423763fd85d072e8da58cc7e | /mldnshiro-realm/src/test/java/cn/mldn/mldnshiro/realm/MySelfDefaultRealm.java | 69d7f4e6ffbed6cf5dea4f2dce6bee0ffadf7257 | []
| no_license | CHENCHENCHU/shiro- | b9629e992898516dfdc4a4b1e88037d9b82d5f2a | a373b7946d02d19f3c54d6f82c3bdd806ace74ae | refs/heads/master | 2021-07-20T21:53:43.610581 | 2017-10-28T03:52:15 | 2017-10-28T03:52:15 | 108,617,766 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,778 | java | package cn.mldn.mldnshiro.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;
/**
* 自定义的Realm处理操作实现,主要提供认证的数据信息
* @author mldn
*/
public class MySelfDefaultRealm implements Realm {
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 实现具体认证处理
String mid = (String) token.getPrincipal() ; // 获取输入用户名
String password = new String((char [])token.getCredentials()); // 获得输入的密码
// 此时是对固定的信息进行认证处理,所以现在定义的用户名为admin、hello
if (!"admin".equals(mid)) { // 用户名不存在
throw new UnknownAccountException("此账户不存在,请确认用户名!") ;
}
if (!"hello".equals(password)) { // 密码不正确
throw new IncorrectCredentialsException("错误的用户名或密码!") ;
}
return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), this.getName()) ;
}
@Override
public String getName() { // 名字随便去编写
return "shiro-default-realm"; // 名字是随意编写的,主要是区分不同的realm
}
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken ; // 现在如果使用的是简单的用户名和密码认证
}
}
| [
"[email protected]"
]
| |
83b080463072fca20bf75edc623050a6c85efc95 | e244f86f8b4926f67061b82f790e1197e49cf2f4 | /src/Team_Pro/servlet/UserPageServlet.java | 7d756534d958bbff1a8d83047a009feba93425a4 | []
| no_license | llauer3/Team-Project | fb4225936d980bd3b8fa0a792b14b27be1699822 | 4821414a64c12f649954e727d8a0668ca416e0b9 | refs/heads/master | 2020-12-14T08:55:26.908750 | 2015-04-29T17:19:40 | 2015-04-29T17:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,107 | java | package Team_Pro.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Team_Pro.controller.Controller;
import Team_Pro.model.Comment;
import Team_Pro.model.User;
public class UserPageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private int pos = 0;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.getSession().getAttribute("user") == null) {
resp.sendRedirect(req.getContextPath() + "/LogIn");
return;
}
Controller controller;
try {
controller = new Controller();
User me = (User) req.getSession().getAttribute("user");
List<Comment> mover = new ArrayList<Comment>();
if (pos == 0) {
mover = controller.userPosts(me.getId());
} else {
mover = controller.likePosts(me.getId());
}
List<Comment> Posts = new ArrayList<Comment>();
for (int i = mover.size()-1; i >= 0; i--) {
Comment post = mover.get(i);
Posts.add(post);
}
req.setAttribute("Posts", Posts);
} catch (Exception e) {
throw new ServletException("Error Retrieving Posts", e);
}
req.getRequestDispatcher("/_view/UserPage.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Controller controller;
try {
controller = new Controller();
if (req.getParameter("mainPage") != null){
resp.sendRedirect(req.getContextPath() + "/MainPage");
return;
} else if (req.getParameter("post") != null) {
String text = req.getParameter("text");
if (text.isEmpty()) {
resp.sendRedirect(req.getContextPath() + "/UserPage");
return;
}
String tag = req.getParameter("tag");
User user = (User) req.getSession().getAttribute("user");
if (text.toLowerCase().contains("tube")) {
text = text.substring(32);
text = "https://www.youtube.com/embed/" + text;
}
controller.post(text, tag, user.getId());
} else if (req.getParameter("log") != null) {
// logout
User user = (User) req.getSession().getAttribute("user");
controller.logout(user.getId());
req.getSession().removeAttribute("user");
resp.sendRedirect(req.getContextPath() + "/LogIn");
return;
} else if (req.getParameter("posts") != null) {
pos = 0;
} else if (req.getParameter("likes") != null) {
pos = 1;
} else {
for (int i = 0; i < controller.allPosts().size(); i++) {
int testId = controller.allPosts().get(i).getId();
if (req.getParameter("delete" + Integer.toString(testId)) != null) {
req.removeAttribute("delete" + Integer.toString(testId));
controller.deletePost(testId);
}
}
}
resp.sendRedirect(req.getContextPath() + "/UserPage");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| [
"[email protected]"
]
| |
60b6493aa64cce4901cc5370d0474088f68bf92f | 96f8d42c474f8dd42ecc6811b6e555363f168d3e | /budejie/sources/com/spriteapp/booklibrary/e/e.java | f5aaa3d50f75ecd4bf7f92d89404fa49a87b4f75 | []
| no_license | aheadlcx/analyzeApk | 050b261595cecc85790558a02d79739a789ae3a3 | 25cecc394dde4ed7d4971baf0e9504dcb7fabaca | refs/heads/master | 2020-03-10T10:24:49.773318 | 2018-04-13T09:44:45 | 2018-04-13T09:44:45 | 129,332,351 | 6 | 2 | null | null | null | null | UTF-8 | Java | false | false | 832 | java | package com.spriteapp.booklibrary.e;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import com.spriteapp.booklibrary.a.a;
import com.spriteapp.booklibrary.util.AppUtil;
import com.spriteapp.booklibrary.util.ScreenUtil;
public class e {
public static Bitmap a(int i) {
Bitmap createBitmap = Bitmap.createBitmap(ScreenUtil.getScreenWidth(), ScreenUtil.getScreenHeight(), Config.ARGB_8888);
switch (i) {
case 0:
createBitmap.eraseColor(AppUtil.getAppContext().getResources().getColor(a.book_reader_read_day_background));
break;
case 1:
createBitmap.eraseColor(AppUtil.getAppContext().getResources().getColor(a.book_reader_read_night_background));
break;
}
return createBitmap;
}
}
| [
"[email protected]"
]
| |
4160bc2a60e7bd6c38e0bfa1c24d00b55b393f6b | 9c308ab8c261aa629931708294db2fed3d9213f5 | /NBDNetworkPrivoder/src/com/nbd/network/networkstatus/OnNetworkStatusListener.java | e3819a7daa93b4426c6e0570d0e5296952267add | []
| no_license | hffsygtc/AndroidCodeNbd | 2cd209643f21e52bc71d5e9e762efd707e16f1aa | 89e6d5459f02ad7855344ced28a3fb087001e66c | refs/heads/master | 2021-01-24T22:35:26.589236 | 2016-09-21T07:52:00 | 2016-09-21T07:52:00 | 68,790,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 136 | java | package com.nbd.network.networkstatus;
public interface OnNetworkStatusListener {
void onNetworkStatusChange(NetworkStatus status);
}
| [
"https://github.com/hffsygtc/NBDApplication.git"
]
| https://github.com/hffsygtc/NBDApplication.git |
446d39155baa4e1c48a518d178f390919f68fd9e | a39a1068d1a48c4c77287bd77c772642b0f98b20 | /src/main/java/com/alphadevs/com/web/rest/UserJWTController.java | d2094b6a5b774c322672f5c7a0daa9102503ef18 | []
| no_license | AlphaDevTeam/JH-6.8-WS-KAFKA | 36c3f2fe0b0c7a9d201c71629621c0632b3556a6 | cba19004bb80c16c09e455ca33061b49e9e460ff | refs/heads/master | 2023-05-14T17:46:41.704252 | 2020-03-16T18:34:02 | 2020-03-16T18:34:02 | 247,788,902 | 0 | 0 | null | 2023-05-08T21:27:14 | 2020-03-16T18:28:41 | Java | UTF-8 | Java | false | false | 2,558 | java | package com.alphadevs.com.web.rest;
import com.alphadevs.com.security.jwt.JWTFilter;
import com.alphadevs.com.security.jwt.TokenProvider;
import com.alphadevs.com.web.rest.vm.LoginVM;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* Controller to authenticate users.
*/
@RestController
@RequestMapping("/api")
public class UserJWTController {
private final TokenProvider tokenProvider;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.tokenProvider = tokenProvider;
this.authenticationManagerBuilder = authenticationManagerBuilder;
}
@PostMapping("/authenticate")
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken;
JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
}
| [
"[email protected]"
]
| |
c3003c7b3ffb7194c954eabf443c6f298635bef9 | 911890cf104f4443c4d34bc5f64cf8c40255cbc5 | /helix/src/generated-sources/jooq/tech/codingclub/helix/tables/Member.java | 7bf6a3a2dc752606cf7e83ad76b64ca1aaa6407b | []
| no_license | subhojit-ghorai/Full-Stack-Development-Java | 1d89f1264744423d1f1a76772b91cbe1c92c412c | a1cb8ed82e3edeab479d11c8eeb00634cbbfb0d5 | refs/heads/master | 2023-05-09T03:18:29.923569 | 2021-06-04T12:30:25 | 2021-06-04T12:30:25 | 373,829,197 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,680 | java | /**
* This class is generated by jOOQ
*/
package tech.codingclub.helix.tables;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.2" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Member extends org.jooq.impl.TableImpl<tech.codingclub.helix.tables.records.MemberRecord> {
private static final long serialVersionUID = 1625233382;
/**
* The singleton instance of <code>public.member</code>
*/
public static final tech.codingclub.helix.tables.Member MEMBER = new tech.codingclub.helix.tables.Member();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<tech.codingclub.helix.tables.records.MemberRecord> getRecordType() {
return tech.codingclub.helix.tables.records.MemberRecord.class;
}
/**
* The column <code>public.member.name</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(100), this, "");
/**
* The column <code>public.member.email</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> EMAIL = createField("email", org.jooq.impl.SQLDataType.VARCHAR.length(100), this, "");
/**
* The column <code>public.member.role</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> ROLE = createField("role", org.jooq.impl.SQLDataType.VARCHAR.length(20), this, "");
/**
* The column <code>public.member.password</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> PASSWORD = createField("password", org.jooq.impl.SQLDataType.VARCHAR.length(30), this, "");
/**
* The column <code>public.member.image</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> IMAGE = createField("image", org.jooq.impl.SQLDataType.VARCHAR.length(100), this, "");
/**
* The column <code>public.member.token</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.String> TOKEN = createField("token", org.jooq.impl.SQLDataType.VARCHAR.length(30), this, "");
/**
* The column <code>public.member.is_verified</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.Boolean> IS_VERIFIED = createField("is_verified", org.jooq.impl.SQLDataType.BOOLEAN, this, "");
/**
* The column <code>public.member.id</code>.
*/
public final org.jooq.TableField<tech.codingclub.helix.tables.records.MemberRecord, java.lang.Long> ID = createField("id", org.jooq.impl.SQLDataType.BIGINT.nullable(false).defaulted(true), this, "");
/**
* Create a <code>public.member</code> table reference
*/
public Member() {
this("member", null);
}
/**
* Create an aliased <code>public.member</code> table reference
*/
public Member(java.lang.String alias) {
this(alias, tech.codingclub.helix.tables.Member.MEMBER);
}
private Member(java.lang.String alias, org.jooq.Table<tech.codingclub.helix.tables.records.MemberRecord> aliased) {
this(alias, aliased, null);
}
private Member(java.lang.String alias, org.jooq.Table<tech.codingclub.helix.tables.records.MemberRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, tech.codingclub.helix.Public.PUBLIC, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Identity<tech.codingclub.helix.tables.records.MemberRecord, java.lang.Long> getIdentity() {
return tech.codingclub.helix.Keys.IDENTITY_MEMBER;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.UniqueKey<tech.codingclub.helix.tables.records.MemberRecord> getPrimaryKey() {
return tech.codingclub.helix.Keys.MEMBER_PKEY;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.UniqueKey<tech.codingclub.helix.tables.records.MemberRecord>> getKeys() {
return java.util.Arrays.<org.jooq.UniqueKey<tech.codingclub.helix.tables.records.MemberRecord>>asList(tech.codingclub.helix.Keys.EMAIL_UNIQUE, tech.codingclub.helix.Keys.MEMBER_PKEY);
}
/**
* {@inheritDoc}
*/
@Override
public tech.codingclub.helix.tables.Member as(java.lang.String alias) {
return new tech.codingclub.helix.tables.Member(alias, this);
}
/**
* Rename this table
*/
public tech.codingclub.helix.tables.Member rename(java.lang.String name) {
return new tech.codingclub.helix.tables.Member(name, null);
}
}
| [
"[email protected]"
]
| |
6ee663a73bc9af86f3cfce54e637f8f3fdff56bd | 869323d12fc4cfc48caf73364fc61b0190575e4d | /editor/plugins/org.fusesource.ide.project/src/org/fusesource/ide/project/camel/CamelModuleDelegate.java | 7563c4db9ea7c2c70d8c71ccadcdba1faa88dbaf | []
| no_license | pramyasree/fuseide | d32da5e41264d39498e62abc58785b692845bebe | 61e8cd41f80fa992fe34762d12f740b9e4463eff | refs/heads/master | 2021-01-23T20:41:12.342436 | 2016-06-06T12:30:10 | 2016-06-06T12:30:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,945 | java | /*******************************************************************************
* Copyright (c) 2016 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.fusesource.ide.project.camel;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.jst.common.internal.modulecore.AddMappedOutputFoldersParticipant;
import org.eclipse.jst.common.internal.modulecore.IgnoreJavaInSourceFolderParticipant;
import org.eclipse.wst.common.componentcore.internal.flat.GlobalHeirarchyParticipant;
import org.eclipse.wst.common.componentcore.internal.flat.IFlattenParticipant;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.jboss.ide.eclipse.as.wtp.core.modules.IJBTModule;
import org.jboss.ide.eclipse.as.wtp.core.modules.JBTFlatModuleDelegate;
import org.jboss.ide.eclipse.as.wtp.core.modules.JBTFlatProjectModuleFactory;
public class CamelModuleDelegate extends JBTFlatModuleDelegate implements IJBTModule {
public CamelModuleDelegate(IProject project,
IVirtualComponent aComponent, JBTFlatProjectModuleFactory myFactory) {
super(project, aComponent, myFactory);
}
@Override
public IFlattenParticipant[] getParticipants() {
List<IFlattenParticipant> participants = new ArrayList<IFlattenParticipant>();
participants.add(new GlobalHeirarchyParticipant());
participants.add(new AddMappedOutputFoldersParticipant());
participants.add(new IgnoreJavaInSourceFolderParticipant());
return participants.toArray(new IFlattenParticipant[participants.size()]);
}
}
| [
"[email protected]"
]
| |
4b74be4affb8ec5df0e55b1068357ce2dd3b3326 | e5c5ec40e130bbbc73a4408fd61416211af984f8 | /app/src/main/java/kr/gsil/dpkepco/activity/SafetyCCTVActivity.java | aa5599807f7c21dcc6b8dc64e86477d7f842511c | []
| no_license | gsio/gsilDpKepcoSafetySystem | e35e37a3ef3f051f95bd181c6eb5f104cd577ce7 | dd2abd9192734d2d54444371b5ae1e80d9ecab78 | refs/heads/master | 2021-01-20T00:14:18.728879 | 2017-12-22T01:49:26 | 2017-12-22T01:49:26 | 101,254,842 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 511 | java | package kr.gsil.dpkepco.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import kr.gsil.dpkepco.R;
import kr.gsil.dpkepco.base.BaseActivity;
public class SafetyCCTVActivity extends BaseActivity {
@Override
public void init() {
}
@Override
public void setData() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_safety_cctv);
}
}
| [
"[email protected]"
]
| |
9ea502c2b4170bbac3f106dfb7a912865b5365ce | 1a3fbc77f08b2e092f4a634f6978ab519b1dd93f | /NetBanking/src/master1/DTO/AccountDTO1.java | 45383099ef31adc6048d5705391c6c78187e256f | []
| no_license | signaturecoder/AdvancedJava | a602ccc82d3585b1738db1d9f240051dd7b58cff | 251e7649a2b9fb73a44e482d534df1f26950a47d | refs/heads/master | 2021-05-08T14:41:29.731983 | 2018-02-25T07:26:43 | 2018-02-25T07:26:43 | 120,095,037 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package master1.DTO;
public class AccountDTO1 {
String accno;
String accp;
String cid;
double bal;
public String getAccno() {
return accno;
}
public void setAccno(String accno) {
this.accno = accno;
}
public String getAccp() {
return accp;
}
public void setAccp(String accp) {
this.accp = accp;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public double getBal() {
return bal;
}
public void setBal(double bal) {
this.bal = bal;
}
}
| [
"[email protected]"
]
| |
20644ba4024dbb564f2c6296a3baf18d00c1aebe | 106a1b5e18c26fa1270fe5e2f8e2f84688f9b398 | /src/main/java/com/arcbees/gwtp/upgrader/ObjectSlotRewriter.java | 08d71f91bf52ebc6c7c5882fb99d9202ad7df686 | []
| no_license | rdwallis/GWTP-Typed-Slot-Upgrader | 0fa062ccc46446c5567fe8a6a203a7d89480bbf3 | 12f28db6a4e04fd885eb457d253b95372181fece | refs/heads/master | 2021-01-01T17:16:06.147921 | 2015-02-11T10:16:13 | 2015-02-11T10:16:13 | 30,020,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,112 | java | package com.arcbees.gwtp.upgrader;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.github.javaparser.ASTHelper;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
public class ObjectSlotRewriter extends AbstractReWriter{
private final static Logger LOGGER = Logger.getGlobal();
private Map<String, Set<String>> slotNames;
private boolean upgrade;
public ObjectSlotRewriter(Map<String, Set<String>> slotNames, boolean upgrade) {
this.slotNames = slotNames;
this.upgrade = upgrade;
}
@Override
void processCompilationUnit() {
if (slotNames.containsKey(getEnclosingClassName())) {
processNode(getCompilationUnit());
}
}
private void processNode(Node node) {
if (node instanceof FieldDeclaration) {
FieldDeclaration fDec = (FieldDeclaration) node;
for (VariableDeclarator v: fDec.getVariables()) {
if (slotNames.get(getEnclosingClassName()).contains(v.getId().getName())) {
if (upgrade) {
addImports("com.gwtplatform.mvp.client.presenter.slots.Slot","com.gwtplatform.mvp.client.PresenterWidget");
}
Type t = fDec.getType();
ReferenceType nt = ASTHelper.createReferenceType(upgrade ? "Slot<PresenterWidget<?>>" : "Object", 0);
if (t instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) t;
rt.setType(nt);
}
Expression scope = null;
if (v.getInit() instanceof ObjectCreationExpr) {
scope = ((ObjectCreationExpr) v.getInit()).getScope();
}
v.setInit(new ObjectCreationExpr(scope, new ClassOrInterfaceType(upgrade ? "Slot<PresenterWidget<?>>" : "Object"), null));
markChanged();
}
}
}
for (Node child: node.getChildrenNodes()) {
processNode(child);
}
}
}
| [
"[email protected]"
]
| |
676baa983ad1c03e101c8e92451bd033d7c7d79e | 8059b0612f12ebbff7267168b34e67b24c4327bc | /src/test/java/com/mycompany/myapp/web/rest/AccountResourceIT.java | 24bf44ca81aa877f762706f38b05280f21276814 | []
| no_license | KamalAmarouche/jhipster-sample-application | 6717a07d5f2e6669471a9bdb6209f2a754e48ca6 | 0c7ac0f1d92ce9b176dbc114236e6fba11a3a4b2 | refs/heads/master | 2021-01-14T20:50:32.298264 | 2020-02-24T14:18:43 | 2020-02-24T14:18:43 | 242,755,063 | 0 | 0 | null | 2020-02-24T14:20:28 | 2020-02-24T14:18:29 | Java | UTF-8 | Java | false | false | 32,564 | java | package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterSampleApplicationApp;
import com.mycompany.myapp.config.Constants;
import com.mycompany.myapp.domain.User;
import com.mycompany.myapp.repository.AuthorityRepository;
import com.mycompany.myapp.repository.UserRepository;
import com.mycompany.myapp.security.AuthoritiesConstants;
import com.mycompany.myapp.service.UserService;
import com.mycompany.myapp.service.dto.PasswordChangeDTO;
import com.mycompany.myapp.service.dto.UserDTO;
import com.mycompany.myapp.web.rest.vm.KeyAndPasswordVM;
import com.mycompany.myapp.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static com.mycompany.myapp.web.rest.AccountResourceIT.TEST_USER_LOGIN;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {@link AccountResource} REST controller.
*/
@AutoConfigureMockMvc
@WithMockUser(value = TEST_USER_LOGIN)
@SpringBootTest(classes = JhipsterSampleApplicationApp.class)
public class AccountResourceIT {
static final String TEST_USER_LOGIN = "test";
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private MockMvc restAccountMockMvc;
@BeforeEach
public void setup() {
userRepository.deleteAll();
}
@Test
@WithUnauthenticatedMockUser
public void testNonAuthenticatedUser() throws Exception {
restAccountMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
public void testAuthenticatedUser() throws Exception {
restAccountMockMvc.perform(get("/api/authenticate")
.with(request -> {
request.setRemoteUser(TEST_USER_LOGIN);
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(TEST_USER_LOGIN));
}
@Test
public void testGetExistingAccount() throws Exception {
Set<String> authorities = new HashSet<>();
authorities.add(AuthoritiesConstants.ADMIN);
UserDTO user = new UserDTO();
user.setLogin(TEST_USER_LOGIN);
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("[email protected]");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
userService.createUser(user);
restAccountMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.login").value(TEST_USER_LOGIN))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("[email protected]"))
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
public void testGetUnknownAccount() throws Exception {
restAccountMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(status().isInternalServerError());
}
@Test
public void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("[email protected]");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse();
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
@Test
public void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log!n");// <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByEmailIgnoreCase("[email protected]");
assertThat(user.isPresent()).isFalse();
}
@Test
public void testRegisterInvalidEmail() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("password");
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("invalid");// <-- invalid
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
public void testRegisterInvalidPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("123");// password with only 3 digits
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
public void testRegisterNullPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword(null);// invalid null password
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("[email protected]");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
public void testRegisterDuplicateLogin() throws Exception {
// First registration
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("alice");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Something");
firstUser.setEmail("[email protected]");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin(firstUser.getLogin());
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail("[email protected]");
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setCreatedBy(firstUser.getCreatedBy());
secondUser.setCreatedDate(firstUser.getCreatedDate());
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// First user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
// Second (non activated) user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("[email protected]");
assertThat(testUser.isPresent()).isTrue();
testUser.get().setActivated(true);
userRepository.save(testUser.get());
// Second (already activated) user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
public void testRegisterDuplicateEmail() throws Exception {
// First user
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("test-register-duplicate-email");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Test");
firstUser.setEmail("[email protected]");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Register first user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser1.isPresent()).isTrue();
// Duplicate email, different login
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin("test-register-duplicate-email-2");
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail(firstUser.getEmail());
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register second (non activated) user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser2.isPresent()).isFalse();
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2");
assertThat(testUser3.isPresent()).isTrue();
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(firstUser.getId());
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
userWithUpperCaseEmail.setEmail("[email protected]");
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register third (not activated) user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3");
assertThat(testUser4.isPresent()).isTrue();
assertThat(testUser4.get().getEmail()).isEqualTo("[email protected]");
testUser4.get().setActivated(true);
userService.updateUser((new UserDTO(testUser4.get())));
// Register 4th (already activated) user
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
public void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("[email protected]");
validUser.setActivated(true);
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
Optional<User> userDup = userRepository.findOneByLogin("badguy");
assertThat(userDup.isPresent()).isTrue();
assertThat(userDup.get().getAuthorities()).hasSize(1)
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get());
}
@Test
public void testActivateAccount() throws Exception {
final String activationKey = "some activation key";
User user = new User();
user.setLogin("activate-account");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(false);
user.setActivationKey(activationKey);
userRepository.save(user);
restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey))
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.getActivated()).isTrue();
}
@Test
public void testActivateAccountWithWrongKey() throws Exception {
restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey"))
.andExpect(status().isInternalServerError());
}
@Test
@WithMockUser("save-account")
public void testSaveAccount() throws Exception {
User user = new User();
user.setLogin("save-account");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
assertThat(updatedUser.getActivated()).isEqualTo(true);
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
User user = new User();
user.setLogin("save-invalid-email");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@Test
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save(user);
User anotherUser = new User();
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("[email protected]");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
userRepository.save(anotherUser);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
@Test
@WithMockUser("save-existing-email-and-login")
public void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
user.setLogin("save-existing-email-and-login");
user.setEmail("[email protected]");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("[email protected]");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restAccountMockMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("[email protected]");
}
@Test
@WithMockUser("change-password-wrong-existing-password")
public void testChangePasswordWrongExistingPassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-wrong-existing-password");
user.setEmail("[email protected]");
userRepository.save(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
@Test
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password");
user.setEmail("[email protected]");
userRepository.save(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))
)
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-small");
user.setEmail("[email protected]");
userRepository.save(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("[email protected]");
userRepository.save(user);
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-empty");
user.setEmail("[email protected]");
userRepository.save(user);
restAccountMockMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))
)
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
public void testRequestPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("[email protected]");
userRepository.save(user);
restAccountMockMvc.perform(post("/api/account/reset-password/init")
.content("[email protected]")
)
.andExpect(status().isOk());
}
@Test
public void testRequestPasswordResetUpperCaseEmail() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("[email protected]");
userRepository.save(user);
restAccountMockMvc.perform(post("/api/account/reset-password/init")
.content("[email protected]")
)
.andExpect(status().isOk());
}
@Test
public void testRequestPasswordResetWrongEmail() throws Exception {
restAccountMockMvc.perform(
post("/api/account/reset-password/init")
.content("[email protected]"))
.andExpect(status().isOk());
}
@Test
public void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.save(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("[email protected]");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.save(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test
public void testFinishPasswordResetWrongKey() throws Exception {
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey("wrong reset key");
keyAndPassword.setNewPassword("new password");
restAccountMockMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
}
}
| [
"[email protected]"
]
| |
eca7643b55d6870ef982cc992d044e8d102d0b76 | 0b2467b38baf01f01c6248e81de9213063b64827 | /platform/com/platform/tools/ToolFormatXml.java | 89943a679adac69d133bb0885dddfdf94d86327a | []
| no_license | waterydd/taotao | 40b5de586d1462ea607b5c9996af91f4b9a7c757 | 4a1dc7f78cb18ca6ba2987d115129de8583a7252 | refs/heads/master | 2020-01-19T21:14:39.001601 | 2016-11-18T08:30:47 | 2016-11-18T08:30:47 | 94,213,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,680 | java | package com.platform.tools;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* xml 格式化
* @author mango [email protected]
*/
public abstract class ToolFormatXml {
public static void main(String[] args) {
String xml = "<xml>";
xml += "<URL><![CDATA[http://littleant.duapp.com/msg]]></URL>";
xml += "<ToUserName><![CDATA[jiu_guang]]></ToUserName>";
xml += "<FromUserName><![CDATA[dongcb678]]></FromUserName>";
xml += "<CreateTime>11</CreateTime>";
xml += "<MsgType><![CDATA[text\\//]]></MsgType>";
xml += "<Content><![CDATA[wentest]]></Content>";
xml += "<MsgId>11</MsgId>";
xml += "</xml>";
System.out.println(formatXML(xml));
}
public static String formatXML(String inputXML) {
String requestXML = null;
Document document = null;
try {
SAXReader reader = new SAXReader();
document = reader.read(new StringReader(inputXML));
} catch (DocumentException e1) {
e1.printStackTrace();
}
if (document != null) {
XMLWriter writer = null;
try {
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat(" ", true);
writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
requestXML = stringWriter.getBuffer().toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
return requestXML;
}
}
| [
"[email protected]"
]
| |
a88646f3d9bb428bcc6ee4795517939b7731f50f | 9fe88de89c17a1ae00ac4757a3842624c243e2fb | /phpunit-converted/src/main/java/com/project/convertedCode/servlets/vendor/phpunit/phpunit/src/Framework/Constraint/servlet_StringEndsWith_php.java | 35cad7fe8ab6dc8eeb8d8b90fac660fa4dd13c46 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause"
]
| permissive | RuntimeConverter/PHPUnit-Java-Converted | bccc849c0c88e8cda7b0e8a1d17883d37beb9f7a | 0a036307ab56c8b787860ad25a74a17584218fda | refs/heads/master | 2020-03-18T17:07:42.956039 | 2018-05-27T02:09:17 | 2018-05-27T02:09:17 | 135,008,061 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,200 | java | package com.project.convertedCode.servlets.vendor.phpunit.phpunit.src.Framework.Constraint;
import com.runtimeconverter.runtime.includes.RuntimeIncludable;
import com.runtimeconverter.runtime.includes.RuntimeConverterServlet;
import com.runtimeconverter.runtime.RuntimeEnv;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet("/vendor/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php")
public class servlet_StringEndsWith_php extends RuntimeConverterServlet {
protected final RuntimeIncludable getInclude() {
return com.project
.convertedCode
.includes
.vendor
.phpunit
.phpunit
.src
.Framework
.Constraint
.file_StringEndsWith_php
.instance;
}
protected final RuntimeEnv getRuntimeEnv(
String httpRequestType, HttpServletRequest req, HttpServletResponse resp) {
return new com.project.convertedCode.main.ConvertedProjectRuntimeEnv(
req, resp, this.getInclude());
}
}
| [
"[email protected]"
]
| |
a9f073ea5ce019cbe6c1f1d2a1d8735513a5bed6 | 9d367f198c57a933d9465ac2f172d1e7095c8486 | /src/test/java/stepDefinitions/MyStepDefinitions.java | 0a0202033a399158da0658303333b5601edf1877 | []
| no_license | prajvith2017/VenkateshRepository | 8b54761765651546dab7da837a856eb128888382 | 2bf261f705807e54a663bdd426fabf2942f8fbec | refs/heads/master | 2022-05-31T04:06:57.782700 | 2020-05-02T15:06:50 | 2020-05-02T15:06:50 | 260,705,976 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,869 | java | package stepDefinitions;
import junit.framework.Assert;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pageObjects.CheckoutPage;
import pageObjects.Home;
import pageObjects.OrderPage;
import Cucumber.Automation.Base;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
public class MyStepDefinitions {
public static WebDriver driver;
Home home;
CheckoutPage checkout;
OrderPage orderpage;
@Given("^User is on Greencart Landing page$")
public void user_is_on_greencart_landing_page() throws Throwable {
driver= Base.getDriver();
}
/*@When("^User searched for \"([^\"]*)\" Vegetable$")
public void user_searched_for_something_vegetable(String strArg1) throws Throwable {
home=new Home(driver);
Thread.sleep(3000);
home.getSearch().sendKeys(strArg1);
//driver.findElement(By.xpath("//input[@type='search']")).sendKeys(strArg1);
Thread.sleep(3000);
}*/
@When("^User searched for (.+) Vegetable$")
public void user_searched_for_vegetable(String vegetablename) throws Throwable {
home=new Home(driver);
Thread.sleep(3000);
home.getSearch().sendKeys(vegetablename);
Thread.sleep(3000);
}
@SuppressWarnings("deprecation")
@Then("^\"([^\"]*)\" results are displayed$")
public void something_results_are_displayed(String strArg1) throws Throwable {
home=new Home(driver);
Assert.assertTrue(home.getSearchItemDisplayed().getText().contains(strArg1));
//Assert.assertTrue(driver.findElement(By.cssSelector("h4.product-name")).getText().contains(strArg1));
}
@And("^Add items to cart$")
public void add_items_to_cart() throws Throwable {
checkout=new CheckoutPage(driver);
Thread.sleep(2000);
checkout.clickPlusSymbolButton().click();
//driver.findElement(By.xpath("//a[@class='increment']")).click();
Thread.sleep(2000);
checkout.clickAddToCartButon().click();
// driver.findElement(By.xpath("//button[text()='ADD TO CART']")).click();
Thread.sleep(2000);
checkout.clickCheckoutImageBtn().click();
//driver.findElement(By.xpath("//a[@class='cart-icon']//img[contains(@class,'')]")).click();
Thread.sleep(2000);
}
@And("^User proceeded to Checkout page for purchase$")
public void user_proceeded_to_checkout_page_for_purchase() throws Throwable {
checkout.clickProccedToCheckoutBtn().click();
//driver.findElement(By.xpath("//button[text()='PROCEED TO CHECKOUT']")).click();
}
} | [
"[email protected]"
]
| |
137b7454218e33ed2d012d2147b2285f69588fa8 | 09ed81c8b384311d56bfa96420b3b7d5a9f966a9 | /src/main/java/org/litesgroup/webapp/web/rest/LogsResource.java | d4f1d254d67094de145cf5a114111dc19e6c1935 | []
| no_license | LitesGroup/lites-webapp | 35882fb6a1a40ceb2e83e01ea3e9b5d0137c0715 | 39f6e257229587c7631baaa6ac0d9f6f031b3b1c | refs/heads/master | 2021-01-19T10:38:57.169909 | 2017-04-11T05:22:08 | 2017-04-11T05:22:08 | 87,886,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,180 | java | package org.litesgroup.webapp.web.rest;
import org.litesgroup.webapp.web.rest.vm.LoggerVM;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Controller for view and managing Log Level at runtime.
*/
@RestController
@RequestMapping("/management")
public class LogsResource {
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
return context.getLoggerList()
.stream()
.map(LoggerVM::new)
.collect(Collectors.toList());
}
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
}
| [
"[email protected]"
]
| |
fc4dfff3978532cf2377977ac987b52d85563f66 | cec74e98a53446a302d52432a3e89025a194a932 | /src/studentdatabaseapp/Student.java | 0817695da8c7f0b6abf602576e04570e6532ce3f | []
| no_license | RyanCrowleyCode/udemy-JavaProjects | c433cc3318f3bd1a4d95a2413c7bf5107e7aad48 | 2653cf80262a2941ed29cef1abfa2590951aed18 | refs/heads/master | 2022-06-13T08:45:35.336961 | 2020-05-06T15:32:24 | 2020-05-06T15:32:24 | 258,550,971 | 0 | 0 | null | 2020-05-06T15:32:26 | 2020-04-24T15:28:13 | Java | UTF-8 | Java | false | false | 2,911 | java | package studentdatabaseapp;
import java.util.ArrayList;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private int gradeYear;
private String studentID;
private final ArrayList<String> courses = new ArrayList<>();
private int tuitionBalance = 0;
private static int costOfCourse = 600;
private static int id = 1000;
// Constructor: prompt user to enter student's name and year
public Student() {
Scanner in = new Scanner(System.in);
System.out.print("Enter student first name: ");
this.firstName = in.nextLine();
System.out.print("Enter student last name: ");
this.lastName = in.nextLine();
System.out.print("1 - Freshman\n2 - Sophomore\n3 - Junior\n4 - Senior\nEnter student grade level: ");
this.gradeYear = in.nextInt();
setStudentID();
}
// Generate an ID
private void setStudentID() {
// Every time we create a student ID, we increment the id by one (static id)
id++;
// Grade Level + ID
this.studentID = gradeYear + "" + id;
}
// Enroll in courses
public void enroll() {
// Get inside a loop, user hits Q
do {
System.out.print("Enter course to enroll (Q to quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if (course.equals("Q") || course.equals("q")) {
break;
}
else {
courses.add(course);
tuitionBalance += costOfCourse;
}
} while (1 !=0);
}
// View balance
public void viewBalance() {
System.out.println("Your balance is: $" + tuitionBalance);
}
// Pay Tuition
public void payTution() {
viewBalance();
System.out.print("Enter your payment: $");
Scanner in = new Scanner(System.in);
int payment = in.nextInt();
if (payment <= tuitionBalance) {
tuitionBalance -= payment;
System.out.println("You have paid $" + payment + ".");
}
else {
System.out.println("Oops! Your payment value cannot exceed your tuition balance. You are attempting to make a payment of $" + payment + ".");
}
viewBalance();
}
// Show courses
public String showCourses(){
String formattedCourseList = "Enrolled Courses:";
for (String course : courses) {
formattedCourseList += "\n\t" + course;
}
return formattedCourseList;
}
// Show status
public String toString() {
return "Name: " + firstName + " " + lastName +
"\nGrade Level: " + gradeYear +
"\nStudent ID: " + studentID +
"\n" + showCourses() +
"\nBalance: $" + tuitionBalance;
}
}
| [
"[email protected]"
]
| |
7fd0a2d9c566e65cab195af5a80850f792873b5f | 33661ea40bd34297674e2ecfc316673fca9d9ead | /src/main/java/com/example/Dto/Dtocliente.java | d2f023f8359b4aac31cdab5f484bc298c9a66c2d | []
| no_license | DerikCaceres/projetoAC1 | 268e5f60274db34d20dcd63f608277a47c640ec6 | ca31b4c52498e1a4b4b4091736f12065110bec9f | refs/heads/master | 2023-03-22T00:25:06.045430 | 2021-03-18T01:56:32 | 2021-03-18T01:56:32 | 348,512,546 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package com.example.Dto;
import com.example.ac1.entities.cliente;
public class Dtocliente {
private String name;
private long id;
public Dtocliente(long nid, String nname) {
setName(nname);
setId(nid);
}
public Dtocliente(cliente cliente) {
setName(cliente.getName());
setId(cliente.getId());
}
public String getName()
{
return name;
}
public void setName(String name){
this.name = name;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
}
| [
"[email protected]"
]
| |
f51be8111dd60c5adad6f5431d38665db05e896b | 4a24e033e383cd71c76893c460e97f9b42cc57c6 | /src/main/java/me/zeroeightsix/botframework/locale/text/TextComponentTranslation.java | 2bc5e9bfcd17b1dfa9d5a69c13a7c06917ed03ba | []
| no_license | BokBoi/BotFramework | f3179179ed37b45dd3795672eabd3c6efb46833c | 0af348c2df647674a494e04196bc6d6535bbee49 | refs/heads/master | 2021-10-11T05:47:37.146863 | 2019-01-22T22:56:50 | 2019-01-22T22:56:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,828 | java | package me.zeroeightsix.botframework.locale.text;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import me.zeroeightsix.botframework.locale.text.translation.I18n;
import java.util.Arrays;
import java.util.IllegalFormatException;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextComponentTranslation extends TextComponentBase
{
private final String key;
private final Object[] formatArgs;
private final Object syncLock = new Object();
private long lastTranslationUpdateTimeInMilliseconds = -1L;
@VisibleForTesting
List<ITextComponent> children = Lists.<ITextComponent>newArrayList();
public static final Pattern STRING_VARIABLE_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)");
public TextComponentTranslation(String translationKey, Object... args)
{
this.key = translationKey;
this.formatArgs = args;
for (Object object : args)
{
if (object instanceof ITextComponent)
{
((ITextComponent)object).getStyle().setParentStyle(this.getStyle());
}
}
}
@VisibleForTesting
/**
* ensures that our children are initialized from the most recent string translation mapping.
*/
synchronized void ensureInitialized()
{
synchronized (this.syncLock)
{
long i = I18n.getLastTranslationUpdateTimeInMilliseconds();
if (i == this.lastTranslationUpdateTimeInMilliseconds)
{
return;
}
this.lastTranslationUpdateTimeInMilliseconds = i;
this.children.clear();
}
try
{
this.initializeFromFormat(I18n.translateToLocal(this.key));
}
catch (TextComponentTranslationFormatException textcomponenttranslationformatexception)
{
this.children.clear();
try
{
this.initializeFromFormat(I18n.translateToFallback(this.key));
}
catch (TextComponentTranslationFormatException var5)
{
throw textcomponenttranslationformatexception;
}
}
}
/**
* initializes our children from a format string, using the format args to fill in the placeholder variables.
*/
protected void initializeFromFormat(String format)
{
Matcher matcher = STRING_VARIABLE_PATTERN.matcher(format);
int i = 0;
int j = 0;
try
{
int l;
for (; matcher.find(j); j = l)
{
int k = matcher.start();
l = matcher.end();
if (k > j)
{
TextComponentString textcomponentstring = new TextComponentString(String.format(format.substring(j, k)));
textcomponentstring.getStyle().setParentStyle(this.getStyle());
this.children.add(textcomponentstring);
}
String s2 = matcher.group(2);
String s = format.substring(k, l);
if ("%".equals(s2) && "%%".equals(s))
{
TextComponentString textcomponentstring2 = new TextComponentString("%");
textcomponentstring2.getStyle().setParentStyle(this.getStyle());
this.children.add(textcomponentstring2);
}
else
{
if (!"s".equals(s2))
{
throw new TextComponentTranslationFormatException(this, "Unsupported format: '" + s + "'");
}
String s1 = matcher.group(1);
int i1 = s1 != null ? Integer.parseInt(s1) - 1 : i++;
if (i1 < this.formatArgs.length)
{
this.children.add(this.getFormatArgumentAsComponent(i1));
}
}
}
if (j < format.length())
{
TextComponentString textcomponentstring1 = new TextComponentString(String.format(format.substring(j)));
textcomponentstring1.getStyle().setParentStyle(this.getStyle());
this.children.add(textcomponentstring1);
}
}
catch (IllegalFormatException illegalformatexception)
{
throw new TextComponentTranslationFormatException(this, illegalformatexception);
}
}
private ITextComponent getFormatArgumentAsComponent(int index)
{
if (index >= this.formatArgs.length)
{
throw new TextComponentTranslationFormatException(this, index);
}
else
{
Object object = this.formatArgs[index];
ITextComponent itextcomponent;
if (object instanceof ITextComponent)
{
itextcomponent = (ITextComponent)object;
}
else
{
itextcomponent = new TextComponentString(object == null ? "null" : object.toString());
itextcomponent.getStyle().setParentStyle(this.getStyle());
}
return itextcomponent;
}
}
public ITextComponent setStyle(Style style)
{
super.setStyle(style);
for (Object object : this.formatArgs)
{
if (object instanceof ITextComponent)
{
((ITextComponent)object).getStyle().setParentStyle(this.getStyle());
}
}
if (this.lastTranslationUpdateTimeInMilliseconds > -1L)
{
for (ITextComponent itextcomponent : this.children)
{
itextcomponent.getStyle().setParentStyle(style);
}
}
return this;
}
public Iterator<ITextComponent> iterator()
{
this.ensureInitialized();
return Iterators.<ITextComponent>concat(createDeepCopyIterator(this.children), createDeepCopyIterator(this.siblings));
}
/**
* Gets the text of this component, without any special formatting codes added, for chat. TODO: why is this two
* different methods?
*/
public String getUnformattedComponentText()
{
this.ensureInitialized();
StringBuilder stringbuilder = new StringBuilder();
for (ITextComponent itextcomponent : this.children)
{
stringbuilder.append(itextcomponent.getUnformattedComponentText());
}
return stringbuilder.toString();
}
/**
* Creates a copy of this component. Almost a deep copy, except the style is shallow-copied.
*/
public TextComponentTranslation createCopy()
{
Object[] aobject = new Object[this.formatArgs.length];
for (int i = 0; i < this.formatArgs.length; ++i)
{
if (this.formatArgs[i] instanceof ITextComponent)
{
aobject[i] = ((ITextComponent)this.formatArgs[i]).createCopy();
}
else
{
aobject[i] = this.formatArgs[i];
}
}
TextComponentTranslation textcomponenttranslation = new TextComponentTranslation(this.key, aobject);
textcomponenttranslation.setStyle(this.getStyle().createShallowCopy());
for (ITextComponent itextcomponent : this.getSiblings())
{
textcomponenttranslation.appendSibling(itextcomponent.createCopy());
}
return textcomponenttranslation;
}
public boolean equals(Object p_equals_1_)
{
if (this == p_equals_1_)
{
return true;
}
else if (!(p_equals_1_ instanceof TextComponentTranslation))
{
return false;
}
else
{
TextComponentTranslation textcomponenttranslation = (TextComponentTranslation)p_equals_1_;
return Arrays.equals(this.formatArgs, textcomponenttranslation.formatArgs) && this.key.equals(textcomponenttranslation.key) && super.equals(p_equals_1_);
}
}
public int hashCode()
{
int i = super.hashCode();
i = 31 * i + this.key.hashCode();
i = 31 * i + Arrays.hashCode(this.formatArgs);
return i;
}
public String toString()
{
return "TranslatableComponent{key='" + this.key + '\'' + ", args=" + Arrays.toString(this.formatArgs) + ", siblings=" + this.siblings + ", style=" + this.getStyle() + '}';
}
public String getKey()
{
return this.key;
}
public Object[] getFormatArgs()
{
return this.formatArgs;
}
}
| [
"[email protected]"
]
| |
3a82af99e379bc781abace848458aa92a71ffde3 | 1f8609ac4f52e892f9d9045ed9966f759e4dfc08 | /app/src/main/java/com/eduschool/eduschoolapp/recReqPOJO/recReqBean.java | af580897aa7d3f95ca842b76a6f626c570a35c0b | []
| no_license | mukulraw/eduschoolapp | 61963e64fed75a590774c8fbc269c9e4c50a9dfc | 01178365e764c2a83b6671326bfd4e3e33bd0403 | refs/heads/master | 2021-05-16T16:58:21.848721 | 2018-03-15T09:28:05 | 2018-03-15T09:28:05 | 120,094,350 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 586 | java | package com.eduschool.eduschoolapp.recReqPOJO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by TBX on 9/20/2017.
*/
public class recReqBean {
@SerializedName("recevrequest_list")
@Expose
private List<RecevrequestList> recevrequestList = null;
public List<RecevrequestList> getRecevrequestList() {
return recevrequestList;
}
public void setRecevrequestList(List<RecevrequestList> recevrequestList) {
this.recevrequestList = recevrequestList;
}
}
| [
"[email protected]"
]
| |
3aa0fe907c55c518d13b5b955cec03b0aff1dfe3 | 8748daf738df196d488d322a38d58d50e0763478 | /app/src/main/java/com/app/collegeattendance/SelectionActivity.java | 561845f33b7b91c003446791d9a244647fe0c54e | []
| no_license | nisargtrivedi/AttendanceApp | 76d0617d3ac2cdd143b9c326a5cd05b7d490056e | 758d188867bff1f5327ea92ccc9707bbda09328a | refs/heads/main | 2023-01-10T03:21:37.237669 | 2020-11-10T08:08:43 | 2020-11-10T08:08:43 | 311,588,204 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,377 | java | package com.app.collegeattendance;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import com.app.collegeattendance.API.AppPreferences;
import com.app.collegeattendance.student.StudentDashboard;
import com.app.collegeattendance.student.StudentLogin;
public class SelectionActivity extends AppCompatActivity {
ImageView teacher,student;
AppCompatButton btnGo;
AppPreferences appPreferences;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appPreferences=new AppPreferences(this);
setContentView(R.layout.select_user_type);
teacher=findViewById(R.id.teacher);
student=findViewById(R.id.student);
btnGo=findViewById(R.id.btnGo);
if(!TextUtils.isEmpty(appPreferences.getString("student_id"))){
finish();
startActivity(new Intent(SelectionActivity.this, StudentDashboard.class));
}else if(!TextUtils.isEmpty(appPreferences.getString("facultyid"))){
finish();
startActivity(new Intent(SelectionActivity.this,HomeActivity.class));
}
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(teacher.isSelected()){
finish();
startActivity(new Intent(SelectionActivity.this,MainActivity.class));
}else if(student.isSelected()){
finish();
startActivity(new Intent(SelectionActivity.this, StudentLogin.class));
}
}
});
teacher.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
teacher.setSelected(true);
student.setSelected(false);
}
});
student.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
teacher.setSelected(false);
student.setSelected(true);
}
});
}
}
| [
"[email protected]"
]
| |
a969a9893112e01c2a458885119eba422c178ab4 | b842bf71deeec94288faf460db42cb1a1d5d9d6c | /tiger/src/main/java/com/hwangjr/mvp/base/BaseFragment.java | 6ded93688350bb98750af584db8ca5e4277fad98 | [
"Apache-2.0"
]
| permissive | AndroidKnife/Tiger-Pro | cd141a498bd2c3981429fd06fd5becfb96e0d2ed | cc4477b2842d895b8d31dad5060f7740fc967d40 | refs/heads/master | 2020-04-11T01:28:44.960088 | 2016-11-04T06:40:34 | 2016-11-04T06:40:34 | 61,051,396 | 10 | 2 | null | null | null | null | UTF-8 | Java | false | false | 5,278 | java | package com.hwangjr.mvp.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import com.hwangjr.mvp.MVPApplication;
import com.hwangjr.mvp.injection.components.ActivityComponent;
import com.hwangjr.mvp.injection.components.DaggerFragmentComponent;
import com.hwangjr.mvp.injection.components.FragmentComponent;
import com.hwangjr.mvp.injection.modules.FragmentModule;
import com.hwangjr.mvp.widget.SnackbarWrapper;
import com.hwangjr.tiger.R;
import com.squareup.leakcanary.RefWatcher;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public abstract class BaseFragment extends Fragment {
protected View mainView;
private Unbinder unbinder;
private boolean isVisibleToUser;
private boolean isViewCreated = false;
private boolean isPageRunning;
private ActivityComponent activityComponent;
private FragmentComponent fragmentComponent;
private ViewStub tipsViewStub;
private View tipsView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
// Should call after activity created
@Deprecated
protected ActivityComponent getActivityComponent() {
try {
if (activityComponent == null) {
activityComponent = ((BaseActivity) getActivity()).getActivityComponent();
}
} catch (Exception e) {
e.printStackTrace();
}
return activityComponent;
}
protected FragmentComponent getFragmentComponent() {
try {
if (fragmentComponent == null) {
fragmentComponent = DaggerFragmentComponent.builder()
.appComponent(MVPApplication.getAppComponent())
.fragmentModule(new FragmentModule(this)).build();
}
} catch (Exception e) {
e.printStackTrace();
}
return fragmentComponent;
}
protected abstract int getLayoutId();
protected abstract void initView();
protected void initData(@Nullable Bundle arguments) {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
if (mainView == null) {
mainView = inflater.inflate(getLayoutId(), container, false);
unbinder = ButterKnife.bind(this, mainView);
initView();
isViewCreated = true;
initData(getArguments());
}
return mainView;
}
@Override
public void onResume() {
super.onResume();
isPageRunning = true;
if (getUserVisibleHint()) {
onUserVisible(true);
}
}
@Override
public void onPause() {
onUserVisible(false);
isPageRunning = false;
super.onPause();
}
@Override
public void onDestroy() {
if (unbinder != null) {
unbinder.unbind();
}
Fragment fragment = getTargetFragment();
if (fragment != null && fragment instanceof BaseFragment) {
BaseFragment targetFragment = (BaseFragment) fragment;
targetFragment.onFragmentResult(getTargetRequestCode());
}
if (mainView != null && mainView.getParent() != null) {
((ViewGroup) mainView.getParent()).removeView(mainView);
}
super.onDestroy();
RefWatcher refWatcher = MVPApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
protected void onFragmentResult(int requestCode) {
}
protected boolean isVisibleToUser() {
return isVisibleToUser;
}
protected boolean isViewCreated() {
return isViewCreated;
}
protected boolean isPageRunning() {
return isPageRunning;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
this.isVisibleToUser = isVisibleToUser;
onUserVisible(isVisibleToUser);
}
protected void onUserVisible(boolean isVisibleToUser) {
}
protected View getTipsViewFromActivity() {
return ((BaseActivity) getActivity()).getTipsView();
}
protected void initTipsView() {
tipsView = getTipsViewFromActivity();
if (tipsView == null) {
if (getTipsStubViewId() > 0) {
tipsViewStub = (ViewStub) mainView.findViewById(getTipsStubViewId());
if (getTipsRootViewLayoutId() > 0) {
tipsViewStub.setLayoutResource(getTipsRootViewLayoutId());
tipsView = tipsViewStub.inflate();
}
}
}
}
public int getTipsStubViewId() {
return R.id.mvp_tips;
}
public int getTipsRootViewLayoutId() {
return R.layout.mvp_layout_coordinator;
}
public void showTips(String msg) {
if (tipsViewStub == null) {
initTipsView();
}
if (tipsView != null) {
SnackbarWrapper.wrapper(tipsView, msg).show();
}
}
} | [
"[email protected]"
]
| |
8612debb629526ddb417e2772baf8a6b4623f463 | 5a094472ff9a4f5d0417fe4ea1cf135a73d3e8f1 | /src/main/java/com/blogspot/toomuchcoding/topFeaturesYouNeedToKnowAbout/service/WaiterImpl.java | 29e76633bc3643422277db4501b902432e032ef9 | [
"Apache-2.0"
]
| permissive | YunZhang2014/mockito-instant | b412ef331060c203aff489fced1bc9fe409aac42 | e262cfa5aef8665ee0b7e2ed94ae51a7cfc40132 | refs/heads/master | 2022-12-27T00:49:17.929919 | 2020-05-16T02:32:41 | 2020-05-16T02:32:41 | 264,338,211 | 0 | 0 | Apache-2.0 | 2020-10-13T22:01:37 | 2020-05-16T01:54:54 | Java | UTF-8 | Java | false | false | 7,474 | java | package com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.service;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.exception.IAmTooLazyToDoItException;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.exception.TooBusyToCalculateException;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.exception.WrongMealException;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.meal.Meal;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.meal.RomanticDinnerMenu;
import com.blogspot.toomuchcoding.topFeaturesYouNeedToKnowAbout.service.cleaning.*;
import java.util.Iterator;
import java.util.List;
/**
* User: mgrzejszczak
* Date: 14.05.13
* Time: 11:22
*/
public class WaiterImpl implements Waiter {
public static final boolean VEGETARIAN_MEAL = true;
public static final boolean NON_VEGETARIAN_MEAL = false;
private static final boolean RESTAURANT_READY_TO_TAKE_AN_ORDER = true;
private static final boolean RESTAURANT_NOT_READY_TO_TAKE_AN_ORDER = false;
private static final boolean SUCCESSFULLY_CLEANED_THE_RESTAURANT = true;
private static final boolean FAILED_TO_CLEAN_THE_RESTAURANT = false;
private static final boolean SUCCESSFULLY_PREPARED_THE_RESTAURANT_TO_START = true;
private static final boolean FAILED_TO_PREPARE_THE_RESTAURANT_TO_START = false;
private final KitchenService kitchenService;
private final AdministrativeStaffService administrativeStaffService;
private final CleaningServiceFactory cleaningServiceFactory;
public WaiterImpl(final KitchenService kitchenService) {
this.kitchenService = kitchenService;
this.administrativeStaffService = new GreatAdministrativeService();
this.cleaningServiceFactory = new CleaningServiceFactoryImpl();
}
public WaiterImpl(final KitchenService kitchenService, final AdministrativeStaffService administrativeStaffService) {
this.kitchenService = kitchenService;
this.administrativeStaffService = administrativeStaffService;
this.cleaningServiceFactory = new CleaningServiceFactoryImpl();
}
public WaiterImpl(final KitchenService kitchenService, final AdministrativeStaffService administrativeStaffService, final CleaningServiceFactory cleaningServiceFactory) {
this.kitchenService = kitchenService;
this.administrativeStaffService = administrativeStaffService;
this.cleaningServiceFactory = cleaningServiceFactory;
}
public WaiterImpl(final CleaningServiceFactory cleaningServiceFactory) {
this.kitchenService = new SimpleKitchenService();
this.administrativeStaffService = new GreatAdministrativeService();
this.cleaningServiceFactory = cleaningServiceFactory;
}
@Override
public List<Meal> bringOrderedVegetarianMeals(List<String> vegetarianMealNames) {
List<Meal> preparedMeals = kitchenService.prepareVegetarianMeals(vegetarianMealNames);
removeNonVegetarianMeals(preparedMeals);
return preparedMeals;
}
private void removeNonVegetarianMeals(List<Meal> potentiallyNonVegetarianMeals) {
Iterator<Meal> mealIterator = potentiallyNonVegetarianMeals.iterator();
while (mealIterator.hasNext()) {
Meal preparedMeal = mealIterator.next();
if (!preparedMeal.isVegetarian()) {
mealIterator.remove();
}
}
}
@Override
public Meal bringOrderedMeal(String mealName, boolean vegetarian) {
Meal preparedMeal = kitchenService.prepareMeal(mealName, vegetarian);
if (preparedMeal.isVegetarian() != vegetarian) {
throw new WrongMealException("You've prepared a wrong meal!");
}
return preparedMeal;
}
@Override
public int calculateTotalWaitingTime(List<Meal> meals) {
int totalTime = 0;
for (Meal meal : meals) {
try {
totalTime = totalTime + kitchenService.calculatePreparationTime(meal);
} catch (TooBusyToCalculateException tooBusyToCalculateException) {
System.err.printf("I am sorry but I couldn't calculate the preparation time of the meal [%s]%n", meal.getName());
}
}
return totalTime;
}
@Override
public boolean closeTheRestaurant() {
boolean successfullyClosedTheKitchen = true;
try {
kitchenService.cleanTheKitchen();
} catch (IAmTooLazyToDoItException iAmTooLazyToDoItException) {
successfullyClosedTheKitchen = false;
System.err.println("Beat it! I am too lazy to clean the kitchen");
}
return successfullyClosedTheKitchen;
}
@Override
public boolean readyToTakeAnOrder() throws IAmTooLazyToDoItException {
if (administrativeStaffService.isPowerOnline() && kitchenService.isOutfitChanged() && kitchenService.isKitchenPrepared()) {
return RESTAURANT_READY_TO_TAKE_AN_ORDER;
}
return RESTAURANT_NOT_READY_TO_TAKE_AN_ORDER;
}
@Override
public void bullyOtherWorkers() {
administrativeStaffService.isPowerOnline();
kitchenService.isOutfitChanged();
kitchenService.isOutfitChanged();
kitchenService.isKitchenPrepared();
kitchenService.isOutfitChanged();
}
@Override
public String describeTheElementsOfTheRomanticDinner(RomanticDinnerMenu romanticDinnerMenu) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(romanticDinnerMenu.getFirstCourse().getName()).append(" ");
stringBuilder.append(romanticDinnerMenu.getVegetarianFirstCourse().getName()).append(" ");
stringBuilder.append(romanticDinnerMenu.getDessert().getName());
return stringBuilder.toString();
}
@Override
public boolean askTheCleaningServiceToCleanTheRestaurant(TypeOfCleaningService typeOfCleaningService) {
CleaningService cleaningService = cleaningServiceFactory.getMeACleaningService(typeOfCleaningService);
try{
cleaningService.cleanTheTables();
cleaningService.sendInformationAfterCleaning();
return SUCCESSFULLY_CLEANED_THE_RESTAURANT;
}catch(CommunicationException communicationException){
System.err.println("An exception took place while trying to send info about cleaning the restaurant");
return FAILED_TO_CLEAN_THE_RESTAURANT;
}
}
@Override
public boolean prepareTheRestaurantToStart() {
CleaningService cleaningService = cleaningServiceFactory.getMeACleaningService(TypeOfCleaningService.GOOD);
cleaningService.cleanTheTables();
try{
AdministrativeStaffService administrativeStaffService = (AdministrativeStaffService)cleaningService; // that looks bad...
if(administrativeStaffService.isPowerOnline()){
KitchenService kitchenService = (KitchenService)cleaningService; // that looks bad... again...
kitchenService.cleanTheKitchen();
}
return SUCCESSFULLY_PREPARED_THE_RESTAURANT_TO_START;
}catch(ClassCastException classCastException){
System.err.println("Sorry this class can't do more than just clean the restaurant");
return FAILED_TO_PREPARE_THE_RESTAURANT_TO_START;
}
}
public KitchenService getKitchenService() {
return kitchenService;
}
}
| [
"[email protected]"
]
| |
f5de4f36a335d32007ef9795af86d956dfa3aa07 | 0381d6e167025567101f2c8f414d110bee1fc67d | /src/org/wtdiff/util/ui/DiffOpenDialog.java | f05445a6fa07b22d0648692ff6c1134685b835cf | [
"Apache-2.0"
]
| permissive | dnstandish/WTDiff | 23a7d158a0b7c4b907296c89fd2d7d163e31dda0 | 2cad3c2f8961af0328b1ee51ed84e81522a4cf80 | refs/heads/master | 2022-02-05T03:13:29.309434 | 2022-01-09T00:54:50 | 2022-01-09T00:54:50 | 96,142,070 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,116 | java | /*
Copyright 2015 David Standish
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.wtdiff.util.ui;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.wtdiff.util.io.FileUtil;
import org.wtdiff.util.text.DiffController;
import org.wtdiff.util.text.FileInputStreamSource;
public class DiffOpenDialog extends JDialog implements ActionListener {
private static int MIN_FILENAME_TEXT_FIELD_LENGTH = 20;
private DiffController controller;
private String oldFileName;
private String newFileName;
private JButton oldFolderButton;
private JButton newFolderButton;
private JButton okButton;
private JButton cancelButton;
private JTextField oldJText;
private JTextField newJText;
public DiffOpenDialog(Frame parent, DiffController diffController) {
super(parent, Messages.getString("DiffOpenDialog.dialog_title"), true);
controller = diffController;
oldFileName = controller.getOldSourceName();
newFileName = controller.getNewSourceName();
JLabel oldLabel = new JLabel(Messages.getString("DiffOpenDialog.old_label"));
oldFolderButton = new JButton( javax.swing.plaf.metal.MetalIconFactory.getTreeFolderIcon() );
oldFolderButton.addActionListener(this);
oldJText = new JTextField(oldFileName);
if ( oldJText.getColumns() < MIN_FILENAME_TEXT_FIELD_LENGTH) {
oldJText.setColumns(MIN_FILENAME_TEXT_FIELD_LENGTH);
}
oldJText.setEditable(true);
Box oldBox = Box.createHorizontalBox();
oldBox.add(Box.createHorizontalStrut(10));
oldBox.add(oldLabel);
oldBox.add(Box.createHorizontalStrut(5));
oldBox.add(oldFolderButton);
oldBox.add(Box.createHorizontalStrut(5));
oldBox.add(oldJText);
oldBox.add( Box.createHorizontalGlue() );
oldBox.add(Box.createHorizontalStrut(10));
JLabel newLabel = new JLabel(Messages.getString("DiffOpenDialog.new_label"));
newFolderButton = new JButton( javax.swing.plaf.metal.MetalIconFactory.getTreeFolderIcon() );
newFolderButton.addActionListener(this);
newJText = new JTextField(newFileName);
newJText.setEditable(true);
Box newBox = Box.createHorizontalBox();
newBox.add(Box.createHorizontalStrut(10));
newBox.add(newLabel);
newBox.add(Box.createHorizontalStrut(5));
newBox.add(newFolderButton);
newBox.add(Box.createHorizontalStrut(5));
newBox.add(newJText);
newBox.add( Box.createHorizontalGlue() );
newBox.add(Box.createHorizontalStrut(10));
Box mainBox = Box.createVerticalBox();
mainBox.add(oldBox);
mainBox.add(newBox);
add(mainBox, "North");
// ok button
okButton = new JButton(
Messages.getString("DiffOpenDialog.button_ok")
);
okButton.addActionListener(this);
cancelButton = new JButton(
Messages.getString("DiffOpenDialog.button_cancel")
);
cancelButton.addActionListener(this);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add( Box.createHorizontalGlue() );
buttonBox.add( okButton );
buttonBox.add(Box.createHorizontalStrut(5));
buttonBox.add( cancelButton );
buttonBox.add( Box.createHorizontalGlue() );
add( buttonBox, "South" );
}
@Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if ( object == okButton ) {
if ( checkFile( oldJText.getText() ) && checkFile( newJText.getText() ) ) {
try {
FileInputStreamSource oldSource = new FileInputStreamSource( new File (oldJText.getText()) );
FileInputStreamSource newSource = new FileInputStreamSource( new File (newJText.getText()) );
controller.setOldSource( oldSource );
controller.setNewSource( newSource );
setVisible( false );
} catch (IOException ioe) {
JOptionPane.showMessageDialog(
null,
ioe.getMessage(),
Messages.getString("DiffOpenDialog.title_error"), //$NON-NLS-1$
JOptionPane.ERROR_MESSAGE
);
}
}
}
else if ( object == cancelButton ) {
setVisible( false );
}
else if ( object == oldFolderButton ) {
chooseFile(oldJText, DiffController.SourceType.OLD);
}
else if ( object == newFolderButton ) {
chooseFile(newJText, DiffController.SourceType.NEW);
}
}
private boolean checkFile(String path) {
if ( path == null || path.equals("") ) {
JOptionPane.showMessageDialog(
null,
Messages.getString("DiffOpenDialog.empty_name"), //$NON-NLS-1$
Messages.getString("DiffOpenDialog.title_error"), //$NON-NLS-1$
JOptionPane.ERROR_MESSAGE
);
return false;
}
Path f = Paths.get(path);
if ( ! f.toFile().exists() ) { // nio Files.exists(path) returns false in Windows7 if missing read permission
JOptionPane.showMessageDialog(
null,
MessageFormat.format(
Messages.getString("DiffOpenDialog.no_exist"), //$NON-NLS-1$
path
),
Messages.getString("DiffOpenDialog.title_error"), //$NON-NLS-1$
JOptionPane.ERROR_MESSAGE
);
return false;
}
if ( ! Files.isRegularFile(f) ) {
JOptionPane.showMessageDialog(
null,
MessageFormat.format(
Messages.getString("DiffOpenDialog.not_reg_file"), //$NON-NLS-1$
path
),
Messages.getString("DiffOpenDialog.title_error"), //$NON-NLS-1$
JOptionPane.ERROR_MESSAGE
);
return false;
}
if ( ! Files.isReadable(f) ) {
JOptionPane.showMessageDialog(
null,
MessageFormat.format(
Messages.getString("DiffOpenDialog.no_read"), //$NON-NLS-1$
path
),
Messages.getString("DiffOpenDialog.title_error"), //$NON-NLS-1$
JOptionPane.ERROR_MESSAGE
);
return false;
}
return true;
}
private void chooseFile( JTextField path , DiffController.SourceType type ) {
String pathString = FileUtil.bestExistingDirFromString(path.getText() , ".");
// String pathString = "."; //$NON-NLS-1$
// if ( path.getText() != null && path.getText().length() > 0 ) {
// String fileOrDir = path.getText();
// File pathFile = new File(fileOrDir);
// if ( ! pathFile.isDirectory() ) {
// String parent = pathFile.getParent();
// if ( parent != null ) {
// File parentFile = new File(parent);
// if ( parentFile.exists() ) {
// pathString = parent;
// }
// }
// } else if ( pathFile.exists() ) {
// pathString = pathFile.getPath();
// }
// }
JFileChooser c = new JFileChooser(new File(pathString));
c.setFileSelectionMode(JFileChooser.FILES_ONLY);
c.setDialogTitle(
type == DiffController.SourceType.OLD ?
Messages.getString("DiffOpenDialog.title_select_old"):
Messages.getString("DiffOpenDialog.title_select_new")
); //$NON-NLS-1$ //$NON-NLS-2$
int result = c.showDialog(this, Messages.getString("DiffOpenDialog.file_select_approve_button")); //$NON-NLS-1$
if ( result == JFileChooser.APPROVE_OPTION ) {
path.setText( c.getSelectedFile().toString() );
}
}
}
| [
"davidst@041a3167-dd87-4a6a-9bc3-e3c74769f2ba"
]
| davidst@041a3167-dd87-4a6a-9bc3-e3c74769f2ba |
365d427e1d5d8a59658dccc59ddbcfd6f60538d3 | 8523563143e69b9ca0326acafdaa646f1b57bb94 | /tags/plantuml-6939/src/net/sourceforge/plantuml/svek/CucaDiagramFileMakerSvek2.java | 766e6d63b48187e5dcb7589c28a7a926300e85b7 | []
| no_license | svn2github/plantuml | d372e8c5f4b1c5d990b190e2989cd8e5a86ed8fc | 241b60a9081a25079bf73f12c08c476e16993384 | refs/heads/master | 2023-09-03T13:20:47.638892 | 2012-11-20T22:08:10 | 2012-11-20T22:08:10 | 10,839,094 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,178 | java | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* Original Author: Arnaud Roques
*
* Revision $Revision: 6711 $
*
*/
package net.sourceforge.plantuml.svek;
import java.awt.Color;
import java.awt.geom.Dimension2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.plantuml.ColorParam;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.EmptyImageBuilder;
import net.sourceforge.plantuml.FontParam;
import net.sourceforge.plantuml.StringUtils;
import net.sourceforge.plantuml.UmlDiagramType;
import net.sourceforge.plantuml.cucadiagram.Entity;
import net.sourceforge.plantuml.cucadiagram.EntityType;
import net.sourceforge.plantuml.cucadiagram.Group;
import net.sourceforge.plantuml.cucadiagram.GroupType;
import net.sourceforge.plantuml.cucadiagram.IEntity;
import net.sourceforge.plantuml.cucadiagram.Link;
import net.sourceforge.plantuml.cucadiagram.dot.DotData;
import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.GraphicStrings;
import net.sourceforge.plantuml.graphic.HorizontalAlignement;
import net.sourceforge.plantuml.graphic.HtmlColor;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.StringBounderUtils;
import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.graphic.TextBlockUtils;
import net.sourceforge.plantuml.skin.rose.Rose;
import net.sourceforge.plantuml.ugraphic.UFont;
public final class CucaDiagramFileMakerSvek2 {
private final ColorSequence colorSequence = new ColorSequence();
private final DotData dotData;
static private final StringBounder stringBounder;
static {
final EmptyImageBuilder builder = new EmptyImageBuilder(10, 10, Color.WHITE);
stringBounder = StringBounderUtils.asStringBounder(builder.getGraphics2D());
}
public CucaDiagramFileMakerSvek2(DotData dotData) {
this.dotData = dotData;
}
protected UFont getFont(FontParam fontParam) {
return getData().getSkinParam().getFont(fontParam, null);
}
private IEntityImage createEntityImageBlock(DotData dotData, IEntity ent) {
if (ent.getType() == EntityType.CLASS || ent.getType() == EntityType.ABSTRACT_CLASS
|| ent.getType() == EntityType.INTERFACE || ent.getType() == EntityType.ENUM) {
return new EntityImageClass(ent, dotData.getSkinParam(), dotData);
}
if (ent.getType() == EntityType.NOTE) {
return new EntityImageNote(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.ACTIVITY) {
return new EntityImageActivity(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.STATE) {
return new EntityImageState(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.CIRCLE_START) {
return new EntityImageCircleStart(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.CIRCLE_END) {
return new EntityImageCircleEnd(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.USECASE) {
return new EntityImageUseCase(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.BRANCH) {
return new EntityImageBranch(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.LOLLIPOP) {
return new EntityImageLollipopInterface(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.ACTOR) {
return new EntityImageActor(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.COMPONENT) {
return new EntityImageComponent(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.OBJECT) {
return new EntityImageObject(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.SYNCHRO_BAR) {
return new EntityImageSynchroBar(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.CIRCLE_INTERFACE) {
return new EntityImageCircleInterface(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.POINT_FOR_ASSOCIATION) {
return new EntityImageAssociationPoint(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.GROUP) {
return new EntityImageGroup(ent, dotData.getSkinParam());
}
if (ent.getType() == EntityType.EMPTY_PACKAGE) {
return new EntityImageEmptyPackage(ent, dotData.getSkinParam());
}
throw new UnsupportedOperationException(ent.getType().toString());
}
private DotStringFactory dotStringFactory;
private Map<IEntity, Shape> shapeMap;
private String getShapeUid(IEntity ent) {
final Shape result = shapeMap.get(ent);
if (result == null && ent.getType() == EntityType.GROUP) {
for (IEntity i : shapeMap.keySet()) {
if (ent.getParent().getCode().equals(i.getCode())) {
return shapeMap.get(i).getUid();
}
}
if (result == null) {
return "za" + ent.getParent().getUid2();
}
}
return result.getUid();
}
public IEntityImage createFile(String... dotStrings) throws IOException, InterruptedException {
dotStringFactory = new DotStringFactory(colorSequence, stringBounder, dotData.getUmlDiagramType());
shapeMap = new HashMap<IEntity, Shape>();
printGroups(null);
printEntities(getUnpackagedEntities());
final Map<Link, Line> lineMap = new HashMap<Link, Line>();
for (Link link : dotData.getLinks()) {
final String shapeUid1 = getShapeUid(link.getEntity1());
final String shapeUid2 = getShapeUid(link.getEntity2());
String ltail = null;
if (shapeUid1.startsWith("za")) {
ltail = getCluster(link.getEntity1().getParent()).getClusterId();
}
String lhead = null;
if (shapeUid2.startsWith("za")) {
lhead = getCluster(link.getEntity2().getParent()).getClusterId();
}
final FontConfiguration labelFont = new FontConfiguration(dotData.getSkinParam().getFont(
FontParam.ACTIVITY_ARROW, null), HtmlColor.BLACK);
final Line line = new Line(shapeUid1, shapeUid2, link, colorSequence, ltail, lhead, dotData.getSkinParam(),
stringBounder, labelFont);
dotStringFactory.addLine(line);
lineMap.put(link, line);
}
if (dotStringFactory.illegalDotExe()) {
return error(dotStringFactory.getDotExe());
}
final Dimension2D dim = Dimension2DDouble.delta(dotStringFactory.solve(dotStrings), 10);
final HtmlColor border;
if (getData().getUmlDiagramType() == UmlDiagramType.STATE) {
border = getColor(ColorParam.stateBorder, null);
} else {
border = getColor(ColorParam.packageBorder, null);
}
return new SvekResult(dim, dotData, dotStringFactory, border);
}
protected final HtmlColor getColor(ColorParam colorParam, String stereo) {
return new Rose().getHtmlColor(dotData.getSkinParam(), colorParam, stereo);
}
private Cluster getCluster(Group g) {
for (Cluster cl : dotStringFactory.getAllSubCluster()) {
if (cl.getGroup() == g) {
return cl;
}
}
throw new IllegalArgumentException(g.toString());
}
private IEntityImage error(File dotExe) {
final List<String> msg = new ArrayList<String>();
msg.add("Dot Executable: " + dotExe);
if (dotExe != null) {
if (dotExe.exists() == false) {
msg.add("File does not exist");
} else if (dotExe.isDirectory()) {
msg.add("It should be an executable, not a directory");
} else if (dotExe.isFile() == false) {
msg.add("Not a valid file");
} else if (dotExe.canRead() == false) {
msg.add("File cannot be read");
}
}
msg.add("Cannot find Graphviz. You should try");
msg.add(" ");
msg.add("@startuml");
msg.add("testdot");
msg.add("@enduml");
msg.add(" ");
msg.add(" or ");
msg.add(" ");
msg.add("java -jar plantuml.jar -testdot");
return new GraphicStrings(msg);
}
private void printEntities(Collection<? extends IEntity> entities2) {
for (IEntity ent : entities2) {
printEntity(ent);
}
}
private void printEntity(IEntity ent) {
final IEntityImage image;
if (ent.getSvekImage() == null) {
image = createEntityImageBlock(dotData, ent);
} else {
image = ent.getSvekImage();
}
final Dimension2D dim = image.getDimension(stringBounder);
final Shape shape = new Shape(image.getShapeType(), dim.getWidth(), dim.getHeight(), colorSequence, ent.isTop());
dotStringFactory.addShape(shape);
shape.setImage(image);
shapeMap.put(ent, shape);
}
private Collection<IEntity> getUnpackagedEntities() {
final List<IEntity> result = new ArrayList<IEntity>();
for (IEntity ent : dotData.getEntities().values()) {
if (ent.getParent() == dotData.getTopParent()) {
result.add(ent);
}
}
return result;
}
private void printGroups(Group parent) throws IOException {
for (Group g : dotData.getGroupHierarchy().getChildrenGroups(parent)) {
if (dotData.isEmpty(g) && g.getType() == GroupType.PACKAGE) {
final IEntity folder = new Entity(g.getUid1(), g.getUid2(), g.getCode(), g.getDisplay(),
EntityType.EMPTY_PACKAGE, null, null);
printEntity(folder);
} else {
printGroup(g);
}
}
}
private void printGroup(Group g) throws IOException {
if (g.getType() == GroupType.CONCURRENT_STATE) {
return;
}
// final String stereo = g.getStereotype();
int titleWidth = 0;
int titleHeight = 0;
final String label = g.getDisplay();
TextBlock title = null;
if (label != null) {
final UFont font = getFont(g.getType() == GroupType.STATE ? FontParam.STATE : FontParam.PACKAGE);
title = TextBlockUtils.create(StringUtils.getWithNewlines(label), new FontConfiguration(font,
HtmlColor.BLACK), HorizontalAlignement.CENTER);
final Dimension2D dimLabel = title.calculateDimension(stringBounder);
titleWidth = (int) dimLabel.getWidth();
titleHeight = (int) dimLabel.getHeight();
}
dotStringFactory.openCluster(g, titleWidth, titleHeight, title, isSpecialGroup(g));
this.printEntities(g.entities().values());
// sb.append("subgraph " + g.getUid() + " {");
//
// final UFont font =
// getData().getSkinParam().getFont(getFontParamForGroup(), stereo);
// sb.append("fontsize=\"" + font.getSize() + "\";");
// final String fontFamily = font.getFamily(null);
// if (fontFamily != null) {
// sb.append("fontname=\"" + fontFamily + "\";");
// }
//
// if (g.getDisplay() != null) {
// sb.append("label=<" + manageHtmlIB(g.getDisplay(),
// getFontParamForGroup(), stereo) + ">;");
// }
// final String fontColor =
// getAsHtml(getData().getSkinParam().getFontHtmlColor(getFontParamForGroup(),
// stereo));
// sb.append("fontcolor=\"" + fontColor + "\";");
//
// if (getGroupBackColor(g) != null) {
// sb.append("fillcolor=\"" + getAsHtml(getGroupBackColor(g)) + "\";");
// }
//
// if (g.getType() == GroupType.STATE) {
// sb.append("color=" + getColorString(ColorParam.stateBorder, stereo) +
// ";");
// } else {
// sb.append("color=" + getColorString(ColorParam.packageBorder, stereo)
// + ";");
// }
// sb.append("style=\"" + getStyle(g) + "\";");
//
printGroups(g);
//
// this.printEntities(sb, g.entities().values());
// for (Link link : getData().getLinks()) {
// eventuallySameRank(sb, g, link);
// }
// sb.append("}");
dotStringFactory.closeCluster();
}
private boolean isSpecialGroup(Group g) {
if (g.getType() == GroupType.STATE) {
return true;
}
if (g.getType() == GroupType.CONCURRENT_STATE) {
throw new IllegalStateException();
}
if (getData().isThereLink(g)) {
return true;
}
return false;
}
private DotData getData() {
return dotData;
}
private HtmlColor getGroupBackColor(Group g) {
HtmlColor value = g.getBackColor();
if (value == null) {
value = getData().getSkinParam().getHtmlColor(ColorParam.packageBackground, null);
}
return value;
}
}
| [
"arnaud_roques@28b6c6c1-be0e-40f3-8fed-77912e9d39c1"
]
| arnaud_roques@28b6c6c1-be0e-40f3-8fed-77912e9d39c1 |
5c12d538497d1a76557a78762c7f6198cb571ab6 | dc7e268e468ceafbbfb3732fef9d656cadf00e7a | /LearnScalaAndJava/LeetCode/src/main/java/BasicLearn/Enum/EnumTest.java | cbe86d4223ba8d91e7fa84d6ba079f8f3b36dc01 | []
| no_license | hjw199089/DataStructuresAlgorithmLearn | 39337cb0e31401619223eaec191a93dd768ca94d | 5bf01bbee74e9312b513e6a882f3607f764d4886 | refs/heads/master | 2022-12-13T15:21:12.070026 | 2020-02-17T13:45:11 | 2020-02-17T13:45:11 | 101,487,898 | 0 | 1 | null | 2022-11-16T09:37:05 | 2017-08-26T13:36:54 | Java | UTF-8 | Java | false | false | 608 | java | package BasicLearn.Enum;
public class EnumTest {
public enum Option {
IN("in"),
BETWEEN("between"),
EQUALS("="),
NOT_EQUALS("!="),
GREATER_EQUALS(">="),
LESS_EQUALS("<=");
private String option;
Option(String option) {
this.option = option;
}
public String getOption() {
return option;
}
@Override
public String toString() {
return option;
}
}
public static void main(String[] args) {
Option option = Option.BETWEEN;
System.out.println(option.getOption());
System.out.println(Option.GREATER_EQUALS);
}
}
| [
"[email protected]"
]
| |
4ae2bf3be6460e5baf4fb769ad4660e5afd14460 | 8f66c8af20bbe276e970103802e111e53ef05bff | /src/main/java/com/blogen/bootstrap/PostBuilder.java | e101091dd0a8ba9e97242c34ae6477463cae5210 | []
| no_license | strohs/springboot-blogen | f51ee70b0a0d649b6a2e34b11e051b59f766ab11 | 8efe5b98bed44acd1962ebdea1e68429cf35d7d6 | refs/heads/master | 2023-02-24T19:13:15.454791 | 2023-02-08T02:15:00 | 2023-02-08T02:15:00 | 116,441,137 | 5 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,450 | java | package com.blogen.bootstrap;
import com.blogen.domain.Category;
import com.blogen.domain.Post;
import com.blogen.domain.User;
import java.time.LocalDateTime;
/**
* builder for bootstrapping post data
* @author Cliff
*/
public class PostBuilder {
Post post;
public PostBuilder( User user, Category category, String imageUrl, String title, String text, LocalDateTime created ) {
post = new Post();
post.setCreated( created );
post.setUser( user );
post.setCategory( category );
post.setImageUrl( imageUrl );
post.setTitle( title );
post.setText( text );
}
public PostBuilder( Long id, User user, Category category, String imageUrl, String title, String text ) {
post = new Post();
post.setId( id );
post.setUser( user );
post.setCategory( category );
post.setImageUrl( imageUrl );
post.setTitle( title );
post.setText( text );
}
public Post addChildPost( User user, String title, String text, String imageUrl, LocalDateTime created ) {
Post child = new Post();
child.setCreated( created );
child.setUser( user );
child.setCategory( post.getCategory() );
child.setImageUrl( imageUrl );
child.setTitle( title );
child.setText( text );
post.addChild( child );
return post;
}
public Post build() {
return post;
}
}
| [
"[email protected]"
]
| |
1725ef85dc2a7d10e6716a2b0e6fb4b8f07edde2 | 9fb487991c37bf70a96c4901d9a91310695adfd9 | /SpringBootSecurityThymeleaf/src/main/java/net/codejava/model/TypeBook.java | dc99ed7b3e4edcae546b8fed81788bd4ff217348 | []
| no_license | aniziomaia/SpringBootSecurityThymeleaf | f70c909931d7d1e7a1f5d454d57b08c0fde82d66 | c45a33d614f69840b39755f951f6f5c4681d31a4 | refs/heads/master | 2023-08-11T03:36:53.829418 | 2019-06-10T22:39:49 | 2019-06-10T22:39:49 | 190,093,797 | 0 | 0 | null | 2023-07-22T07:28:13 | 2019-06-03T22:58:55 | HTML | UTF-8 | Java | false | false | 121 | java | package net.codejava.model;
public enum TypeBook {
COMMED,
ROMANCE,
TECHNOLOGY,
STORY,
SCIENCE;
}
| [
"aniziomaia@Anizio"
]
| aniziomaia@Anizio |
8ed3cce523e437b13dedb27a899db5c5baf90e81 | ece18e026cc58e0ee3d6524a5b8ed56738021398 | /app/src/main/java/com/mhmmd/snappnews/ui/newsArticles/NewsArticleViewModel.java | f1701261dbf03368acaa1c5e6c025bed0b0341db | []
| no_license | mhmmdyldi/NewsApplication | 04c9e64dfd0a9724c3ced8ba2e1c96a35e968690 | 705d7da1dc416478c6bdc398826a55b7fb0567f4 | refs/heads/master | 2022-11-26T22:58:41.119091 | 2020-07-27T06:05:27 | 2020-07-27T06:05:27 | 281,386,107 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,619 | java | package com.mhmmd.snappnews.ui.newsArticles;
import android.util.Log;
import com.mhmmd.snappnews.data.AppRepository;
import com.mhmmd.snappnews.data.model.db.HeadlineEntity;
import com.mhmmd.snappnews.utils.AppConstants;
import com.mhmmd.snappnews.utils.Resource;
import com.mhmmd.snappnews.utils.Status;
import com.mhmmd.snappnews.utils.rx.SchedulerProvider;
import java.util.List;
import java.util.concurrent.TimeUnit;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
public class NewsArticleViewModel extends ViewModel {
private final AppRepository mAppRepository;
private final SchedulerProvider mSchedulerProvider;
private CompositeDisposable mCompositeDisposable;
private MutableLiveData<Resource<List<HeadlineEntity>>> articles;
private String newsSourceId;
public NewsArticleViewModel(AppRepository mAppRepository, SchedulerProvider mSchedulerProvider) {
this.mAppRepository = mAppRepository;
this.mSchedulerProvider = mSchedulerProvider;
this.mCompositeDisposable = new CompositeDisposable();
this.articles = new MutableLiveData<>();
}
@Override
protected void onCleared() {
super.onCleared();
mCompositeDisposable.dispose();
}
public MutableLiveData<Resource<List<HeadlineEntity>>> getArticles() {
return articles;
}
public void loadNewsArticles(String newsSourceId) {
this.newsSourceId = newsSourceId;
loadCachedArticlesFromLocalDb();
}
private void loadCachedArticlesFromLocalDb() {
mCompositeDisposable.add(mAppRepository.getArticlesOfSourceFromDb(newsSourceId)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(articlesList -> {
if (articlesList.size() > 0) {
articles.postValue(new Resource<>(Status.SUCCESS, articlesList, null));
}
setupSyncArticlesInTimeIntervals();
}, throwable -> {
})
);
}
private void setupSyncArticlesInTimeIntervals() {
mCompositeDisposable.add(Observable
.interval(AppConstants.SYNC_DELAY, AppConstants.SYNC_TIME_INTERVALS, TimeUnit.MINUTES)
.observeOn(mSchedulerProvider.ui())
.subscribe(l -> {
Log.d("SnapppNewsss", "setupSyncArticlesInTimeIntervals: " + l);
loadNewsHeadlinesFromApi();
}
)
);
}
private void loadNewsHeadlinesFromApi() {
mCompositeDisposable.add(
mAppRepository.getArticlesListApiCall(newsSourceId)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(articlesList -> {
// saveArticlesInLocalDb(articlesList);
deletArticlesFromLocalDb(articlesList);
}, throwable -> {
})
);
}
private void deletArticlesFromLocalDb(List<HeadlineEntity> articlesList) {
mCompositeDisposable.add(mAppRepository.deleteArticlesOfSourceFromDB(newsSourceId)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(() -> {
saveArticlesInLocalDb(articlesList);
}, throwable -> {
})
);
}
private void saveArticlesInLocalDb(List<HeadlineEntity> articlesList) {
mCompositeDisposable.add(mAppRepository.saveHeadlineListInDb(articlesList)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(() -> {
loadArticlesFromLocalDB();
}, throwable -> {
})
);
}
private void loadArticlesFromLocalDB() {
mCompositeDisposable.add(mAppRepository.getArticlesOfSourceFromDb(newsSourceId)
.subscribeOn(mSchedulerProvider.io())
.observeOn(mSchedulerProvider.ui())
.subscribe(articlesList -> {
if (articlesList.size() > 0) {
articles.postValue(new Resource<>(Status.SUCCESS, articlesList, null));
}
}, throwable -> {
})
);
}
}
| [
"[email protected]"
]
| |
8d58f5064d79a23c6bd8e1e1c2caa0c687593a88 | a445f898a5bf3188fcd83d113200288f0059ba61 | /src/main/java/com/ullink/FSM.java | 56342bf669c3c06c5910ec1857a0545c03abe17b | []
| no_license | alexandraHancu/fsm-library | ec10aab8201c80e429f8dd68dbd28f8e0b28e19a | d8edeb93266767384e745d37328a02d525423b7e | refs/heads/master | 2020-03-25T11:14:29.652873 | 2018-09-13T11:46:55 | 2018-09-13T11:46:55 | 143,723,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,807 | java | /*************************************************************************
* ULLINK CONFIDENTIAL INFORMATION
* _______________________________
*
* All Rights Reserved.
*
* NOTICE: This file and its content are the property of Ullink. The
* information included has been classified as Confidential and may
* not be copied, modified, distributed, or otherwise disseminated, in
* whole or part, without the express written permission of Ullink.
************************************************************************/
package com.ullink;
public interface FSM<T, K>
{
void addTransition(State<T> current, Transition<K>input , State<T> next);
/**
* method that returns next state WITHOUT performing any action or causing any side-effects
* @param current - current state of machine
* @param input - transition
* @return possible next state, given current state and transition
*/
State<T> getNextState(State<T> current, Transition<K>input);
/**
* Use this method to perform states's side effects
* @param currentState
* @param stateActionParam object to be used when performing the specified side effect on state
*/
void doSideEffects(State<T> currentState, T stateActionParam);
/**
* Use this method to perform transition's side effects
* @param input transition
* @param transitionActionParam object to be used when performing the specified side effect on transition
*/
void doSideEffects(Transition<K> input, K transitionActionParam);
/**
* use this method to check if a state belongs to the fsm
* @param s state to be verified
* @return boolean value that state if the state apears in the fsm or not.
*/
boolean isValidState(State<T> s);
State<T> getErrorState();
}
| [
"[email protected]"
]
| |
5840d655e07a1e2dd6a2dd99132ab4ffa23cfd77 | 7585579752f597f376848e95ab026475247c2a12 | /app/src/main/java/com/example/user/giphymop/Model/FixedWidth.java | e47b5035b1952db37e773cc304094be7c29e617b | []
| no_license | irvin-smersh/GiphyMoP | 2f2758771d6980034716218631c3c28e63d825b9 | 000a88d25221c24993d74e7130a49e3f175a5515 | refs/heads/master | 2020-12-01T05:06:15.161702 | 2019-12-30T11:17:38 | 2019-12-30T11:17:38 | 230,563,726 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,791 | java | package com.example.user.giphymop.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class FixedWidth {
@SerializedName("url")
@Expose
private String url;
@SerializedName("width")
@Expose
private String width;
@SerializedName("height")
@Expose
private String height;
@SerializedName("size")
@Expose
private String size;
@SerializedName("mp4")
@Expose
private String mp4;
@SerializedName("mp4_size")
@Expose
private String mp4Size;
@SerializedName("webp")
@Expose
private String webp;
@SerializedName("webp_size")
@Expose
private String webpSize;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getMp4() {
return mp4;
}
public void setMp4(String mp4) {
this.mp4 = mp4;
}
public String getMp4Size() {
return mp4Size;
}
public void setMp4Size(String mp4Size) {
this.mp4Size = mp4Size;
}
public String getWebp() {
return webp;
}
public void setWebp(String webp) {
this.webp = webp;
}
public String getWebpSize() {
return webpSize;
}
public void setWebpSize(String webpSize) {
this.webpSize = webpSize;
}
}
| [
"[email protected]"
]
| |
a04a61cc6792246141c0bd74e408b00fca078603 | 42abda4d98ff92914fb3b33a0a5f3118fe90b4bb | /app/src/main/java/com/meitu/niqihang/surfaceandtextureviewproject/presenter/SecondFragmentPresenter.java | bc282225a70640708ee320d817938577304c228f | []
| no_license | escnqh/VideoFeedProject | ab2af351c01aaa6da12b3965f0823388953836da | 4885b74b6e0633f155c36c0d2702eb3f44872b43 | refs/heads/master | 2020-03-31T21:40:16.096175 | 2018-10-25T06:47:06 | 2018-10-25T06:47:06 | 152,589,220 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,320 | java | package com.meitu.niqihang.surfaceandtextureviewproject.presenter;
import com.meitu.niqihang.surfaceandtextureviewproject.base.BasePresenter;
import com.meitu.niqihang.surfaceandtextureviewproject.contract.SecondFragmentContract;
import com.meitu.niqihang.surfaceandtextureviewproject.entity.FeedInfoBean;
import com.meitu.niqihang.surfaceandtextureviewproject.model.SecondFragmentModel;
import com.meitu.niqihang.surfaceandtextureviewproject.ui.fragment.SecondFragment;
/**
* @author nqh 2018/10/11.
*/
public class SecondFragmentPresenter extends BasePresenter<SecondFragmentContract.View> implements SecondFragmentContract.Presenter, SecondFragmentContract.InteractionListener {
private SecondFragmentContract.View mView;
private SecondFragmentContract.Model mModel;
public SecondFragmentPresenter(SecondFragmentContract.View view) {
this.mModel = new SecondFragmentModel(this);
this.mView = view;
}
@Override
public void requestShowFeedInfo() {
mModel.loadFeedInfo();
}
@Override
public void start() {
mModel.loadFeedInfo();
}
@Override
public void onRequestSuccess(FeedInfoBean feedInfoBean) {
mView.showFeedInfo(feedInfoBean);
}
@Override
public void onRequestFailed() {
//加载失败
}
}
| [
"[email protected]"
]
| |
7e7922b22c79e49f8fb0c290c06b8696e7ced2c2 | e217712c8eff33b0d822d49c1f18556b7298e2f4 | /src/com/snake/gui/GameOver.java | d8bd2ed1ed43e1235c0cd515de951193d61e33d4 | []
| no_license | Dawid564/Snake-The-Game | 732cfc6a8dba0fd08c2cea861695db69746e4fbe | 0e38218273d5428103f40b2e984b6cac8f498bec | refs/heads/master | 2020-03-22T06:06:05.545773 | 2018-07-07T14:32:36 | 2018-07-07T14:32:36 | 139,610,999 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | package com.snake.gui;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class GameOver {
private Stage stage;
public GameOver(){
stage = new Stage();
stage.setTitle("Game Over");
StackPane root = new StackPane();
Label label = new Label("Game Over");
label.setFont(new Font(40));
root.getChildren().add(label);
stage.setScene(new Scene(root, 250, 150));
stage.show();
}
}
| [
"[email protected]"
]
| |
32297cb6330afeacaa71730eed7612bac29fb4e9 | 39cd19cd00cb151ed518a5f0015dc5050bb4d9ae | /src/main/java/com/lovelyz/washcar/entity/WashStaff.java | 586a1edf4dc6fc1136a02930fb93f3f19bb3887c | []
| no_license | lovelyz580/Washcar | e843f805fb81851e6a10332b822067fd0203519c | e2b70b6394b06043a68dc0bbf5c20c4bcb6ac42f | refs/heads/master | 2022-12-22T13:27:55.149022 | 2021-05-15T02:47:13 | 2021-05-15T02:47:13 | 200,609,489 | 0 | 0 | null | 2022-12-16T07:25:58 | 2019-08-05T07:56:06 | HTML | UTF-8 | Java | false | false | 2,075 | java | package com.lovelyz.washcar.entity;
public class WashStaff {
private Integer id;
private Integer did;
private String staffname;
private String post;
private String tel;
private String username;
private String oldpassword;
private String userpass;
// 分页数据
/**
* 当前页数(如果不进行分页,该条数据默认为-1)
*/
private Integer pagenumber;
/**
* 每页的数据量
*/
private Integer pagesize;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDid() {
return did;
}
public void setDid(Integer did) {
this.did = did;
}
public String getStaffname() {
return staffname;
}
public void setStaffname(String staffname) {
this.staffname = staffname;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpass() {
return userpass;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
public Integer getPagenumber() {
return pagenumber;
}
public void setPagenumber(Integer pagenumber) {
this.pagenumber = pagenumber;
}
public Integer getPagesize() {
return pagesize;
}
public void setPagesize(Integer pagesize) {
this.pagesize = pagesize;
}
public String getOldpassword() {
return oldpassword;
}
public void setOldpassword(String oldpassword) {
this.oldpassword = oldpassword;
}
} | [
"[email protected]"
]
| |
4140a5a037d1eb218cc98cb3f0b6bf5727a5c52f | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_1ace8179021b5a1a65bda2fabe3e074fb3170681/JID/2_1ace8179021b5a1a65bda2fabe3e074fb3170681_JID_s.java | b05199638f3613ecbda0713fb4c7991bcf537772 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,246 | java | /*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.net;
import java.io.Serializable;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.muc.MultiUserChat;
import de.fu_berlin.inf.dpp.util.StackTrace;
/**
* A JID which is used to identify the users of the XMPP network.
*
* @valueObject A JID is a value object, i.e. it is immutable!
*
* @author rdjemili
*/
public class JID implements Serializable {
private static final Logger log = Logger.getLogger(JID.class.getName());
private static final long serialVersionUID = 4830741516870940459L;
protected static final Pattern userAtHostPattern = Pattern.compile(
"^[A-Z0-9._%+-]+@[A-Z0-9.-]+$", Pattern.CASE_INSENSITIVE);
private final String jid;
/**
* Creates the client {@link JID} on the base of a service perspective
* {@link JID} as explained in XEP-0045.
* <p>
* Example: A {@link MultiUserChat} participant has - from the perspective
* of the {@link MultiUserChat} itself - the JID
* <b>[email protected]/[email protected]/Saros</b>.
* This method would return the {@link JID} representing
* <b>[email protected]/Saros</b>.
*
* @see <a href="http://xmpp.org/extensions/xep-0045.html#user">XEP-0045</a>
*
* @param servicePerspectiveJID
* the XMPP address from the perspective of the service
* @return the client JID portion
*/
public static JID createFromServicePerspective(String servicePerspectiveJID) {
return new JID(StringUtils.parseResource(servicePerspectiveJID));
}
/**
* Construct a new JID
*
* @param jid
* the JID in the format of user@host[/resource]. Resource is
* optional.
*/
public JID(String jid) {
if (jid == null)
throw new IllegalArgumentException(JID.class.getSimpleName()
+ " cannot be null");
this.jid = jid;
}
/**
* Construct a new JID
*
* @param rosterEntry
*/
public JID(RosterEntry rosterEntry) {
this(rosterEntry.getUser());
}
/**
* Checks whether the {@link #getBase() base} portion is correctly formated.
*
* @param jid
* @return
*/
public static boolean isValid(JID jid) {
return userAtHostPattern.matcher(jid.getBase()).matches();
}
/**
* Checks whether the {@link #getBase() base} portion is correctly formated.
*
* @return
*/
public boolean isValid() {
return isValid(this);
}
/**
* @return the name segment of this JID.
* @see StringUtils#parseName(String)
*/
public String getName() {
return StringUtils.parseName(this.jid);
}
/**
* @return the JID without resource qualifier.
* @see StringUtils#parseBareAddress(String)
*/
public String getBase() {
return StringUtils.parseBareAddress(this.jid);
}
/**
* @return the domain segment of this JID.
* @see StringUtils#parseServer(String)
*/
public String getDomain() {
return StringUtils.parseServer(this.jid);
}
/**
* @return the resource segment of this JID or the empty string if there is
* none.
* @see StringUtils#parseResource(String)
*/
public String getResource() {
return StringUtils.parseResource(this.jid);
}
/**
* Returns true if this JID does not have a resource part.
*/
public boolean isBareJID() {
return "".equals(getResource());
}
/**
* Returns true if this JID does have a resource part.
*/
public boolean isResourceQualifiedJID() {
return !isBareJID();
}
/**
* Returns the JID without any resource qualifier.
*/
public JID getBareJID() {
return new JID(getBase());
}
/**
* Returns the unmodified JID this object was constructed with
*
* @return
*/
public String getRAW() {
return this.jid;
}
/**
* @return <code>true</code> if the IDs have the same user and domain.
* Resource is ignored.
*/
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj instanceof JID) {
JID other = (JID) obj;
return getBase().equals(other.getBase());
}
log.warn("Comparing a JID to something other a JID is not supported: "
+ obj.getClass(), new StackTrace());
return false;
}
/**
* Returns true if this JID and the given JID are completely identical (this
* includes the resource unlike equals)
*/
public boolean strictlyEquals(JID other) {
return this.jid.equals(other.jid);
}
@Override
public int hashCode() {
return getBase().hashCode();
}
/**
* @return the complete string that was used to construct this object.
*/
@Override
public String toString() {
return this.jid;
}
}
| [
"[email protected]"
]
| |
54e18b26cfaf2ebd17cf2a09b6058fb0bc0057e1 | e207ceacc38cc3bb1a6a8f9b3e7ecae5821a8c14 | /src/main/java/com/beatus/factureIT/authorization/api/FactureITUserType.java | e1c3ecf98ea93312fbfdb3a83cbd2b4ea69618f4 | []
| no_license | goodbyeq/factureIT-app-services | 4c920c2c9f89f41f5e2415aaa9d7777b3f069d75 | b23dc81950c74b7f6946a75f93e73b0c5486f1d3 | refs/heads/master | 2020-03-26T18:59:53.705691 | 2018-10-05T06:10:15 | 2018-10-05T06:10:15 | 145,243,243 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 454 | java | package com.beatus.factureIT.authorization.api;
public enum FactureITUserType {
MANUFACTURER("MANUFACTURER"), DISTRIBUTOR("DISTRIBUTOR"), RETAILER("RETAILER"), CUSTOMER("CUSTOMER"), COLLECTION_AGENT("COLLECTION_AGENT");
private String value;
FactureITUserType(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
}
| [
"[email protected]"
]
| |
e2485f67ac91e3be9983c83e7c4480a2439db322 | 32c91a5f6da45ed27bf25ca15f4503ca5b5376b0 | /instrumentation/tomcat/tomcat-10.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/tomcat/v10_0/Tomcat10InstrumentationModule.java | 12020b17b4d2a09cf6c5b29b26741659d077a20a | [
"Apache-2.0"
]
| permissive | xujianming2017/opentelemetry-java-instrumentation | 1f852f08f1b2affd406420504b17560d264a6d32 | 334c6ec0b599d93b1b512aa7466894973d2619d8 | refs/heads/main | 2023-04-23T16:55:02.064939 | 2021-04-24T00:52:04 | 2021-04-24T00:52:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,460 | java | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.tomcat.v10_0;
import static net.bytebuddy.matcher.ElementMatchers.declaresMethod;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.returns;
import com.google.auto.service.AutoService;
import io.opentelemetry.javaagent.instrumentation.tomcat.common.TomcatServerHandlerInstrumentation;
import io.opentelemetry.javaagent.tooling.InstrumentationModule;
import io.opentelemetry.javaagent.tooling.TypeInstrumentation;
import java.util.Collections;
import java.util.List;
@AutoService(InstrumentationModule.class)
public class Tomcat10InstrumentationModule extends InstrumentationModule {
public Tomcat10InstrumentationModule() {
super("tomcat", "tomcat-10.0");
}
@Override
public List<TypeInstrumentation> typeInstrumentations() {
// Tomcat 10+ is verified by making sure Request has a methods returning
// jakarta.servlet.ReadListener which is returned by getReadListener method on Tomcat 10+
return Collections.singletonList(
new TomcatServerHandlerInstrumentation(
Tomcat10InstrumentationModule.class.getPackage().getName()
+ ".Tomcat10ServerHandlerAdvice",
named("org.apache.coyote.Request")
.and(declaresMethod(returns(named("jakarta.servlet.ReadListener"))))));
}
}
| [
"[email protected]"
]
| |
44e39e9b1a791173ddb9cdcf07fcd5b133e7d958 | 3a75f95c9976052839bf2373f6a1e06f3166dd80 | /restma-demo/src/limeng32/testSpring/pojo/Association.java | 479b635840bba6f22637ef5acbbdc30d448689ac | []
| no_license | limeng32/restma-demo | 268cd78298391a8a9c0d5f0d67aa62df952714f7 | 46a2089efbd7ea512019dfde8d79de38fab980cd | refs/heads/master | 2016-09-09T19:48:55.449754 | 2015-08-23T15:23:00 | 2015-08-23T15:23:00 | 32,455,231 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,653 | java | package limeng32.testSpring.pojo;
import java.io.Serializable;
import limeng32.mybatis.plugin.mapper.annotation.FieldMapperAnnotation;
import limeng32.mybatis.plugin.mapper.annotation.PersistentFlagAnnotation;
import limeng32.mybatis.plugin.mapper.annotation.TableMapperAnnotation;
import org.apache.ibatis.type.JdbcType;
import com.alibaba.fastjson.annotation.JSONField;
@TableMapperAnnotation(tableName = "Association")
public class Association extends PojoSupport<Association> implements
Serializable {
private static final long serialVersionUID = 1L;
@FieldMapperAnnotation(dbFieldName = "id", jdbcType = JdbcType.INTEGER, isUniqueKey = true)
private Integer id;
@FieldMapperAnnotation(dbFieldName = "name", jdbcType = JdbcType.VARCHAR)
private String name;
private java.util.Collection<Writer> writer;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public java.util.Collection<Writer> getWriter() {
if (writer == null)
writer = new java.util.HashSet<Writer>();
return writer;
}
@JSONField(serialize = false)
public java.util.Iterator<Writer> getIteratorWriter() {
if (writer == null)
writer = new java.util.HashSet<Writer>();
return writer.iterator();
}
public void setWriter(java.util.Collection<Writer> newWriter) {
removeAllWriter();
for (java.util.Iterator<Writer> iter = newWriter.iterator(); iter
.hasNext();)
addWriter((Writer) iter.next());
}
public void addWriter(Writer newWriter) {
if (newWriter == null)
return;
if (this.writer == null)
this.writer = new java.util.HashSet<Writer>();
if (!this.writer.contains(newWriter)) {
if (newWriter.getById(this.writer) != null) {
removeWriter(newWriter.getById(this.writer));
}
this.writer.add(newWriter);
newWriter.setAssociation(this);
}
}
public void removeWriter(Writer oldWriter) {
if (oldWriter == null)
return;
if (this.writer != null)
if (oldWriter.belongs(this.writer)) {
oldWriter.quit(this.writer);
oldWriter.setAssociation((Association) null);
}
}
public void removeAllWriter() {
if (writer != null) {
Writer oldWriter;
for (java.util.Iterator<Writer> iter = getIteratorWriter(); iter
.hasNext();) {
oldWriter = (Writer) iter.next();
iter.remove();
oldWriter.setAssociation((Association) null);
}
}
}
@PersistentFlagAnnotation
private String _persistent;
}
| [
"[email protected]"
]
| |
16f814748f991cf11dcb8d58d4a41a7ac0453034 | 7be68ad8de1e89a1b3b71eeac8e2cf24f8ec2bfe | /spring-abstract-cache-redis/src/main/java/com/nestor/springabstractcacheredis/common/plugin/BaseMapperGeneratorPlugin.java | 6c2f862460913665a3c62b650d8e226c0c7aa421 | [
"Apache-2.0"
]
| permissive | nestorbian/spring-boot-examples | 00bf7a8aa04e1973cab7a005ca696caa68607c12 | a502ac55844b62c57f45ef6a7818cf05b69f7a33 | refs/heads/master | 2023-05-09T20:17:38.045822 | 2023-05-03T16:08:02 | 2023-05-03T16:08:02 | 221,206,216 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,948 | java | package com.nestor.springabstractcacheredis.common.plugin;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ObjectUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.config.ModelType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* 支持XMLMAPPER生成对应的mapper接口,如有其他需求可以在此基础上拓展
*
* @author : Nestor.Bian
* @version : V 1.0
* @date : 2020/6/1
*/
@Deprecated
public class BaseMapperGeneratorPlugin extends PluginAdapter {
private static final Logger log = LoggerFactory.getLogger(BaseMapperGeneratorPlugin.class);
public boolean validate(List<String> warnings) {
return true;
}
/**
* 生成mapper接口
*
* @param interfaze
* @param introspectedTable
* @return boolean
* @date : 2020/6/7 16:05
* @author : Nestor.Bian
* @since : 1.0
*/
@Override
public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
String baseMapper = (String) properties.get("baseMapper");
String baseMapperClassName = baseMapper.substring(baseMapper.lastIndexOf(".") + 1);
// 不支持flat模式
String primaryKeyType;
if (introspectedTable.getContext().getDefaultModelType() == ModelType.CONDITIONAL) {
List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
if (primaryKeyColumns.size() > 1) {
primaryKeyType = introspectedTable.getPrimaryKeyType();
} else {
primaryKeyType = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
}
} else if (introspectedTable.getContext().getDefaultModelType() == ModelType.HIERARCHICAL) {
primaryKeyType = introspectedTable.getPrimaryKeyType();
} else {
List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
if (primaryKeyColumns.size() > 1) {
throw new RuntimeException("flat模式下暂不支持组合主键");
}
primaryKeyType = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
}
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(
baseMapperClassName + "<" + introspectedTable.getBaseRecordType() + ","
+ introspectedTable.getExampleType() + "," + primaryKeyType + ">");
FullyQualifiedJavaType imp = new FullyQualifiedJavaType(baseMapper);
// 添加 extends BaseMapper
interfaze.addSuperInterface(fqjt);
interfaze.getImportedTypes().clear();
interfaze.addImportedType(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()));
interfaze.addImportedType(new FullyQualifiedJavaType(introspectedTable.getExampleType()));
// 添加 import BaseMapper;
interfaze.addImportedType(imp);
// 方法不需要
interfaze.getMethods().clear();
// 保留原mapper接口上自定义的方法
try {
Class<?> mapperClass = Class.forName(introspectedTable.getMyBatis3JavaMapperType());
interfaze.getMethods().addAll(buildMybatisMethod(mapperClass, interfaze));
} catch (ClassNotFoundException e) {
log.info(introspectedTable.getMyBatis3JavaMapperType() + "不存在, 无需保留mapper中自定义方法");
} catch (Exception e) {
log.error("BaseMapperGeneratorPlugin发生错误:\n", e);
}
interfaze.getAnnotations().clear();
return true;
}
/**
* 不覆盖,保留原mapper接口上自定义的方法
*
* @param interfaceClass
* @return java.util.List<org.mybatis.generator.api.dom.java.Method>
* @date : 2020/6/7 15:35
* @author : Nestor.Bian
* @since : 1.0
*/
private List<Method> buildMybatisMethod(Class<?> interfaceClass, Interface interfaze) throws Exception {
List<Method> mybatisMethodList = new ArrayList<>();
boolean anInterface = interfaceClass.isInterface();
// 非接口类直接返回
if (!anInterface) {
return mybatisMethodList;
}
List<java.lang.reflect.Method> sortedList = Arrays.stream(interfaceClass.getDeclaredMethods()).sorted(
Comparator.comparing(java.lang.reflect.Method::getName)).collect(Collectors.toList());
for (java.lang.reflect.Method method : sortedList) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) && Modifier.isAbstract(modifiers)) {
Method mybatisMethod = new Method(method.getName());
// 添加注解
Annotation[] methodAnnotation = method.getDeclaredAnnotations();
if (methodAnnotation.length != 0) {
listAnnotationStr(methodAnnotation, interfaze).forEach(mybatisMethod::addAnnotation);
}
// 设置访问权限
mybatisMethod.setConstructor(false);
mybatisMethod.setSynchronized(Modifier.isSynchronized(modifiers));
mybatisMethod.setNative(Modifier.isNative(modifiers));
mybatisMethod.setDefault(false);
mybatisMethod.setAbstract(Modifier.isAbstract(modifiers));
mybatisMethod.setFinal(Modifier.isFinal(modifiers));
mybatisMethod.setVisibility(JavaVisibility.PUBLIC);
mybatisMethod.setStatic(Modifier.isStatic(modifiers));
// 添加异常
Class<?>[] exceptionTypes = method.getExceptionTypes();
Arrays.stream(exceptionTypes).forEach(item -> {
mybatisMethod.addException(new FullyQualifiedJavaType(item.getCanonicalName()));
// 添加import
interfaze.addImportedType(new FullyQualifiedJavaType(item.getCanonicalName()));
});
// 添加参数以及参数注解
java.lang.reflect.Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = new Parameter(
new FullyQualifiedJavaType(parameters[i].getParameterizedType().getTypeName()),
parameters[i].getName());
interfaze.addImportedType(new FullyQualifiedJavaType(parameters[i].getType().getCanonicalName()));
Annotation[] annotations = parameters[i].getAnnotations();
if (annotations.length != 0) {
// 添加参数的注解,暂时仅支持@Transactional@Param,如有其他需要可以自己拓展
listAnnotationStr(annotations, interfaze).forEach(parameter::addAnnotation);
}
mybatisMethod.addParameter(parameter);
}
// 设置返回类型
String reutrnTypeName = method.getGenericReturnType().getTypeName();
mybatisMethod.setReturnType(new FullyQualifiedJavaType(reutrnTypeName));
// 添加import
interfaze.addImportedType(new FullyQualifiedJavaType(method.getReturnType().getCanonicalName()));
mybatisMethodList.add(mybatisMethod);
}
}
return mybatisMethodList;
}
/**
* 获取注解字符串
*
* @param annotations
* @return java.util.List<java.lang.String>
* @date : 2020/6/8 20:57
* @author : Nestor.Bian
* @since : 1.0
*/
private List<String> listAnnotationStr(Annotation[] annotations, Interface interfaze)
throws IllegalAccessException, InvocationTargetException {
List<String> annotationStrList = new ArrayList<>();
for (Annotation item : annotations) {
// 添加import
interfaze.addImportedType(new FullyQualifiedJavaType(item.annotationType().getCanonicalName()));
// 过滤出public abstract的方法Interface interfaze
java.lang.reflect.Method[] annotationDeclaredMethods = item.annotationType().getDeclaredMethods();
Optional<java.lang.reflect.Method> valueMethod = Arrays.stream(annotationDeclaredMethods).filter(
x -> "value".equals(x.getName())).findAny();
List<java.lang.reflect.Method> methodListAfterFilter = Arrays.stream(annotationDeclaredMethods).filter(
x -> !"value".equals(x.getName())).filter(
x -> Modifier.isPublic(x.getModifiers()) && Modifier.isAbstract(x.getModifiers())).sorted(
Comparator.comparing(java.lang.reflect.Method::getName)).collect(
Collectors.toList());
valueMethod.ifPresent(x -> methodListAfterFilter.add(0, x));
StringBuilder annotationBuilder = new StringBuilder(
String.format("@%s", item.annotationType().getSimpleName()));
// 筛选出指定值的方法
List<java.lang.reflect.Method> valueMethods = new ArrayList<>();
for (java.lang.reflect.Method x : methodListAfterFilter) {
if (!ObjectUtils.isEmpty(x.invoke(item)) && !x.invoke(item).equals(x.getDefaultValue())) {
valueMethods.add(x);
}
}
if (!CollectionUtils.isEmpty(valueMethods)) {
annotationBuilder.append("(");
// 添加注解属性
for (java.lang.reflect.Method x : valueMethods) {
annotationBuilder.append(String.format("%s = ", x.getName()));
Object val = x.invoke(item);
if (val.getClass().isArray()) {
Object[] objects = (Object[]) val;
if (objects.length > 1) {
annotationBuilder.append("{");
}
for (Object singleItem : objects) {
concatSingleItem(singleItem, annotationBuilder, interfaze);
annotationBuilder.append(", ");
}
annotationBuilder.delete(annotationBuilder.length() - 2, annotationBuilder.length());
if (objects.length > 1) {
annotationBuilder.append("}");
}
} else {
concatSingleItem(val, annotationBuilder, interfaze);
}
annotationBuilder.append(", ");
}
annotationBuilder.delete(annotationBuilder.length() - 2, annotationBuilder.length());
annotationBuilder.append(")");
}
annotationStrList.add(annotationBuilder.toString());
}
return annotationStrList;
}
/**
* 拼接单个元素
*
* @param val
* @param annotationBuilder
* @param interfaze
* @return void
* @date : 2020/6/13 16:52
* @author : Nestor.Bian
* @since : 1.0
*/
private void concatSingleItem(Object val, StringBuilder annotationBuilder, Interface interfaze) {
if (String.class.equals(val.getClass())) {
annotationBuilder.append(String.format("\"%s\"", val));
} else if (val.getClass().isEnum()) {
// 支持枚举类型value
annotationBuilder.append(val.getClass().getSimpleName()).append(".").append(((Enum) val).name());
interfaze.addImportedType(new FullyQualifiedJavaType(val.getClass().getCanonicalName()));
} else if (val instanceof Class) {
annotationBuilder.append(((Class) val).getSimpleName()).append(".class");
interfaze.addImportedType(new FullyQualifiedJavaType(((Class) val).getCanonicalName()));
} else {
annotationBuilder.append(val);
interfaze.addImportedType(new FullyQualifiedJavaType(val.getClass().getCanonicalName()));
}
}
}
| [
"[email protected]"
]
| |
4d27fecec4e9e94deacbf36fc3da303ccec212b4 | e627f304edf8ff56d8b544d5c8985facc19761a8 | /src/joborder/JobOrderController.java | fc592b87a5a8584ab65b3765c60e44ee4fe7a4c3 | []
| no_license | davidlegare/Exogene-Services | d253ffcc0fbd580915edc722e22282c2139f2fc1 | c58d5ca324822f14931a5fbd8e0b7e37e29f7618 | refs/heads/master | 2020-04-05T02:19:54.848926 | 2018-11-06T03:32:23 | 2018-11-06T03:32:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,630 | java | package joborder;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import java.util.function.Predicate;
import dbUtil.DBConnection;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class JobOrderController implements Initializable{
/* Job Order table */
@FXML private TableView<JobOrderInfo> jobOrderTable;
/* Job Order table columns */
@FXML private TableColumn<JobOrderInfo, String> columnCompany;
@FXML private TableColumn<JobOrderInfo, String> columnEmployType;
@FXML private TableColumn<JobOrderInfo, String> columnStatus;
@FXML private TableColumn<JobOrderInfo, String> columnStatusNote;
@FXML private TableColumn<JobOrderInfo, String> columnStartDate;
@FXML private TextField jobOrderFilter;
@FXML private Button btnAddJobOrder;
private DBConnection DBConn;
private ObservableList<JobOrderInfo> data;
private FilteredList filter;
private String jobOrderQuery = "SELECT * FROM JobOrder";
public void initialize(URL url, ResourceBundle rb) {
String company;
String employType;
String status;
String statusNote;
String startDate;
this.DBConn = new DBConnection();
try {
Connection conn = DBConnection.getConnection();
this.data = FXCollections.observableArrayList();
ResultSet rs = conn.createStatement().executeQuery(jobOrderQuery);
while(rs.next()) {
company = rs.getString(2);
employType = rs.getString(3);
status = rs.getString(4);
statusNote = rs.getString(5);
startDate = rs.getString(6);
this.data.add(new JobOrderInfo(null, company, employType, status, statusNote, startDate));
}
filter = new FilteredList(data, e->true);
conn.close();
}
catch(SQLException e) {
System.err.println("Error: " + e);
}
this.columnCompany.setCellValueFactory(new PropertyValueFactory<JobOrderInfo, String>("company"));
this.columnEmployType.setCellValueFactory(new PropertyValueFactory<JobOrderInfo, String>("employType"));
this.columnStatus.setCellValueFactory(new PropertyValueFactory<JobOrderInfo, String>("status"));
this.columnStatusNote.setCellValueFactory(new PropertyValueFactory<JobOrderInfo, String>("statusNote"));
this.columnStartDate.setCellValueFactory(new PropertyValueFactory<JobOrderInfo, String>("startDate"));
this.jobOrderTable.setItems(null);
this.jobOrderTable.setItems(this.data);
}
@FXML
private void addNewJobOrder(ActionEvent event) throws IOException {
Stage userStage = new Stage();
FXMLLoader loader = new FXMLLoader();
Pane root = (Pane)loader.load(getClass().getResource("AddJobOrder.fxml").openStream());
Scene scene = new Scene(root);
userStage.setScene(scene);
userStage.setTitle("New Job Order");
userStage.setResizable(false);
userStage.show();
}
@SuppressWarnings("unchecked")
@FXML
private void filterList(KeyEvent event) {
jobOrderFilter.textProperty().addListener((observable, oldValue, newValue) -> {
filter.setPredicate((Predicate<? super JobOrderInfo>) (JobOrderInfo JobOrderInfo)-> {
if (newValue.isEmpty() || newValue == null)
return true;
else if (JobOrderInfo.companyProperty().get().toLowerCase().contains(newValue.toLowerCase()))
return true;
else if (JobOrderInfo.employTypeProperty().get().toLowerCase().contains(newValue.toLowerCase()))
return true;
else if (JobOrderInfo.statusProperty().get().toLowerCase().contains(newValue.toLowerCase()))
return true;
else if (JobOrderInfo.statusNoteProperty().get().toLowerCase().contains(newValue.toLowerCase()))
return true;
else if (JobOrderInfo.startDateProperty().get().toLowerCase().contains(newValue.toLowerCase()))
return true;
return false;
});
});
SortedList<JobOrderInfo> sort = new SortedList<JobOrderInfo>(filter);
sort.comparatorProperty().bind(jobOrderTable.comparatorProperty());
jobOrderTable.setItems(sort);
}
}
| [
"[email protected]"
]
| |
c0aa00138bdf6ccec11cff55b2c064c38fd83d83 | 893507cd45170c318b28e854056787f970658966 | /src/main/java/Domain/Users/UserInfo/WorkTime.java | ebe0fb7130e607dc12a64f1f5eac75c1f438d6a0 | []
| no_license | britnall/gym-management-system | a3db134d4608751c18c4bce2243669b2b948bd21 | 9b997a62852490dc321b187094bc58defca217f5 | refs/heads/master | 2021-03-09T17:14:36.571463 | 2020-10-13T23:31:53 | 2020-10-13T23:31:53 | 246,361,061 | 0 | 0 | null | 2020-10-13T23:31:55 | 2020-03-10T17:09:50 | Java | UTF-8 | Java | false | false | 2,502 | java | package src.main.java.Domain.Users.UserInfo;
/**
* Start and End Time for a Day of the Week
*
*/
public class WorkTime {
private TimeOfDay startTime; // time work shift start
private TimeOfDay endTime; // time work shift ends
private Weekday dayOfWeek; // day of work shift
/**
* @param start - time work shift start
* @param end - time work shift ends
* @param day - day of work shift
*/
public WorkTime(TimeOfDay start, TimeOfDay end, Weekday day) {
this.startTime = start;
this.endTime = end;
this.dayOfWeek = day;
}
/**
* @return time work shift start
*/
public TimeOfDay getStartTime() {
return startTime;
}
/**
* @param startTime - time work shift start
*/
public void setStartTime(TimeOfDay startTime) {
this.startTime = startTime;
}
/**
* @return time work shift ends
*/
public TimeOfDay getEndTime() {
return endTime;
}
/**
* @param endTime - time work shift ends
*/
public void setEndTime(TimeOfDay endTime) {
this.endTime = endTime;
}
/**
* @return day of work shift
*/
public Weekday getDayOfWeek() {
return dayOfWeek;
}
/**
* @param dayOfWeek - day of work shift
*/
public void setDayOfWeek(Weekday dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
@Override
public String toString() {
return "[start=" + startTime + ", end=" + endTime + ", day=" + dayOfWeek + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dayOfWeek == null) ? 0 : dayOfWeek.hashCode());
result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WorkTime other = (WorkTime) obj;
if (dayOfWeek != other.dayOfWeek)
return false;
if (endTime == null) {
if (other.endTime != null)
return false;
} else if (!endTime.equals(other.endTime))
return false;
if (startTime == null) {
if (other.startTime != null)
return false;
} else if (!startTime.equals(other.startTime))
return false;
return true;
}
}
| [
"[email protected]"
]
| |
103040f6273b88c2fe24b4fa4f134bb07b2ac2f7 | 7467a22cc9396e5dae1bff0cf0ad7f8dc072451f | /src/test/java/fi/eis/applications/chatapp/login/actions/impl/testhelpers/IOExceptionThrowingDocumentBuilderFactory.java | f66f799b9ba2433d4df64ae93efce27f216972d4 | []
| no_license | eis/simple-suomi24-java-client | 43af1c12e4fc74068668651126f1bd31fa38dda0 | 0f08b1fde27236fa16c9cd58c39b220a430fb06e | refs/heads/master | 2021-01-22T19:26:12.738658 | 2015-08-22T11:24:08 | 2015-08-22T11:24:08 | 26,182,777 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,479 | java | package fi.eis.applications.chatapp.login.actions.impl.testhelpers;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
/**
* Creation Date: 12.11.2014
* Creation Time: 19:02
*
* @author eis
*/
public class IOExceptionThrowingDocumentBuilderFactory extends DocumentBuilderFactory {
@Override
public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
return new DocumentBuilder() {
@Override
public Document parse(InputSource is) throws SAXException, IOException {
throw new IOException("this builder will always throw an exception");
}
@Override
public boolean isNamespaceAware() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean isValidating() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void setEntityResolver(EntityResolver er) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public void setErrorHandler(ErrorHandler eh) {
throw new UnsupportedOperationException("not implemented");
}
@Override
public Document newDocument() {
throw new UnsupportedOperationException("not implemented");
}
@Override
public DOMImplementation getDOMImplementation() {
throw new UnsupportedOperationException("not implemented");
}
};
}
@Override
public void setAttribute(String name, Object value) throws IllegalArgumentException {
// no-op
}
@Override
public Object getAttribute(String name) throws IllegalArgumentException {
return null;
}
@Override
public void setFeature(String name, boolean value) throws ParserConfigurationException {
// no-op
}
@Override
public boolean getFeature(String name) throws ParserConfigurationException {
return false;
}
}
| [
"[email protected]"
]
| |
50b26ec8db48afde4020ee90fa86dd7164c0737a | 8539588c0cca84a452c6bf60c26f36b73cee46d8 | /tapestry-beanvalidator/src/main/java/org/apache/tapestry5/internal/beanvalidator/BeanFieldValidator.java | 43eedfd11b860fbcebf09155d0b0ddf798e44e4d | [
"Apache-2.0"
]
| permissive | agileowl/tapestry-5 | 1ca62b5445ee93fefa213a16bc908dc260ba7e26 | b108e06f4b633d77461dda220a07016ee806c0c7 | refs/heads/master | 2016-09-05T11:43:33.450450 | 2012-11-02T02:28:25 | 2012-11-02T02:28:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,372 | java | // Copyright 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.beanvalidator;
import static java.lang.String.format;
import java.lang.annotation.Annotation;
import java.util.Iterator;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.MessageInterpolator.Context;
import javax.validation.metadata.BeanDescriptor;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.PropertyDescriptor;
import org.apache.tapestry5.Field;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.beanvalidator.BeanValidatorGroupSource;
import org.apache.tapestry5.beanvalidator.ClientConstraintDescriptor;
import org.apache.tapestry5.beanvalidator.ClientConstraintDescriptorSource;
import org.apache.tapestry5.internal.BeanValidationContext;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Environment;
import org.apache.tapestry5.services.FormSupport;
public class BeanFieldValidator implements FieldValidator
{
private final Field field;
private final ValidatorFactory validatorFactory;
private final BeanValidatorGroupSource beanValidationGroupSource;
private final ClientConstraintDescriptorSource clientValidatorSource;
private final FormSupport formSupport;
private final Environment environment;
public BeanFieldValidator(Field field,
ValidatorFactory validatorFactory,
BeanValidatorGroupSource beanValidationGroupSource,
ClientConstraintDescriptorSource clientValidatorSource,
FormSupport formSupport,
Environment environment)
{
this.field = field;
this.validatorFactory = validatorFactory;
this.beanValidationGroupSource = beanValidationGroupSource;
this.clientValidatorSource = clientValidatorSource;
this.formSupport = formSupport;
this.environment = environment;
}
public boolean isRequired()
{
return false;
}
public void render(final MarkupWriter writer)
{
final BeanValidationContext beanValidationContext = environment.peek(BeanValidationContext.class);
if (beanValidationContext == null)
{
return;
}
final Validator validator = validatorFactory.getValidator();
BeanDescriptor beanDescriptor = validator.getConstraintsForClass(beanValidationContext.getBeanType());
String currentProperty = beanValidationContext.getCurrentProperty();
if(currentProperty == null) return;
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(currentProperty);
if(propertyDescriptor == null) return;
for (final ConstraintDescriptor<?> descriptor :propertyDescriptor.getConstraintDescriptors())
{
Class<? extends Annotation> annotationType = descriptor.getAnnotation().annotationType();
ClientConstraintDescriptor clientConstraintDescriptor = clientValidatorSource.getConstraintDescriptor(annotationType);
if(clientConstraintDescriptor != null)
{
String message = format("%s %s", field.getLabel(), interpolateMessage(descriptor));
JSONObject specs = new JSONObject();
for (String attribute : clientConstraintDescriptor.getAttributes())
{
Object object = descriptor.getAttributes().get(attribute);
if (object == null)
{
throw new RuntimeException("Expected attribute is null");
}
specs.put(attribute, object);
}
formSupport.addValidation(field, clientConstraintDescriptor.getValidatorName(), message, specs);
}
}
}
@SuppressWarnings("unchecked")
public void validate(final Object value) throws ValidationException
{
final BeanValidationContext beanValidationContext = environment.peek(BeanValidationContext.class);
if (beanValidationContext == null)
{
return;
}
final Validator validator = validatorFactory.getValidator();
String currentProperty = beanValidationContext.getCurrentProperty();
if(currentProperty == null) return;
BeanDescriptor beanDescriptor = validator.getConstraintsForClass(beanValidationContext.getBeanType());
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(currentProperty);
if(propertyDescriptor == null) return;
final Set<ConstraintViolation<Object>> violations = validator.validateValue(
(Class<Object>) beanValidationContext.getBeanType(), currentProperty,
value, beanValidationGroupSource.get());
if (violations.isEmpty())
{
return;
}
final StringBuilder builder = new StringBuilder();
for (Iterator iterator = violations.iterator(); iterator.hasNext();)
{
ConstraintViolation<?> violation = (ConstraintViolation<Object>) iterator.next();
builder.append(format("%s %s", field.getLabel(), violation.getMessage()));
if(iterator.hasNext())
builder.append(", ");
}
throw new ValidationException(builder.toString());
}
private String interpolateMessage(final ConstraintDescriptor<?> descriptor)
{
String messageTemplate = (String) descriptor.getAttributes().get("message");
MessageInterpolator messageInterpolator = validatorFactory.getMessageInterpolator();
return messageInterpolator.interpolate(messageTemplate, new Context()
{
public ConstraintDescriptor<?> getConstraintDescriptor()
{
return descriptor;
}
public Object getValidatedValue()
{
return null;
}
});
}
}
| [
"[email protected]"
]
| |
7a482467a17da56f08ce23f6afabca21e743715c | 8a89db156088bf4526c6d04c441383d6d69d99ee | /src/main/java/com/tb/commpt/model/XtUserAddressKey.java | 645318d59dba96b622d04c45df059c720ded5857 | []
| no_license | tanbow1/commpt | dc892829a6e33e0b7e57548a3d7e4869e2061624 | 226378c25db99abb25162c2eac45db778b5b8c2c | refs/heads/master | 2021-01-20T09:31:45.901827 | 2017-12-03T14:33:25 | 2017-12-03T14:33:25 | 101,600,931 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 534 | java | package com.tb.commpt.model;
import com.tb.commpt.model.comm.BaseModel;
public class XtUserAddressKey extends BaseModel {
private String userId;
private String address;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
} | [
"[email protected]"
]
| |
571555e1b58be215fc8b43867a9c6ef289bc5e44 | 6c581f6164eebe845a848e8c2d9f8315f7e264fd | /org.abchip.mimo.biz.model/src/org/abchip/mimo/biz/model/product/config/ProductConfigConfig.java | 60a6346fea44421a1e4ff6b0bd591738b8dd94ec | []
| no_license | abchip/mimo-biz20 | 7a0b110fd40733a7f3049d1871ef9559bc08db5c | a3cffeccb98d200ff2ecd629942b4279364d3373 | refs/heads/master | 2023-03-22T22:54:03.865399 | 2021-03-18T20:35:52 | 2021-03-18T20:35:52 | 245,134,382 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,418 | java | /**
* Copyright (c) 2017, 2021 ABChip 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.abchip.mimo.biz.model.product.config;
import org.abchip.mimo.entity.EntityIdentifiable;
import org.abchip.mimo.entity.EntityInfo;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Product Config Config</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigItem <em>Config Item</em>}</li>
* <li>{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigId <em>Config Id</em>}</li>
* <li>{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigOptionId <em>Config Option Id</em>}</li>
* <li>{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getSequenceNum <em>Sequence Num</em>}</li>
* <li>{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getDescription <em>Description</em>}</li>
* </ul>
*
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig()
* @model annotation="mimo-ent-frame title='Existing Product Configurations' dictionary='ProductEntityLabels' formula='description'"
* @generated
*/
public interface ProductConfigConfig extends EntityIdentifiable, EntityInfo {
/**
* Returns the value of the '<em><b>Config Item</b></em>' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the value of the '<em>Config Item</em>' reference.
* @see #setConfigItem(ProductConfigItem)
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig_ConfigItem()
* @model required="true"
* annotation="mimo-ent-slot key='true'"
* @generated
*/
ProductConfigItem getConfigItem();
/**
* Sets the value of the '{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigItem <em>Config Item</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Config Item</em>' reference.
* @see #getConfigItem()
* @generated
*/
void setConfigItem(ProductConfigItem value);
/**
* Returns the value of the '<em><b>Config Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Config Id</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Config Id</em>' attribute.
* @see #setConfigId(String)
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig_ConfigId()
* @model required="true"
* annotation="mimo-ent-slot key='true'"
* annotation="mimo-ent-format length='20'"
* @generated
*/
String getConfigId();
/**
* Sets the value of the '{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigId <em>Config Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Config Id</em>' attribute.
* @see #getConfigId()
* @generated
*/
void setConfigId(String value);
/**
* Returns the value of the '<em><b>Config Option Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Config Option Id</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Config Option Id</em>' attribute.
* @see #setConfigOptionId(String)
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig_ConfigOptionId()
* @model required="true"
* annotation="mimo-ent-slot key='true'"
* annotation="mimo-ent-format length='20'"
* @generated
*/
String getConfigOptionId();
/**
* Sets the value of the '{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getConfigOptionId <em>Config Option Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Config Option Id</em>' attribute.
* @see #getConfigOptionId()
* @generated
*/
void setConfigOptionId(String value);
/**
* Returns the value of the '<em><b>Description</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Description</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Description</em>' attribute.
* @see #setDescription(String)
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig_Description()
* @model annotation="mimo-ent-format type='description'"
* @generated
*/
String getDescription();
/**
* Sets the value of the '{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getDescription <em>Description</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Description</em>' attribute.
* @see #getDescription()
* @generated
*/
void setDescription(String value);
/**
* Returns the value of the '<em><b>Sequence Num</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Sequence Num</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Sequence Num</em>' attribute.
* @see #setSequenceNum(long)
* @see org.abchip.mimo.biz.model.product.config.ConfigPackage#getProductConfigConfig_SequenceNum()
* @model required="true"
* annotation="mimo-ent-slot key='true'"
* annotation="mimo-ent-format precision='20' scale='0'"
* @generated
*/
long getSequenceNum();
/**
* Sets the value of the '{@link org.abchip.mimo.biz.model.product.config.ProductConfigConfig#getSequenceNum <em>Sequence Num</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Sequence Num</em>' attribute.
* @see #getSequenceNum()
* @generated
*/
void setSequenceNum(long value);
} // ProductConfigConfig
| [
"[email protected]"
]
| |
e9cfe4a4a286b2232c530ebd4e9fdab7bceb1226 | 36d7e18bc727ede0f0b5e4e3fa4aad9bf36e4927 | /src/br/com/chess/chess/pieces/King.java | f2e705e4f61ffe3e75d224edb2dd09d01d148c68 | []
| no_license | EdFrade/chess-system-java | e7ea122ff8ae534d0b5dbd352dc135369729df06 | ece02a1c270fac2d53f1fb470b5e09eaa8b436b8 | refs/heads/master | 2020-05-23T07:13:55.714513 | 2019-05-21T01:07:29 | 2019-05-21T01:07:29 | 186,673,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,448 | java | package br.com.chess.chess.pieces;
import br.com.chess.boardgame.Board;
import br.com.chess.boardgame.Position;
import br.com.chess.chess.ChessMatch;
import br.com.chess.chess.ChessPiece;
import br.com.chess.chess.Color;
public class King extends ChessPiece {
private ChessMatch chessMatch;
public King(Board board, Color color, ChessMatch chessMatch) {
super(board, color);
this.chessMatch = chessMatch;
}
@Override
public String toString() {
return "K";
}
private boolean canMove(Position position) {
ChessPiece p = (ChessPiece) getBoard().piece(position);
return p == null || p.getColor() != getColor();
}
private boolean testRookCastling(Position position) {
ChessPiece p = (ChessPiece)getBoard().piece(position);
return p != null && p instanceof Rook && p.getColor() == getColor() && p.getMoveCount() == 0;
}
@Override
public boolean[][] possibleMoves() {
boolean[][] mat = new boolean[getBoard().getRows()][getBoard().getColumns()];
Position p = new Position(0, 0);
// Above
p.setValues(position.getRow() - 1, position.getColumn());
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// Below
p.setValues(position.getRow() + 1, position.getColumn());
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// Left
p.setValues(position.getRow(), position.getColumn() - 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// Right
p.setValues(position.getRow(), position.getColumn() + 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// nw
p.setValues(position.getRow() - 1, position.getColumn() - 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// ne
p.setValues(position.getRow() - 1, position.getColumn() + 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// sw
p.setValues(position.getRow() + 1, position.getColumn() - 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// se
p.setValues(position.getRow() + 1, position.getColumn() + 1);
if (getBoard().positionExists(p) && canMove(p)) {
mat[p.getRow()][p.getColumn()] = true;
}
// #specialmove castling
if (getMoveCount() == 0 && !chessMatch.getCheck()) {
// Rook grande
Position posT1 = new Position(position.getRow(), position.getColumn() + 3);
if (testRookCastling(posT1)) {
Position p1 = new Position(position.getRow(), position.getColumn() + 1);
Position p2 = new Position(position.getRow(), position.getColumn() + 2);
if (getBoard().piece(p1) == null && getBoard().piece(p2) == null) {
mat[position.getRow()][position.getColumn() + 2] = true;
}
}
// rook pequeno
Position posT2 = new Position(position.getRow(), position.getColumn() - 4);
if (testRookCastling(posT2)) {
Position p1 = new Position(position.getRow(), position.getColumn() - 1);
Position p2 = new Position(position.getRow(), position.getColumn() - 2);
Position p3 = new Position(position.getRow(), position.getColumn() - 3);
if (getBoard().piece(p1) == null && getBoard().piece(p2) == null && getBoard().piece(p3) == null) {
mat[position.getRow()][position.getColumn() - 2] = true;
}
}
}
return mat;
}
}
| [
"[email protected]"
]
| |
2b1655fdaee63fa068b5582a14eb855bd8f5134b | abc5c2243cc3d2bd3815f223650bff4b702f4482 | /REST/Tienda/src/com/tienda/bean/Order.java | 6d88a41985126018beb43a6f940350a3a1f43723 | []
| no_license | PoojaShirwaikar/BlockhainTest | b01a9dc547a7b6f282f051bd7c35e414fca167f9 | 05c5ccccf7e02d0d5aaf1703f7874c3d78c6c77d | refs/heads/master | 2021-05-06T02:34:39.278180 | 2018-02-12T10:18:36 | 2018-02-12T10:18:36 | 114,599,664 | 0 | 0 | null | 2020-03-01T09:30:08 | 2017-12-18T05:33:39 | JavaScript | UTF-8 | Java | false | false | 1,435 | java | package com.tienda.bean;
import java.util.Date;
import java.util.Set;
import javax.xml.bind.annotation.XmlRootElement;
import com.tienda.util.OrderStatus;
@XmlRootElement(name = "order")
public class Order {
private int orderId;
private String number;
private Date orderedon;
private User orderedby;
private OrderStatus status;
private Set<Product> cart;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Date getOrderedon() {
return orderedon;
}
public void setOrderedon(Date orderedon) {
this.orderedon = orderedon;
}
public User getOrderedby() {
return orderedby;
}
public void setOrderedby(User orderedby) {
this.orderedby = orderedby;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
public Set<Product> getCart() {
return cart;
}
public void setCart(Set<Product> cart) {
this.cart = cart;
}
public Order(int orderId, String number, Date orderedon, User orderedby,
OrderStatus status, Set<Product> cart) {
super();
this.orderId = orderId;
this.number = number;
this.orderedon = orderedon;
this.orderedby = orderedby;
this.status = status;
this.cart = cart;
}
public Order() {
super();
}
}
| [
"[email protected]"
]
| |
69b0a4b76fda0a35dbd56cd04121e44987ca88ad | 081b4eb04aebfe18fccc80260c470b209c1ade73 | /app/src/androidTest/java/es/ulpgc/eite/android/quiz/screen/question/QuestionActivityTest2.java | 9ae4cb40b40f83692223d1b81f41d4b575197d5a | []
| no_license | JonayCruzDelgado/QuizProject | a21640f45b1bb5bebff9fb6f7adb002d2865420d | 48604798656aabf5900b322abf224f2eeaa68aae | refs/heads/master | 2021-01-09T06:13:19.461862 | 2017-02-10T16:24:00 | 2017-02-10T16:24:00 | 80,937,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,918 | java | package es.ulpgc.eite.android.quiz.screen.question;
import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.hamcrest.core.IsInstanceOf;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import es.ulpgc.eite.android.quiz.R;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
@LargeTest
@RunWith(AndroidJUnit4.class)
public class QuestionActivityTest2 {
@Rule
public ActivityTestRule<QuestionActivity> mActivityTestRule = new ActivityTestRule<>(QuestionActivity.class);
@Test
public void questionActivityTest2() {
ViewInteraction appCompatButton = onView(
allOf(withId(R.id.buttonTrue), withText("True"), isDisplayed()));
appCompatButton.perform(click());
ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.buttonNext), withText("Next"), isDisplayed()));
appCompatButton2.perform(click());
ViewInteraction textView = onView(
allOf(withId(R.id.labelAnswer), withText("Correct!"),
childAtPosition(
childAtPosition(
IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
0),
2),
isDisplayed()));
textView.check(doesNotExist());
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
| [
"[email protected]"
]
| |
68bd279b3635f286f4b6f989a55265d94b78349c | a457be6f9744623f1ccb5b1c0574601d3fe0ff61 | /JDBCWebCRUD/src/com/niit/jdbccrud/config/DBConfig.java | 6bf92d10605b30a7a5c9c54dff15c0e21189b5b5 | []
| no_license | sonam-niit/CRUDDemos | fa033219a7b9f2115ce63a911f54d6bcb6a3965d | 331316f127cd9ed5e8c5a31aaafefc9bb9f67b7c | refs/heads/master | 2020-03-24T13:03:49.844394 | 2018-08-20T09:14:37 | 2018-08-20T09:14:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 444 | java | package com.niit.jdbccrud.config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConfig {
public static Connection getConnection()
{
Connection connection=null;
try {
Class.forName("org.h2.Driver");
connection = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/myDB1","sa","1234");
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
| [
"[email protected]"
]
| |
c4263375ddeba6a8c6aee993bcf3034e000cd459 | 791c9ea88e80fdbfa3688bfa2b2fab06781b9189 | /app/src/main/java/com/iamsafi/crtfehsaas/adapter/PeopleAdapter.java | 3040f774e5224fb2d74ca19cb7371bdc3eadf71c | []
| no_license | iamsafidev/CRTF-Excel-Creator-App | abd4343d6d2d90b2a393637d4d0456923e29f45e | 71cc635d789e62e70611044ae4c61678426dc80e | refs/heads/master | 2022-11-06T20:27:41.800895 | 2020-06-22T15:58:12 | 2020-06-22T15:58:12 | 274,178,349 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,017 | java | package com.iamsafi.crtfehsaas.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.iamsafi.crtfehsaas.R;
import com.iamsafi.crtfehsaas.database.Person;
import java.util.ArrayList;
import java.util.List;
public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.ViewHolder> {
Context context;
List<Person> mPersonList;
LayoutInflater layoutInflater;
public PeopleAdapter(Context context, List<Person> mPersonList) {
this.context = context;
this.mPersonList = mPersonList;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.person_record_row, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.txt_name.setText(mPersonList.get(position).getFull_Name());
holder.txt_cnic.setText(mPersonList.get(position).getCNIC());
holder.txt_issuedate.setText(mPersonList.get(position).getCNIC_Issue_Date());
holder.txt_gender.setText(mPersonList.get(position).getGender() + ", " + mPersonList.get(position).getMartial_Status());
holder.txt_mobile.setText(mPersonList.get(position).getMobile());
// if (mPersonList.get(position).getRegistration_Status().equalsIgnoreCase("UnRegistered")) {
// holder.txt_unregister.setVisibility(View.VISIBLE);
// holder.txt_register.setVisibility(View.GONE);
// } else {
// holder.txt_unregister.setVisibility(View.GONE);
// holder.txt_register.setVisibility(View.VISIBLE);
// }
}
public Person getPersonAtPosition(int position) {
return mPersonList.get(position);
}
@Override
public int getItemCount() {
return mPersonList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt_name;
TextView txt_cnic;
TextView txt_issuedate;
TextView txt_gender;
TextView txt_mobile;
TextView txt_register;
TextView txt_unregister;
public ViewHolder(View itemView) {
super(itemView);
txt_name = itemView.findViewById(R.id.tv_name);
txt_cnic = itemView.findViewById(R.id.tv_cnic);
txt_issuedate = itemView.findViewById(R.id.tvissuedate);
txt_gender = itemView.findViewById(R.id.tvgender);
txt_mobile = itemView.findViewById(R.id.tv_mobile);
txt_register = itemView.findViewById(R.id.tvregister);
txt_unregister = itemView.findViewById(R.id.tvunregister);
}
}
}
| [
"[email protected]"
]
| |
07199e892432f48116e4ac526ca07eb1b95718bc | 3613dfd5927fca32a1630bbb76d7a8318fa1db24 | /src/by/algorithmization/arraysOfArrays/Task14.java | c0c45603a2e416867a8e043206b97e77babb4ed1 | []
| no_license | vitalydervanowsky/Java_Basics_UpSkill_Lab_1 | ae385b17513ada00733ca9f91ac848b4379b44b9 | 57ad215bdf0058608a3135846a138e651208e0eb | refs/heads/main | 2023-04-15T08:30:30.182285 | 2021-04-30T19:36:27 | 2021-04-30T19:36:27 | 312,587,837 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,091 | java | package by.algorithmization.arraysOfArrays;
// Сформировать случайную матрицу m x n, состоящую из нулей и единиц,
// причем в каждом столбце число единиц равно номеру столбца.
public class Task14 {
public static void main(String[] args) {
int n = 10;
int m = 11; // n >= m - 1 !!!!!
int[][] a = new int[n][m];
int[] ones = new int[m];
for (int j = 0; j < m; j++) {
System.out.print("[" + j + "]\t");
while (ones[j] != j) {
ones[j] = 0;
for (int i = 0; i < n; i++) {
a[i][j] = (int) (2 * Math.random());
if (a[i][j] == 1) {
ones[j]++;
}
}
}
}
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
}
| [
"[email protected]"
]
| |
57d7fd66df8cbb0116ac8c039edd48aac3a8560e | bce31e3c7517825fdfa3151322e5d60d6ee59538 | /navisu-domain/src/main/java/bzh/terrevirtuelle/navisu/domain/nmea/model/ais/impl/utils/UtilsRateOfTurn8.java | e78a33ef8b63d7bc597bf1d4b2006c851cf09d1c | []
| no_license | terre-virtuelle/navisu | b0355461b9c77035834f79646036a9dc002f203d | 97bc2baaed37f83c9b773f1973a2a65683dc9e79 | refs/heads/master | 2021-08-04T03:41:09.226887 | 2021-06-17T11:27:22 | 2021-06-17T11:27:22 | 14,243,882 | 31 | 16 | null | null | null | null | UTF-8 | Java | false | false | 3,920 | java | package bzh.terrevirtuelle.navisu.domain.nmea.model.ais.impl.utils;
/** This class provides functions to analyze the rate-of-turn value that is returned by {@link AISMessagePositionReport#getRateOfTurn()}.
* @author Pierre van de Laar
* @author Pierre America
* @author Brian C. Lane
*/
public class UtilsRateOfTurn8 {
/** The rate-of-turn value that is used to signal unavailability, according to the AIS standard. */
private static final int DEFAULTVALUE = -0x80;
/** The minimum rate-of-turn value when a turn indicator is available. */
private static final int MINTurnIndicatorVALUE = -126;
/** The maximum rate-of-turn value when a turn indicator is available. */
private static final int MAXTurnIndicatorVALUE = 126;
/** Checks if rate-of-turn information is available.
* This means that the value does not signal unavailability.
* It is still possible that no turn indicator is available (see {@link UtilsRateOfTurn8#isTurnIndicatorAvailable}).
* @param value the rate-of-turn value that is returned by {@link AISMessagePositionReport#getRateOfTurn()}.
* @return true if the rate-of-turn is available
*/
public static boolean isTurnInformationAvailable( int value )
{
return value != UtilsRateOfTurn8.DEFAULTVALUE;
}
/** Checks if a turn indicator is available.
* This means that the rate-of-turn value provides a numeric estimate of the rate-of-turn,
* which can be computed using {@link UtilsRateOfTurn8#toDegreesPerMinute}.
* @param value the rate-of-turn value that is returned by {@link AISMessagePositionReport#getRateOfTurn()}.
* @return true if the rate-of-turn is available
*/
public static boolean isTurnIndicatorAvailable( int value )
{
return (UtilsRateOfTurn8.MINTurnIndicatorVALUE <= value) && (value <= UtilsRateOfTurn8.MAXTurnIndicatorVALUE);
}
/** Converts the rate-of-turn value ROT<sub>AIS</sub> to a numerical estimate for the rate-of-turn ROT<sub>sensor</sub> (in degrees/minute).
*
* Page 101 of the AIS standard ITU-R M.1371-4 states:
* ROT<sub>AIS</sub> = 4.733 SQRT(ROT<sub>sensor</sub>)
* <br>
* Note that a ROT<sub>AIS</sub> of ±126 indicates a rate-of-turn of 708 degrees/min <b>or higher</b>.
* @precondition isTurnIndicatorAvailable(rot)
* @param rot the rate-of-turn value ROT<sub>AIS</sub> that is returned by {@link AISMessagePositionReport#getRateOfTurn()}.
* @return a numerical estimate for the rate-of-turn ROT<sub>sensor</sub> (in degrees/minute) (positive sign indicates turning right)
*/
public static double toDegreesPerMinute ( int rot )
{
assert(isTurnIndicatorAvailable(rot));
double v = rot/4.733;
double v2 = v*v; // Math.pow(v, 2)
if(rot < 0)
{
return -v2;
}
else
{
return v2;
}
}
/** Makes human-readable text from a rate-of-turn value.
* @param rot the rate-of-turn value that is returned by {@link AISMessagePositionReport#getRateOfTurn()}.
* @return a human-readable string represent the rate-of-turn information
*/
public static String toString(int rot)
{
String direction; //sign of rot is encoded in direction
if (rot < 0)
{ direction = "left";
}
else
{
direction = "right";
}
switch (Math.abs(rot))
{
case 128: return "no turn information available (default)";
case 127: return "turning " + direction + " at more than 5 degrees per 30 s (No TI available)";
case 126: return "turning " + direction + " at 708 degrees per min or higher";
case 0 : return "not turning";
default :
return "turning " + direction + " at " + Math.abs(toDegreesPerMinute(rot)) + " degrees per min";
//abs value since sign of rot is encoded in direction
}
}
/** This constructor is made private to indicate that clients should not construct instances of this class. */
private UtilsRateOfTurn8 () {
}
} | [
"serge@serge-XPS-8500"
]
| serge@serge-XPS-8500 |
5453b2f6e573eaca9236cb382a1b5af6bca10619 | 555a6b907c647a34df3d50c5c2790191377ce48e | /src/main/java/es/poc/reactiveexamples/reactiveexamples/ReactiveexamplesApplication.java | cf8a8afa70cca189c7aa25a2994e32fb3b7f4631 | []
| no_license | nesteban/reactiveexamples | 02e5e84cc37c9a5043d111c69495c7e85d0e343e | 6b6ad5c4e1632c82f98d7da8c1b5ad29122294e7 | refs/heads/master | 2023-06-03T17:40:26.847116 | 2021-06-14T05:24:41 | 2021-06-14T05:24:41 | 376,712,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package es.poc.reactiveexamples.reactiveexamples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReactiveexamplesApplication {
public static void main(String[] args) {
SpringApplication.run(ReactiveexamplesApplication.class, args);
}
}
| [
"[email protected]"
]
| |
8d9ea9c3500e652172f6bdef8c7d5e2b5fe3a955 | 0ea271177f5c42920ac53cd7f01f053dba5c14e4 | /5.3.5/sources/org/telegram/messenger/exoplayer2/extractor/ts/H265Reader$SampleReader.java | 870c1adbe6c5974cc250e60cfb6e8cdc0fb94f1c | []
| no_license | alireza-ebrahimi/telegram-talaeii | 367a81a77f9bc447e729b2ca339f9512a4c2860e | 68a67e6f104ab8a0888e63c605e8bbad12c4a20e | refs/heads/master | 2020-03-21T13:44:29.008002 | 2018-12-09T10:30:29 | 2018-12-09T10:30:29 | 138,622,926 | 12 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,555 | java | package org.telegram.messenger.exoplayer2.extractor.ts;
import org.telegram.messenger.exoplayer2.extractor.TrackOutput;
final class H265Reader$SampleReader {
private static final int FIRST_SLICE_FLAG_OFFSET = 2;
private boolean isFirstParameterSet;
private boolean isFirstSlice;
private boolean lookingForFirstSliceFlag;
private int nalUnitBytesRead;
private boolean nalUnitHasKeyframeData;
private long nalUnitStartPosition;
private long nalUnitTimeUs;
private final TrackOutput output;
private boolean readingSample;
private boolean sampleIsKeyframe;
private long samplePosition;
private long sampleTimeUs;
private boolean writingParameterSets;
public H265Reader$SampleReader(TrackOutput output) {
this.output = output;
}
public void reset() {
this.lookingForFirstSliceFlag = false;
this.isFirstSlice = false;
this.isFirstParameterSet = false;
this.readingSample = false;
this.writingParameterSets = false;
}
public void startNalUnit(long position, int offset, int nalUnitType, long pesTimeUs) {
boolean z;
boolean z2 = false;
this.isFirstSlice = false;
this.isFirstParameterSet = false;
this.nalUnitTimeUs = pesTimeUs;
this.nalUnitBytesRead = 0;
this.nalUnitStartPosition = position;
if (nalUnitType >= 32) {
if (!this.writingParameterSets && this.readingSample) {
outputSample(offset);
this.readingSample = false;
}
if (nalUnitType <= 34) {
this.isFirstParameterSet = !this.writingParameterSets;
this.writingParameterSets = true;
}
}
if (nalUnitType < 16 || nalUnitType > 21) {
z = false;
} else {
z = true;
}
this.nalUnitHasKeyframeData = z;
if (this.nalUnitHasKeyframeData || nalUnitType <= 9) {
z2 = true;
}
this.lookingForFirstSliceFlag = z2;
}
public void readNalUnitData(byte[] data, int offset, int limit) {
if (this.lookingForFirstSliceFlag) {
int headerOffset = (offset + 2) - this.nalUnitBytesRead;
if (headerOffset < limit) {
boolean z;
if ((data[headerOffset] & 128) != 0) {
z = true;
} else {
z = false;
}
this.isFirstSlice = z;
this.lookingForFirstSliceFlag = false;
return;
}
this.nalUnitBytesRead += limit - offset;
}
}
public void endNalUnit(long position, int offset) {
if (this.writingParameterSets && this.isFirstSlice) {
this.sampleIsKeyframe = this.nalUnitHasKeyframeData;
this.writingParameterSets = false;
} else if (this.isFirstParameterSet || this.isFirstSlice) {
if (this.readingSample) {
outputSample(offset + ((int) (position - this.nalUnitStartPosition)));
}
this.samplePosition = this.nalUnitStartPosition;
this.sampleTimeUs = this.nalUnitTimeUs;
this.readingSample = true;
this.sampleIsKeyframe = this.nalUnitHasKeyframeData;
}
}
private void outputSample(int offset) {
this.output.sampleMetadata(this.sampleTimeUs, this.sampleIsKeyframe ? 1 : 0, (int) (this.nalUnitStartPosition - this.samplePosition), offset, null);
}
}
| [
"[email protected]"
]
| |
6fb1f71b776b23029c4a43455cc70c5c260e12ef | 49d20dff92a6a1198a30b3526cfb85b93ba645c4 | /src/main/java/net/schmizz/sshj/sftp/RemoteFile.java | 641055736cd50992507cee9d567620f99f366f13 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
]
| permissive | cloudera/sshj | 40229cb25d0cbf0d86e256cbc621cc12bb486c5f | 3838dd20d7cbc503b98f26bd268f1acdd9fe2a3d | refs/heads/master | 2023-03-21T17:26:56.438973 | 2011-06-23T00:17:57 | 2011-06-23T00:27:58 | 1,856,139 | 6 | 7 | null | null | null | null | UTF-8 | Java | false | false | 5,381 | java | /*
* Copyright 2010, 2011 sshj contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.sftp;
import net.schmizz.sshj.sftp.Response.StatusCode;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class RemoteFile
extends RemoteResource {
public RemoteFile(Requester requester, String path, String handle) {
super(requester, path, handle);
}
public RemoteFileInputStream getInputStream() {
return new RemoteFileInputStream();
}
public RemoteFileOutputStream getOutputStream() {
return new RemoteFileOutputStream();
}
public FileAttributes fetchAttributes()
throws IOException {
return requester.doRequest(newRequest(PacketType.FSTAT))
.ensurePacketTypeIs(PacketType.ATTRS)
.readFileAttributes();
}
public long length()
throws IOException {
return fetchAttributes().getSize();
}
public void setLength(long len)
throws IOException {
setAttributes(new FileAttributes.Builder().withSize(len).build());
}
public int read(long fileOffset, byte[] to, int offset, int len)
throws IOException {
Response res = requester.doRequest(newRequest(PacketType.READ).putUInt64(fileOffset).putUInt32(len));
switch (res.getType()) {
case DATA:
int recvLen = res.readUInt32AsInt();
System.arraycopy(res.array(), res.rpos(), to, offset, recvLen);
return recvLen;
case STATUS:
res.ensureStatusIs(StatusCode.EOF);
return -1;
default:
throw new SFTPException("Unexpected packet: " + res.getType());
}
}
public void write(long fileOffset, byte[] data, int off, int len)
throws IOException {
requester.doRequest(newRequest(PacketType.WRITE)
.putUInt64(fileOffset)
.putUInt32(len - off)
.putRawBytes(data, off, len)
).ensureStatusPacketIsOK();
}
public void setAttributes(FileAttributes attrs)
throws IOException {
requester.doRequest(newRequest(PacketType.FSETSTAT).putFileAttributes(attrs)).ensureStatusPacketIsOK();
}
public int getOutgoingPacketOverhead() {
return 1 + // packet type
4 + // request id
4 + // next length
handle.length() + // next
8 + // file offset
4 + // data length
4; // packet length
}
public class RemoteFileOutputStream
extends OutputStream {
private final byte[] b = new byte[1];
private long fileOffset;
public RemoteFileOutputStream() {
this(0);
}
public RemoteFileOutputStream(long fileOffset) {
this.fileOffset = fileOffset;
}
@Override
public void write(int w)
throws IOException {
b[0] = (byte) w;
write(b, 0, 1);
}
@Override
public void write(byte[] buf, int off, int len)
throws IOException {
RemoteFile.this.write(fileOffset, buf, off, len);
fileOffset += len;
}
}
public class RemoteFileInputStream
extends InputStream {
private final byte[] b = new byte[1];
private long fileOffset;
private long markPos;
private long readLimit;
public RemoteFileInputStream() {
this(0);
}
public RemoteFileInputStream(int fileOffset) {
this.fileOffset = fileOffset;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readLimit) {
this.readLimit = readLimit;
markPos = fileOffset;
}
@Override
public void reset()
throws IOException {
fileOffset = markPos;
}
@Override
public long skip(long n)
throws IOException {
return (this.fileOffset = Math.min(fileOffset + n, length()));
}
@Override
public int read()
throws IOException {
return read(b, 0, 1) == -1 ? -1 : b[0] & 0xff;
}
@Override
public int read(byte[] into, int off, int len)
throws IOException {
int read = RemoteFile.this.read(fileOffset, into, off, len);
if (read != -1) {
fileOffset += read;
if (markPos != 0 && read > readLimit) // Invalidate mark position
markPos = 0;
}
return read;
}
}
}
| [
"[email protected]"
]
| |
d351d991713053c7efdc4bb8d0008d789bfc1adc | b7f35fb322a4d6354fe89c974ad1d432607ee7e2 | /src/main/java/cl/ucn/disc/pdbp/tdd/model/Tipo.java | 6a3224b283feb3be15d4a5c8d60ee6dc5b1bbb75 | [
"MIT"
]
| permissive | Wilber-Navarro/tdd | 176460bffaf9276c723a77b4329b3bc30e2e55ce | 90eba95c6d65e6020ae42ac10d3918e7db019f83 | refs/heads/master | 2022-09-10T22:01:06.475113 | 2020-06-01T10:47:46 | 2020-06-01T10:47:46 | 262,697,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,301 | java | /*
* MIT License
*
* Copyright (c) [2020.] [Wilber Mauricio Navarro Moreira]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package cl.ucn.disc.pdbp.tdd.model;
/**
* Enumeracion de tipo.
* @autor Wilber Navarro.
*/
public enum Tipo {
INTERNO,
EXTERNO
}
| [
"[email protected]"
]
| |
99a74ece1c64cea969182e33408061cf9379f895 | 416e8cf777f81eefecc71fe98d004d735c87aeed | /src/com/zhku/community/action/CartAction.java | 4f48d532268481550e7927188d86a41e46356cbd | []
| no_license | zhouguanglong1/zhku1 | 29147112b6c92e0108236ae7f8fa232162e5a537 | 208acac0be217890a94a63874901f8c4f4204e4f | refs/heads/master | 2021-01-23T04:14:14.909951 | 2017-05-31T09:48:32 | 2017-05-31T09:48:32 | 92,920,925 | 0 | 0 | null | 2017-05-31T09:48:33 | 2017-05-31T08:05:01 | JavaScript | UTF-8 | Java | false | false | 1,514 | java | package com.zhku.community.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zhku.base.action.BaseAct;
import com.zhku.community.bean.shop.Cart;
import com.zhku.community.bean.shop.CartItem;
import com.zhku.community.bean.shop.Product;
import com.zhku.community.service.ProductService;
@Controller
@RequestMapping("/cart")
public class CartAction extends BaseAct {
@Autowired
ProductService productService;
@RequestMapping(value="addCart.action")
public String addCart(Long pid,HttpServletRequest request,HttpServletResponse response) throws Exception{
Product product = productService.findByPid(pid);
CartItem cartItem = new CartItem();
cartItem.setCount(1);
cartItem.setProduct(product);
Cart cart = getCart(request);
cart.addCart(cartItem);
request.setAttribute("product", product);
return "/sys/cartList";
}
/**
* 从session范围获得购物车的代码
*/
public Cart getCart(HttpServletRequest request) {
// 从session的范围获得Cart对象.
Cart cart = (Cart) request.getSession().getAttribute("cart");
// 判断:
if (cart == null) {
// 创建购物车对象
cart = new Cart();
// 将购物车对象放入到session范围:
request.getSession().setAttribute("cart", cart);
}
return cart;
}
}
| [
"[email protected]"
]
| |
2c3f9ff9d528d3732c42dd62e339af41667afc3f | 5743124edc31ddf6925ec229e8b05e70246dae4b | /CrudPpbo/src/Barang/Koneksi.java | 65393bb6ea4dec012e8907e1f2bd1c38b39f82f8 | []
| no_license | danimr26/UASCrudPPBO | 9bae243abaa32dfec57f98de772eab6021832307 | b1ba7fc51cf7caf62afda96a775e733b44a14c69 | refs/heads/main | 2023-06-12T20:49:59.668530 | 2021-07-01T12:53:38 | 2021-07-01T12:53:38 | 382,032,080 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,034 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Barang;
import java.sql.DriverManager;
/**
*
* @author acer
*/
public class Koneksi {
private static java.sql.Connection koneksi;
public static java.sql.Connection getKoneksi () {
if (koneksi == null) {
try {
String url = "jdbc:mysql://localhost:3306/crudppbo";
String user = "root";
String password = "";
DriverManager.registerDriver (new com.mysql.jdbc.Driver());
koneksi = DriverManager.getConnection (url,user,password);
System.out.println("Berhasil Terhubung");
} catch (Exception e) {
System.out.println("Error");
}
}
return koneksi;
}
public static void main(String args[]){
getKoneksi();
}
}
| [
"[email protected]"
]
| |
afae6b650dae308dff8d3ea5599a53997adca23f | aaf4676b5896b48ea7bdee8114b2a1a288c9ccc7 | /src/com/easybuy/action/userManager/RegisterServlet.java | f6e0e7d586385e855c12b5ec3a181fe9607614bf | []
| no_license | TDCQ/easybuy | c9131bc2c56728f86768b22a9aca2a614f80d9c3 | 620214a50d85df1af45dcfeb43ad8c4b6f887d88 | refs/heads/master | 2021-01-19T04:34:00.711492 | 2016-06-17T15:49:06 | 2016-06-17T15:49:06 | 60,859,230 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,510 | java | package com.easybuy.action.userManager;
import com.easybuy.model.User;
import com.easybuy.service.UserService;
import com.easybuy.service.impl.UserServiceImpl;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
/**
* Created by lenovo on 2016/6/12.
*/
@WebServlet(name = "RegisterServlet", urlPatterns = {"/register.html", "/reg-result.html"})
public class RegisterServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("userName");
String email = request.getParameter("email");
String password = request.getParameter("passWord");
User user = userService.getUserByEmail(email);
if(user==null){
user = new User();
user.setEmail(email);
user.setPassword(password);
user.setName(name);
boolean flag = userService.addUser(user);
if(flag){
response.sendRedirect("/index.html");
}else {
out.println(name + "\t" + email + "\t" + password);
out.close();
}
}else{
out.println("duplicate email ");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset='UTF-8'");
OutputStream out = response.getOutputStream();
ServletContext servletContext = this.getServletContext();
InputStream inputStream = servletContext.getResourceAsStream("/html/register.ftl");
byte[] array = new byte[1024];
int len = inputStream.read(array);
while(len!=-1){
out.write(array, 0, len);
len = inputStream.read(array);
}
inputStream.close();
out.close();
}
}
| [
"[email protected]"
]
| |
adfd7bfb2422f2b41a34ad883b041ca9cefef95e | 007af033777f5d859a7474920444dfeeef9aca43 | /src/main/java/com/lionet/publishsubscribe/p/PublishSubscribePublish2.java | ebbfbe959135805afcceb56e3b72a8e30e950908 | []
| no_license | bravelionet/RabbitMQ-_Six_Working_Mode_Cases | 8d7d3785792374c8b2c8027b9c8e4c3da0df40c0 | 7e12b60b5ad5881153c05e78d188a84ae6ce6cc9 | refs/heads/master | 2022-05-31T19:11:50.440368 | 2020-04-27T04:10:49 | 2020-04-27T04:10:49 | 259,198,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,736 | java | package com.lionet.publishsubscribe.p;
import com.lionet.utlis.ConnectionFactoryUtlis;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
* @Authror Lionet
* @Date 2020/4/25 22:41
* @Description Publish/Subscribe 模式
* 1. 生产者只需要声明交换机,将消息发送到交换机即可,再由交换机根据 type 发送到具体的队列
* 2. 交换机没有存储消息的能力,只能进行转发消息,在没有队列绑定此交换机时,客户端向交换机发送的消息将会消息
* 3. 特别注意,声明交换机时,durable参数设置持久化,而不是设置发送的消息设置为持久化,具体请看参数讲解
*/
public class PublishSubscribePublish2 {
// 交换机昵称
private static final String EXCHANGE_NAME = "exchange_test";
private static final String EXCHANGE_BANDING_NAME = "exchange_banding_test";
private static final String EXCHANGE_FANOUT_TYPE = "fanout";
public static void main(String[] args) throws Exception {
// 获取连接
Connection connection = ConnectionFactoryUtlis.getConnection();
// 创建通道
Channel channel = connection.createChannel();
/**
* @param exchange 交换机的昵称
* @param type 交换机类型 : direct,topic,headers,fanout
* @param durable 如果我们声明持久交换,则为true(该交换将在服务器重启后保留下来))
* @param autoDelete 设置是否自动删除。autoDelete设置为true时,则表示自动删除。
* 自动删除的前提是至少有一个队列或者交换器与这个交换器绑定,之后,
* 所有与这个交换器绑定的队列或者交换器都与此解绑。
* 不能错误的理解—当与此交换器连接的客户端都断开连接时,RabbitMq会自动删除本交换器
* @param internal 设置是否内置的。如果设置为true,
* 则表示是内置的交换器,客户端程序无法直接发送消息到这个交换器中,
* 只能通过交换器路由到交换器这种方式。
* @param arguments 用于交换的其他属性(构造参数)
*/
// 创建交换机
channel.exchangeDeclare(EXCHANGE_BANDING_NAME, EXCHANGE_FANOUT_TYPE, false, false, false, null);
// 发送消息体
String msg = "publish/subscribe 模式";
channel.basicPublish(EXCHANGE_NAME,"",null,msg.getBytes());
System.out.println(" publish/subscribe fanout 模式发送完毕");
channel.close();
connection.close();
}
}
| [
"[email protected]"
]
| |
94f772c234d39d48d25161938dca29941c2ae701 | 708febe2ca3561e32bfe66801b11e0ad502d456b | /fabrikam-functions/src/main/java/com/sm/reti/fabrikam_functions/Translator.java | 0974b4c904a0ec018f0f0fe088e5ba6c26e14c96 | []
| no_license | GabrielePisapia/Reti | e2081f75de0d77d94f8b79ec777c1c4fa916aff1 | 9999338d646d15a826ae1adb5b286ea33ba457f3 | refs/heads/master | 2023-02-03T05:48:42.322147 | 2020-12-22T08:20:29 | 2020-12-22T08:20:29 | 313,593,357 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,197 | java | package com.sm.reti.fabrikam_functions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Translator {
public Translator() {
}
public static String translate(String langFrom, String langTo, String text) throws IOException {
// INSERT YOU URL HERE
String urlStr = "https://script.google.com/macros/s/AKfycbwqq5vTO3Ang0a4oitenKzA7MRgVvHBRxuIzO5n2e2pKpG1FHcy/exec" +
"?q=" + URLEncoder.encode(text, "UTF-8") +
"&target=" + langTo +
"&source=" + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
| [
"[email protected]"
]
| |
78334586b1928fc7ef39bfbf168a59d86c0783db | a45aae8a3212e115e8dd03128ef044736283b983 | /app/src/main/java/com/example/vamosjuntoslist/MainActivity.java | b3a027ea4046d04fe666e0601ca2940f630fe01f | []
| no_license | rcuestasjb/RemoteJson | dc8aac96234b91b4dcbff0b00e46f07e5e9932c4 | 6f49bb2c06249fd5b5df43a0bb81f65fbf2ce952 | refs/heads/master | 2020-09-12T05:57:06.609672 | 2019-11-18T00:39:24 | 2019-11-18T00:39:24 | 222,333,380 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,295 | java | package com.example.vamosjuntoslist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
//1) Definicion de la clase evento; esta clase la utilizaremos para rellenar una lista
class Evento {
private String categoria;
private String descripcion;
private String dia;
private String hora;
private String id;
private String titulo;
public Evento(String titulo) {
this.titulo = titulo;
}
public String getTitulo() { return this.titulo; }
}
public class MainActivity extends AppCompatActivity {
//Definición de la interface de retrofit (aqui definimos nuestro endpoint)
interface Api {
//String ENDPOINT = "http://puigverd.org/";
String ENDPOINT = "https://raw.githubusercontent.com/rcuestasjb/m07/master/";
@GET("list.json")
Call<List<Evento>> getEventos();
}
//Componente de la lista de eventos
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
//1) Creacion de la activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//2) Obtenemos el id del list View, mas tarde la rellenaremos
listView = (ListView) findViewById(R.id.listViewEventos);
//3) Preparamos la llamada al endpoint con retrpfit-
Retrofit retrofit = new Retrofit.Builder().baseUrl(Api.ENDPOINT).
addConverterFactory(GsonConverterFactory.create()).build();
Api api = retrofit.create(Api.class);
//3) Realizamos la llamada asincrona es decir no bloquea el programa
Call<List<Evento>> call = api.getEventos();
call.enqueue(new Callback<List<Evento>>() {
//3.1) En caso de obtener una respuesta correcta, http responce 200
@Override
public void onResponse(Call<List<Evento>> call, Response<List<Evento>> response) {
//3.2) Recojemos el resultadao de la peticion es decir el json
List<Evento> eventosList = response.body();
//3.3)Creamos un array de strings con el numero de eventos
String[] eventos = new String[eventosList.size()];
//Rellenamos el array con el Titulo del los eventos
for (int i = 0; i < eventosList.size(); i++) {
eventos[i] = eventosList.get(i).getTitulo();
}
//3.4) Asignamos el array de string al listview de la activity, simple_list_item_1 es el tipo de lista por defecto se puede diseñar una mas chuli
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, eventos));
}
//3.5) En caso de obtener una respuesta correcta, http responce 404 500 etc
@Override
public void onFailure(Call<List<Evento>> call, Throwable t) {
Log.d("error","Error fatal!!!!!");
}
});
}
}
| [
"[email protected]"
]
| |
f6a5a6035f6bd8a16df7efea8e0630e93306a779 | e1f39b8ef8326e6c5624799ff7116ad776fad9d1 | /src/test/java/pagesTest/firefoxtest.java | b6fc950257da662584dc2dda7c68d9c3756194d9 | []
| no_license | mohammad898/SeleniumTestNGextentReport | 94b4ca1f8018d68da036927aca5717fdf34aa324 | fb50b57390dac926c7a00f5af1540419cea2325a | refs/heads/master | 2023-05-11T05:03:02.075306 | 2019-12-16T05:40:58 | 2019-12-16T05:40:58 | 228,277,412 | 0 | 0 | null | 2023-05-09T18:17:14 | 2019-12-16T01:15:57 | HTML | UTF-8 | Java | false | false | 1,032 | java | package pagesTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
public class firefoxtest {
@Test
public void setup(){
WebDriver driver=null;
String projectPath=System.getProperty("user.dir");
System.setProperty("webdriver.gecko.driver",projectPath+ "\\browser-driver\\geckodriver.exe");
// System.setProperty("webdriver.gecko.driver", "C:\\Users\\mohammad.haque01\\Desktop\\Testing\\AmazanAutomation\\browser-driver\\geckodriver2.exe");
// DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// capabilities.setCapability("marionette",true);
//driver= new FirefoxDriver(capabilities);
driver= new FirefoxDriver();
// driver.manage().timeouts().pageLoadTimeout(25, TimeUnit.SECONDS);
driver.get("https://www.amazon.com/");
driver.manage().window().maximize();
}
}
| [
"[email protected]"
]
| |
ec78c760c5e4edecd05251c3bf831871def32b2a | d6bb8711815ad48e6af93d3d7c8923bcc5ede844 | /SpringBootNotes/src/main/java/com/springboot/notes/config/SpringBootConfig.java | e9afc9c91a3dafb20b0ed4fd5ee9169b6b1b411b | []
| no_license | Li-YunHai/PersonalCode | 835dc416286da0aa130d4c915c6f6e1af6038806 | 99a1133879da75c2b3cb2832caadf94168a5b957 | refs/heads/master | 2023-08-15T05:51:38.195684 | 2021-10-08T02:41:05 | 2021-10-08T02:41:05 | 411,565,545 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,533 | java | package com.springboot.notes.config;
import com.springboot.notes.model.Car;
import com.springboot.notes.model.Dog;
import com.springboot.notes.model.Person;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.*;
/**
* 1、配置类本身会注册到spring容器中
* 2、配置类中的bean都是单例的,包括其本身
* 3、proxyBeanMethods
* true:full重量级模式,先从容器中获取,没有则创建对象,并加入到容器中
* false:lite轻量级模式,总是创建新的对象
*/
//@Profile("test") //在这里指定当前配置类的生效环境
@Data
@Configuration
@AutoConfigureBefore(name = {"person"})
public class SpringBootConfig {
@Value("${JAVA_HOME}")
public String JAVA_HOME;
/**
* Spring容器管理对象的生命周期:
* 1、singleton单例模式模式在容器销毁后会自动调用destroyMethod销毁,prototype原型模式不会自动销毁
* 2、InitializingBean初始化接口、DisposableBean销毁对象接口
* 3、使用JSR250注解:@PostConstruct对象装配完成后执行、@PreDestroy对象销毁前执行
* 4、BeanPostProcessor后置处理器接口
* postProcessBeforeInitialization在容器中所有组件init初始化之前执行
* postProcessAfterInitialization在容器中所有组件init初始化之后执行
* @return
*/
@Bean(name = "dog", initMethod = "initMethod", destroyMethod = "destroyMethod")
@Scope("singleton") //singleton、prototype、request、session
@Lazy //懒加载,需与singleton配合使用,默认IOC容器初始化时不加载,第一次获取时才加载单例
public Dog dog(){
return new Dog();
}
@Bean(name = "car")
@DependsOn(value = {"person", "phone"})
@ConditionalOnClass(value = {Person.class}) //condition条件装配
@ConditionalOnBean(name = {"dog"}) //condition条件装配
//@ConditionalOnMissingBean(name = {"person"}) //condition条件装配
public Car car(){
return new Car();
}
}
| [
"[email protected]"
]
| |
6966efef282b326ea5cf56f10bf5995db79238c2 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/16/16_b53780954f6dbbe434eba23e1b1e9893238e60c8/StylesheetBuilder/16_b53780954f6dbbe434eba23e1b1e9893238e60c8_StylesheetBuilder_t.java | a623a8230a44eff1a3a67ec78c8cd31ce4cdd80a | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 10,456 | java | /*******************************************************************************
* Copyright (c) 2007 Chase Technology Ltd - http://www.chasetechnology.co.uk
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Doug Satchwell (Chase Technology Ltd) - initial API and implementation
* David Carver - fix issue with xslElm being null on local variables.
* David Carver (STAR) - bug 243577 - Added retrieving all called-templates.
*******************************************************************************/
package org.eclipse.wst.xsl.core.internal;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.eclipse.wst.xsl.core.XSLCore;
import org.eclipse.wst.xsl.core.internal.util.Debug;
import org.eclipse.wst.xsl.core.model.CallTemplate;
import org.eclipse.wst.xsl.core.model.Import;
import org.eclipse.wst.xsl.core.model.Include;
import org.eclipse.wst.xsl.core.model.Parameter;
import org.eclipse.wst.xsl.core.model.Stylesheet;
import org.eclipse.wst.xsl.core.model.Template;
import org.eclipse.wst.xsl.core.model.Variable;
import org.eclipse.wst.xsl.core.model.XSLAttribute;
import org.eclipse.wst.xsl.core.model.XSLElement;
import org.eclipse.wst.xsl.core.model.XSLNode;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A builder that creates and maintains a cache of <code>Stylesheet</code>'s.
*
* @author Doug Satchwell
*/
public class StylesheetBuilder {
private static StylesheetBuilder instance;
private final Map<IFile, Stylesheet> builtFiles = new HashMap<IFile, Stylesheet>();
private StylesheetBuilder() {
}
/**
* Get the <code>Stylesheet</code> associated with the given file. If either
* the <code>Stylesheet</code> has not yet been created or
* <code>force</code> is specified then the <code>Stylesheet</code> is
* built.
*
* @param file
* the XSL file
* @param force
* <code>true</code> to force a parse of the file
* @return the <code>Stylesheet</code>
*/
public Stylesheet getStylesheet(IFile file, boolean force) {
Stylesheet stylesheet = builtFiles.get(file);
if (stylesheet == null || force) {
stylesheet = build(file);
builtFiles.put(file, stylesheet);
}
return stylesheet;
}
private Stylesheet build(IFile file) {
long start = System.currentTimeMillis();
if (Debug.debugXSLModel) {
System.out.println("Building " + file + "...");
}
Stylesheet stylesheet = null;
IStructuredModel smodel = null;
try {
smodel = StructuredModelManager.getModelManager()
.getExistingModelForRead(file);
if (smodel == null) {
smodel = StructuredModelManager.getModelManager()
.getModelForRead(file);
if (Debug.debugXSLModel) {
long endParse = System.currentTimeMillis();
System.out.println("PARSE " + file + " in "
+ (endParse - start) + "ms");
}
} else if (Debug.debugXSLModel) {
long endParse = System.currentTimeMillis();
System.out.println("NO-PARSE " + file + " in "
+ (endParse - start) + "ms");
}
// start = System.currentTimeMillis();
if (smodel != null && smodel instanceof IDOMModel) {
IDOMModel model = (IDOMModel) smodel;
stylesheet = parseModel(model, file);
}
} catch (IOException e) {
XSLCorePlugin.log(e);
} catch (CoreException e) {
XSLCorePlugin.log(e);
} finally {
if (smodel != null)
smodel.releaseFromRead();
}
if (Debug.debugXSLModel) {
long end = System.currentTimeMillis();
System.out.println("BUILD " + file + " in " + (end - start) + "ms");
}
return stylesheet;
}
private Stylesheet parseModel(IDOMModel model, IFile file) {
IDOMDocument document = model.getDocument();
Stylesheet sf = new Stylesheet(file);
StylesheetParser walker = new StylesheetParser(sf);
walker.walkDocument(document);
return sf;
}
/**
* Get the singleton <code>StylesheetBuilder</code> instance.
*
* @return the <code>StylesheetBuilder</code> instance
*/
public static synchronized StylesheetBuilder getInstance() {
if (instance == null) {
instance = new StylesheetBuilder();
}
return instance;
}
private static class StylesheetParser {
private final Stylesheet sf;
private final Stack<Element> elementStack = new Stack<Element>();
private Template currentTemplate;
private Stack<CallTemplate> callTemplates = new Stack<CallTemplate>();
private XSLElement parentEl;
public StylesheetParser(Stylesheet stylesheet) {
this.sf = stylesheet;
}
public void walkDocument(IDOMDocument document) {
if (document.getDocumentElement() != null)
recurse(document.getDocumentElement());
}
private void recurse(Element element) {
XSLElement xslEl = null;
if (XSLCore.XSL_NAMESPACE_URI.equals(element.getNamespaceURI())) {
String elName = element.getLocalName();
if ("stylesheet".equals(elName) && elementStack.size() == 0) //$NON-NLS-1$
{
NamedNodeMap map = element.getAttributes();
String version = element.getAttribute("version");
sf.setVersion(version);
xslEl = sf;
} else if ("include".equals(elName) && elementStack.size() == 1) //$NON-NLS-1$
{
Include include = new Include(sf);
sf.addInclude(include);
xslEl = include;
} else if ("import".equals(elName) && elementStack.size() == 1) //$NON-NLS-1$
{
Import include = new Import(sf);
sf.addImport(include);
xslEl = include;
} else if ("template".equals(elName) && elementStack.size() == 1) //$NON-NLS-1$
{
currentTemplate = new Template(sf);
sf.addTemplate(currentTemplate);
xslEl = currentTemplate;
} else if ("param".equals(elName) && elementStack.size() == 2 && currentTemplate != null) //$NON-NLS-1$
{
Parameter param = new Parameter(sf);
// determine whether param has a value
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeType() != Node.ATTRIBUTE_NODE) {
param.setValue(true);
break;
}
}
currentTemplate.addParameter(param);
xslEl = param;
} else if ("call-template".equals(elName) && elementStack.size() >= 2) //$NON-NLS-1$
{
CallTemplate currentCallTemplate = new CallTemplate(sf);
callTemplates.push(currentCallTemplate);
sf.addCalledTemplate(currentCallTemplate);
xslEl = currentCallTemplate;
} else if ("with-param".equals(elName) && elementStack.size() >= 3 && callTemplates.size() > 0) //$NON-NLS-1$
{
Parameter param = new Parameter(sf);
// determine whether param has a value
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeType() != Node.ATTRIBUTE_NODE) {
param.setValue(true);
break;
}
}
// get the previous call-template
CallTemplate currentCallTemplate = callTemplates.peek();
currentCallTemplate.addParameter(param);
xslEl = param;
} else if ("variable".equals(elName)) //$NON-NLS-1$
{
if (elementStack.size() == 1)
{// global variable
Variable var = new Variable(sf);
sf.addGlobalVariable(var);
xslEl = var;
}
else if (elementStack.size() > 1 && currentTemplate != null)
{// local variable
Variable var = new Variable(sf);
currentTemplate.addVariable(var);
xslEl = var;
}
}
else {
xslEl = new XSLElement(sf);
}
if (xslEl!=null)
configure((IDOMNode) element, xslEl);
}
elementStack.push(element);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
recurse((Element) node);
}
}
if (xslEl instanceof CallTemplate)
callTemplates.pop();
elementStack.pop();
// currentTemplate = null;
// currentCallTemplate = null;
}
private void configure(IDOMNode node, XSLElement element) {
setPositionInfo(node, element);
IDOMElement domElem = (IDOMElement) node;
element.setName(domElem.getLocalName());
NamedNodeMap map = node.getAttributes();
for (int i = 0; i < map.getLength(); i++) {
IDOMAttr attr = (IDOMAttr) map.item(i);
XSLAttribute xslatt = new XSLAttribute(element, attr.getName(),
attr.getValue());
setPositionInfo(attr, xslatt);
element.setAttribute(xslatt);
}
if (parentEl != null)
parentEl.addChild(element);
parentEl = element;
}
private static void setPositionInfo(IDOMNode node, XSLNode inc) {
try {
IStructuredDocument structuredDocument = node
.getStructuredDocument();
int line = structuredDocument.getLineOfOffset(node
.getStartOffset());
int lineOffset = structuredDocument.getLineOffset(line);
int col = node.getStartOffset() - lineOffset;
inc.setOffset(node.getStartOffset());
inc.setLineNumber(line);
inc.setColumnNumber(col);
inc.setLength(node.getLength());
} catch (BadLocationException e) {
XSLCorePlugin.log(e);
}
}
}
}
| [
"[email protected]"
]
| |
b120f5b3546bff2a4414b926415d0cb1ab453f63 | 5b352b2d8231c2b97f1295ecf4612a0d7293e7fd | /e3-sso-web/src/main/java/com/e3mall/sso/controller/RegisterController.java | f3ccd3b3b5b5ff9e77cdda01023d479b87d8aba7 | []
| no_license | bean95/e3mall-soa | 23451512e9cc11110f70fbe0cfb94cc385145c60 | 1f58d0f9f5dc2a7f87653610515a8563648c5048 | refs/heads/master | 2023-02-02T05:27:13.109656 | 2020-12-16T08:43:03 | 2020-12-16T08:43:03 | 306,545,996 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,110 | java | package com.e3mall.sso.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.e3mall.common.utils.E3Result;
import com.e3mall.pojo.TbUser;
import com.e3mall.sso.service.RegisterService;
@Controller
public class RegisterController {
@Autowired
private RegisterService registerServiceImpl;
@RequestMapping("/page/register")
public String regiester() {
return "register";
}
@RequestMapping("/user/check/{param}/{type}")
@ResponseBody
public E3Result checkData(@PathVariable("param") String param,@PathVariable("type") Integer type) {
return registerServiceImpl.checkData(param, type);
}
@RequestMapping(value= "/user/register",method = RequestMethod.POST)
@ResponseBody
public E3Result register(TbUser user){
return registerServiceImpl.register(user);
}
}
| [
"[email protected]"
]
| |
e2d817c80a281a2460a852dcfff8d01cd84a7ace | 5418a427fca8d6bebf4b6e1f6a36ed07cc0cc11c | /src/anotaciones/VeryImportant.java | e677935161c65ebb5661d41dd9921cfedba6b361 | []
| no_license | musiciancoder/javaPruebas | 4c9bcfd4d4feaa14d9205b5297a9072014f3bd62 | 92105be0f439096b5b4bcbe75fdd3f9e605b12e4 | refs/heads/master | 2023-02-22T02:20:02.441697 | 2023-02-10T14:23:36 | 2023-02-10T14:23:36 | 279,767,652 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 229 | java | package anotaciones;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
public @interface VeryImportant {
String stringPrueba = "soy variable stringPrueba";
}
| [
"[email protected]"
]
| |
fb78cd26ccc9c63b3e874d3f163e8aab1c7f288e | 2a4d3c2940fbaed91478064ad7093aa90fd177c8 | /pki-management/src/main/java/com/multicert/project/v2x/pkimanager/model/Vehicle.java | d59b195219a4a568ef8ab05700b6aaa182801c1a | []
| no_license | LeonardoGoncalves94/chamenta3 | 5af238f744fd053c0376bce17a3ab1dd34f15c0c | fbda76fe79bf412adf61c14dbf0e04f78fe4bc69 | refs/heads/master | 2022-12-21T05:18:27.265479 | 2019-12-14T22:24:05 | 2019-12-14T22:24:05 | 149,788,813 | 1 | 1 | null | 2022-12-10T04:45:06 | 2018-09-21T16:20:40 | Java | UTF-8 | Java | false | false | 1,819 | java | package com.multicert.project.v2x.pkimanager.model;
import java.security.PublicKey;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Entity;
import javax.persistence.FetchType;
@Entity
@Table(name = "vehicle")
public class Vehicle {
public Vehicle(String vehicleId, PublicKey publicKey, Profile profile) {
super();
this.vehicleId = vehicleId;
this.canonicalPublicKey = publicKey;
this.profile = profile;
}
public Vehicle() {
}
@Id
@Column(name="vehicle_id")
@Length(min = 5, max = 20)
@NotEmpty
private String vehicleId;
@Column(name="pubKey")
private PublicKey canonicalPublicKey;
@Column(name="at_count")
private int aTCount = 0;
public int getaTCount() {
return aTCount;
}
public void setaTCount(int aTCount) {
this.aTCount = aTCount;
}
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name="profile_name", nullable=false)
private Profile profile;
public String getVehicleId() {
return vehicleId;
}
public void setVehicleId(String vehicleId) {
this.vehicleId = vehicleId;
}
public PublicKey getPublicKey() {
return canonicalPublicKey;
}
public void setPublicKey(PublicKey publicKey) {
this.canonicalPublicKey = publicKey;
}
public PublicKey getCanonicalPublicKey() {
return canonicalPublicKey;
}
public void setCanonicalPublicKey(PublicKey canonicalPublicKey) {
this.canonicalPublicKey = canonicalPublicKey;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
| [
"[email protected]"
]
| |
e4adbc0324877b46e12d265b0f486ac00ea5eed6 | 9b578a67b8ff69b943764fc34e7ae3030a77adb0 | /src/connection/DatabaseConnection.java | c07318c0ca3ca74bda18d23a941052de0bc5f6f2 | []
| no_license | sadhanaa/UniversityRecordSystem | 08d0637a4743026c5f3ca016d68499526e54d546 | 3b651ecf204b644657e3e4a2ae67fa990ed1aaf2 | refs/heads/master | 2020-05-18T00:22:36.399981 | 2013-05-05T09:24:25 | 2013-05-05T09:24:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 30,690 | java | package connection;
import java.sql.*;
import java.util.*;
import entity.Course;
import entity.Person;
import entity.Instructor;
import entity.PersonCourseMap;
import connection.Configuration;
import com.sun.security.auth.login.ConfigFile;
public class DatabaseConnection {
Connection con = null;
ResultSet rs, rs1, rs2, rs3;
ConnectionPool connectionPool = null;
PreparedStatement ps, ps1, ps2, ps3;
public DatabaseConnection() {
// CP: Connection pooling start
/* connectionPool = ConnectionPool.getInstance();
try {
con =connectionPool.getConnection();
if (!con.isClosed())
System.out.println("Successfully Connected!!!");
}catch (SQLException e)
{ // TODO Auto-generated catch block
e.printStackTrace();
}
*/
// reular without connection pool
try {
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// con = DriverManager.getConnection(
// "jdbc:mysql://localhost:3306/cmpe273", "root", "root");
// if (!con.isClosed()) {
// System.out.println("Successfully Connected!!!");
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// VIEW ALL PERSONS : TRUPTI
public Person[] ViewAllPersons() throws SQLException {
String query;
String querycount;
int Count = 0;
int index = 0;
Person[] allpersons = null;
try {
query = "select * from person";
querycount = "select count(1) from person";
ps = con.prepareStatement(querycount);
rs = ps.executeQuery();
if (rs.next()) {
Count = rs.getInt(1);
}
allpersons = new Person[Count];
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
Person person = new Person();
person.setPersonId(rs.getLong("idperson"));
person.setPassword(rs.getString("pass"));
person.setFirstName(rs.getString("fname"));
person.setLastName(rs.getString("lname"));
person.setAddress(rs.getString("address"));
person.setCity(rs.getString("city"));
person.setState(rs.getString("state"));
person.setZipCode(rs.getString("zipcode"));
person.setPersonType(rs.getString("persontype"));
allpersons[index] = person;
index++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return allpersons;
}
// VIEW ALL STUDENTS : TRUPTI
public Person[] ViewAllStudents() throws SQLException {
String query;
String querycount;
int Count = 0;
int index = 0;
Person[] allstudents = null;
try {
query = "select * from person where persontype = 'S'";
querycount = "select count(1) from person";
ps = con.prepareStatement(querycount);
rs = ps.executeQuery();
if (rs.next()) {
Count = rs.getInt(1);
}
allstudents = new Person[Count];
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
Person student = new Person();
student.setPersonId(rs.getLong("idperson"));
student.setPassword(rs.getString("pass"));
student.setFirstName(rs.getString("fname"));
student.setLastName(rs.getString("lname"));
student.setAddress(rs.getString("address"));
student.setCity(rs.getString("city"));
student.setState(rs.getString("state"));
student.setZipCode(rs.getString("zipcode"));
student.setPersonType(rs.getString("persontype"));
allstudents[index] = student;
index++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return allstudents;
}
// VIEW ALL INSTRUCTURS : TRUPTI
public Instructor[] ViewAllInstructors() throws SQLException {
String query, query2;
String querycount;
int Count = 0;
int index = 0;
Instructor[] allinstructor = null;
try {
query = "select * from person where persontype = 'I'";
querycount = "select count(1) from person";
query2 = "select * from instructor";
ps = con.prepareStatement(querycount);
rs = ps.executeQuery();
if (rs.next()) {
Count = rs.getInt(1);
}
allinstructor = new Instructor[Count];
ps = con.prepareStatement(query);
rs = ps.executeQuery();
ps1 = con.prepareStatement(query2);
rs1 = ps1.executeQuery();
while (rs.next()) {
Instructor instructor = new Instructor();
instructor.setPersonId(rs.getLong("idperson"));
instructor.setPassword(rs.getString("pass"));
instructor.setFirstName(rs.getString("fname"));
instructor.setLastName(rs.getString("lname"));
instructor.setAddress(rs.getString("address"));
instructor.setCity(rs.getString("city"));
instructor.setState(rs.getString("state"));
instructor.setZipCode(rs.getString("zipcode"));
instructor.setPersonType(rs.getString("persontype"));
if (rs1.next()) {
instructor.setDepartment(rs1.getString("department"));
instructor.setOffficeHr(rs1.getString("officeHr"));
instructor.setLocation(rs1.getString("location"));
}
allinstructor[index] = instructor;
index++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
ps1.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return allinstructor;
}
// DISPLAY COURSE INFORMATION : TRUPTI
public Course CourseDetail(long idcourse) throws SQLException {
String query = "";
String query1 = "";
String query2 = "";
String query3 = "";
Course courseInfo = new Course();
List<Instructor> instructorInfo = new ArrayList<Instructor>();
int index = 0;
long[] personid = null;
try {
query = "select * from course where idcourse= ?";
ps = con.prepareStatement(query);
ps.setLong(1, idcourse);
rs = ps.executeQuery();
if (rs.next()) {
courseInfo = new Course();
courseInfo.setCourseId(rs.getInt(1));
courseInfo.setName(rs.getString(2));
courseInfo.setSection(rs.getString(3));
courseInfo.setHours(rs.getString(4));
courseInfo.setLocation(rs.getString(5));
} else {
System.out.println("Course with id = " + idcourse
+ " does not exist.");
return null;
}
query1 = "select idperson from personcoursemap where idcourse = ?";
query2 = "select fname, lname from person where idperson = ? and persontype='I'";
query3 = "select * from instructor where idperson= ?";
// search for the all related person to course
ps1 = con.prepareStatement(query1);
ps1.setLong(1, idcourse);
rs1 = ps1.executeQuery();
// get the count of no of persons related to course
int count = 0;
while (rs1.next()) {
count++;
}
personid = new long[count];
rs1.beforeFirst();// reset pointer on top of the list
while (rs1.next()) {
personid[index] = rs1.getInt(1);
index++;
}
for (int i = 0; i < index - 1; i++) {
Instructor tempInstructor = new Instructor();
// get instructor name info
ps2 = con.prepareStatement(query2);
ps2.setLong(1, personid[i]);
rs2 = ps2.executeQuery();
if (rs2.next()) {
tempInstructor.setFirstName(rs2.getString(1));
tempInstructor.setLastName(rs2.getString(2));
// get instructor official detail
ps3 = con.prepareStatement(query3);
ps3.setLong(1, personid[i]);
rs3 = ps3.executeQuery();
if (rs3.next()) {
tempInstructor.setPersonId(rs3.getLong(1));
tempInstructor.setDepartment(rs3.getString(2));
tempInstructor.setOffficeHr(rs3.getString(3));
tempInstructor.setLocation(rs3.getString(4));
}
}
instructorInfo.add(tempInstructor);
}
courseInfo.setCourseTeachers(instructorInfo
.toArray(new Instructor[instructorInfo.size()]));
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
ps1.close();
ps2.close();
ps3.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return courseInfo;
}
// DISPLAY PERSON INFORMATION : TRUPTI
public Person PersonDetail(long idperson) throws SQLException {
String query,query1= "";
Person personInfo = null;
try {
query = "select * from person where idperson= ?";
ps = con.prepareStatement(query);
ps.setLong(1, idperson);
rs = ps.executeQuery();
if (rs.next()) {
personInfo = new Person();
personInfo.setPersonId(rs.getInt(1));
personInfo.setPassword(rs.getString(2));
personInfo.setFirstName(rs.getString(3));
personInfo.setLastName(rs.getString(4));
personInfo.setAddress(rs.getString(5));
personInfo.setCity(rs.getString(6));
personInfo.setState(rs.getString(7));
personInfo.setZipCode(rs.getString(8));
personInfo.setPersonType(rs.getString(9));
if(personInfo.getPersonType().equals("I"))
{
query1 = "select * from instructor where idperson= ?";
ps1 = con.prepareStatement(query1);
ps1.setLong(1, idperson);
rs1= ps1.executeQuery();
if(rs1.next())
{
Instructor instructorinfo = new Instructor();
instructorinfo.setPersonId(rs1.getLong(1));
instructorinfo.setDepartment(rs1.getString(2));
instructorinfo.setOffficeHr(rs1.getString(3));
instructorinfo.setLocation(rs1.getString(4));
personInfo.setInstructor(instructorinfo);
}
else
{
System.out.println("Intsructor detail for Intsructor with id = " + idperson
+ " didn't found.");
}
}
} else {
System.out.println("Person with id = " + idperson
+ " does not exist.");
return null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
ps1.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return personInfo;
}
// UPDATE PERSON : TRUPTI
public boolean UpdatePerson(long idperson, String pass, String fname,
String lname, String address, String city, String state,
String zipcode, String persontype, String department, String officeHr, String location) throws SQLException {
int rowcount = 0;
boolean result = false;
String query,query1="";
try {
ps = (PreparedStatement) con
.prepareStatement("update person set pass=?, fname=?, lname=?, address=?, city=?, state=?, zipCode=?, persontype =? where idperson=?");
ps.setString(1, pass);
ps.setString(2, fname);
ps.setString(3, lname);
ps.setString(4, address);
ps.setString(5, city);
ps.setString(6, state);
ps.setString(7, zipcode);
ps.setString(8, persontype);
ps.setLong(9, idperson);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
if(persontype =="I")
{
query ="select * from instructor where idperson =?";
ps1 =con.prepareStatement(query);
ps1.setLong(1, idperson);
rs1=ps1.executeQuery();
if(rs1.next())
{
query1 = "update instructor set department=?, officeHr=?, location=? where idperson=?";
ps2=con.prepareStatement(query1);
ps2.setString(1, department);
ps2.setString(2,officeHr);
ps2.setString(3, location);
ps2.setLong(4, idperson);
rowcount =0;
rowcount =ps2.executeUpdate();
if(rowcount>0)
{
result=true;
}
}
else
{
query1="insert into instructor (idperson,department,officeHr,location) values(?,?,?,?)";
ps2=con.prepareStatement(query1);
ps2.setLong(1, idperson);
ps2.setString(2, department);
ps2.setString(3,officeHr);
ps2.setString(4, location);
rowcount = 0;
rowcount =ps2.executeUpdate();
if(rowcount>0)
{
result=true;
}
}
}
else
result= true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
ps1.close();
ps2.close();
// connectionPool.free(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
// ***********************************************************************************
// CREATE STUDENT : VINISHA
public long createStudent(String pass, String fname, String lname,
String address, String city, String state, String zipcode,
String persontype) {
int rowcount = 0;
boolean result = false;
long studentId = -1;
try {
ps = (PreparedStatement) con
.prepareStatement("insert into person(pass, fname, lname, address, city, state, zipcode, persontype) VALUES(?,?,?,?,?,?,?,?)");
ps.setString(1, pass);
ps.setString(2, fname);
ps.setString(3, lname);
ps.setString(4, address);
ps.setString(5, city);
ps.setString(6, state);
ps.setString(7, zipcode);
ps.setString(8, persontype);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("New Student has been created....");
}
if(result)
{
ps = (PreparedStatement) con
.prepareStatement("select idperson from person where fname= ? and lname = ? and zipcode = ?");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, zipcode);
rs = ps.executeQuery();
if (rs.next()) {
studentId = rs.getInt(1);
} else {
System.out.println("Person with fname= " + fname + ", lname= " + lname+ ", zipcode= "+zipcode
+ " does not exist.");
return studentId;
}
}
else
{
System.out.println("New student unable to create....");
return studentId;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return studentId;
}
// REMOVE/REPLACE Instructor: VINISHA
public boolean removeReplaceInstructor(long removeInsructor,
long replaceInstructor, long idcourse) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con
.prepareStatement("UPDATE personcoursemap SET idperson= ? WHERE idperson=? and idcourse=?");
ps.setLong(1, replaceInstructor);
ps.setLong(2, removeInsructor);
ps.setLong(3, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Instructor with ID: " + removeInsructor
+ "has been replaced with" + replaceInstructor
+ "for course ID: " + idcourse);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
// DELETE STUDENT:VINISHA
public boolean deleteStudent(long idperson) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con
.prepareStatement("delete from person where idperson=?");
ps.setLong(1, idperson);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Student with ID: " + idperson + "has been deleted...");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
// CREATE INSTRUCTOR:VINISHA
public boolean createInstructor(String pass, String fname, String lname,
String address, String city, String state, String zipcode,
String persontype, String department, String officeHr, String location) {
int rowcount = 0;
boolean result = false;
try {
long idperson = this.createStudent(pass, fname, lname, address, city, state, zipcode, persontype);
if(idperson != -1)
{
}
else
{
System.out.println("Not able to create record into person table........");
}
ps = (PreparedStatement) con
.prepareStatement("insert into instructor(idperson, department, officeHr, location) VALUES(?,?,?,?)");
ps.setLong(1, idperson);
ps.setString(2, department);
ps.setString(3, officeHr);
ps.setString(4, location);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("New Instructor has been created....");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
// DELETE INSTRUCTOR: VINISHA
public boolean deleteInstructor(long idperson) {
boolean result = false;
result = deleteStudent(idperson);
if(result)
{
System.out.println("Instructor: " + idperson + " has been deleted");
}
else{
System.out.println("Error in delerint Instructor: " + idperson );
}
return result;
}
// ASSIGN COURSE TO INSTRUCTOR : VINISHA
public boolean assignCourseToInstructor(long idperson, long idcourse) {
int rowcount = 0;
boolean result = false;
long studentId = -1;
try {
ps = (PreparedStatement) con
.prepareStatement("insert into personcoursemap(idperson, idcourse) VALUES(?,?)");
ps.setLong(1, idperson);
ps.setLong(2, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Course" + idcourse + " has been Assigned to " + idperson);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//VIEW ALL COURSES : VINISHA
public Course[] viewAllCourse(){
String query;
String countQuery;
int Count = 0;
int index=0;
Course[] courseInfo = null;
try {
query = "select * from course";
countQuery = "select count(1) from course";
ps= con.prepareStatement(countQuery);
rs= ps.executeQuery();
if (rs.next()) {
Count = rs.getInt(1);
}
courseInfo = new Course[Count];
ps= con.prepareStatement(query);
rs= ps.executeQuery();
while (rs.next()) {
Course course = new Course();
course.setCourseId(rs.getInt(1));
course.setName(rs.getString(2));
course.setSection(rs.getString(3));
course.setHours(rs.getString(4));
course.setLocation(rs.getString(5));
courseInfo[index] = course;
index++;
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return courseInfo;
}
// GET ADMIN :VINISHA
public String getAdminUname()
{
return Configuration.ADMIN_UNAME;
}
public String getAdminPass()
{
return Configuration.ADMIN_PASS;
}
//******************************************************************************************************************************************************************
// UPDATE COURSE : HETAL
public boolean UpdateCourse(long idcourse, String name, String section,
String hours, String loc) throws SQLException {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con
.prepareStatement("update course set name=?, section=?, hours=?, loc=? where idcourse=?");
ps.setString(1, name);
ps.setString(2, section);
ps.setString(3, hours);
ps.setString(4, loc);
ps.setLong(5, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//DELETE COURSE :HETAL
public boolean deleteCourse(long idcourse) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con
.prepareStatement("delete from course where idcourse=?");
ps.setLong(1, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Course with ID: " + idcourse + " has been deleted...");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//CREATE COURSE :HETAL
public boolean createCourse(String name, String section, String hours,
String loc) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con
.prepareStatement("insert into course(name, section, hours, loc) VALUES(?,?,?,?)");
ps.setString(1, name);
ps.setString(2, section);
ps.setString(3, hours);
ps.setString(4, loc);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("New Course has been created....");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//ENROLL A STUDENT:HETAL
public boolean enrollStudent(long idperson, long idcourse) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con.prepareStatement("insert into personcoursemap(idperson, idcourse) VALUES(?,?)");
ps.setLong(1, idperson);
ps.setLong(2, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Student " + idperson + " has been enrolled to " + idcourse);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//UNENROLL A STUDENT:HETAL
public boolean unenrollStudent(long idperson, long idcourse) {
int rowcount = 0;
boolean result = false;
try {
ps = (PreparedStatement) con.prepareStatement("delete from personcoursemap where idperson =? and idcourse=?");
ps.setLong(1, idperson);
ps.setLong(2, idcourse);
rowcount = ps.executeUpdate();
if (rowcount > 0) {
result = true;
System.out.println("Student " + idperson + " has been unenrolled from the course " + idcourse);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// connectionPool.free(con);
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
//SEARCH PERSON :HETAL
public Person[] searchPerson(String attributeName, String attributeValue) throws SQLException
{
String query="";
int index=0, count=0;
Person[] personInfo = null;
try{
query="select count(1) from person where "+attributeName+" LIKE '"+attributeValue+"%'"; // also check by having % in the beginning
ps= con.prepareStatement(query);
rs= ps.executeQuery();
System.out.println(query);
if (rs.next()) {
count = rs.getInt(1);
}
personInfo = new Person[count];
query = "select * from movie where "+attributeName+" LIKE '"+attributeValue+"%'"; // also check by having % in the beginning
ps=con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next())
{
Person person = new Person();
person.setPersonId(rs.getLong(1));
person.setPassword(rs.getString(2));
person.setFirstName(rs.getString(3));
person.setAddress(rs.getString(4));
person.setCity(rs.getString(5));
person.setState(rs.getString(6));
person.setPersonType(rs.getString(7));
personInfo[index] = person;
index++;
System.out.println(person.getPersonId()+" "+person.getPassword()+" "+person.getFirstName()+" "+person.getLastName()+ " " +
" "+person.getAddress()+" "+person.getCity()+" "+person.getState()+" "+person.getZipCode()+" "+person.getPersonType());
}
if(index>0)
{
System.out.println("Person found");
}
else
{
System.out.println("Person not found");
return null;
}
}
catch (SQLException e) {
e.printStackTrace();
}finally{
//connectionPool.free(con);
ps.close();
}
return personInfo;
}
//SEARCH Course :HETAL
public Course[] searchCourse(String attributeName, String attributeValue) throws SQLException
{
String query="";
int index=0, count=0;
Course[] courseInfo = null;
try{
query="select count(1) from course where "+attributeName+" LIKE '"+attributeValue+"%'"; // also check by having % in the beginning
ps= con.prepareStatement(query);
rs= ps.executeQuery();
System.out.println(query);
if (rs.next()) {
count = rs.getInt(1);
}
courseInfo = new Course[count];
query = "select * from course where "+attributeName+" LIKE '"+attributeValue+"%'"; // also check by having % in the beginning
ps=con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next())
{
Course course = new Course();
course.setCourseId(rs.getLong(1));
course.setName(rs.getString(2));
course.setSection(rs.getString(3));
course.setHours(rs.getString(4));
course.setLocation(rs.getString(5));
courseInfo[index] = course;
index++;
System.out.println(course.getCourseId()+" "+course.getName()+" "+course.getSection()+" "+course.getHours()+ " " +
" "+course.getLocation());
}
if(index>0)
{
System.out.println("Course found");
}
else
{
System.out.println("Course not found");
return null;
}
}
catch (SQLException e) {
e.printStackTrace();
}finally{
//connectionPool.free(con);
ps.close();
}
return courseInfo;
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.