blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
sequence | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2cb577c303d97371e5df3bacf398fa3452d7145d | 10,299,331,595,385 | 60696057c920e5cadf16f10135c34112ec35b232 | /referencedata2-api/src/main/java/com/portbase/referencedata/api/spring/MvcConfig.java | 125444d282a7635465836e33ed8a93e66123f6d8 | [] | no_license | suna4it/ref-api | https://github.com/suna4it/ref-api | 67d1eed37a7b533900b1f6737621a7e6447ac1e6 | 5b8582aac6fda7625d51597a5dd4cc753b536339 | refs/heads/master | 2017-08-02T05:20:47.573000 | 2017-02-13T13:58:18 | 2017-02-13T13:58:18 | 81,207,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Ident: Portbase Port Community System
* Copyright (c) Portbase bv 2014. All Rights Reserved.
* ------------------------------------------------------------------------------
* Portbase bv * No part of this file may be reproduced or
* * transmitted, in any form or by any means,
* Seattleweg 7 * electronic, mechanical or otherwise,
* 3195 ND Rotterdam * without prior written permission of the
* The Netherlands * copyright holder.
* ------------------------------------------------------------------------------
*/
package com.portbase.referencedata.api.spring;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Java Config for Spring MVC.
*/
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(true);
messageConverter.getObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
converters.add(messageConverter);
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setIgnoreResourceNotFound(true);
ResourceLoader resourceLoader = new DefaultResourceLoader();
configurer.setLocations(resourceLoader.getResource("spring/service-default.properties"),
resourceLoader.getResource("referencedata2-api.properties"));
return configurer;
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
}
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public HttpClient httpClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
HttpClient defaultHttpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
return defaultHttpClient;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
| UTF-8 | Java | 3,615 | java | MvcConfig.java | Java | [] | null | [] | /*
* Ident: Portbase Port Community System
* Copyright (c) Portbase bv 2014. All Rights Reserved.
* ------------------------------------------------------------------------------
* Portbase bv * No part of this file may be reproduced or
* * transmitted, in any form or by any means,
* Seattleweg 7 * electronic, mechanical or otherwise,
* 3195 ND Rotterdam * without prior written permission of the
* The Netherlands * copyright holder.
* ------------------------------------------------------------------------------
*/
package com.portbase.referencedata.api.spring;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Java Config for Spring MVC.
*/
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(true);
messageConverter.getObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
converters.add(messageConverter);
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setIgnoreResourceNotFound(true);
ResourceLoader resourceLoader = new DefaultResourceLoader();
configurer.setLocations(resourceLoader.getResource("spring/service-default.properties"),
resourceLoader.getResource("referencedata2-api.properties"));
return configurer;
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
}
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public HttpClient httpClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
HttpClient defaultHttpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
return defaultHttpClient;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
| 3,615 | 0.756846 | 0.75325 | 92 | 38.29348 | 33.856327 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.467391 | false | false | 4 |
0cc922eaed59a52e57d7327a5961a986a471e34d | 26,147,760,928,488 | 33d4f05a358a94aeee0473b079d3912f95b7501d | /core/src/main/java/tech/tongyu/bct/report/client/service/ClientReportInputService.java | b0f849ffc2b8246ee8a7f5beb8d46e91f002f01c | [] | no_license | moutainhigh/jkzx1 | https://github.com/moutainhigh/jkzx1 | e45bc70504c9610233747f44811cfef3709a8b6d | f9f87e9477364c5f1926241ca23a797357b7f275 | refs/heads/master | 2023-05-14T16:42:23.946000 | 2021-04-10T03:45:15 | 2021-04-10T03:45:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tech.tongyu.bct.report.client.service;
import java.util.List;
import java.util.Map;
public interface ClientReportInputService {
void createPnlReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createPnlHstReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createPositionReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createOtcTradeReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createFinancialOtcFundDetailReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createFinanicalOtcClientFundReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createHedgePnlReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createProfitStatisicsReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createStatisticsOfRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSubjectComputingReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskDetailReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSubsidiaryMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createCounterPartyMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createCounterPartyMarketRiskByUnderlyerReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskBySubUnderlyerReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSpotScenariosReport(List<Map<String, Object>> reports, String valuationDate);
} | UTF-8 | Java | 2,186 | java | ClientReportInputService.java | Java | [] | null | [] | package tech.tongyu.bct.report.client.service;
import java.util.List;
import java.util.Map;
public interface ClientReportInputService {
void createPnlReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createPnlHstReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createPositionReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createOtcTradeReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createFinancialOtcFundDetailReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createFinanicalOtcClientFundReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createHedgePnlReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createProfitStatisicsReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createStatisticsOfRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSubjectComputingReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskDetailReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSubsidiaryMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createCounterPartyMarketRiskReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createCounterPartyMarketRiskByUnderlyerReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createMarketRiskBySubUnderlyerReport(List<Map<String, Object>> reports, String reportName, String valuationDate);
void createSpotScenariosReport(List<Map<String, Object>> reports, String valuationDate);
} | 2,186 | 0.800092 | 0.800092 | 43 | 49.860466 | 53.73777 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.72093 | false | false | 4 |
7fb07b5706f34dd44d3e4b645076fd2d17e50376 | 4,621,384,852,179 | 096e2aac2ab039b4d70653dc067a12e064db6ce4 | /src/main/java/com/betsegaw/cssis/enums/Status.java | 416b7f99a0602c063aa7a08834ef21f2b3aaebc6 | [] | no_license | betsegawlemma/cssis | https://github.com/betsegawlemma/cssis | 5a51eae9deebd02a1a443d922f99cff0d8d6f3f5 | 973899e153a94949afd2be8acde83581cf601b5e | refs/heads/master | 2021-09-04T02:17:03.672000 | 2018-01-14T14:34:41 | 2018-01-14T14:34:41 | 113,874,166 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.betsegaw.cssis.enums;
public enum Status {
PROMOTED, FAILED, TERMINATED, TRANSFERED, WITHDRAWAL, NEW;
}
| UTF-8 | Java | 121 | java | Status.java | Java | [] | null | [] | package com.betsegaw.cssis.enums;
public enum Status {
PROMOTED, FAILED, TERMINATED, TRANSFERED, WITHDRAWAL, NEW;
}
| 121 | 0.752066 | 0.752066 | 5 | 23.200001 | 22.990433 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 4 |
ac4dba5c9967b40e7efa1dce7c2b5ae841336a97 | 27,848,567,950,413 | 2d9957f2c7a6883004b1a801f97eab3b033d9c08 | /pulsar-client/src/test/java/org/apache/pulsar/client/impl/auth/oauth2/protocol/TokenClientTest.java | 2e71e327ccddec368be118b40a26413adf51f7bd | [
"Apache-2.0",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-protobuf"
] | permissive | apache/pulsar | https://github.com/apache/pulsar | ca729cfb8d2c031312d30096e13431b2e29fb9bf | 843b8307f44cd5e3a2d59ab93cc6b766f0c4ce0f | refs/heads/master | 2023-08-31T23:53:41.323000 | 2023-08-31T18:37:00 | 2023-08-31T18:37:00 | 62,117,812 | 11,865 | 3,546 | Apache-2.0 | false | 2023-09-14T12:13:23 | 2016-06-28T07:00:03 | 2023-09-14T10:57:22 | 2023-09-14T12:13:23 | 194,624 | 13,102 | 3,393 | 1,175 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl.auth.oauth2.protocol;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertNotNull;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import org.testng.annotations.Test;
/**
* Token client exchange token mock test.
*/
public class TokenClientTest {
@Test
@SuppressWarnings("unchecked")
public void exchangeClientCredentialsSuccessByScopeTest() throws
IOException, TokenExchangeException, ExecutionException, InterruptedException {
DefaultAsyncHttpClient defaultAsyncHttpClient = mock(DefaultAsyncHttpClient.class);
URL url = new URL("http://localhost");
TokenClient tokenClient = new TokenClient(url, defaultAsyncHttpClient);
ClientCredentialsExchangeRequest request = ClientCredentialsExchangeRequest.builder()
.audience("test-audience")
.clientId("test-client-id")
.clientSecret("test-client-secret")
.scope("test-scope")
.build();
String body = tokenClient.buildClientCredentialsBody(request);
BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
Response response = mock(Response.class);
ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(defaultAsyncHttpClient.preparePost(url.toString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Accept", "application/json")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(body)).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
TokenResult tokenResult = new TokenResult();
tokenResult.setAccessToken("test-access-token");
tokenResult.setIdToken("test-id");
when(response.getResponseBodyAsBytes()).thenReturn(new Gson().toJson(tokenResult).getBytes());
TokenResult tr = tokenClient.exchangeClientCredentials(request);
assertNotNull(tr);
}
@Test
@SuppressWarnings("unchecked")
public void exchangeClientCredentialsSuccessWithoutOptionalClientCredentialsTest() throws
IOException, TokenExchangeException, ExecutionException, InterruptedException {
DefaultAsyncHttpClient defaultAsyncHttpClient = mock(DefaultAsyncHttpClient.class);
URL url = new URL("http://localhost");
TokenClient tokenClient = new TokenClient(url, defaultAsyncHttpClient);
ClientCredentialsExchangeRequest request = ClientCredentialsExchangeRequest.builder()
.clientId("test-client-id")
.clientSecret("test-client-secret")
.build();
String body = tokenClient.buildClientCredentialsBody(request);
BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
Response response = mock(Response.class);
ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(defaultAsyncHttpClient.preparePost(url.toString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Accept", "application/json")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(body)).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
TokenResult tokenResult = new TokenResult();
tokenResult.setAccessToken("test-access-token");
tokenResult.setIdToken("test-id");
when(response.getResponseBodyAsBytes()).thenReturn(new Gson().toJson(tokenResult).getBytes());
TokenResult tr = tokenClient.exchangeClientCredentials(request);
assertNotNull(tr);
}
}
| UTF-8 | Java | 5,322 | java | TokenClientTest.java | Java | [
{
"context": "(\"test-client-id\")\n .clientSecret(\"test-client-secret\")\n .scope(\"test-scope\")\n ",
"end": 2077,
"score": 0.732072114944458,
"start": 2059,
"tag": "KEY",
"value": "test-client-secret"
},
{
"context": "okenResult();\n tokenResult.setAccessToken(\"test-access-token\");\n tokenResult.setIdToken(\"test-id\");\n ",
"end": 3142,
"score": 0.6628260612487793,
"start": 3125,
"tag": "KEY",
"value": "test-access-token"
},
{
"context": "t-access-token\");\n tokenResult.setIdToken(\"test-id\");\n when(response.getResponseBodyAsBytes()",
"end": 3185,
"score": 0.9001312851905823,
"start": 3178,
"tag": "KEY",
"value": "test-id"
},
{
"context": "okenResult();\n tokenResult.setAccessToken(\"test-access-token\");\n tokenResult.setIdToken(\"t",
"end": 5051,
"score": 0.5023474097251892,
"start": 5047,
"tag": "KEY",
"value": "test"
},
{
"context": "Result();\n tokenResult.setAccessToken(\"test-access-token\");\n tokenResult.setIdToken(\"test-id\");\n ",
"end": 5064,
"score": 0.6051312685012817,
"start": 5052,
"tag": "PASSWORD",
"value": "access-token"
},
{
"context": "t-access-token\");\n tokenResult.setIdToken(\"test-id\");\n when(response.getResponseBodyAsByte",
"end": 5104,
"score": 0.6520679593086243,
"start": 5100,
"tag": "KEY",
"value": "test"
},
{
"context": "cess-token\");\n tokenResult.setIdToken(\"test-id\");\n when(response.getResponseBodyAsBytes()",
"end": 5107,
"score": 0.7744256258010864,
"start": 5105,
"tag": "PASSWORD",
"value": "id"
}
] | null | [] | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl.auth.oauth2.protocol;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertNotNull;
import com.google.gson.Gson;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import org.asynchttpclient.BoundRequestBuilder;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import org.testng.annotations.Test;
/**
* Token client exchange token mock test.
*/
public class TokenClientTest {
@Test
@SuppressWarnings("unchecked")
public void exchangeClientCredentialsSuccessByScopeTest() throws
IOException, TokenExchangeException, ExecutionException, InterruptedException {
DefaultAsyncHttpClient defaultAsyncHttpClient = mock(DefaultAsyncHttpClient.class);
URL url = new URL("http://localhost");
TokenClient tokenClient = new TokenClient(url, defaultAsyncHttpClient);
ClientCredentialsExchangeRequest request = ClientCredentialsExchangeRequest.builder()
.audience("test-audience")
.clientId("test-client-id")
.clientSecret("test-client-secret")
.scope("test-scope")
.build();
String body = tokenClient.buildClientCredentialsBody(request);
BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
Response response = mock(Response.class);
ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(defaultAsyncHttpClient.preparePost(url.toString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Accept", "application/json")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(body)).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
TokenResult tokenResult = new TokenResult();
tokenResult.setAccessToken("test-access-token");
tokenResult.setIdToken("test-id");
when(response.getResponseBodyAsBytes()).thenReturn(new Gson().toJson(tokenResult).getBytes());
TokenResult tr = tokenClient.exchangeClientCredentials(request);
assertNotNull(tr);
}
@Test
@SuppressWarnings("unchecked")
public void exchangeClientCredentialsSuccessWithoutOptionalClientCredentialsTest() throws
IOException, TokenExchangeException, ExecutionException, InterruptedException {
DefaultAsyncHttpClient defaultAsyncHttpClient = mock(DefaultAsyncHttpClient.class);
URL url = new URL("http://localhost");
TokenClient tokenClient = new TokenClient(url, defaultAsyncHttpClient);
ClientCredentialsExchangeRequest request = ClientCredentialsExchangeRequest.builder()
.clientId("test-client-id")
.clientSecret("test-client-secret")
.build();
String body = tokenClient.buildClientCredentialsBody(request);
BoundRequestBuilder boundRequestBuilder = mock(BoundRequestBuilder.class);
Response response = mock(Response.class);
ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
when(defaultAsyncHttpClient.preparePost(url.toString())).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Accept", "application/json")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded")).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.setBody(body)).thenReturn(boundRequestBuilder);
when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
when(listenableFuture.get()).thenReturn(response);
when(response.getStatusCode()).thenReturn(200);
TokenResult tokenResult = new TokenResult();
tokenResult.setAccessToken("test-<PASSWORD>");
tokenResult.setIdToken("test-id");
when(response.getResponseBodyAsBytes()).thenReturn(new Gson().toJson(tokenResult).getBytes());
TokenResult tr = tokenClient.exchangeClientCredentials(request);
assertNotNull(tr);
}
}
| 5,320 | 0.738256 | 0.736189 | 100 | 52.220001 | 30.576324 | 129 | false | false | 0 | 0 | 0 | 0 | 68 | 0.012777 | 0.72 | false | false | 4 |
f6cf08d8a3ce85813485e1d36263049be6686289 | 19,292,993,157,172 | 932aae06185bd27bc1ffc463afd298d39cf9707a | /RavenClaw/src/dmcore/agents/coreagents/CAgent.java | 04dc43f48550da283b0921deb947de96dddbf351 | [] | no_license | monkeyduck/RavenClaw-for-Android | https://github.com/monkeyduck/RavenClaw-for-Android | e69b476c3ebe549449bfd31c56985b473ebe65ef | 503e7cf73de6d047de192b847f07e9bd31616294 | refs/heads/master | 2016-09-06T04:45:28.967000 | 2015-07-28T15:01:29 | 2015-07-28T15:01:29 | 39,836,800 | 14 | 4 | null | false | 2015-07-28T15:01:29 | 2015-07-28T13:53:28 | 2015-07-28T13:53:28 | 2015-07-28T15:01:29 | 0 | 0 | 0 | 0 | null | null | null | package dmcore.agents.coreagents;
import java.util.HashMap;
import android.util.Log;
import utils.Const;
import utils.Utils;
import dmcore.agents.coreagents.CRegistry;
import dmcore.agents.mytypedef.AgentFactory;
public class CAgent implements AgentFactory {
//---------------------------------------------------------------------
// Reference to the Registry Object
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// Name and Type class members
//---------------------------------------------------------------------
//
protected String sName; // name of agent
protected String sType; // type of agent
protected HashMap<String,String> s2sConfiguration =
new HashMap<String,String>(); // hash of parameters
//---------------------------------------------------------------------
// Constructors and destructors
//---------------------------------------------------------------------
// default constructor
public CAgent(){
sName="";
sType="";
}
public CAgent(String sAName){
sName = sAName;
SetConfiguration("");
}
// Constructor with sName and sAconfiguration
public CAgent(String sAName,String sAConfiguration){
sName=sAName;
sType = "CAgent";
SetConfiguration(sAConfiguration);
}
public CAgent(String sAName, String sAConfiguration, String sAType) {
this.sName = sAName;
this.sType = sAType;
this.SetConfiguration(sAConfiguration);
}
//-----------------------------------------------------------------------------
// Static function for dynamic agent creation
//-----------------------------------------------------------------------------
public CAgent AgentFactory(String sAName, String sAConfiguration) {
// this method should never end up being called (since CAgent is an
// abstract class) , therefore do a fatal error if this happens
Log.e(Const.CREATE_STREAM_TAG,"CreateAgent method called on CAgent (abstract) class.");
return null;
}
//---------------------------------------------------------------------
// Methods for access to private and protected members
//---------------------------------------------------------------------
public String GetName(){
return sName;
}
public String GetType(){
return sType;
}
public void SetType(String sAType){
this.sType = sAType;
}
// A: Parses a configuration string into a hash of parameters
public void SetConfiguration(String sConfiguration) {
// append to the current list of parameters
HashMap<String, String> lval = new HashMap<String,String>();
lval = Utils.StringToS2SHash(sConfiguration);
s2sConfiguration.putAll(lval);
}
// D: appends to the configuration from a hash
public void SetConfiguration(HashMap<String,String> s2sAConfiguration) {
// append to the current configuration
Utils.AppendToS2S(s2sConfiguration, s2sAConfiguration);
}
// Sets an individual configuration parameter
public void SetParameter(String sParam, String sValue){
s2sConfiguration.put(sParam, sValue);
}
// Tests if a parameter exists in the configuration
public boolean HasParameter(String sParam){
return s2sConfiguration.containsKey(sParam);
}
// Gets the value for a given parameter
public String GetParameterValue(String sParam){
if (s2sConfiguration.containsKey(sParam))
return s2sConfiguration.get(sParam);
else
return "";
}
//---------------------------------------------------------------------
// CAgent specific methods
//---------------------------------------------------------------------
// registering and unregistering the agent
//
public void Register(){
CRegistry.AgentsRegistry.RegisterAgent(sName, this);
}
public void UnRegister(){
CRegistry.AgentsRegistry.UnRegisterAgent(sName);
}
// This method is called immediately after an agent is constructed
// by the AgentsRegistry.CreateAgent function.
//
public void Create(){}
// This method is called to initialize an agent (usually after it's
// mounted in the dialog task tree)
//
public void Initialize(){}
// resets the agent (brings it to the same state as after construction
// and Initialize
//
public void Reset(){}
}
| UTF-8 | Java | 4,225 | java | CAgent.java | Java | [] | null | [] | package dmcore.agents.coreagents;
import java.util.HashMap;
import android.util.Log;
import utils.Const;
import utils.Utils;
import dmcore.agents.coreagents.CRegistry;
import dmcore.agents.mytypedef.AgentFactory;
public class CAgent implements AgentFactory {
//---------------------------------------------------------------------
// Reference to the Registry Object
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// Name and Type class members
//---------------------------------------------------------------------
//
protected String sName; // name of agent
protected String sType; // type of agent
protected HashMap<String,String> s2sConfiguration =
new HashMap<String,String>(); // hash of parameters
//---------------------------------------------------------------------
// Constructors and destructors
//---------------------------------------------------------------------
// default constructor
public CAgent(){
sName="";
sType="";
}
public CAgent(String sAName){
sName = sAName;
SetConfiguration("");
}
// Constructor with sName and sAconfiguration
public CAgent(String sAName,String sAConfiguration){
sName=sAName;
sType = "CAgent";
SetConfiguration(sAConfiguration);
}
public CAgent(String sAName, String sAConfiguration, String sAType) {
this.sName = sAName;
this.sType = sAType;
this.SetConfiguration(sAConfiguration);
}
//-----------------------------------------------------------------------------
// Static function for dynamic agent creation
//-----------------------------------------------------------------------------
public CAgent AgentFactory(String sAName, String sAConfiguration) {
// this method should never end up being called (since CAgent is an
// abstract class) , therefore do a fatal error if this happens
Log.e(Const.CREATE_STREAM_TAG,"CreateAgent method called on CAgent (abstract) class.");
return null;
}
//---------------------------------------------------------------------
// Methods for access to private and protected members
//---------------------------------------------------------------------
public String GetName(){
return sName;
}
public String GetType(){
return sType;
}
public void SetType(String sAType){
this.sType = sAType;
}
// A: Parses a configuration string into a hash of parameters
public void SetConfiguration(String sConfiguration) {
// append to the current list of parameters
HashMap<String, String> lval = new HashMap<String,String>();
lval = Utils.StringToS2SHash(sConfiguration);
s2sConfiguration.putAll(lval);
}
// D: appends to the configuration from a hash
public void SetConfiguration(HashMap<String,String> s2sAConfiguration) {
// append to the current configuration
Utils.AppendToS2S(s2sConfiguration, s2sAConfiguration);
}
// Sets an individual configuration parameter
public void SetParameter(String sParam, String sValue){
s2sConfiguration.put(sParam, sValue);
}
// Tests if a parameter exists in the configuration
public boolean HasParameter(String sParam){
return s2sConfiguration.containsKey(sParam);
}
// Gets the value for a given parameter
public String GetParameterValue(String sParam){
if (s2sConfiguration.containsKey(sParam))
return s2sConfiguration.get(sParam);
else
return "";
}
//---------------------------------------------------------------------
// CAgent specific methods
//---------------------------------------------------------------------
// registering and unregistering the agent
//
public void Register(){
CRegistry.AgentsRegistry.RegisterAgent(sName, this);
}
public void UnRegister(){
CRegistry.AgentsRegistry.UnRegisterAgent(sName);
}
// This method is called immediately after an agent is constructed
// by the AgentsRegistry.CreateAgent function.
//
public void Create(){}
// This method is called to initialize an agent (usually after it's
// mounted in the dialog task tree)
//
public void Initialize(){}
// resets the agent (brings it to the same state as after construction
// and Initialize
//
public void Reset(){}
}
| 4,225 | 0.584852 | 0.582249 | 134 | 30.52985 | 25.705185 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.514925 | false | false | 4 |
0fa8fe237c1aa61209a43745fccd6bb4a01eaf6f | 26,620,207,343,917 | 2fcf7d3e845c76d4d1b84af7ad0e2a5574d0db59 | /bGit/src/bGit/Test.java | 31d0ecdde5950d2bcf2f100975a0492164fecf97 | [] | no_license | SeungHun6450/test2 | https://github.com/SeungHun6450/test2 | 2e7b3dc77006004ada6bdffe4c8927b7a5741c02 | ebb7f1e1a896ed31c224dfafd90d18854e2541fd | refs/heads/master | 2022-07-29T16:55:45.211000 | 2020-05-18T10:21:13 | 2020-05-18T10:21:13 | 264,884,708 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bGit;
public class Test {
public static void main(String[] args) {
System.out.println("안뇽?");
System.out.println("난 조원이얌");
System.out.println("내가 첫번째 수정이야");
}
}
| UHC | Java | 225 | java | Test.java | Java | [] | null | [] | package bGit;
public class Test {
public static void main(String[] args) {
System.out.println("안뇽?");
System.out.println("난 조원이얌");
System.out.println("내가 첫번째 수정이야");
}
}
| 225 | 0.621762 | 0.621762 | 11 | 15.545455 | 15.370358 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 4 |
b4b85c4d1622c73549a7871daad18f744b7626da | 29,867,202,638,850 | e4fe06aa2e694ab79b8aaba76c7802641c9eeb49 | /MIUApp/app/src/main/java/com/example/johnhani/miuapp/Address.java | d66ba3aeb3284fc88fad37299f8c83d7d74c910f | [] | no_license | mostafagamaa/MIU-Register | https://github.com/mostafagamaa/MIU-Register | 5e5461091cde7af69e55b421be699974ad7186ee | 560dace9df893d75031aaa6bb9842e04656d9663 | refs/heads/master | 2020-06-17T16:56:04.558000 | 2019-07-09T10:16:06 | 2019-07-09T10:16:06 | 195,983,566 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.johnhani.miuapp;
public class Address {
public int id;
public String value;
public int level;
public int parent_id;
public Address(){};
public Address(String value,int level,int parent_id){
this.value=value;
this.level=level;
this.parent_id=parent_id;
}
}
| UTF-8 | Java | 329 | java | Address.java | Java | [] | null | [] | package com.example.johnhani.miuapp;
public class Address {
public int id;
public String value;
public int level;
public int parent_id;
public Address(){};
public Address(String value,int level,int parent_id){
this.value=value;
this.level=level;
this.parent_id=parent_id;
}
}
| 329 | 0.644377 | 0.644377 | 14 | 22.5 | 14.145924 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 4 |
70354cd662cc681c125220aaa6026e042cd4e2ac | 18,665,927,880,955 | 4a3a61ce0ae2e08015ccaefa140b7854c05e0b1e | /src/com/kh/jsp/board/controller/SelectOneThumbnailServlet.java | 39589fdb7926eacd3185c6607b12bfb92b1fe5b8 | [] | no_license | 3joNiSaZip/TestProject | https://github.com/3joNiSaZip/TestProject | 9b371998e1a897fae6002878acab735044742614 | 1c85d2c72057af16f8e0197455848ab81cbfe8a5 | refs/heads/master | 2020-03-18T18:55:29.559000 | 2018-05-28T07:18:11 | 2018-05-28T07:18:11 | 135,122,932 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kh.jsp.board.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kh.jsp.board.model.service.BoardService;
import com.kh.jsp.board.model.vo.Attachment;
import com.kh.jsp.board.model.vo.Board;
/**
* Servlet implementation class SelectOneThumbnailServlet
*/
@WebServlet("/selectOne.tn")
public class SelectOneThumbnailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SelectOneThumbnailServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int num = Integer.parseInt(request.getParameter("num"));
System.out.println(num);
HashMap<String, Object> hmap = new BoardService().selectThumbnailMap(num);
System.out.println(hmap);
Board b = (Board) hmap.get("board");
ArrayList<Attachment> fileList = (ArrayList<Attachment>) hmap.get("attachment");
String page = "";
if(hmap != null && !hmap.isEmpty()) {
page = "views/thumbnail/thumbnailDetail.jsp";
request.setAttribute("b", b);
request.setAttribute("fileList", fileList);
}else {
page = "views/common/errorPage.jsp";
request.setAttribute("msg", "사진게시판 상세보기 실패");
}
RequestDispatcher view = request.getRequestDispatcher(page);
view.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| UTF-8 | Java | 2,116 | java | SelectOneThumbnailServlet.java | Java | [] | null | [] | package com.kh.jsp.board.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.kh.jsp.board.model.service.BoardService;
import com.kh.jsp.board.model.vo.Attachment;
import com.kh.jsp.board.model.vo.Board;
/**
* Servlet implementation class SelectOneThumbnailServlet
*/
@WebServlet("/selectOne.tn")
public class SelectOneThumbnailServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SelectOneThumbnailServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int num = Integer.parseInt(request.getParameter("num"));
System.out.println(num);
HashMap<String, Object> hmap = new BoardService().selectThumbnailMap(num);
System.out.println(hmap);
Board b = (Board) hmap.get("board");
ArrayList<Attachment> fileList = (ArrayList<Attachment>) hmap.get("attachment");
String page = "";
if(hmap != null && !hmap.isEmpty()) {
page = "views/thumbnail/thumbnailDetail.jsp";
request.setAttribute("b", b);
request.setAttribute("fileList", fileList);
}else {
page = "views/common/errorPage.jsp";
request.setAttribute("msg", "사진게시판 상세보기 실패");
}
RequestDispatcher view = request.getRequestDispatcher(page);
view.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
| 2,116 | 0.71872 | 0.718243 | 67 | 29.253731 | 27.457073 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.552239 | false | false | 4 |
cd049bfebe66cf81b2d0b8b09b26e777203610f9 | 23,295,902,657,479 | 00efecba7c166b810df60a9ab2c597a4f27802d3 | /kasije-core/src/main/java/com/kasije/core/tpl/TemplateDataBuilder.java | fab5be271b75079776af48f487f1e63e85022c0c | [
"Apache-2.0"
] | permissive | touwolf/kasije | https://github.com/touwolf/kasije | d431aefbeeb7782435eae9518316873be91e7152 | 9a7e57dfc875a72f83810e0d86201a155b9a54b2 | refs/heads/master | 2021-01-21T13:04:56.568000 | 2016-05-13T23:27:15 | 2016-05-13T23:27:15 | 52,138,086 | 3 | 2 | null | false | 2016-02-29T22:13:06 | 2016-02-20T05:19:53 | 2016-02-22T02:04:01 | 2016-02-29T22:13:06 | 607 | 3 | 1 | 0 | Java | null | null | /*
* Copyright 2016 Kasije Framework.
*
* 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.kasije.core.tpl;
import com.kasije.core.RequestContext;
import com.kasije.core.WebPage;
import com.kasije.core.WebSite;
import com.kasije.core.auth.AuthUser;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
/**
*
*/
public class TemplateDataBuilder
{
public static TemplateData parse(RequestContext reqCtx, WebSite site, WebPage page)
{
AuthUser user = null;
if (site.isAdmin())
{
user = reqCtx.get(AuthUser.class);
}
File parent = site.getFile();
String path = page.getRelativePath();
File file = new File(parent, getPathWithExt(path, "xml"));
if (file.exists() && file.canRead())
{
return parseXML(file, user);
}
/*
file = new File(parent, getPathWithExt(path, "json"));
if (file.exists() && file.canRead())
{
return parseJSON(file, user);
}
*/
return null;
}
private static TemplateData parseXML(File file, AuthUser user)
{
try
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
Element docElement = doc.getDocumentElement();
docElement.normalize();
TemplateData data = parseXMLElement(doc.getDocumentElement());
if (data != null && user != null)
{
data.addChild(user.toTemplateData());
}
return data;
}
catch (Exception e)
{
return null;
}
}
private static TemplateData parseXMLElement(Element element)
{
TemplateData data = new TemplateData();
data.setName(element.getNodeName());
data.setText(element.getTextContent());
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node node = attrs.item(i);
data.setAttribute(node.getNodeName(), node.getNodeValue());
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node node = children.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
{
continue;
}
Element child = (Element) node;
data.addChild(parseXMLElement(child));
}
if (data.getTagChildren() != null)
{
data.setText(null);
}
return data;
}
/*
private static TemplateData parseJSON(File file, AuthUser user)
{
//TODO
return null;
}
*/
private static String getPathWithExt(String p, String extension)
{
String path = p;
String ext = extension;
if (path.endsWith("." + ext))
{
return path;
}
if (!path.endsWith("."))
{
path += ".";
}
if (ext.startsWith("."))
{
ext = ext.substring(1);
}
return path + ext;
}
}
| UTF-8 | Java | 3,875 | java | TemplateDataBuilder.java | Java | [] | null | [] | /*
* Copyright 2016 Kasije Framework.
*
* 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.kasije.core.tpl;
import com.kasije.core.RequestContext;
import com.kasije.core.WebPage;
import com.kasije.core.WebSite;
import com.kasije.core.auth.AuthUser;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
/**
*
*/
public class TemplateDataBuilder
{
public static TemplateData parse(RequestContext reqCtx, WebSite site, WebPage page)
{
AuthUser user = null;
if (site.isAdmin())
{
user = reqCtx.get(AuthUser.class);
}
File parent = site.getFile();
String path = page.getRelativePath();
File file = new File(parent, getPathWithExt(path, "xml"));
if (file.exists() && file.canRead())
{
return parseXML(file, user);
}
/*
file = new File(parent, getPathWithExt(path, "json"));
if (file.exists() && file.canRead())
{
return parseJSON(file, user);
}
*/
return null;
}
private static TemplateData parseXML(File file, AuthUser user)
{
try
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
Element docElement = doc.getDocumentElement();
docElement.normalize();
TemplateData data = parseXMLElement(doc.getDocumentElement());
if (data != null && user != null)
{
data.addChild(user.toTemplateData());
}
return data;
}
catch (Exception e)
{
return null;
}
}
private static TemplateData parseXMLElement(Element element)
{
TemplateData data = new TemplateData();
data.setName(element.getNodeName());
data.setText(element.getTextContent());
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++)
{
Node node = attrs.item(i);
data.setAttribute(node.getNodeName(), node.getNodeValue());
}
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node node = children.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
{
continue;
}
Element child = (Element) node;
data.addChild(parseXMLElement(child));
}
if (data.getTagChildren() != null)
{
data.setText(null);
}
return data;
}
/*
private static TemplateData parseJSON(File file, AuthUser user)
{
//TODO
return null;
}
*/
private static String getPathWithExt(String p, String extension)
{
String path = p;
String ext = extension;
if (path.endsWith("." + ext))
{
return path;
}
if (!path.endsWith("."))
{
path += ".";
}
if (ext.startsWith("."))
{
ext = ext.substring(1);
}
return path + ext;
}
}
| 3,875 | 0.570839 | 0.567742 | 149 | 25.006712 | 23.346096 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456376 | false | false | 4 |
a7b8e836fedae7682c2ff11f9d260cab24d88017 | 4,380,866,691,584 | 29b4a04fb2dd744fc30179e12293e24d680ddf29 | /rtp-midi-core/src/test/java/io/github/leovr/rtipmidi/handler/AppleMidiCommandHandlerTest.java | 51ae9c5cd99f3c35d616373041a5cc3f74dfb3ac | [
"Apache-2.0"
] | permissive | LeovR/rtp-midi | https://github.com/LeovR/rtp-midi | e4a8c5dc79afe150d38698c56192d622141485b0 | d900797c448e819e70c480fce0264be515920f37 | refs/heads/master | 2021-01-09T06:09:30.656000 | 2018-03-03T12:49:16 | 2018-03-03T12:49:16 | 80,926,817 | 9 | 3 | null | false | 2017-11-05T10:55:13 | 2017-02-04T15:06:31 | 2017-02-04T19:37:12 | 2017-11-05T10:55:13 | 80 | 1 | 1 | 0 | Java | false | null | package io.github.leovr.rtipmidi.handler;
import io.github.leovr.rtipmidi.AppleMidiCommandListener;
import io.github.leovr.rtipmidi.messages.AppleMidiClockSynchronization;
import io.github.leovr.rtipmidi.messages.AppleMidiEndSession;
import io.github.leovr.rtipmidi.messages.AppleMidiInvitationRequest;
import io.github.leovr.rtipmidi.model.AppleMidiServer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.net.InetAddress;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class AppleMidiCommandHandlerTest {
private AppleMidiCommandHandler handler;
private final byte[] midiInvitationRequest =
{(byte) 0xff, (byte) 0xff, (byte) 0x49, (byte) 0x4e, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
(byte) 0x00, (byte) 0x16, (byte) 0x3d, (byte) 0x91, (byte) 0x75, (byte) 0xb1, (byte) 0xc5,
(byte) 0x1d, (byte) 0x74, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00};
private final byte[] endSession =
{(byte) 0xff, (byte) 0xff, (byte) 0x42, (byte) 0x59, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
(byte) 0xc3, (byte) 0x7a, (byte) 0xa8, (byte) 0xa0, (byte) 0x75, (byte) 0xb1, (byte) 0xc5,
(byte) 0x1d};
private final byte[] clockSynchronization =
{(byte) 0xff, (byte) 0xff, (byte) 0x43, (byte) 0x4b, (byte) 0x75, (byte) 0xb1, (byte) 0xc5, (byte) 0x1d,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x16, (byte) 0xa8, (byte) 0x3f, (byte) 0xe5, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
@Mock
private AppleMidiCommandListener listener;
private AppleMidiServer server;
@Captor
private ArgumentCaptor<AppleMidiInvitationRequest> invitationRequestCaptor;
@Captor
private ArgumentCaptor<AppleMidiEndSession> endSessionArgumentCaptor;
@Captor
private ArgumentCaptor<AppleMidiClockSynchronization> clockSynchronizationArgumentCaptor;
@Mock
private InetAddress inetAddress;
@Before
public void setUp() throws Exception {
handler = new AppleMidiCommandHandler();
handler.registerListener(listener);
server = new AppleMidiServer(inetAddress, 0);
}
@Test
public void testHandleMidiInvitationRequest() throws Exception {
handler.handle(midiInvitationRequest, server);
verify(listener).onMidiInvitation(invitationRequestCaptor.capture(), eq(server));
final AppleMidiInvitationRequest invitationRequest = invitationRequestCaptor.getValue();
assertThat(invitationRequest).isEqualTo(new AppleMidiInvitationRequest(2, 1457553, 1974584605, "test"));
}
@Test
public void testHandleEndSession() throws Exception {
handler.handle(endSession, server);
verify(listener).onEndSession(endSessionArgumentCaptor.capture(), eq(server));
final AppleMidiEndSession endSession = endSessionArgumentCaptor.getValue();
assertThat(endSession).isEqualTo(new AppleMidiEndSession(2, 0xc37aa8a0, 0x75b1c51d));
}
@Test
public void testHandleClockSynchronization() throws Exception {
handler.handle(clockSynchronization, server);
verify(listener).onClockSynchronization(clockSynchronizationArgumentCaptor.capture(), eq(server));
final AppleMidiClockSynchronization clockSynchronization = clockSynchronizationArgumentCaptor.getValue();
assertThat(clockSynchronization)
.isEqualTo(new AppleMidiClockSynchronization(0x75b1c51d, (byte) 0, 0x16a83fe5, 0, 0));
}
@Test
public void testInvalidHeader1() throws Exception {
handler.handle(new byte[]{(byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidHeader2() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidCommand() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidCommandWord() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
}
| UTF-8 | Java | 6,317 | java | AppleMidiCommandHandlerTest.java | Java | [] | null | [] | package io.github.leovr.rtipmidi.handler;
import io.github.leovr.rtipmidi.AppleMidiCommandListener;
import io.github.leovr.rtipmidi.messages.AppleMidiClockSynchronization;
import io.github.leovr.rtipmidi.messages.AppleMidiEndSession;
import io.github.leovr.rtipmidi.messages.AppleMidiInvitationRequest;
import io.github.leovr.rtipmidi.model.AppleMidiServer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.net.InetAddress;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class AppleMidiCommandHandlerTest {
private AppleMidiCommandHandler handler;
private final byte[] midiInvitationRequest =
{(byte) 0xff, (byte) 0xff, (byte) 0x49, (byte) 0x4e, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
(byte) 0x00, (byte) 0x16, (byte) 0x3d, (byte) 0x91, (byte) 0x75, (byte) 0xb1, (byte) 0xc5,
(byte) 0x1d, (byte) 0x74, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00};
private final byte[] endSession =
{(byte) 0xff, (byte) 0xff, (byte) 0x42, (byte) 0x59, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
(byte) 0xc3, (byte) 0x7a, (byte) 0xa8, (byte) 0xa0, (byte) 0x75, (byte) 0xb1, (byte) 0xc5,
(byte) 0x1d};
private final byte[] clockSynchronization =
{(byte) 0xff, (byte) 0xff, (byte) 0x43, (byte) 0x4b, (byte) 0x75, (byte) 0xb1, (byte) 0xc5, (byte) 0x1d,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x16, (byte) 0xa8, (byte) 0x3f, (byte) 0xe5, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
@Mock
private AppleMidiCommandListener listener;
private AppleMidiServer server;
@Captor
private ArgumentCaptor<AppleMidiInvitationRequest> invitationRequestCaptor;
@Captor
private ArgumentCaptor<AppleMidiEndSession> endSessionArgumentCaptor;
@Captor
private ArgumentCaptor<AppleMidiClockSynchronization> clockSynchronizationArgumentCaptor;
@Mock
private InetAddress inetAddress;
@Before
public void setUp() throws Exception {
handler = new AppleMidiCommandHandler();
handler.registerListener(listener);
server = new AppleMidiServer(inetAddress, 0);
}
@Test
public void testHandleMidiInvitationRequest() throws Exception {
handler.handle(midiInvitationRequest, server);
verify(listener).onMidiInvitation(invitationRequestCaptor.capture(), eq(server));
final AppleMidiInvitationRequest invitationRequest = invitationRequestCaptor.getValue();
assertThat(invitationRequest).isEqualTo(new AppleMidiInvitationRequest(2, 1457553, 1974584605, "test"));
}
@Test
public void testHandleEndSession() throws Exception {
handler.handle(endSession, server);
verify(listener).onEndSession(endSessionArgumentCaptor.capture(), eq(server));
final AppleMidiEndSession endSession = endSessionArgumentCaptor.getValue();
assertThat(endSession).isEqualTo(new AppleMidiEndSession(2, 0xc37aa8a0, 0x75b1c51d));
}
@Test
public void testHandleClockSynchronization() throws Exception {
handler.handle(clockSynchronization, server);
verify(listener).onClockSynchronization(clockSynchronizationArgumentCaptor.capture(), eq(server));
final AppleMidiClockSynchronization clockSynchronization = clockSynchronizationArgumentCaptor.getValue();
assertThat(clockSynchronization)
.isEqualTo(new AppleMidiClockSynchronization(0x75b1c51d, (byte) 0, 0x16a83fe5, 0, 0));
}
@Test
public void testInvalidHeader1() throws Exception {
handler.handle(new byte[]{(byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidHeader2() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidCommand() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0x00}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
@Test
public void testInvalidCommandWord() throws Exception {
handler.handle(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, server);
verify(listener, never())
.onClockSynchronization(any(AppleMidiClockSynchronization.class), any(AppleMidiServer.class));
verify(listener, never()).onEndSession(any(AppleMidiEndSession.class), any(AppleMidiServer.class));
verify(listener, never()).onMidiInvitation(any(AppleMidiInvitationRequest.class), any(AppleMidiServer.class));
}
}
| 6,317 | 0.702707 | 0.662815 | 134 | 46.141792 | 40.760521 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.343284 | false | false | 4 |
83b8a45be79746905cfccecaa0c30e03473cf19d | 9,680,856,334,329 | 1676c76b4b98e597a5b029a1ed08f5351dfc2aa6 | /src/main/java/cn/freefly/rabbitmq/config/RabbitMqProperties.java | 650e074e193a587e42b7d964ceade534a713537e | [] | no_license | KeepFlyingBird/rabbitmq | https://github.com/KeepFlyingBird/rabbitmq | 641a5a4972316da2d420f306833c8c1837af63d3 | fcd06c7f66dd12a0cd078a9412ba08539312812a | refs/heads/main | 2023-07-19T03:04:02.402000 | 2021-09-23T01:28:12 | 2021-09-23T01:28:12 | 408,383,504 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.freefly.rabbitmq.config;
import lombok.Data;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @Description:
* @author: xhzl.xiaoyunfei
* @date: 2021.09.22
*/
@Data
@Component
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class RabbitMqProperties {
private String host;
private int port;
private String username;
private String password;
private String virtualHost;
private CachingConnectionFactory.ConfirmType publisherConfirmType;
private TestQueue queue;
private TestQueue queue2;
@Data
public static class TestQueue {
private String queue;
private String exchange;
private String routingkey;
}
}
| UTF-8 | Java | 880 | java | RabbitMqProperties.java | Java | [
{
"context": "t java.util.Map;\n\n/**\n * @Description:\n * @author: xhzl.xiaoyunfei\n * @date: 2021.09.22\n */\n@Data\n@Component\n@Config",
"end": 330,
"score": 0.9968411922454834,
"start": 315,
"tag": "USERNAME",
"value": "xhzl.xiaoyunfei"
}
] | null | [] | package cn.freefly.rabbitmq.config;
import lombok.Data;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @Description:
* @author: xhzl.xiaoyunfei
* @date: 2021.09.22
*/
@Data
@Component
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class RabbitMqProperties {
private String host;
private int port;
private String username;
private String password;
private String virtualHost;
private CachingConnectionFactory.ConfirmType publisherConfirmType;
private TestQueue queue;
private TestQueue queue2;
@Data
public static class TestQueue {
private String queue;
private String exchange;
private String routingkey;
}
}
| 880 | 0.754545 | 0.744318 | 34 | 24.882353 | 20.490694 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
4f9986a8b0545982703996054eb96ed9ec3ebde8 | 16,011,638,102,468 | dad7c3275d7a8ded1044ffad7468b727ef2586a5 | /src/main/ar/edu/undav/views/Creditos.java | 077313b954b7892aec74fdbddb57d2bea4fa3822 | [] | no_license | xxalezxx/CarmenBorbotones | https://github.com/xxalezxx/CarmenBorbotones | e4073e3ad073f9d788a6992b27fc6864ca33053a | 392e634f2491aa97c19fffff7e2a33e438cec8b0 | refs/heads/master | 2020-08-08T17:46:28.442000 | 2019-12-03T14:08:15 | 2019-12-03T14:08:15 | 213,875,386 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ar.edu.undav.views;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.DropMode;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Creditos extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Creditos frame = new Creditos();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void desactivarVista() {
this.setVisible(false);
}
/**
* Create the frame.
*/
public Creditos() {
setTitle("Creditos de desarrollo");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel pGeneral = new JPanel();
contentPane.add(pGeneral, BorderLayout.CENTER);
pGeneral.setLayout(null);
JButton btnAtras = new JButton("Atras");
btnAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
desactivarVista();
}
});
btnAtras.setBounds(165, 217, 89, 23);
pGeneral.add(btnAtras);
JTextArea txtrIntegrantesDelGrupo = new JTextArea();
txtrIntegrantesDelGrupo.setText("Integrantes del grupo:\r\n\r\nAlejandro Santari\r\nCristian Novas\r\nJose Telerman\r\nSabrina Iorgi\r\nYoel Pedemonte\r\n\r\nProgramacion Orientada a Objetos \r\n2019 - 2do Cuatrimestre\r\n\r\n");
txtrIntegrantesDelGrupo.setEditable(false);
txtrIntegrantesDelGrupo.setBounds(10, 11, 404, 195);
pGeneral.add(txtrIntegrantesDelGrupo);
this.setLocationRelativeTo(null);
}
}
| UTF-8 | Java | 2,115 | java | Creditos.java | Java | [
{
"context": "tesDelGrupo.setText(\"Integrantes del grupo:\\r\\n\\r\\nAlejandro Santari\\r\\nCristian Novas\\r\\nJose Telerman\\r\\nSabrina Ior",
"end": 1775,
"score": 0.9998396635055542,
"start": 1757,
"tag": "NAME",
"value": "nAlejandro Santari"
},
{
"context": "ntegrantes del grupo:\\r\\n\\r\\nAlejandro Santari\\r\\nCristian Novas\\r\\nJose Telerman\\r\\nSabrina Iorgi\\r\\nYoel Pedemon",
"end": 1793,
"score": 0.9998710751533508,
"start": 1779,
"tag": "NAME",
"value": "Cristian Novas"
},
{
"context": "po:\\r\\n\\r\\nAlejandro Santari\\r\\nCristian Novas\\r\\nJose Telerman\\r\\nSabrina Iorgi\\r\\nYoel Pedemonte\\r\\n\\r\\nProgram",
"end": 1810,
"score": 0.9998618960380554,
"start": 1797,
"tag": "NAME",
"value": "Jose Telerman"
},
{
"context": "dro Santari\\r\\nCristian Novas\\r\\nJose Telerman\\r\\nSabrina Iorgi\\r\\nYoel Pedemonte\\r\\n\\r\\nProgramacion Orientada a",
"end": 1827,
"score": 0.999882161617279,
"start": 1814,
"tag": "NAME",
"value": "Sabrina Iorgi"
},
{
"context": "istian Novas\\r\\nJose Telerman\\r\\nSabrina Iorgi\\r\\nYoel Pedemonte\\r\\n\\r\\nProgramacion Orientada a Objetos \\r\\n2019 ",
"end": 1845,
"score": 0.9997925162315369,
"start": 1831,
"tag": "NAME",
"value": "Yoel Pedemonte"
}
] | null | [] | package ar.edu.undav.views;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.DropMode;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Creditos extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Creditos frame = new Creditos();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void desactivarVista() {
this.setVisible(false);
}
/**
* Create the frame.
*/
public Creditos() {
setTitle("Creditos de desarrollo");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel pGeneral = new JPanel();
contentPane.add(pGeneral, BorderLayout.CENTER);
pGeneral.setLayout(null);
JButton btnAtras = new JButton("Atras");
btnAtras.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
desactivarVista();
}
});
btnAtras.setBounds(165, 217, 89, 23);
pGeneral.add(btnAtras);
JTextArea txtrIntegrantesDelGrupo = new JTextArea();
txtrIntegrantesDelGrupo.setText("Integrantes del grupo:\r\n\r\<NAME>\r\n<NAME>\r\n<NAME>\r\n<NAME>\r\n<NAME>\r\n\r\nProgramacion Orientada a Objetos \r\n2019 - 2do Cuatrimestre\r\n\r\n");
txtrIntegrantesDelGrupo.setEditable(false);
txtrIntegrantesDelGrupo.setBounds(10, 11, 404, 195);
pGeneral.add(txtrIntegrantesDelGrupo);
this.setLocationRelativeTo(null);
}
}
| 2,073 | 0.708274 | 0.687943 | 74 | 26.581081 | 29.15847 | 231 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.243243 | false | false | 4 |
f7715494f6916c0747f3434ad5d04824723b9fcf | 4,836,133,203,985 | 2e981c2c539efb176cef0b2dee5b6f06b099bf9d | /2DArrayWksht/src/TwoDArrays.java | 4fe3aedb4ddbcfe0cebe355bcca667c633f8212c | [] | no_license | ryan2445/Java_Projects | https://github.com/ryan2445/Java_Projects | 1d28d6877e734ee42ce13615d0e6219576b26aae | eef3a4fa202c8560d5a0bdd647a49310474afa56 | refs/heads/master | 2020-03-29T11:00:14.389000 | 2018-09-26T19:11:35 | 2018-09-26T19:11:35 | 149,829,316 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class TwoDArrays {
public static void main(String[] args) {
int [][]basic = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
int [][]nonsquare = new int[][] { {1,2,3}, {4,5}, {6,7,8,9} };
int [][]negatives = new int[][] { {1,-2,3}, {4,5,6}, {-7,8,-9} };
int [][]rowmagic = new int[][] { {1,2,3}, {-1,5,2}, {4,0,2} };
int [][]colmagic = new int[][] { {1,-1,4,10}, {3,5,0,-6} };
int [][]magic = new int[][] { {2,2,2}, {2,2,2}, {2,2,2} };
int [][]notmagic1 = new int[][] { {1,2,3}, {4,5,6}, {6,8,9} }; //diag sums are not equal
int [][]notmagic2 = new int[][] { {1,5,3}, {4,5,6}, {7,8,9} }; //diag sums //are equal but rows are not
System.out.println(rowSum(basic,1));
System.out.println(columnSum(basic,1));
}
public static int rowSum(int[][] a, int x){
int sum =0;
for(int i=0;i<a.length;i++){
sum+=a[x][i];
}
return sum;
}
public static int columnSum(int[][] a, int x){
int sum =0;
for(int i=0;i<a.length;i++){
sum+=a[i][x];
}
return sum;
}
public static int max(int[][] a){
int max=0;
int max2=0;
for(int i=0;i<a.length;i++){
int max2=a[]
}
}
}
| UTF-8 | Java | 1,176 | java | TwoDArrays.java | Java | [] | null | [] | import java.util.*;
public class TwoDArrays {
public static void main(String[] args) {
int [][]basic = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
int [][]nonsquare = new int[][] { {1,2,3}, {4,5}, {6,7,8,9} };
int [][]negatives = new int[][] { {1,-2,3}, {4,5,6}, {-7,8,-9} };
int [][]rowmagic = new int[][] { {1,2,3}, {-1,5,2}, {4,0,2} };
int [][]colmagic = new int[][] { {1,-1,4,10}, {3,5,0,-6} };
int [][]magic = new int[][] { {2,2,2}, {2,2,2}, {2,2,2} };
int [][]notmagic1 = new int[][] { {1,2,3}, {4,5,6}, {6,8,9} }; //diag sums are not equal
int [][]notmagic2 = new int[][] { {1,5,3}, {4,5,6}, {7,8,9} }; //diag sums //are equal but rows are not
System.out.println(rowSum(basic,1));
System.out.println(columnSum(basic,1));
}
public static int rowSum(int[][] a, int x){
int sum =0;
for(int i=0;i<a.length;i++){
sum+=a[x][i];
}
return sum;
}
public static int columnSum(int[][] a, int x){
int sum =0;
for(int i=0;i<a.length;i++){
sum+=a[i][x];
}
return sum;
}
public static int max(int[][] a){
int max=0;
int max2=0;
for(int i=0;i<a.length;i++){
int max2=a[]
}
}
}
| 1,176 | 0.492347 | 0.420068 | 39 | 28.153847 | 26.789339 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.974359 | false | false | 4 |
6a4c1268de391ee0358de0fd3df206095e5731b2 | 1,348,619,793,171 | 8520e57a45c3b8b09a90f6677a4c9d323c628d3b | /2° Semestre/estudos/testes/annotations/ValidatorsField.java | 3980bcc5a99d9d4fb1f48df9ed7e0e066bae3ba2 | [] | no_license | leonarita/Java | https://github.com/leonarita/Java | e58156f7ef409884a3dfe2c3d8ab84a4b57984f1 | 7dc31112de4d8006f61f2bda1ce4e2b757bbda54 | refs/heads/master | 2023-08-18T15:27:43.598000 | 2022-05-22T15:28:44 | 2022-05-22T15:28:44 | 252,060,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package testes.annotations;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.Period;
import testes.annotations.v1.CPF;
import testes.annotations.v1.IdadeMinima;
import testes.annotations.v1.Length;
public class ValidatorsField {
public static <T> boolean validateCPF(T objeto) {
Class<?> classe = objeto.getClass();
for(Field field : classe.getDeclaredFields()) {
if(field.isAnnotationPresent(CPF.class) ) {
try {
field.setAccessible(true);
String val = ((String)field.get(objeto)).replace(".", "").replace("-", "");
field.setAccessible(false);
return val.length() == 11;
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
public static <T> boolean validador(T objeto) {
Class<?> classe = objeto.getClass();
for (Field field : classe.getDeclaredFields()) {
if (field.isAnnotationPresent(IdadeMinima.class)) {
IdadeMinima idadeMinima = field.getAnnotation(IdadeMinima.class);
try {
field.setAccessible(true);
LocalDate dataNascimento = (LocalDate) field.get(objeto);
return Period.between(dataNascimento, LocalDate.now()).getYears() >= idadeMinima.valor();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
public static <T> boolean validadorName(T objeto) {
Class<?> classe = objeto.getClass();
for (Field field : classe.getDeclaredFields()) {
if (field.isAnnotationPresent(Length.class)) {
Length length = field.getAnnotation(Length.class);
try {
field.setAccessible(true);
String val = ((String)field.get(objeto));
if (length.min() > val.length() || length.max() < val.length()) {
return false;
}
if(length.rules().length != 0 && !length.rules()[0].equals("")) {
for (String s : length.rules()) {
if(s.startsWith("contains ")) {
s = s.replace("contains ", "").replace("'", "");
if(!val.contains(s)) {
return false;
}
}
else if(s.startsWith("at least ")) {
// s = s.replace("at leas ", "").replace(" words", "");
//
// if()
}
}
}
return true;
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
}
| UTF-8 | Java | 2,414 | java | ValidatorsField.java | Java | [] | null | [] | package testes.annotations;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.Period;
import testes.annotations.v1.CPF;
import testes.annotations.v1.IdadeMinima;
import testes.annotations.v1.Length;
public class ValidatorsField {
public static <T> boolean validateCPF(T objeto) {
Class<?> classe = objeto.getClass();
for(Field field : classe.getDeclaredFields()) {
if(field.isAnnotationPresent(CPF.class) ) {
try {
field.setAccessible(true);
String val = ((String)field.get(objeto)).replace(".", "").replace("-", "");
field.setAccessible(false);
return val.length() == 11;
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
public static <T> boolean validador(T objeto) {
Class<?> classe = objeto.getClass();
for (Field field : classe.getDeclaredFields()) {
if (field.isAnnotationPresent(IdadeMinima.class)) {
IdadeMinima idadeMinima = field.getAnnotation(IdadeMinima.class);
try {
field.setAccessible(true);
LocalDate dataNascimento = (LocalDate) field.get(objeto);
return Period.between(dataNascimento, LocalDate.now()).getYears() >= idadeMinima.valor();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
public static <T> boolean validadorName(T objeto) {
Class<?> classe = objeto.getClass();
for (Field field : classe.getDeclaredFields()) {
if (field.isAnnotationPresent(Length.class)) {
Length length = field.getAnnotation(Length.class);
try {
field.setAccessible(true);
String val = ((String)field.get(objeto));
if (length.min() > val.length() || length.max() < val.length()) {
return false;
}
if(length.rules().length != 0 && !length.rules()[0].equals("")) {
for (String s : length.rules()) {
if(s.startsWith("contains ")) {
s = s.replace("contains ", "").replace("'", "");
if(!val.contains(s)) {
return false;
}
}
else if(s.startsWith("at least ")) {
// s = s.replace("at leas ", "").replace(" words", "");
//
// if()
}
}
}
return true;
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return false;
}
}
| 2,414 | 0.591964 | 0.589064 | 114 | 20.175438 | 21.757534 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.570175 | false | false | 4 |
325e375f85433e91c55b450a87292a13b548eb11 | 14,611,478,800,162 | 14081fd5beeb757a4b148132c23e94874d199ca4 | /src/main/java/com/shau/stuff/dao/LinkContentDao.java | 17af37026e75da8a8ebe60dc4328504ee25bff40 | [] | no_license | shausoftware/ShauStuff | https://github.com/shausoftware/ShauStuff | 65c8be02ef6465e4130753ebf5ae1944384280a7 | 26b3a980019ea0fd9f1cc4d1201b6643982fa746 | refs/heads/master | 2021-07-25T22:44:11.299000 | 2019-08-27T08:07:26 | 2019-08-27T08:07:26 | 52,666,845 | 3 | 0 | null | false | 2021-05-18T18:40:43 | 2016-02-27T12:56:55 | 2019-08-27T08:07:37 | 2021-05-18T18:40:41 | 24,597 | 2 | 0 | 6 | JavaScript | false | false | package com.shau.stuff.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.shau.stuff.domain.LinkContent;
@Component("linkContentDao")
@Transactional
public class LinkContentDao {
@Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public List<LinkContent> loadAllLinkContentItems() {
List<LinkContent> results = new ArrayList<LinkContent>();
try {
Criteria criteria = session().createCriteria(LinkContent.class);
criteria.addOrder(Order.asc("displayOrder"));
results = criteria.list();
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
}
| UTF-8 | Java | 1,117 | java | LinkContentDao.java | Java | [] | null | [] | package com.shau.stuff.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.shau.stuff.domain.LinkContent;
@Component("linkContentDao")
@Transactional
public class LinkContentDao {
@Autowired
private SessionFactory sessionFactory;
public Session session() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
public List<LinkContent> loadAllLinkContentItems() {
List<LinkContent> results = new ArrayList<LinkContent>();
try {
Criteria criteria = session().createCriteria(LinkContent.class);
criteria.addOrder(Order.asc("displayOrder"));
results = criteria.list();
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
}
| 1,117 | 0.716204 | 0.716204 | 42 | 25.595238 | 21.679548 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false | 4 |
d25dbee446fe82a84a2231d1ff7ae7447f03419b | 18,726,057,415,816 | be73ac310c0a406eace8c56ae0fa170158e84dbe | /core/src/main/java/com/cucumber/workshop/render/shader/AmbientLight.java | 8840101df96c6b53fa66bd9a8acf0bc8110418fe | [] | no_license | snorrees/cucumber-game | https://github.com/snorrees/cucumber-game | 36dcda5ac2f00bc0354a262d3e2b81e23a49c6a9 | 8bc27c3387ffaab0179b65d22af075bc2e55aaf1 | refs/heads/master | 2020-12-11T01:39:50.137000 | 2016-03-10T16:02:03 | 2016-03-10T16:02:03 | 47,926,221 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cucumber.workshop.render.shader;
import com.badlogic.gdx.graphics.Color;
public class AmbientLight {
final public Color color = new Color(
0.3f,
0.3f,
0.4f,
1f
);
}
| UTF-8 | Java | 235 | java | AmbientLight.java | Java | [] | null | [] | package com.cucumber.workshop.render.shader;
import com.badlogic.gdx.graphics.Color;
public class AmbientLight {
final public Color color = new Color(
0.3f,
0.3f,
0.4f,
1f
);
}
| 235 | 0.570213 | 0.540426 | 12 | 18.583334 | 15.337635 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
a4526b3e9814c8596bc7aaa548f1329653c552ac | 14,766,097,619,381 | ac9f420012c3e2c4cbee34b3077f3dd72c82bf82 | /src/dao/ClientDaoJdbc.java | 7bb9c538d2620c6e7790e9e89ef8313101c6f586 | [] | no_license | holzhey/LP3_BAR | https://github.com/holzhey/LP3_BAR | c3887a674f9417057759d36a47c762a99af8b400 | 741f02e3693bef29f196629139cd2570d3eec6be | refs/heads/master | 2016-08-06T10:07:00.136000 | 2013-08-14T02:29:05 | 2013-08-14T02:29:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import comm.JdbcConnection;
import entities.Account;
import entities.Client;
import java.util.ArrayList;
import java.util.List;
import util.ColumnType;
public class ClientDaoJdbc extends JdbcConnection<Client> implements ClientDao {
public ClientDaoJdbc()
{
super(Client.getEntityName());
super.setColumns(Client.getColumns());
}
@Override
public List<Client> findByLogin(String login) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Client> findByName(String name) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Client> findByEmail(String email) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| UTF-8 | Java | 1,006 | java | ClientDaoJdbc.java | Java | [] | null | [] | package dao;
import comm.JdbcConnection;
import entities.Account;
import entities.Client;
import java.util.ArrayList;
import java.util.List;
import util.ColumnType;
public class ClientDaoJdbc extends JdbcConnection<Client> implements ClientDao {
public ClientDaoJdbc()
{
super(Client.getEntityName());
super.setColumns(Client.getColumns());
}
@Override
public List<Client> findByLogin(String login) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Client> findByName(String name) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List<Client> findByEmail(String email) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 1,006 | 0.717694 | 0.717694 | 33 | 29.484848 | 38.373856 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 4 |
9947bf32e8d47349753b008fb965d156d6dec6b8 | 32,856,499,878,551 | 9f435af386a4b20ebdc5706372c43218f81d8a68 | /week_1/For Loops/TenTimes.java | 11ebf45ba53f1974c48a32c192523d407b26aa11 | [] | no_license | tranmanhlinh/BE_Novahub_Internship_Linh | https://github.com/tranmanhlinh/BE_Novahub_Internship_Linh | f55f67db1c0b0ca71a8cb24311647500b38a6033 | 4683515fb7f646595de8dcd86699060ae7d8d36c | refs/heads/master | 2021-08-24T05:33:43.053000 | 2017-12-08T07:22:58 | 2017-12-08T07:22:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class TenTimes{
public static void main(String[] args) {
for(int i=0; i<10; i++){
System.out.println("Mr Linh is so cool!");
}
}
} | UTF-8 | Java | 146 | java | TenTimes.java | Java | [
{
"context": "\t\tfor(int i=0; i<10; i++){\n\t\t\tSystem.out.println(\"Mr Linh is so cool!\");\n\t\t}\n\t}\n}",
"end": 122,
"score": 0.9442263245582581,
"start": 115,
"tag": "NAME",
"value": "Mr Linh"
}
] | null | [] | public class TenTimes{
public static void main(String[] args) {
for(int i=0; i<10; i++){
System.out.println("<NAME> is so cool!");
}
}
} | 145 | 0.623288 | 0.60274 | 7 | 20 | 17.237833 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.714286 | false | false | 4 |
b1e71d8abda4f1b2e555697d4f8906ba3ccfbb37 | 6,047,313,989,610 | 2ad847b00a655df02463bce366ef4f60a298e181 | /src/main/java/com/michaelszymczak/training/grokalgo/chapter06/GraphSearch.java | a2dca3da6c8e4e5e14a1acf8ab17b28005304424 | [] | no_license | michaelszymczak/training-algorithms4 | https://github.com/michaelszymczak/training-algorithms4 | 6171aae1a1ff15535d897795879df7236bcfd5ba | d6bfa8f2f304aabbed7c3202d7f5710fe48ade9d | refs/heads/master | 2021-07-06T23:16:52.933000 | 2021-05-09T19:09:56 | 2021-05-09T19:09:56 | 41,629,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.michaelszymczak.training.grokalgo.chapter06;
public interface GraphSearch
{
boolean pathExists(final int[][] graph, final int startNode, final int endNode);
}
| UTF-8 | Java | 176 | java | GraphSearch.java | Java | [
{
"context": "package com.michaelszymczak.training.grokalgo.chapter06;\n\npublic interface Gr",
"end": 27,
"score": 0.9306873679161072,
"start": 12,
"tag": "USERNAME",
"value": "michaelszymczak"
}
] | null | [] | package com.michaelszymczak.training.grokalgo.chapter06;
public interface GraphSearch
{
boolean pathExists(final int[][] graph, final int startNode, final int endNode);
}
| 176 | 0.784091 | 0.772727 | 6 | 28.333334 | 32.045109 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 4 |
87ca0fea1dfcb6baa6f89671d26691f9c8d16fe4 | 9,045,201,194,836 | e50cbc9457177884190bcc841a1c3b0dcace9f3a | /src/yost/drew/turtle/Turtle.java | e008af9a50060319fc3ab1694ee76eb5c06e135b | [] | no_license | dsyost/turtle | https://github.com/dsyost/turtle | 33a8e95a53cba91e05709c94aea874af90e99f62 | f88669ef4f70a050e7e51fda6ffd9a59b62b7584 | refs/heads/master | 2022-10-20T14:51:46.660000 | 2020-07-28T08:51:52 | 2020-07-28T08:51:52 | 282,550,183 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package yost.drew.turtle;
import java.awt.Color;
public class Turtle {
private int x, y;
private boolean penDown = true;
private Panel panel;
private Color color = Color.black;
public Turtle(Panel p) {
x = p.getWidth()/2;
y = p.getHeight()/2;
panel = p;
}
public void setColor(Color c) {
color = c;
}
public void turtleDown(boolean b) {
penDown = b;
}
public boolean isTurtleDown() {
return penDown;
}
public void moveTo(int nx, int ny) {
if(penDown) {
panel.addLine(new Line(x,y,nx,ny,color));
}
x = nx;
y = ny;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setThickness(int t) {
panel.setThickness(t);
}
public void forgetPath() {
panel.addClear();
}
}
| UTF-8 | Java | 760 | java | Turtle.java | Java | [] | null | [] | package yost.drew.turtle;
import java.awt.Color;
public class Turtle {
private int x, y;
private boolean penDown = true;
private Panel panel;
private Color color = Color.black;
public Turtle(Panel p) {
x = p.getWidth()/2;
y = p.getHeight()/2;
panel = p;
}
public void setColor(Color c) {
color = c;
}
public void turtleDown(boolean b) {
penDown = b;
}
public boolean isTurtleDown() {
return penDown;
}
public void moveTo(int nx, int ny) {
if(penDown) {
panel.addLine(new Line(x,y,nx,ny,color));
}
x = nx;
y = ny;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setThickness(int t) {
panel.setThickness(t);
}
public void forgetPath() {
panel.addClear();
}
}
| 760 | 0.626316 | 0.623684 | 54 | 13.074074 | 12.626914 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.574074 | false | false | 4 |
deccd0e140f8a9a56fa165b1571eb5647e545398 | 1,529,008,363,295 | 8177cb4c75901d940cab4850f9cedc00b8c6e41e | /src/java/nowick/html/Body.java | 5933ddcb85c470e2f36804c0d74913c7d332d434 | [] | no_license | rbpark/nowick | https://github.com/rbpark/nowick | b1e2d1409e12ae261cf33723a90f865eb8f44f02 | a68664ff7ead32e370be69daff1c6b5055d17797 | refs/heads/master | 2016-09-06T19:59:55.524000 | 2013-04-18T05:31:48 | 2013-04-18T05:31:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nowick.html;
public class Body extends DomElement {
@Override
public String getTag() {
return "body";
}
}
| UTF-8 | Java | 122 | java | Body.java | Java | [] | null | [] | package nowick.html;
public class Body extends DomElement {
@Override
public String getTag() {
return "body";
}
}
| 122 | 0.696721 | 0.696721 | 10 | 11.2 | 12.552291 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.7 | false | false | 4 |
ddcd63686113e07c05210a9d682758d1ab398ae9 | 19,396,072,375,565 | 230c75098c684ae28304a075991a662769352322 | /hartree-common/src/test/java/org/cmayes/hartree/disp/csv/TestCalculationSnapshotCsvDisplay.java | 0573b0a1b513c496759e4a28019d1b6843f4718d | [
"BSD-3-Clause"
] | permissive | team-mayes/hartree | https://github.com/team-mayes/hartree | 5eb200d51f131344c759d315fbc90fbf38e9cf9e | a6a6b65b17df1679f06435a20673ddbf3f19ba2a | refs/heads/master | 2023-06-25T12:04:54.501000 | 2023-06-15T00:21:00 | 2023-06-15T00:21:00 | 3,242,403 | 0 | 0 | NOASSERTION | false | 2023-08-17T22:34:46 | 2012-01-22T22:03:12 | 2022-03-25T23:01:56 | 2023-08-17T22:34:45 | 8,697 | 2 | 0 | 1 | Java | false | false | package org.cmayes.hartree.disp.csv;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import org.cmayes.hartree.model.BaseResult;
import org.cmayes.hartree.model.def.DefaultBaseResult;
import org.junit.Before;
import org.junit.Test;
import au.com.bytecode.opencsv.CSVReader;
import com.cmayes.common.MediaType;
/**
* Tests for {@link SnapshotCsvDisplay}.
*
* @author cmayes
*/
public class TestCalculationSnapshotCsvDisplay {
/** Logger. */
private static final String[] HEAD_LINE = { "File Name", "Solvent type",
"Stoichiometry", "Charge", "Mult", "Functional", "Basis Set",
"Energy (A.U.)", "dipole", "ZPE (Hartrees)", "H298 (Hartrees)",
"G298 (Hartrees)", "Freq 1", "Freq 2", "BSSE (Hartrees)" };
private static final String[] ALT_HEAD_LINE = { "Alt File Name",
"Solvent type", "Stoichiometry", "Charge", "Alt Mult",
"Functional", "Basis Set", "Energy (A.U.)", "dipole",
"ZPE (Hartrees)", "H298 (Hartrees)", "G298 (Hartrees)", "Freq 1",
"Freq 2" };
private static final String[] DATA_LINE = { "someFileName.txt", "water",
"C6H12NaO6(1+)", "1", "1", "m062x", "6-31+g(2df,p)",
"-849.236562347", "19.6701", "0.200499", "-1260.493395",
"-1260.568296", "60.7784", "90.3398", "N/A" };
private static final String[] EMPTY_LINE = { "N/A", "N/A", "N/A", "N/A",
"N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
"N/A", "N/A" };
private SnapshotCsvDisplay disp;
/**
* Create an instance of the display class before each test.
*/
@Before
public void setUp() {
disp = new SnapshotCsvDisplay();
}
/**
* Tests running against a fully-formed test instance.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testFullData() throws Exception {
final StringWriter stringWriter = new StringWriter();
assertTrue(disp.isFirst());
disp.write(stringWriter, getTestInst());
assertFalse(disp.isFirst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(DATA_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Tests running against an empty test instance.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testEmptyData() throws Exception {
final StringWriter stringWriter = new StringWriter();
assertTrue(disp.isFirst());
disp.write(stringWriter, new DefaultBaseResult());
assertFalse(disp.isFirst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(EMPTY_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Tests running against a full instance with an alternate header line.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testAltHead() throws Exception {
assertThat(disp.getMediaType(), equalTo(MediaType.CSV));
assertNull(disp.getHeaderRow());
disp.setHeaderRow(ALT_HEAD_LINE);
assertThat(disp.getHeaderRow(), equalTo(ALT_HEAD_LINE));
final StringWriter stringWriter = new StringWriter();
disp.write(stringWriter, getTestInst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(ALT_HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(DATA_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Creates a test instance to display.
*
* @return A test instance.
*/
private BaseResult getTestInst() {
final DefaultBaseResult snap = new DefaultBaseResult();
snap.setSourceName("someFileName.txt");
snap.setSolvent("water");
snap.setStoichiometry("C6H12NaO6(1+)");
snap.setElecEn(-849.236562347);
snap.setFunctional("m062x");
snap.setCharge(1);
snap.setMult(1);
snap.setFrequencyValues(Arrays.asList(60.7784, 90.3398));
snap.setZpeCorrection(0.200499);
snap.setGibbs298(-1260.568296);
snap.setEnthalpy298(-1260.493395);
snap.setBasisSet("6-31+g(2df,p)");
snap.setDipoleMomentTotal(19.6701);
return snap;
}
}
| UTF-8 | Java | 5,203 | java | TestCalculationSnapshotCsvDisplay.java | Java | [
{
"context": "sts for {@link SnapshotCsvDisplay}.\n * \n * @author cmayes\n */\npublic class TestCalculationSnapshotCsvDispla",
"end": 635,
"score": 0.998681366443634,
"start": 629,
"tag": "USERNAME",
"value": "cmayes"
}
] | null | [] | package org.cmayes.hartree.disp.csv;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import org.cmayes.hartree.model.BaseResult;
import org.cmayes.hartree.model.def.DefaultBaseResult;
import org.junit.Before;
import org.junit.Test;
import au.com.bytecode.opencsv.CSVReader;
import com.cmayes.common.MediaType;
/**
* Tests for {@link SnapshotCsvDisplay}.
*
* @author cmayes
*/
public class TestCalculationSnapshotCsvDisplay {
/** Logger. */
private static final String[] HEAD_LINE = { "File Name", "Solvent type",
"Stoichiometry", "Charge", "Mult", "Functional", "Basis Set",
"Energy (A.U.)", "dipole", "ZPE (Hartrees)", "H298 (Hartrees)",
"G298 (Hartrees)", "Freq 1", "Freq 2", "BSSE (Hartrees)" };
private static final String[] ALT_HEAD_LINE = { "Alt File Name",
"Solvent type", "Stoichiometry", "Charge", "Alt Mult",
"Functional", "Basis Set", "Energy (A.U.)", "dipole",
"ZPE (Hartrees)", "H298 (Hartrees)", "G298 (Hartrees)", "Freq 1",
"Freq 2" };
private static final String[] DATA_LINE = { "someFileName.txt", "water",
"C6H12NaO6(1+)", "1", "1", "m062x", "6-31+g(2df,p)",
"-849.236562347", "19.6701", "0.200499", "-1260.493395",
"-1260.568296", "60.7784", "90.3398", "N/A" };
private static final String[] EMPTY_LINE = { "N/A", "N/A", "N/A", "N/A",
"N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", "N/A",
"N/A", "N/A" };
private SnapshotCsvDisplay disp;
/**
* Create an instance of the display class before each test.
*/
@Before
public void setUp() {
disp = new SnapshotCsvDisplay();
}
/**
* Tests running against a fully-formed test instance.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testFullData() throws Exception {
final StringWriter stringWriter = new StringWriter();
assertTrue(disp.isFirst());
disp.write(stringWriter, getTestInst());
assertFalse(disp.isFirst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(DATA_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Tests running against an empty test instance.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testEmptyData() throws Exception {
final StringWriter stringWriter = new StringWriter();
assertTrue(disp.isFirst());
disp.write(stringWriter, new DefaultBaseResult());
assertFalse(disp.isFirst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(EMPTY_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Tests running against a full instance with an alternate header line.
*
* @throws Exception
* When there is a problem.
*/
@Test
public void testAltHead() throws Exception {
assertThat(disp.getMediaType(), equalTo(MediaType.CSV));
assertNull(disp.getHeaderRow());
disp.setHeaderRow(ALT_HEAD_LINE);
assertThat(disp.getHeaderRow(), equalTo(ALT_HEAD_LINE));
final StringWriter stringWriter = new StringWriter();
disp.write(stringWriter, getTestInst());
final CSVReader csvReader = new CSVReader(new StringReader(
stringWriter.toString()));
try {
assertThat(csvReader.readNext(), equalTo(ALT_HEAD_LINE));
assertThat(csvReader.readNext(), equalTo(DATA_LINE));
assertNull(csvReader.readNext());
} finally {
csvReader.close();
}
}
/**
* Creates a test instance to display.
*
* @return A test instance.
*/
private BaseResult getTestInst() {
final DefaultBaseResult snap = new DefaultBaseResult();
snap.setSourceName("someFileName.txt");
snap.setSolvent("water");
snap.setStoichiometry("C6H12NaO6(1+)");
snap.setElecEn(-849.236562347);
snap.setFunctional("m062x");
snap.setCharge(1);
snap.setMult(1);
snap.setFrequencyValues(Arrays.asList(60.7784, 90.3398));
snap.setZpeCorrection(0.200499);
snap.setGibbs298(-1260.568296);
snap.setEnthalpy298(-1260.493395);
snap.setBasisSet("6-31+g(2df,p)");
snap.setDipoleMomentTotal(19.6701);
return snap;
}
}
| 5,203 | 0.598885 | 0.567365 | 151 | 33.456955 | 23.708979 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.887417 | false | false | 4 |
cefb8bd5da13dcea54d5144cebaa82c82c05adb8 | 30,502,857,753,626 | 49fd3373d12d795ff922128a3f721626268c099a | /src/main/java/com/example/demo/post/controller/PostController.java | 2f3916a89750acb77fbf3c254339be4cd3feb462 | [] | no_license | taesikyoo/kiworkshop-web | https://github.com/taesikyoo/kiworkshop-web | 108507750306c76dc0a16d0271f60800b184f893 | 24a4c498895a39a69082f8bb8722145cd2e68673 | refs/heads/master | 2022-11-06T17:29:11.165000 | 2020-06-19T15:45:59 | 2020-06-19T15:45:59 | 256,544,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.post.controller;
import com.example.demo.post.dto.CreatePostRequest;
import com.example.demo.post.dto.PostResponse;
import com.example.demo.post.service.PostService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping("/posts")
public PostResponse create(HttpSession httpSession, @RequestBody CreatePostRequest createPostRequest) {
return postService.create(httpSession, createPostRequest);
}
@PostMapping("/posts/{id}")
public void likePost(HttpSession httpSession, @PathVariable Long id) {
postService.likePost(httpSession, id);
}
@GetMapping("/posts")
public List<PostResponse> getAll() {
return postService.getAll();
}
@GetMapping("/posts/{id}")
public PostResponse get(@PathVariable Long id) {
return postService.readPost(id);
}
@PutMapping("/posts/{id}")
public PostResponse update(@PathVariable Long id, @RequestParam String content) {
return postService.update(id, content);
}
@DeleteMapping("/posts/{id}")
public void delete(@PathVariable Long id) {
postService.delete(id);
}
}
| UTF-8 | Java | 1,404 | java | PostController.java | Java | [] | null | [] | package com.example.demo.post.controller;
import com.example.demo.post.dto.CreatePostRequest;
import com.example.demo.post.dto.PostResponse;
import com.example.demo.post.service.PostService;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@PostMapping("/posts")
public PostResponse create(HttpSession httpSession, @RequestBody CreatePostRequest createPostRequest) {
return postService.create(httpSession, createPostRequest);
}
@PostMapping("/posts/{id}")
public void likePost(HttpSession httpSession, @PathVariable Long id) {
postService.likePost(httpSession, id);
}
@GetMapping("/posts")
public List<PostResponse> getAll() {
return postService.getAll();
}
@GetMapping("/posts/{id}")
public PostResponse get(@PathVariable Long id) {
return postService.readPost(id);
}
@PutMapping("/posts/{id}")
public PostResponse update(@PathVariable Long id, @RequestParam String content) {
return postService.update(id, content);
}
@DeleteMapping("/posts/{id}")
public void delete(@PathVariable Long id) {
postService.delete(id);
}
}
| 1,404 | 0.710114 | 0.710114 | 49 | 27.653061 | 25.250217 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
780e64977e1e872d0812d84c0f58cc764c9b224c | 27,195,732,921,058 | b72af8716fee0826b53a61cdd015f898d6a70a9f | /user-registration/src/main/java/com/stackroute/registration/controller/UserRegistrationController.java | a0cf7a47e20a7666905601b103606248867d3775 | [
"Apache-2.0"
] | permissive | gopal10/Backup_oracle | https://github.com/gopal10/Backup_oracle | 3ab1d19d7b4d4d29362daf4d6e53eb10db9355ed | 5778efaffa88e46ae17f222b1e4c093c4126af24 | refs/heads/master | 2020-05-02T13:20:09.877000 | 2019-03-27T11:37:25 | 2019-03-27T11:37:25 | 177,981,364 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stackroute.registration.controller;
import com.stackroute.registration.domain.UserRegistation;
import com.stackroute.registration.service.UserRegistrationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1")
@CrossOrigin
public class UserRegistrationController {
private UserRegistrationServiceImpl userRegistrationService;
@Autowired
public UserRegistrationController(UserRegistrationServiceImpl userServiceImpl) {
this.userRegistrationService = userServiceImpl;
}
@PostMapping("/registration")
public ResponseEntity<UserRegistation> saveUser(@RequestBody UserRegistation userRegistation){
return new ResponseEntity<UserRegistation>(userRegistrationService.saveUser(userRegistation),HttpStatus.CREATED);
}
}
| UTF-8 | Java | 976 | java | UserRegistrationController.java | Java | [] | null | [] | package com.stackroute.registration.controller;
import com.stackroute.registration.domain.UserRegistation;
import com.stackroute.registration.service.UserRegistrationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1")
@CrossOrigin
public class UserRegistrationController {
private UserRegistrationServiceImpl userRegistrationService;
@Autowired
public UserRegistrationController(UserRegistrationServiceImpl userServiceImpl) {
this.userRegistrationService = userServiceImpl;
}
@PostMapping("/registration")
public ResponseEntity<UserRegistation> saveUser(@RequestBody UserRegistation userRegistation){
return new ResponseEntity<UserRegistation>(userRegistrationService.saveUser(userRegistation),HttpStatus.CREATED);
}
}
| 976 | 0.82582 | 0.824795 | 25 | 38.040001 | 32.999977 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 4 |
8cc9e77bb9960f39f8bab6737db37f4287ac36a6 | 5,171,140,665,284 | 75bb3a44cd23d42a4440395d5f2c9f19f0c916e0 | /src/main/java/com/bourntec/apmg/entity/ReturnItems.java | 6e60f15c2ac9019010e8df96e218163d2758678d | [] | no_license | Nidhikamal/entity | https://github.com/Nidhikamal/entity | 996a460d78bc6fe3c0278b2e5c8bed72d7ebe7ea | 3013ee704efb4c99ee9e353e803db79cdead93ac | refs/heads/master | 2023-01-08T08:21:47.100000 | 2020-10-27T14:00:12 | 2020-10-27T14:00:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bourntec.apmg.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "return_items")
public class ReturnItems {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "return_no",nullable=false)
private String returnNo;
@Column(name = "job_no",nullable=false)
private String jobNo;
@Column(name = "inv_no",nullable=false)
private String invNo;
@Column(name = "no_pc_p",nullable=false)
private Double noPcP;
@Column(name = "no_pc_w",nullable=true)
private Double noPcW;
@Column(name = "unit_price",nullable=true)
private Double unitPrice;
@Column(name = "\"desc\"",nullable=true)
private String desc;
@Column(name = "misc_chg",nullable=true)
private Double miscChg;
@Column(name = "desc1",nullable=true)
private String desc1;
@Column(name = "location_code",nullable=true)
private String locationCode;
@Column(name = "discount",nullable=true)
private Double discount;
@Column(name = "tax_per",nullable=true)
private Double taxPer;
@Column(name = "item_discount",nullable=true)
private Double itemDiscount;
@Column(name = "original_unitprice",nullable=true)
private Double originalUnitprice;
@Column(name = "from_show",nullable=true)
private String fromShow;
@Column(name = "memo_no",nullable=true)
private String memoNo;
@Column(name = "to_show")
private String toShow;
}
| UTF-8 | Java | 1,741 | java | ReturnItems.java | Java | [] | null | [] | package com.bourntec.apmg.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "return_items")
public class ReturnItems {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "return_no",nullable=false)
private String returnNo;
@Column(name = "job_no",nullable=false)
private String jobNo;
@Column(name = "inv_no",nullable=false)
private String invNo;
@Column(name = "no_pc_p",nullable=false)
private Double noPcP;
@Column(name = "no_pc_w",nullable=true)
private Double noPcW;
@Column(name = "unit_price",nullable=true)
private Double unitPrice;
@Column(name = "\"desc\"",nullable=true)
private String desc;
@Column(name = "misc_chg",nullable=true)
private Double miscChg;
@Column(name = "desc1",nullable=true)
private String desc1;
@Column(name = "location_code",nullable=true)
private String locationCode;
@Column(name = "discount",nullable=true)
private Double discount;
@Column(name = "tax_per",nullable=true)
private Double taxPer;
@Column(name = "item_discount",nullable=true)
private Double itemDiscount;
@Column(name = "original_unitprice",nullable=true)
private Double originalUnitprice;
@Column(name = "from_show",nullable=true)
private String fromShow;
@Column(name = "memo_no",nullable=true)
private String memoNo;
@Column(name = "to_show")
private String toShow;
}
| 1,741 | 0.692131 | 0.690982 | 74 | 22.527027 | 16.785791 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.851351 | false | false | 4 |
72242dc341e885188ecd3c7b86281d252e0006d1 | 26,980,984,556,090 | cab75fc469c08f8e4647c2cbaa835fea94d2d165 | /lunatech.airport-search-app/src/test/java/com/lunatech/airport_search_app/test/service/TestRunwayService.java | 891e7914ea401ae53b93414376b31790f88a4d80 | [
"Apache-2.0"
] | permissive | taoranyan/lunatech.airport-search-app | https://github.com/taoranyan/lunatech.airport-search-app | e59912af3155d15a990f982884580271bd1fe02a | 2e70a2d5ed500262eb0d1a9c439107e8cc2365f3 | refs/heads/master | 2021-01-21T15:04:53.099000 | 2016-09-16T07:23:23 | 2016-09-16T07:23:23 | 68,359,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lunatech.airport_search_app.test.service;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lunatech.airport_search_app.dao.AirportDAO;
import com.lunatech.airport_search_app.dao.RunwayDAO;
import com.lunatech.airport_search_app.model.Airport;
import com.lunatech.airport_search_app.model.Runway;
import com.lunatech.airport_search_app.service.RunwayService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:airport-search-app-application-context.xml")
public class TestRunwayService {
@Autowired
private RunwayService rserv;
@Autowired
private AirportDAO adao;
@Autowired
private RunwayDAO rdao;
@Before
public void setup()
{
Airport a1 = new Airport();
a1.setId(2001);
a1.setIdent("Test2001");
a1.setName("TestAirportDAO1");
a1.setIsoCountry("CHINA");
adao.save(a1);
Runway r1 = new Runway();
r1.setId(3001);
r1.setAirportRef(2001);
r1.setAirportIdent("Test2001");
r1.setAirport(a1);
Runway r2 = new Runway();
r2.setId(3002);
r2.setAirportRef(2001);
r2.setAirportIdent("Test2001");
r2.setAirport(a1);
rdao.save(r1);
rdao.save(r2);
}
@Test
public void TestGetRunwaysByAirportId()
{
Integer id = 2001;
List<Runway> runways = rserv.getRunwaysByAirportId(id);
assertEquals(runways.size(), 2);
}
@Test
public void TestGetRunwaysByAirport()
{
Airport airport = adao.getAirportById(2001);
List<Runway> runways = rserv.getRunwaysByAirport(airport);
assertEquals(runways.size(), 2);
}
@Test
public void TestGetALlRunways(){
List<Runway> runways = rserv.getAllRunway();
assertEquals(runways.size(), 2);
}
@Test
public void TestDumpRunwayFromCSV(){
}
@Test
public void deleteMocks()
{
Airport a1 = adao.getAirportById(2001);
Runway r1 = rdao.getRunwayById(3001);
Runway r2 = rdao.getRunwayById(3002);
adao.delete(a1);
rdao.delete(r1);
rdao.delete(r2);
}
}
| UTF-8 | Java | 2,246 | java | TestRunwayService.java | Java | [] | null | [] | package com.lunatech.airport_search_app.test.service;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lunatech.airport_search_app.dao.AirportDAO;
import com.lunatech.airport_search_app.dao.RunwayDAO;
import com.lunatech.airport_search_app.model.Airport;
import com.lunatech.airport_search_app.model.Runway;
import com.lunatech.airport_search_app.service.RunwayService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:airport-search-app-application-context.xml")
public class TestRunwayService {
@Autowired
private RunwayService rserv;
@Autowired
private AirportDAO adao;
@Autowired
private RunwayDAO rdao;
@Before
public void setup()
{
Airport a1 = new Airport();
a1.setId(2001);
a1.setIdent("Test2001");
a1.setName("TestAirportDAO1");
a1.setIsoCountry("CHINA");
adao.save(a1);
Runway r1 = new Runway();
r1.setId(3001);
r1.setAirportRef(2001);
r1.setAirportIdent("Test2001");
r1.setAirport(a1);
Runway r2 = new Runway();
r2.setId(3002);
r2.setAirportRef(2001);
r2.setAirportIdent("Test2001");
r2.setAirport(a1);
rdao.save(r1);
rdao.save(r2);
}
@Test
public void TestGetRunwaysByAirportId()
{
Integer id = 2001;
List<Runway> runways = rserv.getRunwaysByAirportId(id);
assertEquals(runways.size(), 2);
}
@Test
public void TestGetRunwaysByAirport()
{
Airport airport = adao.getAirportById(2001);
List<Runway> runways = rserv.getRunwaysByAirport(airport);
assertEquals(runways.size(), 2);
}
@Test
public void TestGetALlRunways(){
List<Runway> runways = rserv.getAllRunway();
assertEquals(runways.size(), 2);
}
@Test
public void TestDumpRunwayFromCSV(){
}
@Test
public void deleteMocks()
{
Airport a1 = adao.getAirportById(2001);
Runway r1 = rdao.getRunwayById(3001);
Runway r2 = rdao.getRunwayById(3002);
adao.delete(a1);
rdao.delete(r1);
rdao.delete(r2);
}
}
| 2,246 | 0.738647 | 0.700801 | 103 | 20.805826 | 20.02186 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.660194 | false | false | 4 |
dd215bfb24a0106ea7fee9e44179b816b307fa8e | 10,264,971,846,580 | 76c055e35dfae4420987b5c2e709212e4b47cd08 | /src/main/java/myTasks/Todo.java | ca66658f46d74d5a4479847f1b0c69bcc594a835 | [] | no_license | zyleet/duke | https://github.com/zyleet/duke | 1768262467f7ecaebf1da9097fd964d60ae1314c | 6c4b98ae116d9c1116fd951181a62a170233c087 | refs/heads/master | 2020-07-09T08:58:39.502000 | 2019-09-12T07:48:03 | 2019-09-12T07:48:03 | 203,934,595 | 0 | 0 | null | true | 2019-08-23T06:07:01 | 2019-08-23T06:07:01 | 2019-08-17T23:01:41 | 2019-08-22T11:20:21 | 1,388 | 0 | 0 | 0 | null | false | false | package myTasks;
import myTasks.Task;
/**
* Class that inherits many of its methods from its superclass Task.
* Unlike the deadline and event task classes, this class does not parse date inputs.
*
* @author Lee Zhen Yu
* @version %I%
* @since 1.0
*/
public class Todo extends Task {
protected String by;
/**
* Constructor that takes in the task description.
*
* @param description The description of this toodo class.
*/
public Todo(String description) {
super(description);
}
/**
* Method to return the type of task.
*
* @return Since this is a todoo class, return [T}
*/
public String getType() {
return "[T]";
}
/**
* Method that overrides the same method in the parent class.
* It returns the full data of this toddo task in a format readable to the user.
*
* @return The full data of the task class as a string.
*/
//Override by using the same name of function from parent
public String getStatusIcon() {
return "[T]" + "[" + (isDone ? "Y" : "N") + "] " + this.description;
}
}
| UTF-8 | Java | 1,131 | java | Todo.java | Java | [
{
"context": "is class does not parse date inputs.\n *\n * @author Lee Zhen Yu\n * @version %I%\n * @since 1.0\n */\npublic class To",
"end": 224,
"score": 0.9998027682304382,
"start": 213,
"tag": "NAME",
"value": "Lee Zhen Yu"
}
] | null | [] | package myTasks;
import myTasks.Task;
/**
* Class that inherits many of its methods from its superclass Task.
* Unlike the deadline and event task classes, this class does not parse date inputs.
*
* @author <NAME>
* @version %I%
* @since 1.0
*/
public class Todo extends Task {
protected String by;
/**
* Constructor that takes in the task description.
*
* @param description The description of this toodo class.
*/
public Todo(String description) {
super(description);
}
/**
* Method to return the type of task.
*
* @return Since this is a todoo class, return [T}
*/
public String getType() {
return "[T]";
}
/**
* Method that overrides the same method in the parent class.
* It returns the full data of this toddo task in a format readable to the user.
*
* @return The full data of the task class as a string.
*/
//Override by using the same name of function from parent
public String getStatusIcon() {
return "[T]" + "[" + (isDone ? "Y" : "N") + "] " + this.description;
}
}
| 1,126 | 0.611848 | 0.61008 | 46 | 23.565218 | 25.605412 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.173913 | false | false | 4 |
3776ff93984cba13773d35ca164f627505e21d63 | 2,723,009,274,968 | 3e5a7e2a6ca3aa7571dd00e3a7ad2667a78a17a1 | /src/main/java/hudson/plugins/tasks/TaskAnnotationsLabelProvider.java | 781e07124dc3a8e9922dcc9f850ccd9d597552c6 | [
"MIT"
] | permissive | jenkinsci/tasks-plugin | https://github.com/jenkinsci/tasks-plugin | 804a1dab888ba832763946e01bfe8f3d52e62b32 | cffedd526897adaf326291fce53e59f93765aa8c | refs/heads/master | 2023-06-01T03:11:00.835000 | 2019-09-24T11:34:22 | 2019-09-24T11:34:22 | 1,169,225 | 1 | 8 | MIT | false | 2019-09-24T10:34:24 | 2010-12-14T20:39:05 | 2019-06-10T18:19:39 | 2018-12-21T13:54:20 | 2,022 | 7 | 9 | 1 | Java | false | false | package hudson.plugins.tasks;
import hudson.plugins.analysis.util.model.AnnotationsLabelProvider;
/**
* A label provider with a different 'warnings' tab.
*
* @author Ullrich Hafner
*/
public class TaskAnnotationsLabelProvider extends AnnotationsLabelProvider {
public TaskAnnotationsLabelProvider(final String packageCategoryTitle) {
super(packageCategoryTitle);
}
@Override
public String getWarnings() {
return Messages.Tasks_ProjectAction_Name();
}
}
| UTF-8 | Java | 496 | java | TaskAnnotationsLabelProvider.java | Java | [
{
"context": "der with a different 'warnings' tab.\n *\n * @author Ullrich Hafner\n */\npublic class TaskAnnotationsLabelProvider ext",
"end": 185,
"score": 0.9998477101325989,
"start": 171,
"tag": "NAME",
"value": "Ullrich Hafner"
}
] | null | [] | package hudson.plugins.tasks;
import hudson.plugins.analysis.util.model.AnnotationsLabelProvider;
/**
* A label provider with a different 'warnings' tab.
*
* @author <NAME>
*/
public class TaskAnnotationsLabelProvider extends AnnotationsLabelProvider {
public TaskAnnotationsLabelProvider(final String packageCategoryTitle) {
super(packageCategoryTitle);
}
@Override
public String getWarnings() {
return Messages.Tasks_ProjectAction_Name();
}
}
| 488 | 0.745968 | 0.745968 | 19 | 25.105263 | 26.619926 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false | 4 |
4117639374cadeb2eda003955a62d96173f5f4b0 | 28,226,525,108,530 | f0ff8f3671d7d842d4010676670225fca6f9cab3 | /src/main/java/przan/mobilnaredovalnica/Registracija.java | 8325ddfd942267373e84c473f15c4f5593a411a9 | [] | no_license | RokKos/MobilnaRedovalnica | https://github.com/RokKos/MobilnaRedovalnica | 5d978591e2dc93e0861e4205e7305eef564c733c | b1f14d5123018d472bec2338a2f12295f5c3fc7a | refs/heads/master | 2020-04-25T04:06:22.353000 | 2014-08-16T18:10:53 | 2014-08-16T18:10:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package przan.mobilnaredovalnica;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by rok on 7/5/13.
*/
public class Registracija extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registracija);
}
public void makeNewUser(View view){
Sola prev = Sola.getsola();
//Ustvarjanje novega uporabnika
EditText upor = (EditText)findViewById(R.id.editUpor);
EditText geslo1 = (EditText)findViewById(R.id.editGeslo1);
EditText geslo2 = (EditText)findViewById(R.id.editGeslo2);
//preverjanje če uporabnik ze obstaja
boolean jenot = false;
for (int i=0; i<prev.sola.size(); i++){
if (prev.sola.get(i).username.equals(upor.getText().toString())){
jenot = true;
break;
}
}
AlertDialog.Builder ald;
if (jenot){
upor.setText("");
geslo1.setText("");
geslo2.setText("");
ald = new AlertDialog.Builder(this)
.setTitle("Napaka")
.setMessage("Uporabnik že obstaja!")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
ald.show();
}
//Preverjanje gesel
else if (!geslo1.getText().toString().equals(geslo2.getText().toString())){
geslo1.setText("");
geslo2.setText("");
ald = new AlertDialog.Builder(this)
.setTitle("Napaka")
.setMessage("Gesli se ne ujemata. Prosim poskusite ponovno.")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
ald.show();
}
//Delanje uporabnika z default settingi
else{
Sola newUser = Sola.getsola();
User ime = new User();
ime.username = upor.getText().toString();
ime.password = geslo1.getText().toString();
ArrayList<Letnik> pred = new ArrayList<Letnik>();
String[] let = new String[] { "1.letnik","2.letnik","3.letnik","4.letnik",};
Letnik t;
//Pretvarjanje
for (int i=0; i<let.length; i++){
t= new Letnik();
t.ime=let[i];
pred.add(t);
}
ArrayList<Predmet> predmet = new ArrayList<Predmet>();
String [] imepred = new String[] { "Matematika", "Slovenščina", "Angleščina"};
Predmet p;
//Pretvarjanje
for (int i=0; i<imepred.length; i++){
p=new Predmet();
p.ime=imepred[i];
predmet.add(p);
}
Integer index = new Integer(newUser.sola.size());
if (index<0) index=0;
//Dodajanje in shranjevanje
newUser.sola.add(ime);
for (int i=0; i<pred.size(); i++){
newUser.sola.get(index).letnik.add(pred.get(i));
}
for (int i=0; i<pred.size(); i++){
for(int j=0; j<predmet.size(); j++){
newUser.sola.get(index).letnik.get(i).predmeti.add(predmet.get(j));
}
}
newUser.shrani();
ald = new AlertDialog.Builder(this)
.setTitle("Čestitamo")
.setMessage("Uporabnik je bil uspešno narejen")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ald.show();
}
}
} | UTF-8 | Java | 4,214 | java | Registracija.java | Java | [
{
"context": "t;\n\nimport java.util.ArrayList;\n\n/**\n * Created by rok on 7/5/13.\n */\npublic class Registracija extends ",
"end": 271,
"score": 0.9995672106742859,
"start": 268,
"tag": "USERNAME",
"value": "rok"
},
{
"context": " User ime = new User();\n ime.username = upor.getText().toString();\n ime.password = ",
"end": 2399,
"score": 0.9926900863647461,
"start": 2395,
"tag": "USERNAME",
"value": "upor"
},
{
"context": "r.getText().toString();\n ime.password = geslo1.getText().toString();\n ArrayList<Letni",
"end": 2455,
"score": 0.9976997375488281,
"start": 2449,
"tag": "PASSWORD",
"value": "geslo1"
}
] | null | [] | package przan.mobilnaredovalnica;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by rok on 7/5/13.
*/
public class Registracija extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registracija);
}
public void makeNewUser(View view){
Sola prev = Sola.getsola();
//Ustvarjanje novega uporabnika
EditText upor = (EditText)findViewById(R.id.editUpor);
EditText geslo1 = (EditText)findViewById(R.id.editGeslo1);
EditText geslo2 = (EditText)findViewById(R.id.editGeslo2);
//preverjanje če uporabnik ze obstaja
boolean jenot = false;
for (int i=0; i<prev.sola.size(); i++){
if (prev.sola.get(i).username.equals(upor.getText().toString())){
jenot = true;
break;
}
}
AlertDialog.Builder ald;
if (jenot){
upor.setText("");
geslo1.setText("");
geslo2.setText("");
ald = new AlertDialog.Builder(this)
.setTitle("Napaka")
.setMessage("Uporabnik že obstaja!")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
ald.show();
}
//Preverjanje gesel
else if (!geslo1.getText().toString().equals(geslo2.getText().toString())){
geslo1.setText("");
geslo2.setText("");
ald = new AlertDialog.Builder(this)
.setTitle("Napaka")
.setMessage("Gesli se ne ujemata. Prosim poskusite ponovno.")
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
ald.show();
}
//Delanje uporabnika z default settingi
else{
Sola newUser = Sola.getsola();
User ime = new User();
ime.username = upor.getText().toString();
ime.password = <PASSWORD>.getText().toString();
ArrayList<Letnik> pred = new ArrayList<Letnik>();
String[] let = new String[] { "1.letnik","2.letnik","3.letnik","4.letnik",};
Letnik t;
//Pretvarjanje
for (int i=0; i<let.length; i++){
t= new Letnik();
t.ime=let[i];
pred.add(t);
}
ArrayList<Predmet> predmet = new ArrayList<Predmet>();
String [] imepred = new String[] { "Matematika", "Slovenščina", "Angleščina"};
Predmet p;
//Pretvarjanje
for (int i=0; i<imepred.length; i++){
p=new Predmet();
p.ime=imepred[i];
predmet.add(p);
}
Integer index = new Integer(newUser.sola.size());
if (index<0) index=0;
//Dodajanje in shranjevanje
newUser.sola.add(ime);
for (int i=0; i<pred.size(); i++){
newUser.sola.get(index).letnik.add(pred.get(i));
}
for (int i=0; i<pred.size(); i++){
for(int j=0; j<predmet.size(); j++){
newUser.sola.get(index).letnik.get(i).predmeti.add(predmet.get(j));
}
}
newUser.shrani();
ald = new AlertDialog.Builder(this)
.setTitle("Čestitamo")
.setMessage("Uporabnik je bil uspešno narejen")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
ald.show();
}
}
} | 4,218 | 0.510699 | 0.50428 | 117 | 34.957264 | 23.745947 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.649573 | false | false | 4 |
b1d75b750e92f94a43b88c43c2f5e9639fb8d68d | 2,602,750,222,587 | a6e09fda8d2986f4cf55febd55377d5a630f10c3 | /src/main/java/com/kodilla/car_rent_backend/domain/VehicleParam.java | c835ea6f4d0c258b8c321bf9c66a79e139fd99ba | [] | no_license | nowy513/car_rent-backend | https://github.com/nowy513/car_rent-backend | 99b62980ba35268536a5601cd45882c10d5ab793 | da280d8cd72b8882651680856672425e33526338 | refs/heads/master | 2023-07-15T21:37:43.048000 | 2021-08-18T10:10:33 | 2021-08-18T10:10:33 | 394,635,820 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kodilla.car_rent_backend.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "VEHICLE_PARAMETERS")
public class VehicleParam {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "VEHICLE_PARAM_ID", unique = true)
private Long id;
@NotNull
@Column(name = "BRAND")
private String brand;
@NotNull
@Column(name = "MODEL")
private String model;
@NotNull
@Column(name = "COLOR")
private String color;
@NotNull
@Column(name = "BODY_TYPE")
private String bodyType;
@NotNull
@Column(name = "FUEL_TYPE")
private String fuelType;
@NotNull
@Column(name = "NUMBER_OF_SEATS")
private int numberOfSeats;
@NotNull
@Column(name = "NUMBER_OF_DOORS")
private int numberOfDoors;
@NotNull
@Column(name = "ENGINE_CAPACITY")
private double engineCapacity;
@NotNull
@Column(name = "VEHICLE_MILEAGE")
private BigDecimal vehicleMileage;
@NotNull
@Column(name = "VIN_NUMBER")
private int vinNumber;
@NotNull
@Column(name = "POWER")
private double power;
@OneToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
@JoinColumn(name = "VEHICLE_ID")
private Vehicle vehicle;
} | UTF-8 | Java | 1,503 | java | VehicleParam.java | Java | [] | null | [] | package com.kodilla.car_rent_backend.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "VEHICLE_PARAMETERS")
public class VehicleParam {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "VEHICLE_PARAM_ID", unique = true)
private Long id;
@NotNull
@Column(name = "BRAND")
private String brand;
@NotNull
@Column(name = "MODEL")
private String model;
@NotNull
@Column(name = "COLOR")
private String color;
@NotNull
@Column(name = "BODY_TYPE")
private String bodyType;
@NotNull
@Column(name = "FUEL_TYPE")
private String fuelType;
@NotNull
@Column(name = "NUMBER_OF_SEATS")
private int numberOfSeats;
@NotNull
@Column(name = "NUMBER_OF_DOORS")
private int numberOfDoors;
@NotNull
@Column(name = "ENGINE_CAPACITY")
private double engineCapacity;
@NotNull
@Column(name = "VEHICLE_MILEAGE")
private BigDecimal vehicleMileage;
@NotNull
@Column(name = "VIN_NUMBER")
private int vinNumber;
@NotNull
@Column(name = "POWER")
private double power;
@OneToOne(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
@JoinColumn(name = "VEHICLE_ID")
private Vehicle vehicle;
} | 1,503 | 0.685296 | 0.685296 | 72 | 19.888889 | 15.600531 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.319444 | false | false | 4 |
34efd90ead570818d2196049a9beaf3a9f37263e | 12,455,405,200,921 | 1e2e29f06e725364a868933d1f5778cc566efd9e | /camelot-test-maven-plugin/src/main/java/ru/yandex/qatools/camelot/maven/RunMojo.java | bea49e7562a3e4fda83d53207ee68c6a202d4a61 | [
"Apache-2.0"
] | permissive | karelinoleg/camelot | https://github.com/karelinoleg/camelot | 10c1bf28939e2522179c427c59afb04e9a649eb1 | 3ea4afbb12fad03a3bd83548f4be5811e2197b0a | refs/heads/master | 2020-03-28T18:50:05.714000 | 2018-09-15T18:33:51 | 2018-09-15T18:33:51 | 148,916,959 | 0 | 0 | null | true | 2018-09-15T15:58:01 | 2018-09-15T15:58:01 | 2017-11-25T13:41:45 | 2016-04-28T20:44:01 | 1,605 | 0 | 0 | 0 | null | false | null | package ru.yandex.qatools.camelot.maven;
import ch.lambdaj.function.convert.Converter;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;
import ru.qatools.clay.aether.Aether;
import ru.qatools.clay.aether.AetherException;
import ru.qatools.clay.utils.archive.PathJarEntryFilter;
import ru.yandex.qatools.camelot.config.Plugin;
import ru.yandex.qatools.camelot.config.PluginsConfig;
import ru.yandex.qatools.camelot.config.PluginsSource;
import ru.yandex.qatools.camelot.maven.web.ConfigurableWroManagerFactory;
import ru.yandex.qatools.camelot.maven.web.WroFilter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import static ch.lambdaj.Lambda.convert;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.codehaus.plexus.util.FileUtils.copyFile;
import static ru.qatools.clay.aether.Aether.aether;
import static ru.qatools.clay.utils.archive.ArchiveUtil.unpackJar;
import static ru.yandex.qatools.camelot.core.util.ReflectUtil.resolveResourcesAsStringsFromPattern;
import static ru.yandex.qatools.camelot.maven.service.CamelotRunner.camelot;
import static ru.yandex.qatools.camelot.maven.util.FileUtil.processTemplate;
import static ru.yandex.qatools.camelot.maven.util.FileUtil.replaceInFile;
import static ru.yandex.qatools.camelot.util.MapUtil.map;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 08.07.14
*/
@SuppressWarnings("JavaDoc unused")
@Mojo(name = "run", requiresDirectInvocation = true, requiresDependencyResolution = ResolutionScope.COMPILE)
public class RunMojo extends AbstractMojo {
public static final String PLUGIN_PROPERTIES = "/plugin.properties";
public static final String CAMELOT_PROPERTIES = "/camelot-default.properties";
public static final String VERSION_PROPERTY_NAME = "version";
public static final String CAMELOT_WEB = "camelot-web";
public static final String CAMELOT_UTILS = "camelot-utils";
public static final String WAR = "war";
public static final String JAR = "jar";
public static final String PROPERTIES_FTL = "/plugin.camelot.properties.ftl";
public static final String WEB_CONTEXT_XML_FTL = "/plugin.camelot-web-context.xml.ftl";
@Component
protected MavenProject project;
@Component
protected PluginDescriptor plugin;
// Jetty server configuration
@Parameter(defaultValue = "8080")
protected int jettyPort;
@Parameter(defaultValue = "/camelot")
protected String contextPath;
@Parameter(defaultValue = "${project.build.directory}/camelot")
protected File outputDir;
@Parameter(property = "camelot-test.runForked", defaultValue = "false")
protected boolean runForked;
@Parameter(defaultValue = "-Xmx512m -Xms256m -XX:MaxPermSize=512m")
protected String jvmArgs;
@Parameter(defaultValue = "true")
protected boolean waitUntilFinished;
// Dependency resolving
@Component
protected RepositorySystem system;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
protected RepositorySystemSession session;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
protected List<RemoteRepository> remotes;
// Camelot webapp artifact configuration
@Parameter
protected String camelotWebArtifact = null;
@Parameter
protected String camelotUtilsArtifact = null;
@Parameter
protected String camelotVersion = null;
// Camelot config
@Parameter(defaultValue = "${project.build.outputDirectory}/camelot.xml")
protected File camelotConfigOutputFile;
@Parameter(defaultValue = "${project.build.outputDirectory}")
protected String srcOutputDir;
@Parameter(defaultValue = "${project.build.testOutputDirectory}")
protected String testOutputDir;
@Parameter(defaultValue = "${localRepository}", readonly = true, required = true)
protected ArtifactRepository localRepo;
@Parameter(defaultValue = "${project.basedir}/src/main/resources")
protected String srcResDir;
@Parameter(defaultValue = "${project.basedir}/src/test/resources")
protected String testSrcResDir;
@Parameter(defaultValue = "${project.basedir}/src/main/resources/camelot.xml")
protected File camelotConfigSrcFile;
@Parameter(defaultValue = "")
protected String additionalProperties;
@Parameter(property = "camelot-test.disableMinification", defaultValue = "true")
private boolean disableMinification;
@Parameter(property = "camelot-test.inputUri", defaultValue = "direct:events.input")
protected String mainInputUri;
@Parameter(property = "camelot-test.outputUri", defaultValue = "direct:plugin.stop")
protected String mainOutputUri;
// Fields
protected Properties properties;
protected String groupId;
protected Configuration cfg;
protected Aether aether;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
init();
camelotVersion = getCamelotVersion();
camelotWebArtifact = getCamelotWebArtifact();
File camelotWeb = aether.resolve(camelotWebArtifact, false).get()
.get(0).getArtifact().getFile();
checkDirectory(outputDir);
unpackJar(camelotWeb, outputDir);
removeExtraCamelotConfigFile();
copyOriginalPropertiesFile();
File newConfig = createNewPropertiesFile();
createNewCamelotWebContext(newConfig);
processWebXmlFile();
processPluginsScriptsIfNeeded();
copyCamelotExtensionArtifactToLib();
camelot().jetty(outputDir, contextPath, jettyPort)
.jettyClassPath(createJettyClassPath())
.applicationClassPath(createApplicationClassPath())
.forked(runForked)
.jvmArgs(jvmArgs)
.waitFor(waitUntilFinished)
.run();
} catch (Exception e) {
final String message = "Failed to run camelot";
getLog().error(message, e);
throw new MojoFailureException(message, e);
}
}
/**
* Load plugin properties, extract groupId property and init freemarked configuration.
*
* @throws IOException if can't read properties file
*/
public void init() throws IOException {
properties = loadPluginProperties();
groupId = properties.getProperty("groupId");
cfg = new Configuration();
cfg.setClassForTemplateLoading(getClass(), "/");
aether = aether(system, session, remotes);
}
public void processPluginsScriptsIfNeeded() throws Exception { //NOSONAR
if (camelotConfigSrcFile.exists()) {
processMainLayoutFile();
removePluginsScriptsPattern();
}
}
public void processMainLayoutFile() throws Exception { //NOSONAR
final File mainLayoutFile = new File(outputDir + "/WEB-INF/layouts/main.jade");
replaceInFile(mainLayoutFile, map(
" {1,8}script\\(src=\"#\\{context_path\\}/wro/plugins.js\\\"\\)", buildPluginsScripts()
));
}
public String buildPluginsScripts() throws Exception { //NOSONAR
StringBuilder pluginsScripts = new StringBuilder();
pluginsScripts.append(" script(src='#{context_path}/wro/plugins.js')\n");
for (PluginsSource source : loadPluginsConfig().getSources()) {
for (Plugin plugin : source.getPlugins()) {
if (StringUtil.isEmpty(plugin.getId())) {
plugin.setId(!StringUtil.isEmpty(plugin.getAggregator()) ? plugin.getAggregator() : plugin.getProcessor());
}
appendPluginResources(pluginsScripts, plugin, plugin.getResource());
appendPluginResources(pluginsScripts, plugin, plugin.getAggregator());
appendPluginResources(pluginsScripts, plugin, plugin.getProcessor());
}
}
return pluginsScripts.toString();
}
public void appendPluginResources(StringBuilder pluginsScripts, Plugin plugin, String baseClass) {
for (String js : findTemplatePaths(baseClass, "**/*", ".js", ".coffee")) {
final String prePath = (contextPath.endsWith("/")) ? contextPath.substring(0, contextPath.length() - 1) : contextPath;
pluginsScripts.append(" script(src='").append(prePath).append("/plugin/").
append(plugin.getId()).append("/").append(js).append("')\n");
}
}
public List<String> findTemplatePaths(String resClass, String fileBaseName, String... extensions) {
List<String> paths = new ArrayList<>();
if (isBlank(resClass)) {
return Collections.emptyList();
}
String basePath = resClass.replaceAll("\\.", separator) + separator;
for (String ext : extensions) {
try {
for (String res : resolveResourcesAsStringsFromPattern("file:" + srcResDir + separator + basePath + fileBaseName + ext)) {
paths.add(res.substring(res.indexOf(basePath) + basePath.length()));
}
} catch (Exception e) {
getLog().warn("Failed to find template paths", e);
}
}
return paths;
}
/**
* Loads the plugin system configuration according to the setup
*
* @return loaded plugin configuration
*/
public PluginsConfig loadPluginsConfig() throws Exception { //NOSONAR
JAXBContext jc = JAXBContext.newInstance(PluginsConfig.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
return ((PluginsConfig) unmarshaller.unmarshal(camelotConfigSrcFile));
}
/**
* Remove plugins search scripts pattern in wro.xml
*
* @throws IOException if an I/O error occurs while reading wro.xml file
*/
public void removePluginsScriptsPattern() throws IOException {
File wroXmlFile = new File(outputDir + "/WEB-INF/wro.xml");
replaceInFile(wroXmlFile, map(
" {1,8}<js>plugins://\\*\\.js</js>", ""
));
}
/**
* Change web.xml file
*
* @throws IOException if an I/O error occurs while reading web.xml file
* @see #disableMinificationIfNeeded(java.io.File)
* @see #overrideWroConfiguration(java.io.File)
*/
public void processWebXmlFile() throws IOException {
File webXmlFile = new File(outputDir + "/WEB-INF/web.xml");
overrideWroConfiguration(webXmlFile);
disableMinificationIfNeeded(webXmlFile);
}
/**
* Remove {@code <cssMinJawr>} and {@code <googleClosureSimple>} attributes
* from web.xml if {@link #disableMinification} is true do nothing otherwise
*
* @param webXmlFile web.xml file
* @throws IOException if an I/O error occurs while reading web.xml file
*/
public void disableMinificationIfNeeded(File webXmlFile) throws IOException {
if (disableMinification) {
replaceInFile(webXmlFile, map(
",cssMinJawr,googleClosureSimple", ""
));
}
}
/**
* Override wro configuration. Change wro filter to {@link ru.yandex.qatools.camelot.web.wro.WroFilter} and
* wro manager factory to {@link ru.yandex.qatools.camelot.web.wro.ConfigurableWroManagerFactory}
*
* @param webXmlFile web.xml file
* @throws IOException if an I/O error occurs while reading web.xml file
*/
public void overrideWroConfiguration(File webXmlFile) throws IOException {
replaceInFile(webXmlFile, map(
ru.yandex.qatools.camelot.web.wro.WroFilter.class.getName(), WroFilter.class.getName(),
ru.yandex.qatools.camelot.web.wro.ConfigurableWroManagerFactory.class.getName(), ConfigurableWroManagerFactory.class.getName()
));
}
/**
* Copy camelot-default.properties file from camelot jar
*/
public void copyOriginalPropertiesFile() throws IOException {
try {
File originalConfigFile = new File(outputDir + "/WEB-INF/classes/camelot-default.properties");
File camelotCoreJar = new File(format("%s/WEB-INF/lib/camelot-core-%s.jar", outputDir, camelotVersion));
unpackJar(camelotCoreJar, originalConfigFile, new PathJarEntryFilter(CAMELOT_PROPERTIES));
} catch (IOException | SecurityException e) {
getLog().error("Can't copy original properties file", e);
}
}
/**
* Remove duplicate camelot.xml from build output directory
*/
public void removeExtraCamelotConfigFile() {
try {
camelotConfigOutputFile.delete();
} catch (Exception e) {
getLog().debug(String.format("Can't delete %s file", camelotConfigOutputFile), e);
}
}
/**
* Create new camelot web context
*
* @param newConfigFile new configuration file {@link #createNewPropertiesFile()}
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
* @throws TemplateException if an exception occurs during template processing
*/
public void createNewCamelotWebContext(File newConfigFile) throws IOException, TemplateException {
File appContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml");
File originalAppContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml.orig.xml");
File newCamelotWebContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml");
copyFile(appContextFile, originalAppContextFile);
processTemplate(cfg, WEB_CONTEXT_XML_FTL, new FileWriter(newCamelotWebContextFile), map(
"originalAppContextFile", originalAppContextFile.getAbsolutePath(),
"newConfigFile", newConfigFile.getAbsolutePath(),
"additionalProperties", additionalProperties,
"srcResDir", srcResDir,
"testSrcResDir", testSrcResDir
));
}
/**
* Create new properties file from {@link #PROPERTIES_FTL} template
*
* @return {@link java.io.File} new properties file
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
* @throws TemplateException if an exception occurs during template processing
*/
public File createNewPropertiesFile() throws IOException, TemplateException {
File newConfigFile = new File(outputDir + "/WEB-INF/classes/new.camelot-default.properties");
processTemplate(cfg, PROPERTIES_FTL, new FileWriter(newConfigFile), map(
"localRepo", localRepo.getBasedir(),
"remoteRepos", StringUtils.join(convertRemotesToUrls(remotes), ","),
"newConfigFile", newConfigFile.getAbsolutePath(),
"mainInputUri", mainInputUri,
"mainOutputUri", mainOutputUri,
"srcResDir", srcResDir,
"testSrcResDir", testSrcResDir
));
return newConfigFile;
}
/**
* Convert list of remote repositories to list of strings
*
* @param remotes the remotes to convert.
* @return converted list
*/
public static List<String> convertRemotesToUrls(List<RemoteRepository> remotes) {
return convert(remotes, new Converter<RemoteRepository, String>() {
@Override
public String convert(RemoteRepository from) {
return from.getUrl();
}
});
}
public List<String> convertPathsToUrls(String... strings) {
return convert(strings, new Converter<String, String>() {
@Override
public String convert(String from) {
return new File(from).toURI().toString();
}
});
}
public void copyCamelotExtensionArtifactToLib() throws IOException, AetherException {
File camelotExtensionsJarFile = aether.resolve(
getCamelotUtilsArtifact(), false
).get().get(0).getArtifact().getFile();
copyFile(camelotExtensionsJarFile,
new File(outputDir + "/WEB-INF/lib/" + camelotExtensionsJarFile.getName())
);
}
public String[] createJettyClassPath() throws Exception { //NOSONAR
List<String> classpath = convertPathsToUrls(srcResDir);
classpath.addAll(getCamelotExtensionsArtifactClassPath());
return classpath.toArray(new String[classpath.size()]);
}
/**
* Create classpath for application. Contains all compile artifacts from project and camelot-extension artifact
*
* @return classpath for application
* @throws Exception if can't resolve camelot-utils
*/
public String[] createApplicationClassPath() throws Exception { //NOSONAR
List<String> classpath = convertPathsToUrls("/WEB-INF/classes", srcOutputDir);
classpath.addAll(getCompileArtifacts(project.getArtifacts()));
return classpath.toArray(new String[classpath.size()]);
}
/**
* Get all classpath elements from camelot-extensions artifact
*
* @return classpath elements for camelot-extensions
* @throws Exception if can't resolve camelot-extensions
*/
public List<String> getCamelotExtensionsArtifactClassPath() throws Exception { //NOSONAR
return Arrays.asList(aether.resolve(getCamelotUtilsArtifact()).getAsClassPath());
}
/**
* Convert collection of artifacts to classpath
*
* @param artifacts to convert
* @return classpath
*/
public List<String> getCompileArtifacts(Collection<Artifact> artifacts) {
List<String> classpath = new ArrayList<>();
for (Artifact artifact : artifacts) {
classpath.add(artifact.getFile().toURI().toString());
}
return classpath;
}
/**
* Load properties from {@link #PLUGIN_PROPERTIES} file
*
* @return created {@link java.util.Properties}
* @throws IOException if can't read properties file
*/
public Properties loadPluginProperties() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(PLUGIN_PROPERTIES));
return properties;
}
/**
* Get version of camelot-web artifact.
*
* @return version of camelot-web artifact
*/
public String getCamelotVersion() {
if (isBlank(camelotVersion)) {
camelotVersion = properties.getProperty(VERSION_PROPERTY_NAME);
}
return camelotVersion;
}
/**
* Get camelot-web artifact coordinates as {groupId}:{artifactId}:{extension}:{version}
*
* @return artifact coordinates
*/
public String getCamelotWebArtifact() {
if (isBlank(camelotWebArtifact)) {
camelotWebArtifact = getArtifactCoords(groupId, CAMELOT_WEB, WAR, getCamelotVersion());
}
return camelotWebArtifact;
}
/**
* Get camelot-utils artifact coordinates as {groupId}:{artifactId}:{extension}:{version}
*
* @return artifact coordinates
*/
public String getCamelotUtilsArtifact() {
if (isBlank(camelotUtilsArtifact)) {
camelotUtilsArtifact = getArtifactCoords(groupId, CAMELOT_UTILS, JAR, getCamelotVersion());
}
return camelotUtilsArtifact;
}
public String getArtifactCoords(String groupId, String artifactId, String extensions, String version) {
return String.format("%s:%s:%s:%s", groupId, artifactId, extensions, version);
}
/**
* Check given directory. Try to create directory if doesn't exist.
*
* @param dir a directory to check
* @throws MojoExecutionException if can't create directory
*/
public void checkDirectory(File dir) throws MojoExecutionException {
if (!dir.exists() && !dir.mkdirs()) {
throw new MojoExecutionException("Report directory doesn't exists and can't be created.");
}
}
}
| UTF-8 | Java | 21,435 | java | RunMojo.java | Java | [
{
"context": ".qatools.camelot.util.MapUtil.map;\n\n/**\n * @author Dmitry Baev charlie@yandex-team.ru\n * Date: 08.07.14\n",
"end": 2354,
"score": 0.999868631362915,
"start": 2343,
"tag": "NAME",
"value": "Dmitry Baev"
},
{
"context": "elot.util.MapUtil.map;\n\n/**\n * @author Dmitry Baev charlie@yandex-team.ru\n * Date: 08.07.14\n */\n@SuppressWarnings(\"",
"end": 2377,
"score": 0.9999217391014099,
"start": 2355,
"tag": "EMAIL",
"value": "charlie@yandex-team.ru"
}
] | null | [] | package ru.yandex.qatools.camelot.maven;
import ch.lambdaj.function.convert.Converter;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;
import ru.qatools.clay.aether.Aether;
import ru.qatools.clay.aether.AetherException;
import ru.qatools.clay.utils.archive.PathJarEntryFilter;
import ru.yandex.qatools.camelot.config.Plugin;
import ru.yandex.qatools.camelot.config.PluginsConfig;
import ru.yandex.qatools.camelot.config.PluginsSource;
import ru.yandex.qatools.camelot.maven.web.ConfigurableWroManagerFactory;
import ru.yandex.qatools.camelot.maven.web.WroFilter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import static ch.lambdaj.Lambda.convert;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.codehaus.plexus.util.FileUtils.copyFile;
import static ru.qatools.clay.aether.Aether.aether;
import static ru.qatools.clay.utils.archive.ArchiveUtil.unpackJar;
import static ru.yandex.qatools.camelot.core.util.ReflectUtil.resolveResourcesAsStringsFromPattern;
import static ru.yandex.qatools.camelot.maven.service.CamelotRunner.camelot;
import static ru.yandex.qatools.camelot.maven.util.FileUtil.processTemplate;
import static ru.yandex.qatools.camelot.maven.util.FileUtil.replaceInFile;
import static ru.yandex.qatools.camelot.util.MapUtil.map;
/**
* @author <NAME> <EMAIL>
* Date: 08.07.14
*/
@SuppressWarnings("JavaDoc unused")
@Mojo(name = "run", requiresDirectInvocation = true, requiresDependencyResolution = ResolutionScope.COMPILE)
public class RunMojo extends AbstractMojo {
public static final String PLUGIN_PROPERTIES = "/plugin.properties";
public static final String CAMELOT_PROPERTIES = "/camelot-default.properties";
public static final String VERSION_PROPERTY_NAME = "version";
public static final String CAMELOT_WEB = "camelot-web";
public static final String CAMELOT_UTILS = "camelot-utils";
public static final String WAR = "war";
public static final String JAR = "jar";
public static final String PROPERTIES_FTL = "/plugin.camelot.properties.ftl";
public static final String WEB_CONTEXT_XML_FTL = "/plugin.camelot-web-context.xml.ftl";
@Component
protected MavenProject project;
@Component
protected PluginDescriptor plugin;
// Jetty server configuration
@Parameter(defaultValue = "8080")
protected int jettyPort;
@Parameter(defaultValue = "/camelot")
protected String contextPath;
@Parameter(defaultValue = "${project.build.directory}/camelot")
protected File outputDir;
@Parameter(property = "camelot-test.runForked", defaultValue = "false")
protected boolean runForked;
@Parameter(defaultValue = "-Xmx512m -Xms256m -XX:MaxPermSize=512m")
protected String jvmArgs;
@Parameter(defaultValue = "true")
protected boolean waitUntilFinished;
// Dependency resolving
@Component
protected RepositorySystem system;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
protected RepositorySystemSession session;
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
protected List<RemoteRepository> remotes;
// Camelot webapp artifact configuration
@Parameter
protected String camelotWebArtifact = null;
@Parameter
protected String camelotUtilsArtifact = null;
@Parameter
protected String camelotVersion = null;
// Camelot config
@Parameter(defaultValue = "${project.build.outputDirectory}/camelot.xml")
protected File camelotConfigOutputFile;
@Parameter(defaultValue = "${project.build.outputDirectory}")
protected String srcOutputDir;
@Parameter(defaultValue = "${project.build.testOutputDirectory}")
protected String testOutputDir;
@Parameter(defaultValue = "${localRepository}", readonly = true, required = true)
protected ArtifactRepository localRepo;
@Parameter(defaultValue = "${project.basedir}/src/main/resources")
protected String srcResDir;
@Parameter(defaultValue = "${project.basedir}/src/test/resources")
protected String testSrcResDir;
@Parameter(defaultValue = "${project.basedir}/src/main/resources/camelot.xml")
protected File camelotConfigSrcFile;
@Parameter(defaultValue = "")
protected String additionalProperties;
@Parameter(property = "camelot-test.disableMinification", defaultValue = "true")
private boolean disableMinification;
@Parameter(property = "camelot-test.inputUri", defaultValue = "direct:events.input")
protected String mainInputUri;
@Parameter(property = "camelot-test.outputUri", defaultValue = "direct:plugin.stop")
protected String mainOutputUri;
// Fields
protected Properties properties;
protected String groupId;
protected Configuration cfg;
protected Aether aether;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
init();
camelotVersion = getCamelotVersion();
camelotWebArtifact = getCamelotWebArtifact();
File camelotWeb = aether.resolve(camelotWebArtifact, false).get()
.get(0).getArtifact().getFile();
checkDirectory(outputDir);
unpackJar(camelotWeb, outputDir);
removeExtraCamelotConfigFile();
copyOriginalPropertiesFile();
File newConfig = createNewPropertiesFile();
createNewCamelotWebContext(newConfig);
processWebXmlFile();
processPluginsScriptsIfNeeded();
copyCamelotExtensionArtifactToLib();
camelot().jetty(outputDir, contextPath, jettyPort)
.jettyClassPath(createJettyClassPath())
.applicationClassPath(createApplicationClassPath())
.forked(runForked)
.jvmArgs(jvmArgs)
.waitFor(waitUntilFinished)
.run();
} catch (Exception e) {
final String message = "Failed to run camelot";
getLog().error(message, e);
throw new MojoFailureException(message, e);
}
}
/**
* Load plugin properties, extract groupId property and init freemarked configuration.
*
* @throws IOException if can't read properties file
*/
public void init() throws IOException {
properties = loadPluginProperties();
groupId = properties.getProperty("groupId");
cfg = new Configuration();
cfg.setClassForTemplateLoading(getClass(), "/");
aether = aether(system, session, remotes);
}
public void processPluginsScriptsIfNeeded() throws Exception { //NOSONAR
if (camelotConfigSrcFile.exists()) {
processMainLayoutFile();
removePluginsScriptsPattern();
}
}
public void processMainLayoutFile() throws Exception { //NOSONAR
final File mainLayoutFile = new File(outputDir + "/WEB-INF/layouts/main.jade");
replaceInFile(mainLayoutFile, map(
" {1,8}script\\(src=\"#\\{context_path\\}/wro/plugins.js\\\"\\)", buildPluginsScripts()
));
}
public String buildPluginsScripts() throws Exception { //NOSONAR
StringBuilder pluginsScripts = new StringBuilder();
pluginsScripts.append(" script(src='#{context_path}/wro/plugins.js')\n");
for (PluginsSource source : loadPluginsConfig().getSources()) {
for (Plugin plugin : source.getPlugins()) {
if (StringUtil.isEmpty(plugin.getId())) {
plugin.setId(!StringUtil.isEmpty(plugin.getAggregator()) ? plugin.getAggregator() : plugin.getProcessor());
}
appendPluginResources(pluginsScripts, plugin, plugin.getResource());
appendPluginResources(pluginsScripts, plugin, plugin.getAggregator());
appendPluginResources(pluginsScripts, plugin, plugin.getProcessor());
}
}
return pluginsScripts.toString();
}
public void appendPluginResources(StringBuilder pluginsScripts, Plugin plugin, String baseClass) {
for (String js : findTemplatePaths(baseClass, "**/*", ".js", ".coffee")) {
final String prePath = (contextPath.endsWith("/")) ? contextPath.substring(0, contextPath.length() - 1) : contextPath;
pluginsScripts.append(" script(src='").append(prePath).append("/plugin/").
append(plugin.getId()).append("/").append(js).append("')\n");
}
}
public List<String> findTemplatePaths(String resClass, String fileBaseName, String... extensions) {
List<String> paths = new ArrayList<>();
if (isBlank(resClass)) {
return Collections.emptyList();
}
String basePath = resClass.replaceAll("\\.", separator) + separator;
for (String ext : extensions) {
try {
for (String res : resolveResourcesAsStringsFromPattern("file:" + srcResDir + separator + basePath + fileBaseName + ext)) {
paths.add(res.substring(res.indexOf(basePath) + basePath.length()));
}
} catch (Exception e) {
getLog().warn("Failed to find template paths", e);
}
}
return paths;
}
/**
* Loads the plugin system configuration according to the setup
*
* @return loaded plugin configuration
*/
public PluginsConfig loadPluginsConfig() throws Exception { //NOSONAR
JAXBContext jc = JAXBContext.newInstance(PluginsConfig.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
return ((PluginsConfig) unmarshaller.unmarshal(camelotConfigSrcFile));
}
/**
* Remove plugins search scripts pattern in wro.xml
*
* @throws IOException if an I/O error occurs while reading wro.xml file
*/
public void removePluginsScriptsPattern() throws IOException {
File wroXmlFile = new File(outputDir + "/WEB-INF/wro.xml");
replaceInFile(wroXmlFile, map(
" {1,8}<js>plugins://\\*\\.js</js>", ""
));
}
/**
* Change web.xml file
*
* @throws IOException if an I/O error occurs while reading web.xml file
* @see #disableMinificationIfNeeded(java.io.File)
* @see #overrideWroConfiguration(java.io.File)
*/
public void processWebXmlFile() throws IOException {
File webXmlFile = new File(outputDir + "/WEB-INF/web.xml");
overrideWroConfiguration(webXmlFile);
disableMinificationIfNeeded(webXmlFile);
}
/**
* Remove {@code <cssMinJawr>} and {@code <googleClosureSimple>} attributes
* from web.xml if {@link #disableMinification} is true do nothing otherwise
*
* @param webXmlFile web.xml file
* @throws IOException if an I/O error occurs while reading web.xml file
*/
public void disableMinificationIfNeeded(File webXmlFile) throws IOException {
if (disableMinification) {
replaceInFile(webXmlFile, map(
",cssMinJawr,googleClosureSimple", ""
));
}
}
/**
* Override wro configuration. Change wro filter to {@link ru.yandex.qatools.camelot.web.wro.WroFilter} and
* wro manager factory to {@link ru.yandex.qatools.camelot.web.wro.ConfigurableWroManagerFactory}
*
* @param webXmlFile web.xml file
* @throws IOException if an I/O error occurs while reading web.xml file
*/
public void overrideWroConfiguration(File webXmlFile) throws IOException {
replaceInFile(webXmlFile, map(
ru.yandex.qatools.camelot.web.wro.WroFilter.class.getName(), WroFilter.class.getName(),
ru.yandex.qatools.camelot.web.wro.ConfigurableWroManagerFactory.class.getName(), ConfigurableWroManagerFactory.class.getName()
));
}
/**
* Copy camelot-default.properties file from camelot jar
*/
public void copyOriginalPropertiesFile() throws IOException {
try {
File originalConfigFile = new File(outputDir + "/WEB-INF/classes/camelot-default.properties");
File camelotCoreJar = new File(format("%s/WEB-INF/lib/camelot-core-%s.jar", outputDir, camelotVersion));
unpackJar(camelotCoreJar, originalConfigFile, new PathJarEntryFilter(CAMELOT_PROPERTIES));
} catch (IOException | SecurityException e) {
getLog().error("Can't copy original properties file", e);
}
}
/**
* Remove duplicate camelot.xml from build output directory
*/
public void removeExtraCamelotConfigFile() {
try {
camelotConfigOutputFile.delete();
} catch (Exception e) {
getLog().debug(String.format("Can't delete %s file", camelotConfigOutputFile), e);
}
}
/**
* Create new camelot web context
*
* @param newConfigFile new configuration file {@link #createNewPropertiesFile()}
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
* @throws TemplateException if an exception occurs during template processing
*/
public void createNewCamelotWebContext(File newConfigFile) throws IOException, TemplateException {
File appContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml");
File originalAppContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml.orig.xml");
File newCamelotWebContextFile = new File(outputDir + "/WEB-INF/classes/camelot-web-context.xml");
copyFile(appContextFile, originalAppContextFile);
processTemplate(cfg, WEB_CONTEXT_XML_FTL, new FileWriter(newCamelotWebContextFile), map(
"originalAppContextFile", originalAppContextFile.getAbsolutePath(),
"newConfigFile", newConfigFile.getAbsolutePath(),
"additionalProperties", additionalProperties,
"srcResDir", srcResDir,
"testSrcResDir", testSrcResDir
));
}
/**
* Create new properties file from {@link #PROPERTIES_FTL} template
*
* @return {@link java.io.File} new properties file
* @throws IOException if the file exists but is a directory rather than
* a regular file, does not exist but cannot be created,
* or cannot be opened for any other reason
* @throws TemplateException if an exception occurs during template processing
*/
public File createNewPropertiesFile() throws IOException, TemplateException {
File newConfigFile = new File(outputDir + "/WEB-INF/classes/new.camelot-default.properties");
processTemplate(cfg, PROPERTIES_FTL, new FileWriter(newConfigFile), map(
"localRepo", localRepo.getBasedir(),
"remoteRepos", StringUtils.join(convertRemotesToUrls(remotes), ","),
"newConfigFile", newConfigFile.getAbsolutePath(),
"mainInputUri", mainInputUri,
"mainOutputUri", mainOutputUri,
"srcResDir", srcResDir,
"testSrcResDir", testSrcResDir
));
return newConfigFile;
}
/**
* Convert list of remote repositories to list of strings
*
* @param remotes the remotes to convert.
* @return converted list
*/
public static List<String> convertRemotesToUrls(List<RemoteRepository> remotes) {
return convert(remotes, new Converter<RemoteRepository, String>() {
@Override
public String convert(RemoteRepository from) {
return from.getUrl();
}
});
}
public List<String> convertPathsToUrls(String... strings) {
return convert(strings, new Converter<String, String>() {
@Override
public String convert(String from) {
return new File(from).toURI().toString();
}
});
}
public void copyCamelotExtensionArtifactToLib() throws IOException, AetherException {
File camelotExtensionsJarFile = aether.resolve(
getCamelotUtilsArtifact(), false
).get().get(0).getArtifact().getFile();
copyFile(camelotExtensionsJarFile,
new File(outputDir + "/WEB-INF/lib/" + camelotExtensionsJarFile.getName())
);
}
public String[] createJettyClassPath() throws Exception { //NOSONAR
List<String> classpath = convertPathsToUrls(srcResDir);
classpath.addAll(getCamelotExtensionsArtifactClassPath());
return classpath.toArray(new String[classpath.size()]);
}
/**
* Create classpath for application. Contains all compile artifacts from project and camelot-extension artifact
*
* @return classpath for application
* @throws Exception if can't resolve camelot-utils
*/
public String[] createApplicationClassPath() throws Exception { //NOSONAR
List<String> classpath = convertPathsToUrls("/WEB-INF/classes", srcOutputDir);
classpath.addAll(getCompileArtifacts(project.getArtifacts()));
return classpath.toArray(new String[classpath.size()]);
}
/**
* Get all classpath elements from camelot-extensions artifact
*
* @return classpath elements for camelot-extensions
* @throws Exception if can't resolve camelot-extensions
*/
public List<String> getCamelotExtensionsArtifactClassPath() throws Exception { //NOSONAR
return Arrays.asList(aether.resolve(getCamelotUtilsArtifact()).getAsClassPath());
}
/**
* Convert collection of artifacts to classpath
*
* @param artifacts to convert
* @return classpath
*/
public List<String> getCompileArtifacts(Collection<Artifact> artifacts) {
List<String> classpath = new ArrayList<>();
for (Artifact artifact : artifacts) {
classpath.add(artifact.getFile().toURI().toString());
}
return classpath;
}
/**
* Load properties from {@link #PLUGIN_PROPERTIES} file
*
* @return created {@link java.util.Properties}
* @throws IOException if can't read properties file
*/
public Properties loadPluginProperties() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(PLUGIN_PROPERTIES));
return properties;
}
/**
* Get version of camelot-web artifact.
*
* @return version of camelot-web artifact
*/
public String getCamelotVersion() {
if (isBlank(camelotVersion)) {
camelotVersion = properties.getProperty(VERSION_PROPERTY_NAME);
}
return camelotVersion;
}
/**
* Get camelot-web artifact coordinates as {groupId}:{artifactId}:{extension}:{version}
*
* @return artifact coordinates
*/
public String getCamelotWebArtifact() {
if (isBlank(camelotWebArtifact)) {
camelotWebArtifact = getArtifactCoords(groupId, CAMELOT_WEB, WAR, getCamelotVersion());
}
return camelotWebArtifact;
}
/**
* Get camelot-utils artifact coordinates as {groupId}:{artifactId}:{extension}:{version}
*
* @return artifact coordinates
*/
public String getCamelotUtilsArtifact() {
if (isBlank(camelotUtilsArtifact)) {
camelotUtilsArtifact = getArtifactCoords(groupId, CAMELOT_UTILS, JAR, getCamelotVersion());
}
return camelotUtilsArtifact;
}
public String getArtifactCoords(String groupId, String artifactId, String extensions, String version) {
return String.format("%s:%s:%s:%s", groupId, artifactId, extensions, version);
}
/**
* Check given directory. Try to create directory if doesn't exist.
*
* @param dir a directory to check
* @throws MojoExecutionException if can't create directory
*/
public void checkDirectory(File dir) throws MojoExecutionException {
if (!dir.exists() && !dir.mkdirs()) {
throw new MojoExecutionException("Report directory doesn't exists and can't be created.");
}
}
}
| 21,415 | 0.671519 | 0.670166 | 544 | 38.402573 | 32.020409 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538603 | false | false | 4 |
a0205e4f75c69082afc670fa0ff96b67c14bee2c | 19,945,828,177,785 | c0d88af413318ac115323e15fc7a9d2c381addbc | /src/main/java/com/example/exp4/WelcomeActivity.java | 4e6918ecfd4bbb9f4c0853b07323ab09c4367ef0 | [] | no_license | roc-20/Android-music-player | https://github.com/roc-20/Android-music-player | 35c071011bfd09a3db072630c598f368a60623fc | 910538401faf19a0d59044a182412e2a74e64bf5 | refs/heads/main | 2023-02-08T02:35:39.230000 | 2020-12-30T07:25:58 | 2020-12-30T07:25:58 | 325,483,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.exp4;
import android.content.Intent;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener {
Button bt_list;
Button bt_like;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
bt_like=(Button)findViewById(R.id.bt_like);
bt_list=(Button)findViewById(R.id.bt_list);
bt_list.setOnClickListener(this);
bt_like.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.bt_list:
Intent intent=new Intent(WelcomeActivity.this,MainActivity.class);
startActivity(intent);
break;
case R.id.bt_like:
Intent intent1=new Intent(WelcomeActivity.this,LikeActivity.class);
startActivity(intent1);
break;
}
}
}
| UTF-8 | Java | 1,251 | java | WelcomeActivity.java | Java | [] | null | [] | package com.example.exp4;
import android.content.Intent;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener {
Button bt_list;
Button bt_like;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
bt_like=(Button)findViewById(R.id.bt_like);
bt_list=(Button)findViewById(R.id.bt_list);
bt_list.setOnClickListener(this);
bt_like.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.bt_list:
Intent intent=new Intent(WelcomeActivity.this,MainActivity.class);
startActivity(intent);
break;
case R.id.bt_like:
Intent intent1=new Intent(WelcomeActivity.this,LikeActivity.class);
startActivity(intent1);
break;
}
}
}
| 1,251 | 0.645084 | 0.641886 | 37 | 31.81081 | 22.231993 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.648649 | false | false | 4 |
edb10c1299ae6846c181fa829cadf775ae3581c6 | 1,194,000,936,818 | 3aea92baaca147d8234cf5ae18adee53cbcb2ab1 | /app/src/main/java/com/cj/qmuiapplication/manager/QDDataManager.java | 2d4465a6f8da92763fc9099fa82cdfbfeb562bc3 | [] | no_license | cj200622550/QMUIApplication | https://github.com/cj200622550/QMUIApplication | de7978e96d3c007cebc58ce16d45accc01b57263 | 63e29b9ef8ccfaf92f16f73fb6abc0dd7a021a4f | refs/heads/master | 2021-04-27T11:23:53.051000 | 2018-02-23T02:14:49 | 2018-02-23T02:14:49 | 122,560,991 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cj.qmuiapplication.manager;
import com.cj.qmuiapplication.QDWidgetContainer;
import com.cj.qmuiapplication.base.BaseFragment;
import com.cj.qmuiapplication.fragment.components.QDBottomSheetFragment;
import com.cj.qmuiapplication.fragment.components.QDButtonFragment;
import com.cj.qmuiapplication.fragment.components.QDCollapsingTopBarLayoutFragment;
import com.cj.qmuiapplication.fragment.components.QDDialogFragment;
import com.cj.qmuiapplication.fragment.components.QDEmptyViewFragment;
import com.cj.qmuiapplication.fragment.components.QDFloatLayoutFragment;
import com.cj.qmuiapplication.fragment.components.QDGroupListViewFragment;
import com.cj.qmuiapplication.fragment.components.QDLinkTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDPopupFragment;
import com.cj.qmuiapplication.fragment.components.QDProgressBarFragment;
import com.cj.qmuiapplication.fragment.components.QDPullRefreshFragment;
import com.cj.qmuiapplication.fragment.components.QDQQFaceFragment;
import com.cj.qmuiapplication.fragment.components.QDRadiusImageViewFragment;
import com.cj.qmuiapplication.fragment.components.QDSpanFragment;
import com.cj.qmuiapplication.fragment.components.QDSpanTouchFixTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDTabSegmentFragment;
import com.cj.qmuiapplication.fragment.components.QDTipDialogFragment;
import com.cj.qmuiapplication.fragment.components.QDVerticalTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDViewPagerFragment;
import com.cj.qmuiapplication.fragment.lab.QDAnimationListViewFragment;
import com.cj.qmuiapplication.fragment.lab.QDSnapHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDColorHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDDeviceHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDDrawableHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDStatusBarHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDViewHelperFragment;
import com.cj.qmuiapplication.model.QDItemDescription;
import java.util.ArrayList;
import java.util.List;
/**
* 作者: 陈骏
* 创建时间: 2018/2/2
* 博客: https://www.jianshu.com/u/c5ada9939f6d
* Q Q: 200622550
* 作用:数据管理
*/
public class QDDataManager {
private static QDDataManager _sInstance;
private QDWidgetContainer mWidgetContainer;
private List<Class<? extends BaseFragment>> mComponentsNames;
private List<Class<? extends BaseFragment>> mUtilNames;
private List<Class<? extends BaseFragment>> mLabNames;
public QDDataManager() {
mWidgetContainer = QDWidgetContainer.getInstance();
initComponentsDesc();
initUtilDesc();
initLabDesc();
}
/**
* 单列
* @return
*/
public static QDDataManager getInstance() {
if (_sInstance == null) {
_sInstance = new QDDataManager();
}
return _sInstance;
}
/**
* Components
*/
private void initComponentsDesc() {
mComponentsNames = new ArrayList<>();
mComponentsNames.add(QDButtonFragment.class);
mComponentsNames.add(QDDialogFragment.class);
mComponentsNames.add(QDFloatLayoutFragment.class);
mComponentsNames.add(QDEmptyViewFragment.class);
mComponentsNames.add(QDTabSegmentFragment.class);
mComponentsNames.add(QDProgressBarFragment.class);
mComponentsNames.add(QDBottomSheetFragment.class);
mComponentsNames.add(QDGroupListViewFragment.class);
mComponentsNames.add(QDTipDialogFragment.class);
mComponentsNames.add(QDRadiusImageViewFragment.class);
mComponentsNames.add(QDVerticalTextViewFragment.class);
mComponentsNames.add(QDPullRefreshFragment.class);
mComponentsNames.add(QDPopupFragment.class);
mComponentsNames.add(QDSpanTouchFixTextViewFragment.class);
mComponentsNames.add(QDLinkTextViewFragment.class);
mComponentsNames.add(QDQQFaceFragment.class);
mComponentsNames.add(QDSpanFragment.class);
mComponentsNames.add(QDCollapsingTopBarLayoutFragment.class);
mComponentsNames.add(QDViewPagerFragment.class);
}
/**
* Helper
*/
private void initUtilDesc() {
mUtilNames = new ArrayList<>();
mUtilNames.add(QDColorHelperFragment.class);
mUtilNames.add(QDDeviceHelperFragment.class);
mUtilNames.add(QDDrawableHelperFragment.class);
mUtilNames.add(QDStatusBarHelperFragment.class);
mUtilNames.add(QDViewHelperFragment.class);
}
/**
* Lab
*/
private void initLabDesc() {
mLabNames = new ArrayList<>();
mLabNames.add(QDAnimationListViewFragment.class);
mLabNames.add(QDSnapHelperFragment.class);
}
public QDItemDescription getDescription(Class<? extends BaseFragment> cls) {
return mWidgetContainer.get(cls);
}
public String getName(Class<? extends BaseFragment> cls) {
QDItemDescription itemDescription = getDescription(cls);
if (itemDescription == null) {
return null;
}
return itemDescription.getName();
}
public List<QDItemDescription> getComponentsDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mComponentsNames.size(); i++) {
list.add(mWidgetContainer.get(mComponentsNames.get(i)));
}
return list;
}
public List<QDItemDescription> getUtilDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mUtilNames.size(); i++) {
list.add(mWidgetContainer.get(mUtilNames.get(i)));
}
return list;
}
public List<QDItemDescription> getLabDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mLabNames.size(); i++) {
list.add(mWidgetContainer.get(mLabNames.get(i)));
}
return list;
}
}
| UTF-8 | Java | 6,020 | java | QDDataManager.java | Java | [
{
"context": "til.ArrayList;\nimport java.util.List;\n\n/**\n * 作者: 陈骏\n * 创建时间: 2018/2/2\n * 博客: https://www.jianshu.com/",
"end": 2123,
"score": 0.9881618022918701,
"start": 2121,
"tag": "NAME",
"value": "陈骏"
}
] | null | [] | package com.cj.qmuiapplication.manager;
import com.cj.qmuiapplication.QDWidgetContainer;
import com.cj.qmuiapplication.base.BaseFragment;
import com.cj.qmuiapplication.fragment.components.QDBottomSheetFragment;
import com.cj.qmuiapplication.fragment.components.QDButtonFragment;
import com.cj.qmuiapplication.fragment.components.QDCollapsingTopBarLayoutFragment;
import com.cj.qmuiapplication.fragment.components.QDDialogFragment;
import com.cj.qmuiapplication.fragment.components.QDEmptyViewFragment;
import com.cj.qmuiapplication.fragment.components.QDFloatLayoutFragment;
import com.cj.qmuiapplication.fragment.components.QDGroupListViewFragment;
import com.cj.qmuiapplication.fragment.components.QDLinkTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDPopupFragment;
import com.cj.qmuiapplication.fragment.components.QDProgressBarFragment;
import com.cj.qmuiapplication.fragment.components.QDPullRefreshFragment;
import com.cj.qmuiapplication.fragment.components.QDQQFaceFragment;
import com.cj.qmuiapplication.fragment.components.QDRadiusImageViewFragment;
import com.cj.qmuiapplication.fragment.components.QDSpanFragment;
import com.cj.qmuiapplication.fragment.components.QDSpanTouchFixTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDTabSegmentFragment;
import com.cj.qmuiapplication.fragment.components.QDTipDialogFragment;
import com.cj.qmuiapplication.fragment.components.QDVerticalTextViewFragment;
import com.cj.qmuiapplication.fragment.components.QDViewPagerFragment;
import com.cj.qmuiapplication.fragment.lab.QDAnimationListViewFragment;
import com.cj.qmuiapplication.fragment.lab.QDSnapHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDColorHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDDeviceHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDDrawableHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDStatusBarHelperFragment;
import com.cj.qmuiapplication.fragment.util.QDViewHelperFragment;
import com.cj.qmuiapplication.model.QDItemDescription;
import java.util.ArrayList;
import java.util.List;
/**
* 作者: 陈骏
* 创建时间: 2018/2/2
* 博客: https://www.jianshu.com/u/c5ada9939f6d
* Q Q: 200622550
* 作用:数据管理
*/
public class QDDataManager {
private static QDDataManager _sInstance;
private QDWidgetContainer mWidgetContainer;
private List<Class<? extends BaseFragment>> mComponentsNames;
private List<Class<? extends BaseFragment>> mUtilNames;
private List<Class<? extends BaseFragment>> mLabNames;
public QDDataManager() {
mWidgetContainer = QDWidgetContainer.getInstance();
initComponentsDesc();
initUtilDesc();
initLabDesc();
}
/**
* 单列
* @return
*/
public static QDDataManager getInstance() {
if (_sInstance == null) {
_sInstance = new QDDataManager();
}
return _sInstance;
}
/**
* Components
*/
private void initComponentsDesc() {
mComponentsNames = new ArrayList<>();
mComponentsNames.add(QDButtonFragment.class);
mComponentsNames.add(QDDialogFragment.class);
mComponentsNames.add(QDFloatLayoutFragment.class);
mComponentsNames.add(QDEmptyViewFragment.class);
mComponentsNames.add(QDTabSegmentFragment.class);
mComponentsNames.add(QDProgressBarFragment.class);
mComponentsNames.add(QDBottomSheetFragment.class);
mComponentsNames.add(QDGroupListViewFragment.class);
mComponentsNames.add(QDTipDialogFragment.class);
mComponentsNames.add(QDRadiusImageViewFragment.class);
mComponentsNames.add(QDVerticalTextViewFragment.class);
mComponentsNames.add(QDPullRefreshFragment.class);
mComponentsNames.add(QDPopupFragment.class);
mComponentsNames.add(QDSpanTouchFixTextViewFragment.class);
mComponentsNames.add(QDLinkTextViewFragment.class);
mComponentsNames.add(QDQQFaceFragment.class);
mComponentsNames.add(QDSpanFragment.class);
mComponentsNames.add(QDCollapsingTopBarLayoutFragment.class);
mComponentsNames.add(QDViewPagerFragment.class);
}
/**
* Helper
*/
private void initUtilDesc() {
mUtilNames = new ArrayList<>();
mUtilNames.add(QDColorHelperFragment.class);
mUtilNames.add(QDDeviceHelperFragment.class);
mUtilNames.add(QDDrawableHelperFragment.class);
mUtilNames.add(QDStatusBarHelperFragment.class);
mUtilNames.add(QDViewHelperFragment.class);
}
/**
* Lab
*/
private void initLabDesc() {
mLabNames = new ArrayList<>();
mLabNames.add(QDAnimationListViewFragment.class);
mLabNames.add(QDSnapHelperFragment.class);
}
public QDItemDescription getDescription(Class<? extends BaseFragment> cls) {
return mWidgetContainer.get(cls);
}
public String getName(Class<? extends BaseFragment> cls) {
QDItemDescription itemDescription = getDescription(cls);
if (itemDescription == null) {
return null;
}
return itemDescription.getName();
}
public List<QDItemDescription> getComponentsDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mComponentsNames.size(); i++) {
list.add(mWidgetContainer.get(mComponentsNames.get(i)));
}
return list;
}
public List<QDItemDescription> getUtilDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mUtilNames.size(); i++) {
list.add(mWidgetContainer.get(mUtilNames.get(i)));
}
return list;
}
public List<QDItemDescription> getLabDescriptions() {
List<QDItemDescription> list = new ArrayList<>();
for (int i = 0; i < mLabNames.size(); i++) {
list.add(mWidgetContainer.get(mLabNames.get(i)));
}
return list;
}
}
| 6,020 | 0.736525 | 0.732508 | 153 | 38.045753 | 26.463278 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.594771 | false | false | 4 |
0d4414013c3d5e90574424622e080698c431a13e | 26,877,905,376,444 | 43f270eb67a9f8f569a3a470a584775c31a87250 | /src/main/java/hashwork/client/content/common/location/models/AddressTypeModel.java | 100b01154ba51258bb1eb7f2f0769f19589f956f | [] | no_license | boniface/hashwork | https://github.com/boniface/hashwork | b9af26beebd326c03947151fab0b71c1cdc61ba2 | 8ed0af2b4c85bf40bfdc1b0cf2579f316fc2eae6 | refs/heads/master | 2016-08-16T18:40:26.471000 | 2016-01-30T07:58:31 | 2016-01-30T07:58:31 | 39,587,985 | 0 | 20 | null | false | 2016-01-30T07:58:33 | 2015-07-23T19:34:52 | 2016-01-14T07:17:35 | 2016-01-30T07:58:33 | 1,857 | 0 | 10 | 9 | Java | null | null | package hashwork.client.content.common.location.models;
import java.io.Serializable;
/**
* Created by hashcode on 2015/09/07.
*/
public class AddressTypeModel implements Serializable {
private String addressTypeName;
public String getAddressTypeName() {
return addressTypeName;
}
public void setAddressTypeName(String addressTypeName) {
this.addressTypeName = addressTypeName;
}
}
| UTF-8 | Java | 424 | java | AddressTypeModel.java | Java | [
{
"context": ";\n\nimport java.io.Serializable;\n\n/**\n * Created by hashcode on 2015/09/07.\n */\npublic class AddressTypeModel ",
"end": 113,
"score": 0.9995516538619995,
"start": 105,
"tag": "USERNAME",
"value": "hashcode"
}
] | null | [] | package hashwork.client.content.common.location.models;
import java.io.Serializable;
/**
* Created by hashcode on 2015/09/07.
*/
public class AddressTypeModel implements Serializable {
private String addressTypeName;
public String getAddressTypeName() {
return addressTypeName;
}
public void setAddressTypeName(String addressTypeName) {
this.addressTypeName = addressTypeName;
}
}
| 424 | 0.731132 | 0.712264 | 19 | 21.31579 | 22.045534 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 4 |
b14b91a1e7a741a314e1ae6b1dd7723b5173dbec | 13,168,369,784,855 | d760582446ba0937aa346dbaf41e541b2cfcd80f | /src/main/java/com/guaiwolo/modules/video/controller/TestController.java | 2ca59e2d394afa5d36a60ee4e91e5edb7ddba3e1 | [] | no_license | guaiwolou/xd | https://github.com/guaiwolou/xd | ef058b167aacb8818898ca9d6337d7847793d981 | 7910d4e0b9a91b7f4822115eac9eb85deff03d53 | refs/heads/master | 2023-01-30T11:32:21.649000 | 2020-12-14T14:49:57 | 2020-12-14T14:49:57 | 318,744,029 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.guaiwolo.modules.video.controller;
import com.guaiwolo.modules.video.utils.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
@RequestMapping("api/v1/test")
@PropertySource({"classpath:pay.properties"})
public class TestController {
@Value("${wxpay.id}")
private String payAppid;
@Value("${wxpay.sercert}")
private String paySercert;
@GetMapping("get_config")
public JsonData test(){
HashMap<String, String> map = new HashMap<>();
map.put("appid", payAppid);
map.put("sercert", paySercert);
return JsonData.buildSuccess(map);
}
@GetMapping("list")
public JsonData testExt(){
int i = 1/0;
return JsonData.buildSuccess("");
}
}
| UTF-8 | Java | 1,042 | java | TestController.java | Java | [] | null | [] | package com.guaiwolo.modules.video.controller;
import com.guaiwolo.modules.video.utils.JsonData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
@RequestMapping("api/v1/test")
@PropertySource({"classpath:pay.properties"})
public class TestController {
@Value("${wxpay.id}")
private String payAppid;
@Value("${wxpay.sercert}")
private String paySercert;
@GetMapping("get_config")
public JsonData test(){
HashMap<String, String> map = new HashMap<>();
map.put("appid", payAppid);
map.put("sercert", paySercert);
return JsonData.buildSuccess(map);
}
@GetMapping("list")
public JsonData testExt(){
int i = 1/0;
return JsonData.buildSuccess("");
}
}
| 1,042 | 0.71785 | 0.714971 | 38 | 26.421053 | 20.843567 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
b3f8c4500303810605d2573fe59fc2ef5445574c | 30,167,850,341,571 | 472554edb61f78bb89297ddad0d5a6023497ad07 | /GULLI-View/src/main/java/com/saemann/gulli/view/timeline/customCell/SortButtonRenderer.java | daad7cb645128dc8f31e4b5b1ec2e445d5bb0cfc | [
"MIT"
] | permissive | rsaemann/GULLI | https://github.com/rsaemann/GULLI | 47f9664efda79aeb509c120cc38fbfb28947009c | 87241fd410a3f05b6a24231cfd00b6d05f5b4683 | refs/heads/Gulli/master | 2023-07-21T01:48:56.800000 | 2023-07-12T12:59:17 | 2023-07-12T13:00:53 | 153,114,643 | 7 | 0 | MIT | false | 2023-03-27T22:21:38 | 2018-10-15T13:07:59 | 2021-12-05T17:34:28 | 2023-03-27T22:21:37 | 89,540 | 5 | 0 | 1 | Java | false | false | package com.saemann.gulli.view.timeline.customCell;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
/**
*
* @author saemann
*/
public class SortButtonRenderer extends AbstractCellEditor implements ActionListener, TableCellRenderer, TableCellEditor {
protected JPanel panel;
protected JButton buttonUP, buttonDown;
public enum DIRECTION {
UP, DOWN, NO
};
protected DIRECTION direction = DIRECTION.NO;
public SortButtonRenderer() {
panel = new JPanel(new GridLayout(1, 2));
buttonUP = new JButton() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.drawString("\u2191", this.getWidth() / 2 - 3, (this.getHeight() + this.getFont().getSize()) / 2);
}
};
buttonDown = new JButton() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.setColor(Color.darkGray);
grphcs.drawString("\u2193", this.getWidth() / 2 - 3, (this.getHeight() + this.getFont().getSize()) / 2);//
}
};
buttonUP.addActionListener(this);
buttonDown.addActionListener(this);
panel.add(buttonUP);
panel.add(buttonDown);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.buttonUP.setSelected(false);
this.buttonDown.setSelected(false);
return panel;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
// if (value != null) {
// if (value instanceof SortButtonRenderer) {
// SortButtonRenderer in = (SortButtonRenderer) value;
//// if(in.direction==DIRECTION.UP){
//// this.buttonUP.setSelected(true);
//// this.buttonUP.requestFocus();
//// this.buttonDown.setSelected(false);
//// }else if(in.direction==DIRECTION.DOWN){
//// this.buttonDown.setSelected(true);
//// this.buttonDown.requestFocus();
//// this.buttonUP.setSelected(false);
//// }else{
//
//// }
// } else {
// System.out.println(getClass() + "::input is of Class " + value.getClass());
// }
// }
this.buttonUP.setSelected(false);
this.buttonDown.setSelected(false);
return panel;
}
@Override
public Object getCellEditorValue() {
return this;
}
@Override
public void actionPerformed(ActionEvent ae) {
direction = DIRECTION.NO;
if (ae.getSource().equals(buttonUP)) {
direction = DIRECTION.UP;
} else if (ae.getSource().equals(buttonDown)) {
direction = DIRECTION.DOWN;
}
// System.out.println("action event: " + ae);
fireEditingStopped();
}
public DIRECTION getDirection() {
return direction;
}
}
| UTF-8 | Java | 3,597 | java | SortButtonRenderer.java | Java | [
{
"context": ".swing.table.TableCellRenderer;\n\n/**\n *\n * @author saemann\n */\npublic class SortButtonRenderer extends Abstr",
"end": 463,
"score": 0.99942946434021,
"start": 456,
"tag": "USERNAME",
"value": "saemann"
}
] | null | [] | package com.saemann.gulli.view.timeline.customCell;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
/**
*
* @author saemann
*/
public class SortButtonRenderer extends AbstractCellEditor implements ActionListener, TableCellRenderer, TableCellEditor {
protected JPanel panel;
protected JButton buttonUP, buttonDown;
public enum DIRECTION {
UP, DOWN, NO
};
protected DIRECTION direction = DIRECTION.NO;
public SortButtonRenderer() {
panel = new JPanel(new GridLayout(1, 2));
buttonUP = new JButton() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.drawString("\u2191", this.getWidth() / 2 - 3, (this.getHeight() + this.getFont().getSize()) / 2);
}
};
buttonDown = new JButton() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.setColor(Color.darkGray);
grphcs.drawString("\u2193", this.getWidth() / 2 - 3, (this.getHeight() + this.getFont().getSize()) / 2);//
}
};
buttonUP.addActionListener(this);
buttonDown.addActionListener(this);
panel.add(buttonUP);
panel.add(buttonDown);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.buttonUP.setSelected(false);
this.buttonDown.setSelected(false);
return panel;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
// if (value != null) {
// if (value instanceof SortButtonRenderer) {
// SortButtonRenderer in = (SortButtonRenderer) value;
//// if(in.direction==DIRECTION.UP){
//// this.buttonUP.setSelected(true);
//// this.buttonUP.requestFocus();
//// this.buttonDown.setSelected(false);
//// }else if(in.direction==DIRECTION.DOWN){
//// this.buttonDown.setSelected(true);
//// this.buttonDown.requestFocus();
//// this.buttonUP.setSelected(false);
//// }else{
//
//// }
// } else {
// System.out.println(getClass() + "::input is of Class " + value.getClass());
// }
// }
this.buttonUP.setSelected(false);
this.buttonDown.setSelected(false);
return panel;
}
@Override
public Object getCellEditorValue() {
return this;
}
@Override
public void actionPerformed(ActionEvent ae) {
direction = DIRECTION.NO;
if (ae.getSource().equals(buttonUP)) {
direction = DIRECTION.UP;
} else if (ae.getSource().equals(buttonDown)) {
direction = DIRECTION.DOWN;
}
// System.out.println("action event: " + ae);
fireEditingStopped();
}
public DIRECTION getDirection() {
return direction;
}
}
| 3,597 | 0.593272 | 0.588824 | 108 | 32.305557 | 28.671013 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 4 |
2ea89b4d03a4916b64e1767a0600c14324c325aa | 28,467,043,279,485 | 932831ad9ae9387395099e270da43eed6f81b70b | /app/src/main/java/com/membattle/domain/service/Service.java | 5181417d92b01742e353d2d65faf8fb8e9a7e628 | [] | no_license | bondiano/memebattle_android | https://github.com/bondiano/memebattle_android | f839a8cfbc4d89c58b6b2225ebab703788783174 | 951e27f5551d921bd9b3e26308cc03e280d48285 | refs/heads/master | 2021-03-24T10:47:36.283000 | 2018-03-08T05:18:11 | 2018-03-08T05:18:11 | 121,388,928 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.membattle.domain.service;
import com.membattle.data.api.API;
import com.membattle.data.api.req.Id;
import com.membattle.data.api.req.RegistrationUser;
import com.membattle.data.api.req.Secret;
import com.membattle.data.api.res.Exres;
import com.membattle.data.api.res.rate.Rate;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class Service {
private final API api;
public Service(API api) {
this.api = api;
}
public Subscription signIn(RegistrationUser registrationUser, final AuthCallback callback) {
return api.signIn(registrationUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public Subscription signUp(RegistrationUser registrationUser, final AuthCallback callback) {
return api.signUp(registrationUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public interface AuthCallback {
void onSuccess(Exres exres);
void onError(Throwable e);
}
public Subscription getRateList(String secret, Id id, final RateCallback callback) {
return api.getRateList(secret, id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public interface RateCallback {
void onSuccess(Rate rate);
void onError(Throwable e);
}
public Subscription refreshToken(String secret, Secret refreshToken, final AuthCallback callback) {
return api.refreshToken(secret, refreshToken)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
} | UTF-8 | Java | 2,030 | java | Service.java | Java | [] | null | [] | package com.membattle.domain.service;
import com.membattle.data.api.API;
import com.membattle.data.api.req.Id;
import com.membattle.data.api.req.RegistrationUser;
import com.membattle.data.api.req.Secret;
import com.membattle.data.api.res.Exres;
import com.membattle.data.api.res.rate.Rate;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class Service {
private final API api;
public Service(API api) {
this.api = api;
}
public Subscription signIn(RegistrationUser registrationUser, final AuthCallback callback) {
return api.signIn(registrationUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public Subscription signUp(RegistrationUser registrationUser, final AuthCallback callback) {
return api.signUp(registrationUser)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public interface AuthCallback {
void onSuccess(Exres exres);
void onError(Throwable e);
}
public Subscription getRateList(String secret, Id id, final RateCallback callback) {
return api.getRateList(secret, id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
public interface RateCallback {
void onSuccess(Rate rate);
void onError(Throwable e);
}
public Subscription refreshToken(String secret, Secret refreshToken, final AuthCallback callback) {
return api.refreshToken(secret, refreshToken)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(callback::onSuccess, callback::onError);
}
} | 2,030 | 0.678818 | 0.678818 | 57 | 34.63158 | 27.015026 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561404 | false | false | 4 |
22d779736714b7241e8904b6671b83a6a54502de | 22,703,197,155,718 | e4acfacc5be1abe51be445b41814d5668b4cb0fb | /lectureCode-sp18/exercises/DIY/syntax3/accessControl/syntax3/map/IterationDemo.java | 09c816a3410ee34388475b6645b08d5d28412447 | [
"MIT"
] | permissive | Zhenye-Na/data-structures-ucb | https://github.com/Zhenye-Na/data-structures-ucb | 24a53bbc9a6c478caaedefddef1083eac7cf04d0 | ac1e4cdf63461673717dafdaed6b4c67af822ba4 | refs/heads/master | 2022-09-18T19:05:55.055000 | 2022-05-20T20:47:31 | 2022-07-22T05:40:11 | 125,691,541 | 81 | 37 | MIT | false | 2022-07-22T05:40:12 | 2018-03-18T04:10:21 | 2022-07-20T16:00:39 | 2022-07-22T05:40:11 | 296,875 | 85 | 33 | 0 | Java | false | false | package syntax3.map;
import java.util.Iterator;
public class IterationDemo {
public static void main(String[] args) {
ArrayMap<String, Integer> am = new ArrayMap<String, Integer>();
am.put("hello", 5);
am.put("syrups", 10);
am.put("kingdom", 10);
Iterator<String> it = am.iterator();
for (String s : am) {
System.out.println(s);
}
}
}
| UTF-8 | Java | 416 | java | IterationDemo.java | Java | [] | null | [] | package syntax3.map;
import java.util.Iterator;
public class IterationDemo {
public static void main(String[] args) {
ArrayMap<String, Integer> am = new ArrayMap<String, Integer>();
am.put("hello", 5);
am.put("syrups", 10);
am.put("kingdom", 10);
Iterator<String> it = am.iterator();
for (String s : am) {
System.out.println(s);
}
}
}
| 416 | 0.560096 | 0.545673 | 19 | 20.894737 | 19.265171 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 4 |
589fcde61de1fec50e035e2f3879fcef47ea7b4a | 16,441,134,842,588 | 365aefb818d81241ba603e311e6e840658c0e268 | /Mmt/src/com/mapgis/mmt/constant/ExpressionManager.java | 6f48b2a2fb8c846333aca522725303aedee2be9c | [] | no_license | github188/Android-171017 | https://github.com/github188/Android-171017 | a5839fb173b7866bece594c7250ba4c9e3cd7ede | bafd2f0be41e0796f515b5ad3a90ce4fec90eead | refs/heads/master | 2021-04-26T22:11:36.438000 | 2017-10-20T09:06:06 | 2017-10-20T09:06:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mapgis.mmt.constant;
import java.util.ArrayList;
import java.util.List;
/**
* 惯用语管理器
*/
public class ExpressionManager {
/** 默认惯用语 */
public static final int EXPRESSION_NORMAL = 0;
/** 事件上报惯用语 */
public static final int EXPRESSION_FLOWREPORTER = 1;
/** 其他惯用语 */
public static final int EXPRESSION_OTHER = 2;
public List<String> getExpression(int expressionFlag) {
List<String> expressions = null;
switch (expressionFlag) {
case EXPRESSION_FLOWREPORTER:
expressions = new FlowReporterExpression().getFlowReporterExpressions();
break;
case EXPRESSION_OTHER:
expressions = new OthersExpression().getOtherExpressions();
break;
default:
expressions = new NormalExpression().getNormalExpressions();
break;
}
return expressions;
}
/** 默认惯用语 */
class NormalExpression {
public final List<String> normalExpressions = new ArrayList<String>();
public NormalExpression() {
normalExpressions.add("默认惯用语1");
normalExpressions.add("默认惯用语2");
normalExpressions.add("默认惯用语3");
normalExpressions.add("默认惯用语4");
}
public List<String> getNormalExpressions() {
return normalExpressions;
}
}
/** 事件上报惯用语 */
class FlowReporterExpression extends NormalExpression {
public final List<String> flowReporterExpressions = new ArrayList<String>();
public FlowReporterExpression() {
super();
flowReporterExpressions.addAll(normalExpressions);
}
public List<String> getFlowReporterExpressions() {
return flowReporterExpressions;
}
}
/** 其他惯用语 */
class OthersExpression extends NormalExpression {
public final List<String> otherExpressions = new ArrayList<String>();
public OthersExpression() {
super();
otherExpressions.addAll(normalExpressions);
}
public List<String> getOtherExpressions() {
return otherExpressions;
}
}
}
| UTF-8 | Java | 2,044 | java | ExpressionManager.java | Java | [] | null | [] | package com.mapgis.mmt.constant;
import java.util.ArrayList;
import java.util.List;
/**
* 惯用语管理器
*/
public class ExpressionManager {
/** 默认惯用语 */
public static final int EXPRESSION_NORMAL = 0;
/** 事件上报惯用语 */
public static final int EXPRESSION_FLOWREPORTER = 1;
/** 其他惯用语 */
public static final int EXPRESSION_OTHER = 2;
public List<String> getExpression(int expressionFlag) {
List<String> expressions = null;
switch (expressionFlag) {
case EXPRESSION_FLOWREPORTER:
expressions = new FlowReporterExpression().getFlowReporterExpressions();
break;
case EXPRESSION_OTHER:
expressions = new OthersExpression().getOtherExpressions();
break;
default:
expressions = new NormalExpression().getNormalExpressions();
break;
}
return expressions;
}
/** 默认惯用语 */
class NormalExpression {
public final List<String> normalExpressions = new ArrayList<String>();
public NormalExpression() {
normalExpressions.add("默认惯用语1");
normalExpressions.add("默认惯用语2");
normalExpressions.add("默认惯用语3");
normalExpressions.add("默认惯用语4");
}
public List<String> getNormalExpressions() {
return normalExpressions;
}
}
/** 事件上报惯用语 */
class FlowReporterExpression extends NormalExpression {
public final List<String> flowReporterExpressions = new ArrayList<String>();
public FlowReporterExpression() {
super();
flowReporterExpressions.addAll(normalExpressions);
}
public List<String> getFlowReporterExpressions() {
return flowReporterExpressions;
}
}
/** 其他惯用语 */
class OthersExpression extends NormalExpression {
public final List<String> otherExpressions = new ArrayList<String>();
public OthersExpression() {
super();
otherExpressions.addAll(normalExpressions);
}
public List<String> getOtherExpressions() {
return otherExpressions;
}
}
}
| 2,044 | 0.693347 | 0.689709 | 85 | 20.635294 | 22.054396 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.647059 | false | false | 4 |
781611a5c8f9c4b2183e0612312deb0ec629ee33 | 27,865,747,846,222 | b17c4bac0a7bd52e2376ee48e9c8a726fdcb1699 | /app/extend/mq/MQListener.java | d8bc3b5aeb427e4a1295d0fd8945b18e14f36d11 | [] | no_license | ewingcode/ewingcenter | https://github.com/ewingcode/ewingcenter | 5cc17fa4af71d0eb86859f78106d4680d0d20ccf | 2ec700b21d64710a9e532e600a0f5440d718f26e | refs/heads/master | 2016-08-11T06:54:45.994000 | 2016-01-29T09:37:03 | 2016-01-29T09:37:03 | 50,322,504 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package extend.mq;
import java.util.HashMap;
import java.util.Map;
import javax.jms.MessageListener;
import org.apache.activemq.ActiveMQConnection;
import jws.Jws;
import jws.Logger;
/**
* 消息队列的监听者抽象类
*
* @author tanson lam
* @createDate 2015年2月26日
*
*/
public abstract class MQListener {
protected final MQReceiver receiver;
protected Map<String, Class<? extends MessageListener>> queueListnerMap = new HashMap<String, Class<? extends MessageListener>>();
public MQListener(final MQReceiver receiver) {
this.receiver = receiver;
}
/**
* 获取定义的消息监听器
*
* @return
*/
public abstract Map<String, Class<? extends MessageListener>> getMessageListener();
/**
* 添加消息监听器
*
* @param queue 消息队列
* @param messageListenerClazz 消息队列的监听器类
*/
public void addMessageListener(String queue,
Class<? extends MessageListener> messageListenerClazz) {
if (queueListnerMap.get(queue) == null)
queueListnerMap.put(queue, messageListenerClazz);
}
/**
* 启动所有队列监听器
*/
public void startListeners() {
Logger.info("Messagequeue start listeners");
queueListnerMap.putAll(getMessageListener());
if (queueListnerMap.isEmpty())
return;
for (String queue : queueListnerMap.keySet()) {
Class<? extends MessageListener> messageListenerClazz = queueListnerMap.get(queue);
try {
Logger.info("Messagequeue initialize listener, queue[" + queue + "] listenerClazz["
+ messageListenerClazz.getName() + "]");
Integer listenerNum = Integer.valueOf(Jws.configuration.getProperty(
"messagequeue.listener." + queue + ".number", "1"));
for (int i = 0; i < listenerNum; i++)
receiver.setMessageListener(queue, messageListenerClazz.newInstance());
} catch (InstantiationException e) {
Logger.error(e, e.getMessage());
} catch (IllegalAccessException e) {
Logger.error(e, e.getMessage());
}
}
}
}
| UTF-8 | Java | 2,274 | java | MQListener.java | Java | [
{
"context": "ort jws.Logger;\n\n/**\n * 消息队列的监听者抽象类\n * \n * @author tanson lam\n * @createDate 2015年2月26日\n * \n */\npublic abstract",
"end": 232,
"score": 0.9974362850189209,
"start": 222,
"tag": "NAME",
"value": "tanson lam"
}
] | null | [] | package extend.mq;
import java.util.HashMap;
import java.util.Map;
import javax.jms.MessageListener;
import org.apache.activemq.ActiveMQConnection;
import jws.Jws;
import jws.Logger;
/**
* 消息队列的监听者抽象类
*
* @author <NAME>
* @createDate 2015年2月26日
*
*/
public abstract class MQListener {
protected final MQReceiver receiver;
protected Map<String, Class<? extends MessageListener>> queueListnerMap = new HashMap<String, Class<? extends MessageListener>>();
public MQListener(final MQReceiver receiver) {
this.receiver = receiver;
}
/**
* 获取定义的消息监听器
*
* @return
*/
public abstract Map<String, Class<? extends MessageListener>> getMessageListener();
/**
* 添加消息监听器
*
* @param queue 消息队列
* @param messageListenerClazz 消息队列的监听器类
*/
public void addMessageListener(String queue,
Class<? extends MessageListener> messageListenerClazz) {
if (queueListnerMap.get(queue) == null)
queueListnerMap.put(queue, messageListenerClazz);
}
/**
* 启动所有队列监听器
*/
public void startListeners() {
Logger.info("Messagequeue start listeners");
queueListnerMap.putAll(getMessageListener());
if (queueListnerMap.isEmpty())
return;
for (String queue : queueListnerMap.keySet()) {
Class<? extends MessageListener> messageListenerClazz = queueListnerMap.get(queue);
try {
Logger.info("Messagequeue initialize listener, queue[" + queue + "] listenerClazz["
+ messageListenerClazz.getName() + "]");
Integer listenerNum = Integer.valueOf(Jws.configuration.getProperty(
"messagequeue.listener." + queue + ".number", "1"));
for (int i = 0; i < listenerNum; i++)
receiver.setMessageListener(queue, messageListenerClazz.newInstance());
} catch (InstantiationException e) {
Logger.error(e, e.getMessage());
} catch (IllegalAccessException e) {
Logger.error(e, e.getMessage());
}
}
}
}
| 2,270 | 0.612546 | 0.608395 | 73 | 28.698629 | 29.391399 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452055 | false | false | 4 |
9c82b48fe9dd236545d0bda58a31268f857c26cf | 3,204,045,663,443 | 134da720d0a5cd858975bdc785dad3171c70c851 | /src/main/java/com/zdh/hm/fthfldtl/service/FthfldtlService.java | 193c65d723aa98dfdcfe8fe39939429d270a8ef1 | [] | no_license | xxget/hm | https://github.com/xxget/hm | 0bb751bdc86a9a738f04d0333f5995bf4c23c936 | 0212f927e0c6e7ceb0111bd46fa789506ecd5667 | refs/heads/master | 2023-03-10T13:54:01.052000 | 2021-02-24T06:29:15 | 2021-02-24T06:29:15 | 341,119,068 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zdh.hm.fthfldtl.service;
import com.zdh.hm.fthfldtl.entity.Fthfldtl;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* (Fthfldtl)表服务接口
*
* @author xxg
* @since 2021-02-23 11:14:12
*/
public interface FthfldtlService {
/**
* 通过ID查询单条数据
*
* @param colltime 主键
* @return 实例对象
*/
Fthfldtl queryById(Date colltime);
/**
* 查询多条数据
*
* @param offset 查询起始位置
* @param limit 查询条数
* @return 对象列表
*/
List<Fthfldtl> queryAllByLimit(int offset, int limit);
/**
* 新增数据
*
* @param fthfldtl 实例对象
* @return 实例对象
*/
Fthfldtl insert(Fthfldtl fthfldtl);
/**
* 修改数据
*
* @param fthfldtl 实例对象
* @return 实例对象
*/
Fthfldtl update(Fthfldtl fthfldtl);
/**
* 通过主键删除数据
*
* @param colltime 主键
* @return 是否成功
*/
boolean deleteById(Date colltime);
}
| UTF-8 | Java | 1,115 | java | FthfldtlService.java | Java | [
{
"context": "a.util.List;\n\n/**\n * (Fthfldtl)表服务接口\n *\n * @author xxg\n * @since 2021-02-23 11:14:12\n */\npublic interfac",
"end": 217,
"score": 0.9996336698532104,
"start": 214,
"tag": "USERNAME",
"value": "xxg"
}
] | null | [] | package com.zdh.hm.fthfldtl.service;
import com.zdh.hm.fthfldtl.entity.Fthfldtl;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* (Fthfldtl)表服务接口
*
* @author xxg
* @since 2021-02-23 11:14:12
*/
public interface FthfldtlService {
/**
* 通过ID查询单条数据
*
* @param colltime 主键
* @return 实例对象
*/
Fthfldtl queryById(Date colltime);
/**
* 查询多条数据
*
* @param offset 查询起始位置
* @param limit 查询条数
* @return 对象列表
*/
List<Fthfldtl> queryAllByLimit(int offset, int limit);
/**
* 新增数据
*
* @param fthfldtl 实例对象
* @return 实例对象
*/
Fthfldtl insert(Fthfldtl fthfldtl);
/**
* 修改数据
*
* @param fthfldtl 实例对象
* @return 实例对象
*/
Fthfldtl update(Fthfldtl fthfldtl);
/**
* 通过主键删除数据
*
* @param colltime 主键
* @return 是否成功
*/
boolean deleteById(Date colltime);
}
| 1,115 | 0.575442 | 0.560874 | 58 | 15.568966 | 14.060352 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.189655 | false | false | 4 |
fd8e5fe2042e186d0bc6cf8108418127f0ae9330 | 30,116,310,691,763 | 86421f4cfd6fb93e73f96db02498b4cd3b65d4b9 | /3-simple-chat-api/src/main/java/dsergeyev/example/resources/validation/password/PasswordMatchesValidator.java | 0644d6cffd307e870c215d64a2346533c713d404 | [] | no_license | DmitrySergeyev/MyCodeExamples | https://github.com/DmitrySergeyev/MyCodeExamples | 1761022c72b64d97ee590cf3fe8c22239b6df040 | b434f32dbe545f4dc31580acf1debf09187f0207 | refs/heads/master | 2020-05-25T23:53:49.359000 | 2017-03-13T18:50:01 | 2017-03-13T18:50:01 | 82,557,866 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dsergeyev.example.resources.validation.password;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import dsergeyev.example.models.user.User;
public class PasswordMatchesValidator implements ConstraintValidator<UserPasswordsMatch, Object> {
@Override
public void initialize(UserPasswordsMatch constraintAnnotation) {
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
User user = (User) obj;
if(user.getPassword() == null || user.getConfirmationPassword() == null) {
context.disableDefaultConstraintViolation();
context
.buildConstraintViolationWithTemplate("User registration request should contain valid 'password' and 'confirmationPassword' fields")
.addConstraintViolation();
return false;
}
return user.getPassword().equals(user.getConfirmationPassword());
}
}
| UTF-8 | Java | 933 | java | PasswordMatchesValidator.java | Java | [] | null | [] | package dsergeyev.example.resources.validation.password;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import dsergeyev.example.models.user.User;
public class PasswordMatchesValidator implements ConstraintValidator<UserPasswordsMatch, Object> {
@Override
public void initialize(UserPasswordsMatch constraintAnnotation) {
}
@Override
public boolean isValid(Object obj, ConstraintValidatorContext context) {
User user = (User) obj;
if(user.getPassword() == null || user.getConfirmationPassword() == null) {
context.disableDefaultConstraintViolation();
context
.buildConstraintViolationWithTemplate("User registration request should contain valid 'password' and 'confirmationPassword' fields")
.addConstraintViolation();
return false;
}
return user.getPassword().equals(user.getConfirmationPassword());
}
}
| 933 | 0.76313 | 0.76313 | 28 | 32.32143 | 36.196934 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.285714 | false | false | 4 |
bb1e0cf5b2df2fd118768d106f833f95a62e3816 | 12,987,981,167,819 | feafadb452f1561814045e754ce87ac81bac4c49 | /app/src/main/java/au/edu/deakin/lbeasle/diyhub/MainActivity.java | 00bd2b51fbfcb73b220bd2a6bf9603270024d5fa | [] | no_license | lbeasle/DIYHub | https://github.com/lbeasle/DIYHub | 5eed635911726ef53fd60573c5df62f2abce80d8 | 8118c4f51b1c37bcf703ca4234e438af6d92d07e | refs/heads/master | 2018-03-29T01:50:14.700000 | 2017-05-16T07:16:47 | 2017-05-16T07:16:47 | 87,623,646 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package au.edu.deakin.lbeasle.diyhub;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
/**
* Author: Llewellyn Beasley
*/
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private String[] navDrawerEntries;
private ListView navDrawerListView;
private DrawerLayout navDrawerLayout;
private ActionBarDrawerToggle navDrawerToggle;
private MenuItem sMenuItem;
private SearchView sView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNavigationDrawer();
if(savedInstanceState == null) {
// Load the Home Fragment if none have been loaded already.
Fragment homeFragment = new HomeFragment();
// Use the fragment manager to show the home fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, homeFragment)
.commit();
}
// Setup a button that can be pressed in the action bar that will open and close the navigation drawer.
// Based on documentation from Google:
// https://developer.android.com/training/implementing-navigation/nav-drawer.html
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navDrawerToggle = new ActionBarDrawerToggle(this, navDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
// Drawer closed
super.onDrawerClosed(view);
getSupportActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View view) {
// Drawer open
super.onDrawerOpened(view);
getSupportActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
navDrawerLayout.addDrawerListener(navDrawerToggle);
// Add the home button to the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// To show the search icon in the action bar, load the menu xml and display it.
// Search implemenation based off code and information from here:
// https://coderwall.com/p/zpwrsg/add-search-function-to-list-view-in-android
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
// Set up the search manager which is used to perform the search.
SearchManager sManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
sMenuItem = menu.findItem(R.id.guide_search);
sView = (SearchView)sMenuItem.getActionView();
sView.setSearchableInfo(sManager.getSearchableInfo(getComponentName()));
sView.setSubmitButtonEnabled(true);
sView.setOnQueryTextListener(this);
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the navigation drawer state after onRestoreInstanceState has occurred.
navDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
navDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// When the menu button is pressed, open the navigation drawer.
if (navDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void createNavigationDrawer() {
// Navigation Drawer implemented using documentation from here:
// https://developer.android.com/training/implementing-navigation/nav-drawer.html
// Populate the navigation drawer menu.
navDrawerListView = (ListView) findViewById(R.id.navigation_list);
// Get the array of list items.
navDrawerEntries = getResources().getStringArray(R.array.navigation_drawer_entries);
// Set the adapter to use in the list view.
navDrawerListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, navDrawerEntries));
// Attach the OnItemClickListener listener to the list view.
navDrawerListView.setOnItemClickListener(new NavigationDrawerItemClickListener());
}
private void selectItem(int position) {
// This method is called after an item in the navigation drawer is selected.
// It shows the selected fragment on the screen.
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new CategoriesFragment();
break;
case 2:
fragment = new GuidesFragment();
break;
case 3:
fragment = GuidesFragment.newInstance(true);
break;
case 4:
fragment = new AboutFragment();
break;
}
if (fragment != null)
{
// Use the fragment manager to show the selected fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("")
.commit();
}
}
@Override
public boolean onQueryTextSubmit(String query) {
// Create a new instance of the Guides fragment and pass the category ID.
Fragment fragment = SearchResultsFragment.newInstance(query);
// Use the fragment manager to show the search results fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("")
.commit();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
// Implement the OnItemClickListener for the navigation drawer.
private class NavigationDrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
| UTF-8 | Java | 7,300 | java | MainActivity.java | Java | [
{
"context": "\nimport android.widget.SearchView;\n\n/**\n * Author: Llewellyn Beasley\n */\npublic class MainActivity extends AppCompatAc",
"end": 673,
"score": 0.9998832941055298,
"start": 656,
"tag": "NAME",
"value": "Llewellyn Beasley"
}
] | null | [] | package au.edu.deakin.lbeasle.diyhub;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
/**
* Author: <NAME>
*/
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private String[] navDrawerEntries;
private ListView navDrawerListView;
private DrawerLayout navDrawerLayout;
private ActionBarDrawerToggle navDrawerToggle;
private MenuItem sMenuItem;
private SearchView sView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createNavigationDrawer();
if(savedInstanceState == null) {
// Load the Home Fragment if none have been loaded already.
Fragment homeFragment = new HomeFragment();
// Use the fragment manager to show the home fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, homeFragment)
.commit();
}
// Setup a button that can be pressed in the action bar that will open and close the navigation drawer.
// Based on documentation from Google:
// https://developer.android.com/training/implementing-navigation/nav-drawer.html
navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navDrawerToggle = new ActionBarDrawerToggle(this, navDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
// Drawer closed
super.onDrawerClosed(view);
getSupportActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View view) {
// Drawer open
super.onDrawerOpened(view);
getSupportActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
navDrawerLayout.addDrawerListener(navDrawerToggle);
// Add the home button to the action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// To show the search icon in the action bar, load the menu xml and display it.
// Search implemenation based off code and information from here:
// https://coderwall.com/p/zpwrsg/add-search-function-to-list-view-in-android
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
// Set up the search manager which is used to perform the search.
SearchManager sManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
sMenuItem = menu.findItem(R.id.guide_search);
sView = (SearchView)sMenuItem.getActionView();
sView.setSearchableInfo(sManager.getSearchableInfo(getComponentName()));
sView.setSubmitButtonEnabled(true);
sView.setOnQueryTextListener(this);
return true;
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the navigation drawer state after onRestoreInstanceState has occurred.
navDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
navDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// When the menu button is pressed, open the navigation drawer.
if (navDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void createNavigationDrawer() {
// Navigation Drawer implemented using documentation from here:
// https://developer.android.com/training/implementing-navigation/nav-drawer.html
// Populate the navigation drawer menu.
navDrawerListView = (ListView) findViewById(R.id.navigation_list);
// Get the array of list items.
navDrawerEntries = getResources().getStringArray(R.array.navigation_drawer_entries);
// Set the adapter to use in the list view.
navDrawerListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, navDrawerEntries));
// Attach the OnItemClickListener listener to the list view.
navDrawerListView.setOnItemClickListener(new NavigationDrawerItemClickListener());
}
private void selectItem(int position) {
// This method is called after an item in the navigation drawer is selected.
// It shows the selected fragment on the screen.
Fragment fragment = null;
switch (position)
{
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new CategoriesFragment();
break;
case 2:
fragment = new GuidesFragment();
break;
case 3:
fragment = GuidesFragment.newInstance(true);
break;
case 4:
fragment = new AboutFragment();
break;
}
if (fragment != null)
{
// Use the fragment manager to show the selected fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("")
.commit();
}
}
@Override
public boolean onQueryTextSubmit(String query) {
// Create a new instance of the Guides fragment and pass the category ID.
Fragment fragment = SearchResultsFragment.newInstance(query);
// Use the fragment manager to show the search results fragment.
FragmentManager fragMgr = getFragmentManager();
fragMgr.beginTransaction()
.replace(R.id.content, fragment)
.addToBackStack("")
.commit();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
// Implement the OnItemClickListener for the navigation drawer.
private class NavigationDrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
| 7,289 | 0.659041 | 0.657808 | 200 | 35.5 | 28.387144 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455 | false | false | 4 |
58dd576e3519f0dce81d65436d67c0ee64232b5c | 17,978,733,127,300 | 879e6958689e7dd36935b6b09e31a7e236ba85bd | /EParser/src/main/java/nl/elmar/model/EParserException.java | 5840ba1ac0e188706c8ce31e506d671a8c07f1d6 | [] | no_license | giorgiovinci/giorgioparser | https://github.com/giorgiovinci/giorgioparser | cea68fbbd48524bcd7c45363bc6bef936c4873bf | 2e28117d8c0430ffc444fdd6c348ec66284033d4 | refs/heads/master | 2016-09-06T12:36:12.445000 | 2010-07-09T11:37:00 | 2010-07-09T11:37:00 | 32,893,023 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nl.elmar.model;
public class EParserException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EParserException() {
}
public EParserException(String s) {
super(s);
}
public EParserException(String s, Throwable throwable) {
super(s, throwable);
}
public EParserException(Throwable throwable) {
super(throwable);
}
} | UTF-8 | Java | 422 | java | EParserException.java | Java | [] | null | [] | package nl.elmar.model;
public class EParserException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EParserException() {
}
public EParserException(String s) {
super(s);
}
public EParserException(String s, Throwable throwable) {
super(s, throwable);
}
public EParserException(Throwable throwable) {
super(throwable);
}
} | 422 | 0.668246 | 0.665877 | 21 | 19.142857 | 20.764635 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
f238873a02a348c5c66f3d6c9a59532fa36ae4bf | 19,851,338,885,845 | 5d4d1b576dd06c7636de3a4cd45c9f9d7d5a95f6 | /src/main/java/com/yunmai/oa/service/impl/EmployeeServiceImpl.java | 43a636dad826f82b025b48b7c92b96b39c7a3558 | [] | no_license | jnuYT/yunmai-web-oa-github | https://github.com/jnuYT/yunmai-web-oa-github | 088bf79969bf2f70be951e1bef3be7bb74c4f8dd | 58a21ea5e9766a886ab97a4c48c8b807b1bf820f | refs/heads/master | 2017-09-02T04:53:18.083000 | 2016-08-11T18:26:36 | 2016-08-11T18:26:36 | 39,843,718 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yunmai.oa.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yunmai.oa.mapper.EmployeeMapper;
import com.yunmai.oa.model.po.Employee;
import com.yunmai.oa.service.EmployeeService;
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
EmployeeMapper mapper;
@Override
public List<Employee> getListByDepartmentId(Integer departmentId) {
return mapper.getListByDepartmentId(departmentId);
}
@Override
public Integer save(Employee employee) {
return mapper.save(employee);
}
@Override
public List<Employee> search(Employee employee) {
return mapper.search(employee);
}
@Override
public void batchDelete(List<Integer> idList) {
mapper.batchDelete(idList);
}
@Override
public void update(Employee employee) {
mapper.update(employee);
}
@Override
public Integer getCountByDepartmentId(Integer departmentId) {
return mapper.getCountByDepartmentId(departmentId);
}
}
| UTF-8 | Java | 1,050 | java | EmployeeServiceImpl.java | Java | [] | null | [] | package com.yunmai.oa.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yunmai.oa.mapper.EmployeeMapper;
import com.yunmai.oa.model.po.Employee;
import com.yunmai.oa.service.EmployeeService;
@Service
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
EmployeeMapper mapper;
@Override
public List<Employee> getListByDepartmentId(Integer departmentId) {
return mapper.getListByDepartmentId(departmentId);
}
@Override
public Integer save(Employee employee) {
return mapper.save(employee);
}
@Override
public List<Employee> search(Employee employee) {
return mapper.search(employee);
}
@Override
public void batchDelete(List<Integer> idList) {
mapper.batchDelete(idList);
}
@Override
public void update(Employee employee) {
mapper.update(employee);
}
@Override
public Integer getCountByDepartmentId(Integer departmentId) {
return mapper.getCountByDepartmentId(departmentId);
}
}
| 1,050 | 0.789524 | 0.789524 | 48 | 20.875 | 21.756824 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
0dc37d50e21bd64d695f3797709fd79ea8cbc867 | 1,142,461,334,129 | d006fa6dbf28158af1eb5e231abc2e50f2cf04aa | /LeetCode/ValidParentheses.java | 055a767b88442ab30be0c6364282c7421b117cad | [] | no_license | chenjyr/AlgorithmProblems | https://github.com/chenjyr/AlgorithmProblems | e0dde9965b08afdb03f3bc9ca6c6a407a043b35f | 8608f78aaee76745e77222917f5cb48efcb91fba | refs/heads/master | 2020-05-17T17:16:56.484000 | 2014-05-25T07:13:18 | 2014-05-25T07:13:18 | 15,222,088 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
*
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
public boolean isValid(String s) {
if (s == null) return false;
Stack<Character> brackets = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (isOpeningBracket(c)) brackets.push(c);
else if (isClosingBracket(c)
&& (brackets.isEmpty() || ! isSameType(brackets.pop(), c))) return false;
}
return brackets.isEmpty();
}
private boolean isOpeningBracket(char c) {
return c == '(' || c == '{' || c == '[';
}
private boolean isClosingBracket(char c) {
return c == ')' || c == '}' || c == ']';
}
private boolean isSameType(char opening, char closing) {
return (opening == '(' && closing == ')')
|| (opening == '{' && closing == '}')
|| (opening == '[' && closing == ']');
}
| UTF-8 | Java | 1,074 | java | ValidParentheses.java | Java | [] | null | [] | /**
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
*
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
*/
public boolean isValid(String s) {
if (s == null) return false;
Stack<Character> brackets = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (isOpeningBracket(c)) brackets.push(c);
else if (isClosingBracket(c)
&& (brackets.isEmpty() || ! isSameType(brackets.pop(), c))) return false;
}
return brackets.isEmpty();
}
private boolean isOpeningBracket(char c) {
return c == '(' || c == '{' || c == '[';
}
private boolean isClosingBracket(char c) {
return c == ')' || c == '}' || c == ']';
}
private boolean isSameType(char opening, char closing) {
return (opening == '(' && closing == ')')
|| (opening == '{' && closing == '}')
|| (opening == '[' && closing == ']');
}
| 1,074 | 0.518622 | 0.517691 | 37 | 28.027027 | 30.522907 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.891892 | false | false | 4 |
9d487450879d82495a09b3afebd727dd2049fff1 | 22,230,750,788,279 | 2f05bf264bd87f533803906811ffc89685688dba | /Java_013_method/src/com/callor/method/Method_08.java | 9b4a454a3223d25eb761c8f2d558367568e59c2b | [] | no_license | dkdud8140/Biz_403_2021_03_Java | https://github.com/dkdud8140/Biz_403_2021_03_Java | 3d6a9cf8cd692b78047606665fd888a8ca6ed80f | a24f241a8d12e13c9d6a8a6be78a6b66e5856c31 | refs/heads/master | 2023-06-23T03:51:46.025000 | 2021-07-26T08:35:43 | 2021-07-26T08:35:43 | 348,207,335 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.callor.method;
import com.callor.method.service.NumberServiceV6;
/*
* method_08.main() 에서
* NumberServiceV6.inputNum()을 호출하고
* InputService.inputValue(String title)을 호출하고
* QUIT : return null ;
* 아니면 : return 정수값 ;
* retNum에 되돌려 받기
* null 이면 return null
* 아니면 0 ~ 100까지인지 검사
* 아니면 다시 InputService.inputValue(String title)
* 아니면 return retNum
*
* retNum에 되돌려 받아
* 화면에 출력
*
*/
public class Method_08 {
public static void main(String[] args) {
NumberServiceV6 nsV6 = new NumberServiceV6();
Integer intNum = nsV6.inputNum();
System.out.println("입력한 값 : " + intNum);
}
}
| UTF-8 | Java | 772 | java | Method_08.java | Java | [] | null | [] | package com.callor.method;
import com.callor.method.service.NumberServiceV6;
/*
* method_08.main() 에서
* NumberServiceV6.inputNum()을 호출하고
* InputService.inputValue(String title)을 호출하고
* QUIT : return null ;
* 아니면 : return 정수값 ;
* retNum에 되돌려 받기
* null 이면 return null
* 아니면 0 ~ 100까지인지 검사
* 아니면 다시 InputService.inputValue(String title)
* 아니면 return retNum
*
* retNum에 되돌려 받아
* 화면에 출력
*
*/
public class Method_08 {
public static void main(String[] args) {
NumberServiceV6 nsV6 = new NumberServiceV6();
Integer intNum = nsV6.inputNum();
System.out.println("입력한 값 : " + intNum);
}
}
| 772 | 0.638719 | 0.617378 | 34 | 18.294117 | 17.202137 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.705882 | false | false | 4 |
94915b76d70d1a97dbbb91f4a98c2fc7ddba8d76 | 2,714,419,337,837 | 24dd4c85b7eca73184edba9d2cfd1096ef7c62a9 | /day_0421/src/com/day/C.java | ba9a92c944f656d27f9df9e8a923f176c1d22075 | [] | no_license | sungu1516/java_study | https://github.com/sungu1516/java_study | 70e2ecc0a9e7aa121aca3a61d6bf628bd558d2d3 | f6b81b371931de70bc6ee0c0c1109f0e234e52e7 | refs/heads/master | 2023-05-22T18:20:55.278000 | 2021-06-09T07:32:52 | 2021-06-09T07:32:52 | 357,819,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.day;
import java.util.ArrayList;
public class C extends Cs{
String[] title = { "레옹", "쉰들러리스트", "타이타닉", "기생충", "클래식" };
String[] director = { "뤽베송", "스필버그", "카메론", "봉준호", "곽재용" };
String[] genre = { "액션", "드라마", "드라마", "스릴러", "멜로드라마" };
String[] count = { "100만", "300만", "900만", "1000만", "150만" };
String[] actor = { "장르노", "리암니슨", "디카프리오", "송강호", "조승우" };
String[] actress = { "나탈리포트만", "엠베스", "케이트윈슬렛", "조여정", "손예진" };
String[] time = { "100", "200분", "160분", "120분", "120분" };
public C(int i) {
setTitle(title[i]);
setDirector(director[i]);
setGenre(genre[i]);
setCount(count[i]);
setActor(actor[i]);
setActress(actress[i]);
setTime(time[i]);
}
public C() {
// TODO Auto-generated constructor stub
}
}
| UHC | Java | 949 | java | C.java | Java | [
{
"context": "\npublic class C extends Cs{\n\n\tString[] title = { \"레옹\", \"쉰들러리스트\", \"타이타닉\", \"기생충\", \"클래식\" };\n\tString[] dir",
"end": 98,
"score": 0.9089536070823669,
"start": 96,
"tag": "NAME",
"value": "레옹"
},
{
"context": "class C extends Cs{\n\n\tString[] title = { \"레옹\", \"쉰들러리스트\", \"타이타닉\", \"기생충\", \"클래식\" };\n\tString[] director =",
"end": 105,
"score": 0.5456923842430115,
"start": 104,
"tag": "NAME",
"value": "러"
},
{
"context": ", \"타이타닉\", \"기생충\", \"클래식\" };\n\tString[] director = { \"뤽베송\", \"스필버그\", \"카메론\", \"봉준호\", \"곽재용\" };\n\tString[] genre ",
"end": 162,
"score": 0.9993142485618591,
"start": 159,
"tag": "NAME",
"value": "뤽베송"
},
{
"context": "\", \"기생충\", \"클래식\" };\n\tString[] director = { \"뤽베송\", \"스필버그\", \"카메론\", \"봉준호\", \"곽재용\" };\n\tString[] genre = { \"액션\"",
"end": 170,
"score": 0.9987820386886597,
"start": 166,
"tag": "NAME",
"value": "스필버그"
},
{
"context": ", \"클래식\" };\n\tString[] director = { \"뤽베송\", \"스필버그\", \"카메론\", \"봉준호\", \"곽재용\" };\n\tString[] genre = { \"액션\", \"드라마\"",
"end": 177,
"score": 0.999442994594574,
"start": 174,
"tag": "NAME",
"value": "카메론"
},
{
"context": " };\n\tString[] director = { \"뤽베송\", \"스필버그\", \"카메론\", \"봉준호\", \"곽재용\" };\n\tString[] genre = { \"액션\", \"드라마\", \"드라마\"",
"end": 184,
"score": 0.9996374845504761,
"start": 181,
"tag": "NAME",
"value": "봉준호"
},
{
"context": "ring[] director = { \"뤽베송\", \"스필버그\", \"카메론\", \"봉준호\", \"곽재용\" };\n\tString[] genre = { \"액션\", \"드라마\", \"드라마\", \"스릴러\"",
"end": 191,
"score": 0.951191782951355,
"start": 188,
"tag": "NAME",
"value": "곽재용"
},
{
"context": ", \"900만\", \"1000만\", \"150만\" };\n\tString[] actor = { \"장르노\", \"리암니슨\", \"디카프리오\", \"송강호\", \"조승우\" };\n\tString[] actr",
"end": 341,
"score": 0.9914085268974304,
"start": 338,
"tag": "NAME",
"value": "장르노"
},
{
"context": "\", \"1000만\", \"150만\" };\n\tString[] actor = { \"장르노\", \"리암니슨\", \"디카프리오\", \"송강호\", \"조승우\" };\n\tString[] actress = { ",
"end": 349,
"score": 0.998225212097168,
"start": 345,
"tag": "NAME",
"value": "리암니슨"
},
{
"context": "\" };\n\tString[] actor = { \"장르노\", \"리암니슨\", \"디카프리오\", \"송강호\", \"조승우\" };\n\tString[] actress = { \"나탈리포트만\", \"엠베스\",",
"end": 365,
"score": 0.998570442199707,
"start": 362,
"tag": "NAME",
"value": "송강호"
},
{
"context": "tring[] actor = { \"장르노\", \"리암니슨\", \"디카프리오\", \"송강호\", \"조승우\" };\n\tString[] actress = { \"나탈리포트만\", \"엠베스\", \"케이트윈슬",
"end": 372,
"score": 0.9849414825439453,
"start": 369,
"tag": "NAME",
"value": "조승우"
},
{
"context": "[] actress = { \"나탈리포트만\", \"엠베스\", \"케이트윈슬렛\", \"조여정\", \"손예진\" };\n\tString[] time = { \"100\", \"200분\", \"160분\", \"",
"end": 435,
"score": 0.5301678776741028,
"start": 434,
"tag": "NAME",
"value": "손"
},
{
"context": "] actress = { \"나탈리포트만\", \"엠베스\", \"케이트윈슬렛\", \"조여정\", \"손예진\" };\n\tString[] time = { \"100\", \"200분\", \"160분\", \"12",
"end": 437,
"score": 0.5535892844200134,
"start": 435,
"tag": "NAME",
"value": "예진"
}
] | null | [] | package com.day;
import java.util.ArrayList;
public class C extends Cs{
String[] title = { "레옹", "쉰들러리스트", "타이타닉", "기생충", "클래식" };
String[] director = { "뤽베송", "스필버그", "카메론", "봉준호", "곽재용" };
String[] genre = { "액션", "드라마", "드라마", "스릴러", "멜로드라마" };
String[] count = { "100만", "300만", "900만", "1000만", "150만" };
String[] actor = { "장르노", "리암니슨", "디카프리오", "송강호", "조승우" };
String[] actress = { "나탈리포트만", "엠베스", "케이트윈슬렛", "조여정", "손예진" };
String[] time = { "100", "200분", "160분", "120분", "120분" };
public C(int i) {
setTitle(title[i]);
setDirector(director[i]);
setGenre(genre[i]);
setCount(count[i]);
setActor(actor[i]);
setActress(actress[i]);
setTime(time[i]);
}
public C() {
// TODO Auto-generated constructor stub
}
}
| 949 | 0.561753 | 0.520584 | 29 | 24.965517 | 22.347542 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.551724 | false | false | 4 |
401c434c2e6fb4fb2408c8c021ddf903fb7a79b5 | 18,966,575,641,761 | d1cef9fc912b56c8e6151b03ab08b9c48daf0df1 | /main/plugins/org.talend.designer.core/src/main/java/org/talend/designer/core/ui/action/business/CrossPlatformProcessNodeDeleteAction.java | 8ad3097e245ff72ce864671a3c41affac3e30d30 | [
"Apache-2.0"
] | permissive | Talend/tdi-studio-se | https://github.com/Talend/tdi-studio-se | 4f342918a8e2f7f705694b7381278bf2212525b4 | 5c3148ac71a9706cc7c7dda1f9ac6af8d0958d81 | refs/heads/master | 2023-08-22T16:19:52.169000 | 2023-08-18T06:51:05 | 2023-08-18T06:51:05 | 21,090,723 | 145 | 240 | null | false | 2023-09-14T08:15:41 | 2014-06-22T10:10:03 | 2023-09-13T07:51:33 | 2023-09-14T08:15:39 | 815,856 | 141 | 134 | 212 | Java | false | false | // ============================================================================
//
// Copyright (C) 2006-2023 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.designer.core.ui.action.business;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.talend.commons.ui.runtime.custom.ICommonUIHandler;
import org.talend.commons.ui.runtime.custom.ICrossPlatformPreferenceStore;
import org.talend.commons.ui.runtime.custom.MessageDialogWithToggleBusinessHandler;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.model.components.IComponent;
import org.talend.core.model.process.IProcess;
import org.talend.core.model.process.IProcess2;
import org.talend.core.ui.IJobletProviderService;
import org.talend.designer.core.DesignerPlugin;
import org.talend.designer.core.i18n.Messages;
import org.talend.designer.core.model.process.AbstractProcessProvider;
import org.talend.designer.core.ui.editor.CrossPlatformPartFactory;
import org.talend.designer.core.ui.editor.connections.Connection;
import org.talend.designer.core.ui.editor.connections.ConnectionLabel;
import org.talend.designer.core.ui.editor.connections.ICrossPlatformConnLabelEditPart;
import org.talend.designer.core.ui.editor.connections.ICrossPlatformConnectionPart;
import org.talend.designer.core.ui.editor.jobletcontainer.CrossPlatformJobletContainerFigure;
import org.talend.designer.core.ui.editor.jobletcontainer.ICrossPlatformJobletContainerPart;
import org.talend.designer.core.ui.editor.jobletcontainer.JobletContainer;
import org.talend.designer.core.ui.editor.nodecontainer.ICrossPlatformNodeContainerPart;
import org.talend.designer.core.ui.editor.nodecontainer.NodeContainer;
import org.talend.designer.core.ui.editor.nodes.CrossPlatformNodeEditPolicy;
import org.talend.designer.core.ui.editor.nodes.CrossPlatformNodePart;
import org.talend.designer.core.ui.editor.nodes.ICrossPlatformNodePart;
import org.talend.designer.core.ui.editor.nodes.Node;
import org.talend.designer.core.ui.editor.notes.ICrossPlatformNoteEditPart;
import org.talend.designer.core.ui.editor.notes.Note;
import org.talend.designer.core.ui.editor.process.CrossPlatformProcessPart;
import org.talend.designer.core.ui.editor.subjobcontainer.CrossPlatformGroupRequest;
import org.talend.designer.core.ui.editor.subjobcontainer.ICrossPlatformEditPart;
import org.talend.designer.core.ui.editor.subjobcontainer.ICrossPlatformSubjobContainerPart;
import org.talend.designer.core.ui.editor.subjobcontainer.SubjobContainer;
import org.talend.designer.core.ui.preferences.TalendDesignerPrefConstants;
/**
* DOC cmeng class global comment. Detailled comment
*/
public class CrossPlatformProcessNodeDeleteAction extends AbsCrossPlatformProcessEditorAction {
private List<Object> objectsToDelete;
public CrossPlatformProcessNodeDeleteAction(IProcess2 process, ICrossPlatformActionHook actionHook) {
super(process, actionHook);
}
@Override
public boolean isEnabled(List<Object> objects) {
objectsToDelete = new ArrayList<>(objects);
if (objects.isEmpty() || (objects.size() == 1 && objects.get(0) instanceof CrossPlatformProcessPart)) {
return false;
}
if (!(objects.get(0) instanceof ICrossPlatformEditPart)) {
return false;
}
AbstractProcessProvider pProvider = AbstractProcessProvider.findProcessProviderFromPID(IComponent.JOBLET_PID);
if (pProvider != null) {
Map<ICrossPlatformJobletContainerPart, List<ICrossPlatformNodePart>> jobletMap = new HashMap<>();
boolean nodeInJoblet = false;
boolean allJunitnode = true;
boolean hasNode = false;
int i = 0;
for (Object o : objects) {
if (o instanceof ICrossPlatformNodePart) {
hasNode = true;
ICrossPlatformNodePart nodePart = (ICrossPlatformNodePart) o;
Node no = (Node) ((ICrossPlatformNodePart) o).getCrossPlatformModel();
if (no.getProcess().isReadOnly()) {
return false;
}
if (no.isReadOnly()) {
i++;
}
if (no.getJunitNode() == null) {
allJunitnode = false;
}
if (!pProvider.canDeleteNode(no)) {
return false;
}
boolean isCollapsedNode = false;
if (getProcess().getGraphicalNodes().contains(nodePart.getCrossPlatformModel())) {
isCollapsedNode = true;
}
if (!isCollapsedNode && nodePart.getCrossPlatformParentPart() instanceof ICrossPlatformJobletContainerPart) {
ICrossPlatformJobletContainerPart jobletContainer = (ICrossPlatformJobletContainerPart) nodePart
.getCrossPlatformParentPart();
List<ICrossPlatformNodePart> jobletNodeParts = jobletMap.get(jobletContainer);
if (jobletNodeParts == null) {
jobletNodeParts = new ArrayList<>();
jobletMap.put(jobletContainer, jobletNodeParts);
}
jobletNodeParts.add(nodePart);
}
} else if (o instanceof ICrossPlatformConnectionPart) {
Connection conn = (Connection) ((ICrossPlatformConnectionPart) o).getCrossPlatformModel();
if (conn.getSource().getProcess().isReadOnly()) {
return false;
}
if (conn.isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformConnLabelEditPart) {
ConnectionLabel connLabel = (ConnectionLabel) ((ICrossPlatformConnLabelEditPart) o).getCrossPlatformModel();
if (connLabel.getConnection().getSource().getProcess().isReadOnly()) {
return false;
}
if (connLabel.getConnection().isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformNoteEditPart) {
allJunitnode = false;
Note note = (Note) ((ICrossPlatformNoteEditPart) o).getCrossPlatformModel();
if (note.isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformSubjobContainerPart) {
SubjobContainer subjob = (SubjobContainer) ((ICrossPlatformSubjobContainerPart) o).getCrossPlatformModel();
if (subjob.getProcess().isReadOnly()) {
return false;
}
if (subjob.isReadOnly()) {
i++;
continue;
}
boolean isAllReadonly = true;
boolean subjobAllJunit = true;
for (NodeContainer nc : subjob.getNodeContainers()) {
Node node = nc.getNode();
if (!node.isReadOnly()) {
isAllReadonly = false;
}
if (node.getJunitNode() == null) {
subjobAllJunit = false;
}
}
if (isAllReadonly || subjobAllJunit) {
i++;
}
}
}
for (ICrossPlatformJobletContainerPart jobletContainer : jobletMap.keySet()) {
boolean copyJobletNode = true;
List<ICrossPlatformNodePart> list = jobletMap.get(jobletContainer);
for (Object obj : jobletContainer.getCrossPlatformChildren()) {
if (obj instanceof ICrossPlatformNodePart) {
if (!list.contains(obj)) {
copyJobletNode = false;
break;
}
}
}
if (copyJobletNode) {
objectsToDelete.removeAll(list);
CrossPlatformPartFactory factory = new CrossPlatformPartFactory();
CrossPlatformNodePart createEditPart = (CrossPlatformNodePart) factory.createEditPart(jobletContainer,
((NodeContainer) jobletContainer.getCrossPlatformModel()).getNode());
createEditPart.setParentPart(jobletContainer);
createEditPart.installEditPolicy(EditPolicy.COMPONENT_ROLE, new CrossPlatformNodeEditPolicy());
objectsToDelete.add(createEditPart);
} else {
nodeInJoblet = true;
}
}
if (((nodeInJoblet || allJunitnode) && hasNode) || i == objects.size()) {
return false;
}
}
return true;
}
public static List<Object> filterSameObject(List<Object> list) {
List<Object> newList = new ArrayList<>();
for (Object object : list) {
if (!newList.contains(object)) {
newList.add(object);
}
}
return newList;
}
@Override
public Command createCommand(List<Object> objs) {
List<Object> objects = objectsToDelete;
objects = filterSameObject(objects);
if (objects.isEmpty()) {
return null;
}
if (!(objects.get(0) instanceof ICrossPlatformEditPart)) {
return null;
}
ICrossPlatformEditPart object = (ICrossPlatformEditPart) objects.get(0);
// for TUP-1015
boolean isConnAttachedJLTriggerComp = false;
ICrossPlatformConnectionPart connectionPart = null;
if (object instanceof ICrossPlatformConnectionPart) {
connectionPart = (ICrossPlatformConnectionPart) object;
} else if (object instanceof ICrossPlatformConnLabelEditPart) {
connectionPart = (ICrossPlatformConnectionPart) object.getCrossPlatformParentPart();
}
if (connectionPart != null) {
Node srcNode = null;
Object srcModel = connectionPart.getCrossPlatformSource().getCrossPlatformModel();
if (srcModel instanceof Node) {
srcNode = (Node) srcModel;
}
Node tarNode = null;
Object tarModel = connectionPart.getCrossPlatformTarget().getCrossPlatformModel();
if (tarModel instanceof Node) {
tarNode = (Node) tarModel;
}
if (srcNode == null || tarNode == null) {
return null;
}
IProcess process = srcNode.getProcess();
if (AbstractProcessProvider.isExtensionProcessForJoblet(process)) {
IJobletProviderService service = (IJobletProviderService) GlobalServiceRegister.getDefault()
.getService(IJobletProviderService.class);
if (service != null && (service.isTriggerNode(srcNode) || service.isTriggerNode(tarNode))) {
isConnAttachedJLTriggerComp = true;
}
}
}
ICrossPlatformPreferenceStore store = DesignerPlugin.getDefault().getCrossPlatformPreferenceStore();
String preKey = TalendDesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;
boolean notShowWarning = false;
if (store != null) {
notShowWarning = store.getBoolean(preKey);
}
if (isConnAttachedJLTriggerComp && !notShowWarning) {
MessageDialogWithToggleBusinessHandler bh = new MessageDialogWithToggleBusinessHandler(ICommonUIHandler.WARNING,
Messages.getString("GEFDeleteAction.deleteConnectionDialog.title"),
Messages.getString("GEFDeleteAction.deleteConnectionDialog.msg"),
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0,
Messages.getString("GEFDeleteAction.deleteConnectionDialog.toggleMsg"), notShowWarning);
bh.setPreferenceStore(store);
bh.setPrefKey(preKey);
MessageDialogWithToggleBusinessHandler result = ICommonUIHandler.get().openToggle(bh);
if (!result.getOpenResult().equals(IDialogConstants.YES_ID)) {
return null;
}
if (store != null) {
store.setValue(preKey, result.getToggleState());
}
}
List nodeParts = new ArrayList();
List noteParts = new ArrayList();
List others = new ArrayList(objects);
for (Object o : objects) {
if (o instanceof ICrossPlatformNodePart) {
others.remove(o);
Node model = (Node) ((ICrossPlatformNodePart) o).getCrossPlatformModel();
if (model.getJobletNode() != null) {
continue;
}
if (model.getJunitNode() != null) {
continue;
}
nodeParts.add(o);
} else if (o instanceof ICrossPlatformNoteEditPart) {
noteParts.add(o);
others.remove(o);
} else if (o instanceof ICrossPlatformSubjobContainerPart) {
others.remove(o);
ICrossPlatformSubjobContainerPart subjob = (ICrossPlatformSubjobContainerPart) o;
for (Iterator iterator = subjob.getCrossPlatformChildren().iterator(); iterator.hasNext();) {
ICrossPlatformNodeContainerPart nodeContainerPart = (ICrossPlatformNodeContainerPart) iterator.next();
if (nodeContainerPart instanceof ICrossPlatformJobletContainerPart) {
JobletContainer jobletCon = (JobletContainer) ((ICrossPlatformJobletContainerPart) nodeContainerPart)
.getCrossPlatformModel();
CrossPlatformJobletContainerFigure jobletFigure = (CrossPlatformJobletContainerFigure) ((ICrossPlatformJobletContainerPart) nodeContainerPart)
.getCrossPlatformFigure();
if (!jobletCon.isCollapsed()) {
jobletFigure.doCollapse();
}
}
ICrossPlatformNodePart nodePart = nodeContainerPart.getCrossPlatformNodePart();
if (nodePart != null) {
Node model = (Node) nodePart.getCrossPlatformModel();
if (model.getJunitNode() != null) {
continue;
}
nodeParts.add(nodePart);
}
}
}
}
if (others.size() == 0) { // so notes & nodes only
CompoundCommand cpdCmd = new CompoundCommand();
cpdCmd.setLabel(Messages.getString("GEFDeleteAction.DeleteItems")); //$NON-NLS-1$
if (nodeParts.size() != 0) {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(nodeParts);
cpdCmd.add(((ICrossPlatformEditPart) nodeParts.get(0)).getCommand(deleteReq));
}
if (noteParts.size() != 0) {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(noteParts);
cpdCmd.add(((ICrossPlatformEditPart) noteParts.get(0)).getCommand(deleteReq));
}
return cpdCmd;
} else {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(objects);
Command cmd = object.getCommand(deleteReq);
return cmd;
}
}
}
| UTF-8 | Java | 17,218 | java | CrossPlatformProcessNodeDeleteAction.java | Java | [
{
"context": "rences.TalendDesignerPrefConstants;\r\n\r\n/**\r\n * DOC cmeng class global comment. Detailled comment\r\n */\r\npu",
"end": 3317,
"score": 0.998741090297699,
"start": 3312,
"tag": "USERNAME",
"value": "cmeng"
},
{
"context": "latformPreferenceStore();\r\n String preKey = TalendDesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGG",
"end": 12524,
"score": 0.9577767252922058,
"start": 12496,
"tag": "KEY",
"value": "TalendDesignerPrefConstants."
},
{
"context": " String preKey = TalendDesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;\r",
"end": 12541,
"score": 0.8996888399124146,
"start": 12528,
"tag": "KEY",
"value": "SHOW_WARNING_"
},
{
"context": " TalendDesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;\r\n ",
"end": 12545,
"score": 0.9524981379508972,
"start": 12545,
"tag": "KEY",
"value": ""
},
{
"context": "DesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;\r\n boolean ",
"end": 12558,
"score": 0.8440799117088318,
"start": 12553,
"tag": "KEY",
"value": "LINK_"
},
{
"context": "efConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;\r\n boolean notShowWarning = false;\r\n ",
"end": 12589,
"score": 0.8260548710823059,
"start": 12563,
"tag": "KEY",
"value": "JOBLETTRIGGERLINKCOMPONENT"
}
] | null | [] | // ============================================================================
//
// Copyright (C) 2006-2023 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.designer.core.ui.action.business;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.talend.commons.ui.runtime.custom.ICommonUIHandler;
import org.talend.commons.ui.runtime.custom.ICrossPlatformPreferenceStore;
import org.talend.commons.ui.runtime.custom.MessageDialogWithToggleBusinessHandler;
import org.talend.core.GlobalServiceRegister;
import org.talend.core.model.components.IComponent;
import org.talend.core.model.process.IProcess;
import org.talend.core.model.process.IProcess2;
import org.talend.core.ui.IJobletProviderService;
import org.talend.designer.core.DesignerPlugin;
import org.talend.designer.core.i18n.Messages;
import org.talend.designer.core.model.process.AbstractProcessProvider;
import org.talend.designer.core.ui.editor.CrossPlatformPartFactory;
import org.talend.designer.core.ui.editor.connections.Connection;
import org.talend.designer.core.ui.editor.connections.ConnectionLabel;
import org.talend.designer.core.ui.editor.connections.ICrossPlatformConnLabelEditPart;
import org.talend.designer.core.ui.editor.connections.ICrossPlatformConnectionPart;
import org.talend.designer.core.ui.editor.jobletcontainer.CrossPlatformJobletContainerFigure;
import org.talend.designer.core.ui.editor.jobletcontainer.ICrossPlatformJobletContainerPart;
import org.talend.designer.core.ui.editor.jobletcontainer.JobletContainer;
import org.talend.designer.core.ui.editor.nodecontainer.ICrossPlatformNodeContainerPart;
import org.talend.designer.core.ui.editor.nodecontainer.NodeContainer;
import org.talend.designer.core.ui.editor.nodes.CrossPlatformNodeEditPolicy;
import org.talend.designer.core.ui.editor.nodes.CrossPlatformNodePart;
import org.talend.designer.core.ui.editor.nodes.ICrossPlatformNodePart;
import org.talend.designer.core.ui.editor.nodes.Node;
import org.talend.designer.core.ui.editor.notes.ICrossPlatformNoteEditPart;
import org.talend.designer.core.ui.editor.notes.Note;
import org.talend.designer.core.ui.editor.process.CrossPlatformProcessPart;
import org.talend.designer.core.ui.editor.subjobcontainer.CrossPlatformGroupRequest;
import org.talend.designer.core.ui.editor.subjobcontainer.ICrossPlatformEditPart;
import org.talend.designer.core.ui.editor.subjobcontainer.ICrossPlatformSubjobContainerPart;
import org.talend.designer.core.ui.editor.subjobcontainer.SubjobContainer;
import org.talend.designer.core.ui.preferences.TalendDesignerPrefConstants;
/**
* DOC cmeng class global comment. Detailled comment
*/
public class CrossPlatformProcessNodeDeleteAction extends AbsCrossPlatformProcessEditorAction {
private List<Object> objectsToDelete;
public CrossPlatformProcessNodeDeleteAction(IProcess2 process, ICrossPlatformActionHook actionHook) {
super(process, actionHook);
}
@Override
public boolean isEnabled(List<Object> objects) {
objectsToDelete = new ArrayList<>(objects);
if (objects.isEmpty() || (objects.size() == 1 && objects.get(0) instanceof CrossPlatformProcessPart)) {
return false;
}
if (!(objects.get(0) instanceof ICrossPlatformEditPart)) {
return false;
}
AbstractProcessProvider pProvider = AbstractProcessProvider.findProcessProviderFromPID(IComponent.JOBLET_PID);
if (pProvider != null) {
Map<ICrossPlatformJobletContainerPart, List<ICrossPlatformNodePart>> jobletMap = new HashMap<>();
boolean nodeInJoblet = false;
boolean allJunitnode = true;
boolean hasNode = false;
int i = 0;
for (Object o : objects) {
if (o instanceof ICrossPlatformNodePart) {
hasNode = true;
ICrossPlatformNodePart nodePart = (ICrossPlatformNodePart) o;
Node no = (Node) ((ICrossPlatformNodePart) o).getCrossPlatformModel();
if (no.getProcess().isReadOnly()) {
return false;
}
if (no.isReadOnly()) {
i++;
}
if (no.getJunitNode() == null) {
allJunitnode = false;
}
if (!pProvider.canDeleteNode(no)) {
return false;
}
boolean isCollapsedNode = false;
if (getProcess().getGraphicalNodes().contains(nodePart.getCrossPlatformModel())) {
isCollapsedNode = true;
}
if (!isCollapsedNode && nodePart.getCrossPlatformParentPart() instanceof ICrossPlatformJobletContainerPart) {
ICrossPlatformJobletContainerPart jobletContainer = (ICrossPlatformJobletContainerPart) nodePart
.getCrossPlatformParentPart();
List<ICrossPlatformNodePart> jobletNodeParts = jobletMap.get(jobletContainer);
if (jobletNodeParts == null) {
jobletNodeParts = new ArrayList<>();
jobletMap.put(jobletContainer, jobletNodeParts);
}
jobletNodeParts.add(nodePart);
}
} else if (o instanceof ICrossPlatformConnectionPart) {
Connection conn = (Connection) ((ICrossPlatformConnectionPart) o).getCrossPlatformModel();
if (conn.getSource().getProcess().isReadOnly()) {
return false;
}
if (conn.isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformConnLabelEditPart) {
ConnectionLabel connLabel = (ConnectionLabel) ((ICrossPlatformConnLabelEditPart) o).getCrossPlatformModel();
if (connLabel.getConnection().getSource().getProcess().isReadOnly()) {
return false;
}
if (connLabel.getConnection().isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformNoteEditPart) {
allJunitnode = false;
Note note = (Note) ((ICrossPlatformNoteEditPart) o).getCrossPlatformModel();
if (note.isReadOnly()) {
i++;
}
} else if (o instanceof ICrossPlatformSubjobContainerPart) {
SubjobContainer subjob = (SubjobContainer) ((ICrossPlatformSubjobContainerPart) o).getCrossPlatformModel();
if (subjob.getProcess().isReadOnly()) {
return false;
}
if (subjob.isReadOnly()) {
i++;
continue;
}
boolean isAllReadonly = true;
boolean subjobAllJunit = true;
for (NodeContainer nc : subjob.getNodeContainers()) {
Node node = nc.getNode();
if (!node.isReadOnly()) {
isAllReadonly = false;
}
if (node.getJunitNode() == null) {
subjobAllJunit = false;
}
}
if (isAllReadonly || subjobAllJunit) {
i++;
}
}
}
for (ICrossPlatformJobletContainerPart jobletContainer : jobletMap.keySet()) {
boolean copyJobletNode = true;
List<ICrossPlatformNodePart> list = jobletMap.get(jobletContainer);
for (Object obj : jobletContainer.getCrossPlatformChildren()) {
if (obj instanceof ICrossPlatformNodePart) {
if (!list.contains(obj)) {
copyJobletNode = false;
break;
}
}
}
if (copyJobletNode) {
objectsToDelete.removeAll(list);
CrossPlatformPartFactory factory = new CrossPlatformPartFactory();
CrossPlatformNodePart createEditPart = (CrossPlatformNodePart) factory.createEditPart(jobletContainer,
((NodeContainer) jobletContainer.getCrossPlatformModel()).getNode());
createEditPart.setParentPart(jobletContainer);
createEditPart.installEditPolicy(EditPolicy.COMPONENT_ROLE, new CrossPlatformNodeEditPolicy());
objectsToDelete.add(createEditPart);
} else {
nodeInJoblet = true;
}
}
if (((nodeInJoblet || allJunitnode) && hasNode) || i == objects.size()) {
return false;
}
}
return true;
}
public static List<Object> filterSameObject(List<Object> list) {
List<Object> newList = new ArrayList<>();
for (Object object : list) {
if (!newList.contains(object)) {
newList.add(object);
}
}
return newList;
}
@Override
public Command createCommand(List<Object> objs) {
List<Object> objects = objectsToDelete;
objects = filterSameObject(objects);
if (objects.isEmpty()) {
return null;
}
if (!(objects.get(0) instanceof ICrossPlatformEditPart)) {
return null;
}
ICrossPlatformEditPart object = (ICrossPlatformEditPart) objects.get(0);
// for TUP-1015
boolean isConnAttachedJLTriggerComp = false;
ICrossPlatformConnectionPart connectionPart = null;
if (object instanceof ICrossPlatformConnectionPart) {
connectionPart = (ICrossPlatformConnectionPart) object;
} else if (object instanceof ICrossPlatformConnLabelEditPart) {
connectionPart = (ICrossPlatformConnectionPart) object.getCrossPlatformParentPart();
}
if (connectionPart != null) {
Node srcNode = null;
Object srcModel = connectionPart.getCrossPlatformSource().getCrossPlatformModel();
if (srcModel instanceof Node) {
srcNode = (Node) srcModel;
}
Node tarNode = null;
Object tarModel = connectionPart.getCrossPlatformTarget().getCrossPlatformModel();
if (tarModel instanceof Node) {
tarNode = (Node) tarModel;
}
if (srcNode == null || tarNode == null) {
return null;
}
IProcess process = srcNode.getProcess();
if (AbstractProcessProvider.isExtensionProcessForJoblet(process)) {
IJobletProviderService service = (IJobletProviderService) GlobalServiceRegister.getDefault()
.getService(IJobletProviderService.class);
if (service != null && (service.isTriggerNode(srcNode) || service.isTriggerNode(tarNode))) {
isConnAttachedJLTriggerComp = true;
}
}
}
ICrossPlatformPreferenceStore store = DesignerPlugin.getDefault().getCrossPlatformPreferenceStore();
String preKey = TalendDesignerPrefConstants.NOT_SHOW_WARNING_WHEN_DELETE_LINK_WITH_JOBLETTRIGGERLINKCOMPONENT;
boolean notShowWarning = false;
if (store != null) {
notShowWarning = store.getBoolean(preKey);
}
if (isConnAttachedJLTriggerComp && !notShowWarning) {
MessageDialogWithToggleBusinessHandler bh = new MessageDialogWithToggleBusinessHandler(ICommonUIHandler.WARNING,
Messages.getString("GEFDeleteAction.deleteConnectionDialog.title"),
Messages.getString("GEFDeleteAction.deleteConnectionDialog.msg"),
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0,
Messages.getString("GEFDeleteAction.deleteConnectionDialog.toggleMsg"), notShowWarning);
bh.setPreferenceStore(store);
bh.setPrefKey(preKey);
MessageDialogWithToggleBusinessHandler result = ICommonUIHandler.get().openToggle(bh);
if (!result.getOpenResult().equals(IDialogConstants.YES_ID)) {
return null;
}
if (store != null) {
store.setValue(preKey, result.getToggleState());
}
}
List nodeParts = new ArrayList();
List noteParts = new ArrayList();
List others = new ArrayList(objects);
for (Object o : objects) {
if (o instanceof ICrossPlatformNodePart) {
others.remove(o);
Node model = (Node) ((ICrossPlatformNodePart) o).getCrossPlatformModel();
if (model.getJobletNode() != null) {
continue;
}
if (model.getJunitNode() != null) {
continue;
}
nodeParts.add(o);
} else if (o instanceof ICrossPlatformNoteEditPart) {
noteParts.add(o);
others.remove(o);
} else if (o instanceof ICrossPlatformSubjobContainerPart) {
others.remove(o);
ICrossPlatformSubjobContainerPart subjob = (ICrossPlatformSubjobContainerPart) o;
for (Iterator iterator = subjob.getCrossPlatformChildren().iterator(); iterator.hasNext();) {
ICrossPlatformNodeContainerPart nodeContainerPart = (ICrossPlatformNodeContainerPart) iterator.next();
if (nodeContainerPart instanceof ICrossPlatformJobletContainerPart) {
JobletContainer jobletCon = (JobletContainer) ((ICrossPlatformJobletContainerPart) nodeContainerPart)
.getCrossPlatformModel();
CrossPlatformJobletContainerFigure jobletFigure = (CrossPlatformJobletContainerFigure) ((ICrossPlatformJobletContainerPart) nodeContainerPart)
.getCrossPlatformFigure();
if (!jobletCon.isCollapsed()) {
jobletFigure.doCollapse();
}
}
ICrossPlatformNodePart nodePart = nodeContainerPart.getCrossPlatformNodePart();
if (nodePart != null) {
Node model = (Node) nodePart.getCrossPlatformModel();
if (model.getJunitNode() != null) {
continue;
}
nodeParts.add(nodePart);
}
}
}
}
if (others.size() == 0) { // so notes & nodes only
CompoundCommand cpdCmd = new CompoundCommand();
cpdCmd.setLabel(Messages.getString("GEFDeleteAction.DeleteItems")); //$NON-NLS-1$
if (nodeParts.size() != 0) {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(nodeParts);
cpdCmd.add(((ICrossPlatformEditPart) nodeParts.get(0)).getCommand(deleteReq));
}
if (noteParts.size() != 0) {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(noteParts);
cpdCmd.add(((ICrossPlatformEditPart) noteParts.get(0)).getCommand(deleteReq));
}
return cpdCmd;
} else {
CrossPlatformGroupRequest deleteReq = new CrossPlatformGroupRequest(RequestConstants.REQ_DELETE);
deleteReq.setEditParts(objects);
Command cmd = object.getCommand(deleteReq);
return cmd;
}
}
}
| 17,218 | 0.582646 | 0.580613 | 351 | 47.054131 | 32.854076 | 166 | false | false | 0 | 0 | 0 | 0 | 76 | 0.008828 | 0.561254 | false | false | 4 |
428b7ee9470585c9c89b382b2a39f4cff6a16977 | 13,829,794,755,845 | 489a56de7fce32f0c5fdcfa916da891047c7712b | /gewara-new/src/main/java/com/gewara/web/action/subject/SubjectProxyController.java | 656c484c1942061077f7cae27fb93d54c36c37c8 | [] | no_license | xie-summer/GWR | https://github.com/xie-summer/GWR | f5506ea6f41800788463e33377d34ebefca21c01 | 0894221d00edfced294f1f061c9f9e6aa8d51617 | refs/heads/master | 2021-06-22T04:45:17.720000 | 2017-06-15T09:48:32 | 2017-06-15T09:48:32 | 89,137,292 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gewara.web.action.subject;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.hibernate.StaleObjectStateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gewara.constant.DiaryConstant;
import com.gewara.constant.DrawActicityConstant;
import com.gewara.constant.MemberConstant;
import com.gewara.constant.SmsConstant;
import com.gewara.constant.Status;
import com.gewara.constant.TagConstant;
import com.gewara.constant.content.SignName;
import com.gewara.constant.sys.MongoData;
import com.gewara.constant.ticket.OrderConstant;
import com.gewara.helper.sys.RelateClassHelper;
import com.gewara.json.bbs.MarkCountData;
import com.gewara.model.BaseObject;
import com.gewara.model.bbs.Diary;
import com.gewara.model.bbs.qa.GewaAnswer;
import com.gewara.model.bbs.qa.GewaQuestion;
import com.gewara.model.common.VersionCtl;
import com.gewara.model.content.GewaCommend;
import com.gewara.model.content.News;
import com.gewara.model.content.Picture;
import com.gewara.model.content.Video;
import com.gewara.model.drama.Drama;
import com.gewara.model.draw.DrawActivity;
import com.gewara.model.draw.Prize;
import com.gewara.model.draw.WinnerInfo;
import com.gewara.model.goods.BaseGoods;
import com.gewara.model.movie.Cinema;
import com.gewara.model.movie.CityPrice;
import com.gewara.model.movie.Movie;
import com.gewara.model.movie.SpecialActivity;
import com.gewara.model.pay.SMSRecord;
import com.gewara.model.pay.Spcounter;
import com.gewara.model.pay.SpecialDiscount;
import com.gewara.model.pay.TicketOrder;
import com.gewara.model.sport.Sport;
import com.gewara.model.ticket.OpenPlayItem;
import com.gewara.model.user.Member;
import com.gewara.model.user.MemberInfo;
import com.gewara.model.user.MemberPicture;
import com.gewara.model.user.ShareMember;
import com.gewara.mongo.MongoService;
import com.gewara.service.OperationService;
import com.gewara.service.bbs.BlogService;
import com.gewara.service.bbs.CommonVoteService;
import com.gewara.service.bbs.DiaryService;
import com.gewara.service.bbs.MarkService;
import com.gewara.service.bbs.QaService;
import com.gewara.service.content.NewsService;
import com.gewara.service.content.PictureService;
import com.gewara.service.content.RecommendService;
import com.gewara.service.content.VideoService;
import com.gewara.service.drama.DrawActivityService;
import com.gewara.service.gewapay.PaymentService;
import com.gewara.service.movie.MCPService;
import com.gewara.service.order.OrderQueryService;
import com.gewara.service.ticket.MoviePriceService;
import com.gewara.service.ticket.OpenPlayService;
import com.gewara.support.ErrorCode;
import com.gewara.support.ServiceHelper;
import com.gewara.untrans.CommentService;
import com.gewara.untrans.CommonService;
import com.gewara.untrans.ShareService;
import com.gewara.untrans.UntransService;
import com.gewara.untrans.activity.SynchActivityService;
import com.gewara.untrans.gym.SynchGymService;
import com.gewara.untrans.impl.ControllerService;
import com.gewara.util.BeanUtil;
import com.gewara.util.DateUtil;
import com.gewara.util.HttpResult;
import com.gewara.util.HttpUtils;
import com.gewara.util.JsonUtils;
import com.gewara.util.ObjectId;
import com.gewara.util.RandomUtils;
import com.gewara.util.RelatedHelper;
import com.gewara.util.StringUtil;
import com.gewara.util.ValidateUtil;
import com.gewara.util.VmUtils;
import com.gewara.util.WebUtils;
import com.gewara.web.action.AnnotationController;
import com.gewara.xmlbind.activity.RemoteActivity;
import com.gewara.xmlbind.bbs.Comment;
import com.gewara.xmlbind.gym.RemoteGym;
import com.mongodb.BasicDBObject;
import com.mongodb.QueryOperators;
@Controller
public class SubjectProxyController extends AnnotationController {
@Autowired@Qualifier("commentService")
protected CommentService commentService;
@Autowired@Qualifier("recommendService")
private RecommendService recommendService;
@Autowired@Qualifier("diaryService")
private DiaryService diaryService;
@Autowired@Qualifier("newsService")
private NewsService newsService;
@Autowired@Qualifier("synchActivityService")
private SynchActivityService synchActivityService;
@Autowired@Qualifier("shareService")
private ShareService shareService;
@Autowired@Qualifier("mongoService")
private MongoService mongoService;
@Autowired@Qualifier("drawActivityService")
private DrawActivityService drawActivityService;
@Autowired@Qualifier("untransService")
private UntransService untransService;
@Autowired@Qualifier("operationService")
private OperationService operationService;
@Autowired@Qualifier("blogService")
private BlogService blogService;
@Autowired@Qualifier("orderQueryService")
private OrderQueryService orderQueryService;
@Autowired@Qualifier("synchGymService")
private SynchGymService synchGymService;
@Autowired@Qualifier("openPlayService")
private OpenPlayService openPlayService;
@Autowired@Qualifier("mcpService")
private MCPService mcpService;
@Autowired@Qualifier("commonVoteService")
private CommonVoteService commonVoteService;
@Autowired@Qualifier("markService")
private MarkService markService;
@Autowired@Qualifier("moviePriceService")
private MoviePriceService moviePriceService;
@Autowired@Qualifier("paymentService")
private PaymentService paymentService;
@Autowired@Qualifier("commonService")
private CommonService commonService;
@Autowired@Qualifier("pictureService")
private PictureService pictureService;
@Autowired@Qualifier("videoService")
private VideoService videoService;
@Autowired@Qualifier("qaService")
private QaService qaService;
@Autowired@Qualifier("controllerService")
protected ControllerService controllerService;
@RequestMapping("/subject/test1.xhtml")
public String test1(ModelMap model){
HttpResult result = HttpUtils.getUrlAsString("http://180.153.146.137:82/subject/proxy1.xhtml");
return showDirectJson(model, result.getResponse());
}
@RequestMapping("/subject/test2.xhtml")
public String test2(ModelMap model){
HttpResult result = HttpUtils.getUrlAsString("http://180.153.146.137:82/partner/bestv/index.xhtml");
return showDirectJson(model, result.getResponse());
}
@RequestMapping("/subject/proxy1.xhtml")
public String proxy1(ModelMap model){
return forwardMessage(model, "proxy1");
}
@RequestMapping("/subject/proxy2.xhtml")
public String proxy2(ModelMap model){
return forwardMessage(model, "proxy2");
}
// 根据tag + ID, 返回对象
@RequestMapping("/subject/proxy/getObjectByTagAndID.xhtml")
public String getObjectByTagAndID(String tag, Long id, ModelMap model){
BaseObject object = daoService.getObject(RelateClassHelper.getRelateClazz(tag), id);
if(object == null) return showJsonError_NOT_FOUND(model);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(object));
}
// 根据tag + ID, 返回对象
@RequestMapping("/subject/proxy/getRelatedObject.xhtml")
public String getRelatedObject(String tag, Long id, ModelMap model){
Object object = relateService.getRelatedObject(tag, id);
if(object == null) return showJsonError_NOT_FOUND(model);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(object));
}
//用户绑定微薄
@RequestMapping("/ajax/member/synInfo.xhtml")
public String ajaxForMemberSynInfo(String sessid, String ip, ModelMap model){
Member member = loginService.getLogonMemberBySessid(ip, sessid);
if(member == null) return showJsonError_NOT_LOGIN(model);
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA, MemberConstant.SOURCE_QQ),member.getId());
List<String> appList = BeanUtil.getBeanPropertyList(shareMemberList, String.class, "source", true);
Map result = new HashMap();
result.put("appList", appList);
return showJsonSuccess(model, result);
}
//用户登录信息
@RequestMapping("/subject/proxy/memberlogin.xhtml")
//"id", "nickname", "headpicUrl","mobile","addtime"
public String ajaxMemberLogin(String sessid, String ip, ModelMap model){
Member member = loginService.getLogonMemberBySessid(ip, sessid);
if(member == null) return showJsonError_NOT_LOGIN(model);
Map memberMap = memberService.getCacheMemberInfoMap(member.getId());
if(member.isBindMobile()){
memberMap.put("mobile", member.getMobile());
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(memberMap));
}
@RequestMapping("/subject/proxy/getSpecialDiscountAllowaddnum.xhtml")
public String getSpecialDiscountAllowaddnum(Long spid ,ModelMap model){
if(spid == null){
return showJsonError(model, "参数错误!");
}
SpecialDiscount sd = daoService.getObject(SpecialDiscount.class, spid);
Spcounter spcounter = paymentService.getSpdiscountCounter(sd);
if(spcounter != null){
if(StringUtils.equals(spcounter.getCtltype(), Spcounter.CTLTYPE_QUANTITY) ){
int allow1 = spcounter.getLimitmaxnum() - spcounter.getAllquantity();
int allow2 = spcounter.getBasenum() - spcounter.getSellquantity();
return showJsonSuccess(model,"" + Math.min(allow1, allow2));
}else{
int allow1 = spcounter.getLimitmaxnum() - spcounter.getAllordernum();
int allow2 = spcounter.getBasenum() - spcounter.getSellordernum();
return showJsonSuccess(model,"" + Math.min(allow1, allow2));
}
}else{
return showJsonError(model, "特价活动数量未设置!");
}
}
/**
* 获取电影哇啦总数
* @param mid
* @param model
* @return
*/
@RequestMapping("/subject/proxy/getwalaCountByRelatedId.xhtml")
public String getCommentCountByRelatedId(Long mid ,ModelMap model){
if(mid == null){
return showJsonError(model, "参数错误!");
}
Integer commentCount = commentService.getCommentCountByRelatedId("movie", mid);
return showJsonSuccess(model,commentCount + "");
}
@RequestMapping("/subject/proxy/loadWalaByTag.xhtml")
public String loadWala(String tag,int rows,long relatedid, ModelMap model){
List<Comment> commentList = commentService.getCommentListByRelatedId(tag,null, relatedid, null, 0, rows);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentList));
}
//根据话题得到哇啦
@RequestMapping("/subject/proxy/getwala.xhtml")
public String blackmengetwala(String topic, Integer form, Integer max, ModelMap model){
if(StringUtils.isBlank(topic) || form == null || max == null) return showJsonError(model, "参数错误!");
List<Comment> commentList = commentService.getModeratorDetailList(topic, false, form, max);
List<Map> commentMapList = BeanUtil.getBeanMapList(commentList, new String[]{"memberid", "nickname", "topic", "body", "addtime"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
// 根据话题得到哇啦数量
@RequestMapping("/subject/proxy/getwalaCount.xhtml")
public String blackmengetwala(String topic, ModelMap model){
if(StringUtils.isBlank(topic)) return showJsonError(model, "参数错误!");
int count = commentService.getModeratorDetailCount(topic);
return showJsonSuccess(model, count+"");
}
//根据电影ID得到影评
@RequestMapping("/subject/proxy/getDiary.xhtml")
public String getDiary(Long movieid, String order, String citycode, Integer formnum, Integer maxnum, ModelMap model){
if(movieid == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(StringUtils.isBlank(order)) order = "poohnum";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<Diary> diaryList = diaryService.getDiaryList(Diary.class, citycode, DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieid, formnum, maxnum, order);
List<Map> commentMapList = BeanUtil.getBeanMapList(diaryList, new String[]{"id","memberid", "membername", "subject", "summary", "addtime"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
//根据电影ID得到资讯
@RequestMapping("/subject/proxy/getNews.xhtml")
public String getNews(Long movieid, String citycode, Integer formnum, Integer maxnum, ModelMap model){
if(movieid == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<News> newsList = newsService.getNewsList(citycode, "movie", movieid, null, formnum, maxnum);
List<Map> commentMapList = BeanUtil.getBeanMapList(newsList, new String[]{"id","title"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
//tag+id得到此电影或运动等图片
@RequestMapping("/subject/proxy/getPictureList.xhtml")
public String getPictureList(String tag, Long relatedid, String type, Integer formnum, Integer maxnum, ModelMap model) {
if(StringUtils.isBlank(tag) || relatedid == null || StringUtils.isBlank(type)) return showJsonError(model, "参数错误!");
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<Map> picMapList = new ArrayList<Map>();
if(StringUtils.contains(type, "apic")){
List<Picture> pictureList = pictureService.getPictureListByRelatedid(tag, relatedid, formnum, maxnum);
picMapList.addAll(BeanUtil.getBeanMapList(pictureList, new String[]{"id","picturename"}));
}
if(StringUtils.contains(type, "mpic")){
List<MemberPicture> memberPictureList = pictureService.getMemberPictureList(relatedid, tag, null, TagConstant.FLAG_PIC, Status.Y, formnum, maxnum);
picMapList.addAll(BeanUtil.getBeanMapList(memberPictureList, new String[]{"id","picturename"}));
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(picMapList));
}
//tag+id得到此电影或运动等视频
@RequestMapping("/subject/proxy/getVideoList.xhtml")
public String getVideoList(String tag, Long relatedid, Integer formnum, Integer maxnum, ModelMap model) {
if(StringUtils.isBlank(tag) || relatedid == null) return showJsonError(model, "参数错误!");
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 5;
List<Video> videoList = videoService.getVideoListByTag(tag, relatedid, formnum, maxnum);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(videoList));
}
//根据物品IDS得到物品
@RequestMapping("/subject/proxy/getGoodsListByGoodsId.xhtml")
public String getGoodsListByGoodsId(String goodsids, ModelMap model){
List<Long> idList = BeanUtil.getIdList(goodsids, ",");
if(idList.isEmpty()) return showJsonError(model, "参数错误!");
List<BaseGoods> goodsList = daoService.getObjectList(BaseGoods.class, idList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(BeanUtil.getBeanMapList(goodsList, new String[]{"id","goodsname","shortname","oriprice","unitprice","sales","allowaddnum","quantity","maxbuy","limg","fromtime","totime"})));
}
//根据条件得到活动
@RequestMapping("/subject/proxy/getActivity.xhtml")
public String getActivity(Long relatedid, String citycode, String type, Integer formnum, String order, String tag, Integer maxnum, ModelMap model){
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 5;
if(StringUtils.isBlank(type)) type = RemoteActivity.ATYPE_GEWA;
ErrorCode<List<RemoteActivity>> code = synchActivityService.getActivityListByOrder(citycode, type, RemoteActivity.TIME_CURRENT, null, null, tag, relatedid, order, formnum, maxnum);
if(code.isSuccess()){
List<RemoteActivity> activityList = code.getRetval();
List<Map> activityMapList = BeanUtil.getBeanMapList(activityList, new String[]{"id","title","address","clickedtimes","logo","startdate","enddate"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activityMapList));
}
return showJsonError(model, code.getMsg());
}
//根据 type、tag 查询资讯、剧照、视频
@RequestMapping("/subject/proxy/getInfoList.xhtml")
public String getInfoList(String type,String tag, Integer from, Integer max, ModelMap model){
if(from == null) from = 0;
if(max == null) max = 5;
Map params = new HashMap();
params.put(MongoData.ACTION_TYPE, type);
params.put(MongoData.ACTION_TAG, tag);
BasicDBObject query = new BasicDBObject();
query.put(QueryOperators.GT, 0);
params.put(MongoData.ACTION_ORDERNUM, query);
List<Map> list = mongoService.find(MongoData.NS_ACTIVITY_COMMON_PICTRUE, params, MongoData.ACTION_ORDERNUM, true, from, max);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(list));
}
//根据 type、tag 查询 数量
@RequestMapping("/subject/proxy/getPictureCount.xhtml")
public String getCheckPictureCount(String type,String tag, ModelMap model){
if(StringUtils.isBlank(type)) return showJsonError(model, "参数错误!");
Map params = new HashMap();
params.put(MongoData.ACTION_TYPE, type);
params.put(MongoData.ACTION_TAG, tag);
BasicDBObject query = new BasicDBObject();
query.put(QueryOperators.GT, 0);
params.put(MongoData.ACTION_ORDERNUM, query);
int count = mongoService.getCount(MongoData.NS_ACTIVITY_COMMON_PICTRUE, params);
return showJsonSuccess(model, count+"");
}
//根据用户ID得到用户信息(从缓存拿)
@RequestMapping("/subject/proxy/getMemberInfoList.xhtml")
public String getMemberInfoList(String ids, ModelMap model){
if(StringUtils.isBlank(ids)) return showJsonError(model, "参数错误!");
List<Long> idList = BeanUtil.getIdList(ids, ",");
addCacheMember(model, idList);
Map<Long, Map> map = (Map<Long, Map>) model.get("cacheMemberMap");
return showJsonSuccess(model, JsonUtils.writeObjectToJson(map));
}
//根据activityid查询活动
@RequestMapping("/subject/proxy/getActivityInfo.xhtml")
public String getActivityInfo(Long id, ModelMap model){
if(id == null) return showJsonError(model, "参数错误!");
ErrorCode<RemoteActivity> code = synchActivityService.getRemoteActivity(id);
if(code.isSuccess()){
RemoteActivity activity = code.getRetval();
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activity));
}
return showJsonError(model, code.getMsg());
}
//判断是否是disney用户
@RequestMapping("/subject/proxy/isDisneyMember.xhtml")
public String isDisneyMember(Long memberid, ModelMap model) {
Map params = new HashMap();
params.put("memberid", memberid);
Map memberMap = mongoService.findOne(MongoData.NS_DISNEY_MEMBER, params);
if(memberMap == null) return showJsonSuccess(model, "nodisney");
return showJsonSuccess(model);
}
//专题发送短信
@RequestMapping("/subject/proxy/sendMessage.xhtml")
public String sendMessage(String ztid, Long memberid, String mobile, String sendTime, String msgContent, String captchaId, String captcha, String hasCaptcha, String ip, ModelMap model){
if(memberid == null) return showJsonSuccess(model, "请先登录!");
if(!StringUtils.equals(hasCaptcha, Status.N)){
boolean isValidCaptcha = controllerService.validateCaptcha(captchaId, captcha, ip);
if(!isValidCaptcha) return showJsonError_CAPTCHA_ERROR(model);
}
if(!ValidateUtil.isMobile(mobile)) return showJsonError(model, "手机号码不能为空!");
if(StringUtils.isBlank(msgContent)) return showJsonError(model, "短信内容不能为空!");
if(VmUtils.getByteLength(msgContent) > 128) return showJsonError(model, "短信内容过长!");
boolean isSendMsg = StringUtils.isNotBlank(blogService.filterAllKey(msgContent));
String[] stimes = StringUtils.split(sendTime, ",");
if(stimes == null) return showJsonError(model, "参数错误,发送时间不能为空!");
for(String stime : stimes){
Timestamp st = DateUtil.parseTimestamp(stime);
SMSRecord sms = new SMSRecord(mobile);
if(isSendMsg){
sms.setStatus(SmsConstant.STATUS_FILTER);
}
if(StringUtils.isBlank(ztid)){
sms.setTradeNo("zt"+DateUtil.format(st, "yyyyMMdd"));
}else{
sms.setTradeNo("zt"+ztid);
}
sms.setContent(msgContent);
sms.setSendtime(st);
sms.setSmstype(SmsConstant.SMSTYPE_MANUAL);
sms.setValidtime(DateUtil.getLastTimeOfDay(st));
sms.setTag(TagConstant.TAG_ZHUANTI);
sms.setMemberid(memberid);
untransService.addMessage(sms);
}
return showJsonSuccess(model);
}
//得到推荐信息集合
@RequestMapping("/subject/proxy/getRecommendedListByPage.xhtml")
public String getRecommendedListByPage(String tag, String signname, String page, String parentid, String para, ModelMap model){
if(StringUtils.isBlank(tag) && StringUtils.isBlank(signname) || StringUtils.isBlank(para)) return showJsonSuccess(model);
String[] param = StringUtils.split(para ,",");
List<Map> dataMap = recommendService.getRecommendMap(tag, signname, parentid);
if(dataMap != null && StringUtils.isNotBlank(page)){
for(Map data : dataMap){
data.remove("id");
Object object = relateService.getRelatedObject(page, new Long(data.get(MongoData.ACTION_BOARDRELATEDID).toString().trim()));
if(object != null){
data.putAll(BeanUtil.getBeanMapWithKey(object, param));
}
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(dataMap));
}
//得到未知推荐信息集合
@RequestMapping("/subject/proxy/getRecommendedList.xhtml")
public String getRecommendedList(String tag, String signname, String parentid, ModelMap model){
if(StringUtils.isBlank(tag) && StringUtils.isBlank(signname)) return showJsonSuccess(model);
List<Map> dataMap = recommendService.getRecommendMap(tag, signname, parentid);
if(dataMap != null){
List<Long> activityIds = new ArrayList<Long>();
for(Map data : dataMap){
if(data.get("newsboard") == null) continue;
String type = data.get("newsboard")+"";
Long relatedid = new Long(data.get(MongoData.ACTION_BOARDRELATEDID)+"");
if(StringUtils.equals(type, "movie")){
Movie movie = daoService.getObject(Movie.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(movie, "moviename", "highlight", "director", "actors", "language", "videolen", "rclickedtimes", "boughtcount", "limg", "id"));
}else if(StringUtils.equals(type, "drama")){
Drama drama = daoService.getObject(Drama.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(drama, "dramaname", "highlight", "dramatype", "releasedate", "enddate", "clickedtimes", "boughtcount", "limg", "id"));
}else if(StringUtils.equals(type, "activity")){
activityIds.add(relatedid);
/*ErrorCode<RemoteActivity> code = synchActivityService.getRemoteActivity(relatedid);
if(code.isSuccess()){
RemoteActivity activity = code.getRetval();
data.putAll(BeanUtil.getBeanMapWithKey(activity, "title", "membername", "memberid", "address", "limg", "clickedtimes", "membercount", "id"));
}*/
}else if(StringUtils.equals(type, "gym")){
ErrorCode<RemoteGym> code = synchGymService.getRemoteGym(relatedid, true);
if(code.isSuccess()){
RemoteGym gym = code.getRetval();
data.putAll(BeanUtil.getBeanMapWithKey(gym, "name", "address", "clickedtimes", "limg", "content", "generalmarkedtimes", "id"));
}
}else if(StringUtils.equals(type, "sport")){
Sport sport = daoService.getObject(Sport.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(sport, "name", "address", "clickedtimes", "feature", "limg", "generalmarkedtimes", "id"));
}
}
//------------抽取在循环内调用http请求
if(!activityIds.isEmpty()){
ErrorCode<List<RemoteActivity>> activitysCode = synchActivityService.getRemoteActivityListByIds(activityIds);
if(activitysCode.isSuccess() && activitysCode.getRetval() != null){
for(Map data : dataMap){
if(data.get("newsboard") == null) continue;
String type = data.get("newsboard")+"";
Long relatedid = new Long(data.get(MongoData.ACTION_BOARDRELATEDID)+"");
if(StringUtils.equals(type, "activity")){
for(RemoteActivity activity : activitysCode.getRetval()){
if(activity.getId().equals(relatedid)){
data.putAll(BeanUtil.getBeanMapWithKey(activity, "title", "membername", "memberid", "address", "limg", "clickedtimes", "membercount", "id"));
break;
}
}
}
}
}
}
//-----------------------------------------
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(dataMap));
}
//得到抽奖奖品信息
@RequestMapping("/subject/proxy/getPrizeInfo.xhtml")
public String getPrizeInfo(String ids, ModelMap model){
if(StringUtils.isBlank(ids)) return showJsonError(model, "参数错误!");
List<Long> idList = BeanUtil.getIdList(ids, ",");
List<Prize> prizeList = daoService.getObjectList(Prize.class, idList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(BeanUtil.getBeanMapList(prizeList, new String[]{"id","pnumber","psendout","otype"})));
}
//disney活动专题
private static final List<String> tagList = Arrays.asList("wreckitralph");
//抽奖公用
@RequestMapping("/subject/proxy/clickDraw.xhtml")
public String clickDraw(Long memberid, String check, String gewatoken, String pointxy, String tag, String noLimitDraw, HttpServletRequest request, ModelMap model){
if(StringUtils.isBlank(tag)) return showJsonSuccess(model, "syserror");
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) return showJsonSuccess(model, "nologin");
Member member = daoService.getObject(Member.class, memberid);
if(member == null) return showJsonSuccess(model, "nologin");
if(tagList.contains(tag) && StringUtils.isBlank(gewatoken)){
Map params = new HashMap();
params.put("memberid", member.getId());
Map memberMap = mongoService.findOne(MongoData.NS_DISNEY_MEMBER, params);
if(memberMap == null) return showJsonSuccess(model, "nodsn");
}
MemberInfo memberInfo = daoService.getObject(MemberInfo.class, member.getId());
String opkey = tag + member.getId();
boolean allow = operationService.updateOperation(opkey, 10);
if(!allow) return showJsonSuccess(model, "frequent");
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null||!da.isJoin()) return showJsonSuccess(model, "nostart");
Timestamp cur = DateUtil.getCurFullTimestamp();
Integer num = 1;
Map<String, String> otherinfoMap = VmUtils.readJsonToMap(da.getOtherinfo());
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOBILE)) && !member.isBindMobile()) return showJsonSuccess(model, "nobindMobile");
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_EMAIL)) && !memberInfo.isFinishedTask(MemberConstant.TASK_CONFIRMREG)) return showJsonSuccess(model, "noemail");
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_TICKET)) && StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOVIEID))){
Long movieid = Long.parseLong(otherinfoMap.get(DrawActicityConstant.TASK_MOVIEID));
int pay = orderQueryService.getMemberOrderCountByMemberid(member.getId(), movieid);
if(pay == 0) return showJsonSuccess(model, "noticket");
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOREDRAW))){
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_HOUR))){
Timestamp startTime = DateUtil.addHour(cur,-Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_HOUR)));
List<WinnerInfo> winnerList = drawActivityService.getWinnerList(da.getId(), null, startTime, cur, "system", member.getId(), null, null, 0, 1);
if(winnerList.size() == 1) return showJsonSuccess(model, "nodrawcount");
Timestamp from = DateUtil.getCurTruncTimestamp();
Timestamp to = DateUtil.getMillTimestamp();
int today = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), from, to);
num = today + 1;
}else if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND))){
Date date = DateUtil.currentTime();
Timestamp startTime = DateUtil.getBeginTimestamp(date);
Timestamp endTime = DateUtil.getEndTimestamp(date);
Integer winnerCount = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), startTime, endTime);
Integer inviteCount = memberService.getInviteCountByMemberid(member.getId(), startTime, endTime);
if(inviteCount - winnerCount >= Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND))) num = inviteCount / Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND));
}
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_WEIBO))){
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA, MemberConstant.SOURCE_QQ),member.getId());
if(VmUtils.isEmptyList(shareMemberList)) return showJsonSuccess(model, "noweibo");
int today = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), da.getStarttime(), da.getEndtime());
if(today > 0) return showJsonSuccess(model, "nocount");
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_ONLYONE))){
int drawtimes = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), da.getStarttime(), da.getEndtime());
if(drawtimes > 0) return showJsonSuccess(model, "nocount");
}
if (!StringUtils.equals(noLimitDraw, "Y")) {
Integer count = drawActivityService.getCurDrawActivityNum(da, member.getId(), num);
if(count <= 0) return showJsonSuccess(model, "nodrawcount");
}
VersionCtl mvc = drawActivityService.gainMemberVc(""+member.getId());
try {
//FIXME:黄牛??
ErrorCode<WinnerInfo> ec = drawActivityService.baseClickDraw(da, mvc, false, member);
if(ec == null || !ec.isSuccess()) return showJsonSuccess(model, ec.getErrcode());
WinnerInfo winnerInfo = ec.getRetval();
if(winnerInfo == null) return showJsonSuccess(model, "syserror");
Prize prize = daoService.getObject(Prize.class, winnerInfo.getPrizeid());
if(prize == null) return showJsonSuccess(model, "syserror");
SMSRecord sms =drawActivityService.sendPrize(prize, winnerInfo, true);
if(sms !=null) untransService.sendMsgAtServer(sms, false);
Map otherinfo = VmUtils.readJsonToMap(prize.getOtherinfo());
if(otherinfo.get(DrawActicityConstant.TASK_WALA_CONTENT) != null){
String link = null;
if(otherinfo.get(DrawActicityConstant.TASK_WALA_LINK) != null){
link = otherinfo.get(DrawActicityConstant.TASK_WALA_LINK)+"";
link = "<a href=\""+link+"\" target=\"_blank\" rel=\"nofollow\">"+"链接地址"+"</a>";
}
String pointx = null, pointy = null;
if(StringUtils.isNotBlank(pointxy)){
List<String> pointList = Arrays.asList(StringUtils.split(pointxy, ":"));
if(pointList.size() == 2){
pointx = pointList.get(0);
pointy = pointList.get(1);
}
}
ErrorCode<Comment> result = commentService.addComment(member, TagConstant.TAG_TOPIC, null, otherinfo.get(DrawActicityConstant.TASK_WALA_CONTENT)+"", link, false, pointx, pointy, WebUtils.getRemoteIp(request));
if(result.isSuccess()) {
shareService.sendShareInfo("wala",result.getRetval().getId(), result.getRetval().getMemberid(), null);
}
}
return showJsonSuccess(model, "content="+prize.getPlevel()+"&ptype="+prize.getPtype()+"&prize="+prize.getOtype());
}catch(StaleObjectStateException e){
return showJsonSuccess(model, "syserror");
}catch(HibernateOptimisticLockingFailureException e){
return showJsonSuccess(model, "syserror");
}
}
//获取排片信息
@RequestMapping("/subject/proxy/getOpenplayInfo.xhtml")
public String getOpenplayInfo(Timestamp timeTo,String citycode,Long cinemaId, Long movieId,String edition, ModelMap model){
Timestamp timeFrom = DateUtil.getCurFullTimestamp();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
List<OpenPlayItem> list = openPlayService.getOpiList(citycode, cinemaId, movieId, timeFrom, timeTo, true);
for (OpenPlayItem opi: list) {
if(StringUtils.containsIgnoreCase(opi.getEdition(), edition)){
Map<String, Object> map = new HashMap<String, Object>();
map.put("mpid", opi.getMpid());
map.put("gewaprice", opi.getGewaprice());
map.put("costprice", opi.getCostprice());
map.put("playtime", opi.getPlaytime());
result.add(map);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
/**
* 007专题暂用查DMAX厅影片场次信息
*
* */
@RequestMapping("/subject/proxy/getOpenplaySpyInfo.xhtml")
public String getOpenplaySpyInfo(Timestamp timeTo,String citycode,Long cinemaId, Long movieId,Long roomId, ModelMap model){
Timestamp timeFrom = DateUtil.getCurFullTimestamp();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
List<OpenPlayItem> list = openPlayService.getOpiList(citycode, cinemaId, movieId, timeFrom, timeTo, true);
for (OpenPlayItem opi: list) {
if(opi.getRoomid().equals(roomId)){
Map<String, Object> map = new HashMap<String, Object>();
map.put("mpid", opi.getMpid());
map.put("gewaprice", opi.getGewaprice());
map.put("costprice", opi.getCostprice());
map.put("playtime", opi.getPlaytime());
result.add(map);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
//根据城市ID得到城市的电影和影院
@RequestMapping("/subject/proxy/getCurCinemaAndMovieByCitycode.xhtml")
public String getCurCinemaAndMovieByCitycode(String citycodes, ModelMap model){
Map resultMap = new HashMap();
if(StringUtils.isNotBlank(citycodes)){
for(String citycode : StringUtils.split(citycodes, ",")){
Integer cinemaCount = mcpService.getTicketCinemaCount(citycode, null, null, null);
List<Long> movieIdList = mcpService.getCurMovieIdList(citycode);
resultMap.put("cinema"+citycode, cinemaCount);
resultMap.put("movie"+citycode, movieIdList.size());
}
}
return showJsonSuccess(model, JsonUtils.writeMapToJson(resultMap));
}
//根据城市ID得到城市的电影院
@RequestMapping("/subject/proxy/getCinemaByCitycode.xhtml")
public String getCinemaByCitycode(String citycodes, ModelMap model){
List resultList = new LinkedList();
if(StringUtils.isNotBlank(citycodes)){
for(String citycode : StringUtils.split(citycodes, ",")){
List<Cinema> cinemas = mcpService.getCinemaListByCitycode(citycode, 0, 100);
if(!cinemas.isEmpty()){
Map<String,List<Map>> resultMap = new HashMap<String,List<Map>>();
for(Cinema cinema : cinemas){
if(StringUtils.isNotBlank(cinema.getCountycode())){
List<Map> cinemaList = resultMap.get(cinema.getCountycode());
if(cinemaList == null){
cinemaList = new LinkedList<Map>();
resultMap.put(cinema.getCountycode(), cinemaList);
}
cinemaList.add(BeanUtil.getBeanMapWithKey(cinema,"id","name","countycode","countyname","citycode"));
}
}
resultList.add(resultMap);
}
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(resultList));
}
//保存投票信息
@RequestMapping("/subject/proxy/saveVote.xhtml")
public String saveVote(Long memberid, String tag, String itemid, Integer count, ModelMap model){
if(memberid == null) return showJsonSuccess(model, "请先登录!");
Map memberMap = commonVoteService.getSingleVote(tag, memberid, null);
if(memberMap == null){
memberMap = new HashMap();
memberMap.put("tag", tag);
memberMap.put("memberid", memberid);
memberMap.put(MongoData.SYSTEM_ID, ObjectId.uuid());
}
memberMap.put("addtime", DateUtil.getCurFullTimestampStr());
memberMap.put("itemid", itemid);
mongoService.saveOrUpdateMap(memberMap, MongoData.SYSTEM_ID, MongoData.NS_COMMON_VOTE);
vote(tag, itemid, count, model);
return showJsonSuccess(model);
}
//得到投票信息
@RequestMapping("/subject/proxy/getMemberVoteInfo.xhtml")
public String getMemberVoteInfo(Long memberid, String tag, String itemid, ModelMap model){
Map memberMap = commonVoteService.getSingleVote(tag, memberid, itemid);
return showJsonSuccess(model, JsonUtils.writeMapToJson(memberMap));
}
//得到票数
@RequestMapping("/subject/proxy/vote/movieList.xhtml")
public String votemovieList(String flag, ModelMap model){
List<Map> list = commonVoteService.getItemVoteList(flag);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(list));
}
// 得到最新投票人
@RequestMapping("/subject/proxy/getVoteInfo.xhtml")
public String getVoteInfo(String tag, Integer from, Integer maxnum, ModelMap model){
if(StringUtils.isBlank(tag)) return showJsonSuccess(model);
if(from == null) from = 0;
if(maxnum == null) maxnum = 20;
List<Map> result = commonVoteService.getVoteInfo(tag, from, maxnum);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
@RequestMapping("/subject/proxy/indexCommend.xhtml")
public String indexCommend(String cityCode,String signName,int from, int maxnum, ModelMap model){
if(maxnum > 50){
maxnum = 50;
}
List<GewaCommend> gewaCommends = commonService.getGewaCommendList(cityCode,signName, null, null, true, from, maxnum);
if(StringUtils.equals(SignName.INDEX_MOVIELIST, signName) || StringUtils.equals(SignName.INDEX_MOVIELIST_NEW, signName)){
RelatedHelper rh = new RelatedHelper();
commonService.initGewaCommendList("gcMovieList", rh, gewaCommends);
List<Map> maps = new LinkedList<Map>();
for(GewaCommend gewaCommend :gewaCommends) {
Map map = new HashMap();
Movie movie = (Movie)rh.getR1("gcMovieList",gewaCommend.getId());
map.put("id",movie.getId());
map.put("moviename", movie.getMoviename());
map.put("gmark",VmUtils.getLastMarkStar(movie, "general",markService.getMarkCountByTagRelatedid(gewaCommend.getTag(), gewaCommend.getRelatedid()),markService.getMarkdata(TagConstant.TAG_MOVIE)));
if(StringUtils.isNotBlank(gewaCommend.getLogo())){
map.put("logo", gewaCommend.getLogo());
}else{
map.put("logo", movie.getLimg());
}
map.put("edition", movie.getEdition());
map.put("hotvalue",movie.getHotvalue());
CityPrice cityPrice = moviePriceService.getCityPrice(gewaCommend.getRelatedid(), cityCode, TagConstant.TAG_MOVIE);
if(cityPrice != null){
map.put("cinemas",cityPrice.getCquantity());//播放影片影院数量
map.put("mpids",cityPrice.getQuantity());//影片排片数量
}else{
map.put("cinemas",0);
map.put("mpids",0);
}
maps.add(map);
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(maps));
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(gewaCommends));
}
//投票
private String vote(String tag, String itemid, Integer count, ModelMap model){
if(count == null) count = RandomUtils.randomInt(3)+3;
int support = commonVoteService.getSupportCount(tag, itemid);
commonVoteService.addCommonVote(tag, itemid, support+count);
return showJsonSuccess(model);
}
@RequestMapping("/subject/proxy/movieListByIds.xhtml")
public String movieListByIds(String movieids, ModelMap model){
if(movieids==null) return showJsonSuccess(model, "传递参数错误!");
List<Long> movieidList = BeanUtil.getIdList(movieids, ",");
List<Movie> movieList = daoService.getObjectList(Movie.class, movieidList);
List<Map> mapList = BeanUtil.getBeanMapList(movieList, "id","name","logo","moviename","highlight","director","actors", "language", "state","videolen","type");
for (int i = 0; i < mapList.size(); i++) {
MarkCountData markCount = markService.getMarkCountByTagRelatedid(TagConstant.TAG_MOVIE, Long.valueOf(mapList.get(i).get("id").toString()));
Integer general = VmUtils.getLastMarkStar(siftMovie(movieList,Long.valueOf(mapList.get(i).get("id").toString())), "general", markCount, markService.getMarkdata(TagConstant.TAG_MOVIE));
mapList.get(i).put("generalmark", general);//general / 10 + "." + general % 10;
}
model.put("movieList", mapList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(mapList));
}
private Movie siftMovie(List<Movie> movieList,Long id){
for (int i = 0; i < movieList.size(); i++) {
if (movieList.get(i).getId().equals(id)) {
return movieList.get(i);
}
}
return null;
}
@RequestMapping("/subject/proxy/activityListByIds.xhtml")
public String activityListByIds(String aids, ModelMap model){
if(aids == null) return showJsonError(model, "参数错误!");
List<Long> aidList = BeanUtil.getIdList(aids, ",");
ErrorCode<List<RemoteActivity>> code = synchActivityService.getRemoteActivityListByIds(aidList);
if(code.isSuccess()){
List<RemoteActivity> activityList = code.getRetval();
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activityList));
}
return showJsonError(model, code.getMsg());
}
@RequestMapping("/subject/proxy/videoListBymid.xhtml")
public String videoListBymid(String movieId , ModelMap model){
List<Video> videoList = videoService.getVideoListByTag("movie", Long.valueOf(movieId), 0, 1000);
List<MemberPicture> memberVideoList = pictureService.getMemberPictureList(Long.valueOf(movieId), TagConstant.TAG_MOVIE, null, TagConstant.FLAG_VIDEO,
Status.Y, 0, 1000);
Map<String , List> videoMap =new HashMap<String, List>();
videoMap.put("videoList", videoList);
videoMap.put("memberVideoList", memberVideoList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(videoMap));
}
@RequestMapping("/subject/proxy/commentListBymid.xhtml")
public String commentListBymid(Long memberId, Long movieId, String myOrder, String friend, Integer pageNo, String citycode , ModelMap model) {
Map<String, Object> map = new HashMap<String, Object>();
Movie movie = daoService.getObject(Movie.class, movieId);
if (movie == null)
return showJsonError(model, "电影不存在或已经删除!");
if (pageNo == null)
pageNo = 0;
int rowsPerPage = 10;
int first = rowsPerPage * pageNo;
List<Diary> diaryList = new ArrayList<Diary>();
if (StringUtils.isBlank(myOrder))
myOrder = "poohnum";//addtime
Member member = (Member)relateService.getRelatedObject("member", memberId);
if (StringUtils.isNotBlank(friend) && member != null) {
diaryList = diaryService.getFriendDiaryList(DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieId, member.getId(), first, rowsPerPage);
map.put("friend", true);
} else {
//rowsCount = diaryService.getDiaryCount(Diary.class, citycode, Diary.DIARY_TYPE_COMMENT, "movie", movieId);
diaryList = diaryService.getDiaryList(Diary.class, citycode, DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieId, first, rowsPerPage, myOrder);
}
addCacheMember(model, ServiceHelper.getMemberIdListFromBeanList(diaryList));
map.put("diaryList", diaryList);
map.put("cacheMemberMap", model.get("cacheMemberMap"));
return showJsonSuccess(model, JsonUtils.writeObjectToJson(map));
}
@RequestMapping("/subject/proxy/winnerInfoList.xhtml")
public String winnerInfoList(String tag, int limit, String prizeType, ModelMap model){
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(prizeType)) prizeType = "A,D,P,drama,remark,waibi";
List<Prize> pList = drawActivityService.getPrizeListByDid(da.getId(), StringUtils.split(prizeType, ","));
List<Long> pIdList = BeanUtil.getBeanPropertyList(pList,Long.class,"id",true);
List<WinnerInfo> infoList = drawActivityService.getWinnerList(da.getId(),pIdList, null , null, "system",null,null,null,0,limit);
List<Map> winnerMapList = BeanUtil.getBeanMapList(infoList, new String[]{"memberid", "nickname", "prizeid","addtime"});
for(Map info : winnerMapList){
Prize prize = daoService.getObject(Prize.class, Long.valueOf(info.get("prizeid")+""));
info.put("plevel", prize.getPlevel());
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(winnerMapList));
}
@RequestMapping("/subject/proxy/pictureListBymid.xhtml")
public String pictureListBymid(String movieId , ModelMap model){
if(StringUtils.isBlank(movieId)) return showJsonError(model, "noMovieId");
Movie movie = daoService.getObject(Movie.class, Long.valueOf(movieId));
if (movie == null)
return showJsonError(model, "该影片不存在或被删除!");
List<Picture> pictureList = pictureService.getPictureListByRelatedid(TagConstant.TAG_MOVIE, Long.valueOf(movieId), 0, 1000);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(pictureList));
}
@RequestMapping("/subject/proxy/recommendationSubject.xhtml")
public String recommendationSubject(String actName,String keywords,String desc,String pageURL,String flag,String userId,String check,ModelMap model){
String checkcode = StringUtil.md5(userId + "rcs!@#");
if(!StringUtils.equals(check, checkcode)) return showJsonSuccess(model, "nologin");
SpecialActivity specialActivity = new SpecialActivity("");
specialActivity.setActivityname(actName);
specialActivity.setSeokeywords(keywords);
specialActivity.setSeodescription(desc);
specialActivity.setWebsite(pageURL);
specialActivity.setFlag(flag);
try {
daoService.saveObject(specialActivity);
} catch (Exception e) {
return showJsonError(model, e.getMessage());
}
return showJsonSuccess(model,"发布成功!");
}
@RequestMapping("/subject/proxy/addDeliveryAddress.xhtml")
public String addDeliveryAddress(String memberid,String check,String tag, String realname, String email, String sex, String address,String mobile,ModelMap model){
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) return showJsonError(model, "nologin");
String opkey = memberid+"addDeliveryAddress";
boolean allow = operationService.updateOperation(opkey, 10, 20);
if(!allow) return showJsonError(model, "操作太频繁!");
if(StringUtils.isBlank(tag)) return showJsonError(model, "非法操作!");
if(StringUtils.isBlank(realname)) return showJsonError(model, "姓名不能为空!");
if(WebUtils.checkString(realname)) return showJsonError(model, "姓名中含有非法字符!");
if(StringUtils.isNotBlank(email)&&!ValidateUtil.isEmail(email)) return showJsonError(model, "邮箱格式错误!");
if(StringUtils.isNotBlank(sex)&&StringUtil.getByteLength(sex)>2) return showJsonError(model, "性别错误!");
if(StringUtils.isBlank(address)) return showJsonError(model, "地址内容不能为空!");
if(StringUtil.getByteLength(address)>400) return showJsonError(model, "地址内容过长!");
if(WebUtils.checkString(address)) return showJsonError(model, "地址中含有非法字符!");
if(!ValidateUtil.isMobile(mobile)) return showJsonError(model, "手机号码格式有误!");
Map winning = new HashMap();
winning.put(MongoData.ACTION_TAG, tag);
winning.put(MongoData.GEWA_CUP_MEMBERID, Long.valueOf(memberid));
mongoService.removeObjectList(MongoData.NS_WINNING_RECEIPT_INFO, winning);
winning.put(MongoData.SYSTEM_ID, System.currentTimeMillis() + StringUtil.getRandomString(5));
winning.put(MongoData.ACTION_ADDTIME, DateUtil.getCurFullTimestamp());
winning.put(MongoData.FIELD_REAL_NAME, realname);
winning.put(MongoData.FIELD_TELEPHONE, mobile);
winning.put(MongoData.FIELD_RECEIPT_ADDRESS, address);
if (StringUtils.isNotBlank(email)) {
winning.put(MongoData.FIELD_EMAIL, email);
}
if (StringUtils.isNotBlank(sex)) {
winning.put(MongoData.FIELD_SEX, sex);
}
mongoService.saveOrUpdateMap(winning, MongoData.SYSTEM_ID, MongoData.NS_WINNING_RECEIPT_INFO);
return showJsonSuccess(model,"success");
}
/**
* 上海电影艺术联盟获取排片数据
* @param citycode
* @param cinemaIds
* @param movieIds
* @param from
* @param maxnum
* @return
*/
@RequestMapping("/subject/proxy/getArtFilmAllianceOpi.xhtml")
public String getArtFilmAllianceOpi(String citycode,String cinemaIds, String movieIds, int from, int maxnum, ModelMap model){
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
if (from < 0) {
from = 0;
}
if (maxnum <= 0 || maxnum >= 200) {
maxnum = 200;
}
List<OpenPlayItem> opiList = openPlayService.getArtFilmAllianceOpi(citycode, cinemaIds, movieIds, from, maxnum);
result = BeanUtil.getBeanMapList(opiList, true);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
//分享微博
@RequestMapping("/subject/proxy/shareInfo.xhtml")
public String sharesTicketInfo(Long memberid, String check, String content, String picurl, ModelMap model){
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) {
return showJsonError(model, "请先登录!");
}
Member member = daoService.getObject(Member.class, memberid);
if(member == null) {
return showJsonError(model, "请先登录!");
}
if(StringUtils.isBlank(content)) {
return showJsonError(model, "分享内容不能为空!");
}
boolean allow = operationService.updateOperation("shareFilmFest" + member.getId(), OperationService.HALF_MINUTE, 5);
if(!allow) {
return showJsonError(model, "你操作过于频繁,请稍后再试!");
}
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA), member.getId());
if(shareMemberList.isEmpty()) {
return showJsonError(model, "请先绑定微博!");
}
shareService.sendShareInfo("subject", null, member.getId(), content, picurl);
return showJsonSuccess(model);
}
//得到知道
@RequestMapping("/subject/proxy/getQuestionList.xhtml")
public String getQuestionList(String tag, Long relatedid, ModelMap model){
List<GewaQuestion> questionList = qaService.getQuestionByCategoryAndCategoryid(null, tag, relatedid, -1, -1);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(questionList));
}
//得到知道的答案
@RequestMapping("/subject/proxy/getAnswerList.xhtml")
public String getQuestionList(String qids, Integer maxnum, ModelMap model){
if(maxnum == null) maxnum = 3;
Map<Long,List<GewaAnswer>> answersMap = new HashMap<Long,List<GewaAnswer>>();
String[] ids = StringUtils.split(qids, ",");
Long answerMemberid = qaService.getGewaraAnswerByMemberid();
if(ids != null){
for (String id : ids) {
int max = maxnum;
Long qid = Long.parseLong(id);
List<GewaAnswer> answers = new ArrayList<GewaAnswer>();
//先查找管理员的回复
List<GewaAnswer> ga = qaService.getAnswerListByQuestionAndMemId(0, 1, qid, answerMemberid);
if(ga!=null&&!ga.isEmpty()){
answers.add(ga.get(0));
max = 2;
}
List<GewaAnswer> gac = qaService.getAnswerListByQuestionId(0, max, qid);
answers.addAll(gac);
answersMap.put(qid, answers);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(answersMap));
}
@RequestMapping("/subject/proxy/getMuOrderCount.xhtml")
public String getMuOrderCount(String memberids, Long relatedid, Timestamp fromtime, Timestamp totime, ModelMap model){
if(fromtime == null) fromtime = DateUtil.getMonthFirstDay(DateUtil.getCurFullTimestamp());
if(totime == null) totime = DateUtil.getCurFullTimestamp();
List<Long> idList = BeanUtil.getIdList(memberids, ",");
int count = orderQueryService.getMUOrderCountByMbrids(idList, relatedid, fromtime, totime);
return showJsonSuccess(model, count+"");
}
@RequestMapping("/subject/proxy/getMemberWinnerCount.xhtml")
public String getMemberWinnerCount(String tag, Long memberid, ModelMap model){
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null || !da.isJoin() || memberid == null) return showJsonSuccess(model, "0");
int count = drawActivityService.getMemberWinnerCount(memberid, da.getId(), da.getStarttime(), da.getEndtime());
return showJsonSuccess(model, ""+count);
}
@RequestMapping("/subject/proxy/getMemberFirstTime.xhtml")
public String getMemberFirstTime(Long memberid, String citycode, ModelMap model){
Map<String , Object> firstInfo = new HashMap<String, Object>();
MemberInfo mi = daoService.getObject(MemberInfo.class, memberid);
firstInfo.put("addTime", mi.getAddtime());
Map map = mongoService.findOne(MongoData.NS_FIRSTORDER, MongoData.SYSTEM_ID, memberid);
if (map != null && map.get("ticket") != null) {
TicketOrder order = daoService.getObjectByUkey(TicketOrder.class, "tradeNo", map.get("ticket")+"");
if (order != null) {
firstInfo.put("orderTime", order.getCreatetime());
Movie movie = daoService.getObject(Movie.class, order.getMovieid());
firstInfo.put("movieName", movie.getName());
}
}
int movieCount = orderQueryService.getMemberTicketCountByMemberid(memberid, DateUtil.parseTimestamp("2012-11-22", "yyyy-MM-dd"), DateUtil.parseTimestamp("2013-11-28", "yyyy-MM-dd"), OrderConstant.STATUS_PAID_SUCCESS, citycode);
firstInfo.put("movieCount", movieCount);
return showJsonSuccess(model , JsonUtils.writeObjectToJson(firstInfo));
}
@RequestMapping("/subject/proxy/getColorBall.xhtml")
public String getColorBall(Long memberid,String mobile,String msgContent, ModelMap model) {
ErrorCode<SMSRecord> code = drawActivityService.getColorBall(memberid, mobile, msgContent);
if (!code.isSuccess()) {
return showJsonError(model, code.getErrcode());
}
daoService.saveObject(code.getRetval());
untransService.sendMsgAtServer(code.getRetval(), false);
return showJsonSuccess(model,"success");
}
@RequestMapping("/subject/proxy/getCouponCode.xhtml")
public String getCouponCode(Long memberid,String mobile,String msgContent, ModelMap model) {
ErrorCode<SMSRecord> code = drawActivityService.getCouponCode(memberid, mobile, msgContent);
if (!code.isSuccess()) {
return showJsonError(model, code.getErrcode());
}
daoService.saveObject(code.getRetval());
untransService.sendMsgAtServer(code.getRetval(), false);
return showJsonSuccess(model,"success");
}
} | GB18030 | Java | 55,248 | java | SubjectProxyController.java | Java | [
{
"context": "pResult result = HttpUtils.getUrlAsString(\"http://180.153.146.137:82/subject/proxy1.xhtml\");\r\n\t\treturn showDirectJ",
"end": 6541,
"score": 0.9995610117912292,
"start": 6527,
"tag": "IP_ADDRESS",
"value": "180.153.146.13"
},
{
"context": "pResult result = HttpUtils.getUrlAsString(\"http://180.153.146.137:82/partner/bestv/index.xhtml\");\r\n\t\treturn showDir",
"end": 6781,
"score": 0.9996852874755859,
"start": 6766,
"tag": "IP_ADDRESS",
"value": "180.153.146.137"
},
{
"context": "ng(\"/subject/proxy/memberlogin.xhtml\")\r\n\t//\"id\", \"nickname\", \"headpicUrl\",\"mobile\",\"addtime\"\r\n\tpublic String",
"end": 8605,
"score": 0.9902898669242859,
"start": 8597,
"tag": "USERNAME",
"value": "nickname"
},
{
"context": "MemberVc(\"\"+member.getId());\r\n\t\ttry {\r\n\t\t\t//FIXME:黄牛??\r\n\t\t\tErrorCode<WinnerInfo> ec = drawActivityServ",
"end": 29838,
"score": 0.843799352645874,
"start": 29836,
"tag": "NAME",
"value": "黄牛"
}
] | null | [] | package com.gewara.web.action.subject;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.hibernate.StaleObjectStateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gewara.constant.DiaryConstant;
import com.gewara.constant.DrawActicityConstant;
import com.gewara.constant.MemberConstant;
import com.gewara.constant.SmsConstant;
import com.gewara.constant.Status;
import com.gewara.constant.TagConstant;
import com.gewara.constant.content.SignName;
import com.gewara.constant.sys.MongoData;
import com.gewara.constant.ticket.OrderConstant;
import com.gewara.helper.sys.RelateClassHelper;
import com.gewara.json.bbs.MarkCountData;
import com.gewara.model.BaseObject;
import com.gewara.model.bbs.Diary;
import com.gewara.model.bbs.qa.GewaAnswer;
import com.gewara.model.bbs.qa.GewaQuestion;
import com.gewara.model.common.VersionCtl;
import com.gewara.model.content.GewaCommend;
import com.gewara.model.content.News;
import com.gewara.model.content.Picture;
import com.gewara.model.content.Video;
import com.gewara.model.drama.Drama;
import com.gewara.model.draw.DrawActivity;
import com.gewara.model.draw.Prize;
import com.gewara.model.draw.WinnerInfo;
import com.gewara.model.goods.BaseGoods;
import com.gewara.model.movie.Cinema;
import com.gewara.model.movie.CityPrice;
import com.gewara.model.movie.Movie;
import com.gewara.model.movie.SpecialActivity;
import com.gewara.model.pay.SMSRecord;
import com.gewara.model.pay.Spcounter;
import com.gewara.model.pay.SpecialDiscount;
import com.gewara.model.pay.TicketOrder;
import com.gewara.model.sport.Sport;
import com.gewara.model.ticket.OpenPlayItem;
import com.gewara.model.user.Member;
import com.gewara.model.user.MemberInfo;
import com.gewara.model.user.MemberPicture;
import com.gewara.model.user.ShareMember;
import com.gewara.mongo.MongoService;
import com.gewara.service.OperationService;
import com.gewara.service.bbs.BlogService;
import com.gewara.service.bbs.CommonVoteService;
import com.gewara.service.bbs.DiaryService;
import com.gewara.service.bbs.MarkService;
import com.gewara.service.bbs.QaService;
import com.gewara.service.content.NewsService;
import com.gewara.service.content.PictureService;
import com.gewara.service.content.RecommendService;
import com.gewara.service.content.VideoService;
import com.gewara.service.drama.DrawActivityService;
import com.gewara.service.gewapay.PaymentService;
import com.gewara.service.movie.MCPService;
import com.gewara.service.order.OrderQueryService;
import com.gewara.service.ticket.MoviePriceService;
import com.gewara.service.ticket.OpenPlayService;
import com.gewara.support.ErrorCode;
import com.gewara.support.ServiceHelper;
import com.gewara.untrans.CommentService;
import com.gewara.untrans.CommonService;
import com.gewara.untrans.ShareService;
import com.gewara.untrans.UntransService;
import com.gewara.untrans.activity.SynchActivityService;
import com.gewara.untrans.gym.SynchGymService;
import com.gewara.untrans.impl.ControllerService;
import com.gewara.util.BeanUtil;
import com.gewara.util.DateUtil;
import com.gewara.util.HttpResult;
import com.gewara.util.HttpUtils;
import com.gewara.util.JsonUtils;
import com.gewara.util.ObjectId;
import com.gewara.util.RandomUtils;
import com.gewara.util.RelatedHelper;
import com.gewara.util.StringUtil;
import com.gewara.util.ValidateUtil;
import com.gewara.util.VmUtils;
import com.gewara.util.WebUtils;
import com.gewara.web.action.AnnotationController;
import com.gewara.xmlbind.activity.RemoteActivity;
import com.gewara.xmlbind.bbs.Comment;
import com.gewara.xmlbind.gym.RemoteGym;
import com.mongodb.BasicDBObject;
import com.mongodb.QueryOperators;
@Controller
public class SubjectProxyController extends AnnotationController {
@Autowired@Qualifier("commentService")
protected CommentService commentService;
@Autowired@Qualifier("recommendService")
private RecommendService recommendService;
@Autowired@Qualifier("diaryService")
private DiaryService diaryService;
@Autowired@Qualifier("newsService")
private NewsService newsService;
@Autowired@Qualifier("synchActivityService")
private SynchActivityService synchActivityService;
@Autowired@Qualifier("shareService")
private ShareService shareService;
@Autowired@Qualifier("mongoService")
private MongoService mongoService;
@Autowired@Qualifier("drawActivityService")
private DrawActivityService drawActivityService;
@Autowired@Qualifier("untransService")
private UntransService untransService;
@Autowired@Qualifier("operationService")
private OperationService operationService;
@Autowired@Qualifier("blogService")
private BlogService blogService;
@Autowired@Qualifier("orderQueryService")
private OrderQueryService orderQueryService;
@Autowired@Qualifier("synchGymService")
private SynchGymService synchGymService;
@Autowired@Qualifier("openPlayService")
private OpenPlayService openPlayService;
@Autowired@Qualifier("mcpService")
private MCPService mcpService;
@Autowired@Qualifier("commonVoteService")
private CommonVoteService commonVoteService;
@Autowired@Qualifier("markService")
private MarkService markService;
@Autowired@Qualifier("moviePriceService")
private MoviePriceService moviePriceService;
@Autowired@Qualifier("paymentService")
private PaymentService paymentService;
@Autowired@Qualifier("commonService")
private CommonService commonService;
@Autowired@Qualifier("pictureService")
private PictureService pictureService;
@Autowired@Qualifier("videoService")
private VideoService videoService;
@Autowired@Qualifier("qaService")
private QaService qaService;
@Autowired@Qualifier("controllerService")
protected ControllerService controllerService;
@RequestMapping("/subject/test1.xhtml")
public String test1(ModelMap model){
HttpResult result = HttpUtils.getUrlAsString("http://172.16.17.327:82/subject/proxy1.xhtml");
return showDirectJson(model, result.getResponse());
}
@RequestMapping("/subject/test2.xhtml")
public String test2(ModelMap model){
HttpResult result = HttpUtils.getUrlAsString("http://192.168.3.11:82/partner/bestv/index.xhtml");
return showDirectJson(model, result.getResponse());
}
@RequestMapping("/subject/proxy1.xhtml")
public String proxy1(ModelMap model){
return forwardMessage(model, "proxy1");
}
@RequestMapping("/subject/proxy2.xhtml")
public String proxy2(ModelMap model){
return forwardMessage(model, "proxy2");
}
// 根据tag + ID, 返回对象
@RequestMapping("/subject/proxy/getObjectByTagAndID.xhtml")
public String getObjectByTagAndID(String tag, Long id, ModelMap model){
BaseObject object = daoService.getObject(RelateClassHelper.getRelateClazz(tag), id);
if(object == null) return showJsonError_NOT_FOUND(model);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(object));
}
// 根据tag + ID, 返回对象
@RequestMapping("/subject/proxy/getRelatedObject.xhtml")
public String getRelatedObject(String tag, Long id, ModelMap model){
Object object = relateService.getRelatedObject(tag, id);
if(object == null) return showJsonError_NOT_FOUND(model);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(object));
}
//用户绑定微薄
@RequestMapping("/ajax/member/synInfo.xhtml")
public String ajaxForMemberSynInfo(String sessid, String ip, ModelMap model){
Member member = loginService.getLogonMemberBySessid(ip, sessid);
if(member == null) return showJsonError_NOT_LOGIN(model);
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA, MemberConstant.SOURCE_QQ),member.getId());
List<String> appList = BeanUtil.getBeanPropertyList(shareMemberList, String.class, "source", true);
Map result = new HashMap();
result.put("appList", appList);
return showJsonSuccess(model, result);
}
//用户登录信息
@RequestMapping("/subject/proxy/memberlogin.xhtml")
//"id", "nickname", "headpicUrl","mobile","addtime"
public String ajaxMemberLogin(String sessid, String ip, ModelMap model){
Member member = loginService.getLogonMemberBySessid(ip, sessid);
if(member == null) return showJsonError_NOT_LOGIN(model);
Map memberMap = memberService.getCacheMemberInfoMap(member.getId());
if(member.isBindMobile()){
memberMap.put("mobile", member.getMobile());
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(memberMap));
}
@RequestMapping("/subject/proxy/getSpecialDiscountAllowaddnum.xhtml")
public String getSpecialDiscountAllowaddnum(Long spid ,ModelMap model){
if(spid == null){
return showJsonError(model, "参数错误!");
}
SpecialDiscount sd = daoService.getObject(SpecialDiscount.class, spid);
Spcounter spcounter = paymentService.getSpdiscountCounter(sd);
if(spcounter != null){
if(StringUtils.equals(spcounter.getCtltype(), Spcounter.CTLTYPE_QUANTITY) ){
int allow1 = spcounter.getLimitmaxnum() - spcounter.getAllquantity();
int allow2 = spcounter.getBasenum() - spcounter.getSellquantity();
return showJsonSuccess(model,"" + Math.min(allow1, allow2));
}else{
int allow1 = spcounter.getLimitmaxnum() - spcounter.getAllordernum();
int allow2 = spcounter.getBasenum() - spcounter.getSellordernum();
return showJsonSuccess(model,"" + Math.min(allow1, allow2));
}
}else{
return showJsonError(model, "特价活动数量未设置!");
}
}
/**
* 获取电影哇啦总数
* @param mid
* @param model
* @return
*/
@RequestMapping("/subject/proxy/getwalaCountByRelatedId.xhtml")
public String getCommentCountByRelatedId(Long mid ,ModelMap model){
if(mid == null){
return showJsonError(model, "参数错误!");
}
Integer commentCount = commentService.getCommentCountByRelatedId("movie", mid);
return showJsonSuccess(model,commentCount + "");
}
@RequestMapping("/subject/proxy/loadWalaByTag.xhtml")
public String loadWala(String tag,int rows,long relatedid, ModelMap model){
List<Comment> commentList = commentService.getCommentListByRelatedId(tag,null, relatedid, null, 0, rows);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentList));
}
//根据话题得到哇啦
@RequestMapping("/subject/proxy/getwala.xhtml")
public String blackmengetwala(String topic, Integer form, Integer max, ModelMap model){
if(StringUtils.isBlank(topic) || form == null || max == null) return showJsonError(model, "参数错误!");
List<Comment> commentList = commentService.getModeratorDetailList(topic, false, form, max);
List<Map> commentMapList = BeanUtil.getBeanMapList(commentList, new String[]{"memberid", "nickname", "topic", "body", "addtime"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
// 根据话题得到哇啦数量
@RequestMapping("/subject/proxy/getwalaCount.xhtml")
public String blackmengetwala(String topic, ModelMap model){
if(StringUtils.isBlank(topic)) return showJsonError(model, "参数错误!");
int count = commentService.getModeratorDetailCount(topic);
return showJsonSuccess(model, count+"");
}
//根据电影ID得到影评
@RequestMapping("/subject/proxy/getDiary.xhtml")
public String getDiary(Long movieid, String order, String citycode, Integer formnum, Integer maxnum, ModelMap model){
if(movieid == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(StringUtils.isBlank(order)) order = "poohnum";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<Diary> diaryList = diaryService.getDiaryList(Diary.class, citycode, DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieid, formnum, maxnum, order);
List<Map> commentMapList = BeanUtil.getBeanMapList(diaryList, new String[]{"id","memberid", "membername", "subject", "summary", "addtime"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
//根据电影ID得到资讯
@RequestMapping("/subject/proxy/getNews.xhtml")
public String getNews(Long movieid, String citycode, Integer formnum, Integer maxnum, ModelMap model){
if(movieid == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<News> newsList = newsService.getNewsList(citycode, "movie", movieid, null, formnum, maxnum);
List<Map> commentMapList = BeanUtil.getBeanMapList(newsList, new String[]{"id","title"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(commentMapList));
}
//tag+id得到此电影或运动等图片
@RequestMapping("/subject/proxy/getPictureList.xhtml")
public String getPictureList(String tag, Long relatedid, String type, Integer formnum, Integer maxnum, ModelMap model) {
if(StringUtils.isBlank(tag) || relatedid == null || StringUtils.isBlank(type)) return showJsonError(model, "参数错误!");
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 10;
List<Map> picMapList = new ArrayList<Map>();
if(StringUtils.contains(type, "apic")){
List<Picture> pictureList = pictureService.getPictureListByRelatedid(tag, relatedid, formnum, maxnum);
picMapList.addAll(BeanUtil.getBeanMapList(pictureList, new String[]{"id","picturename"}));
}
if(StringUtils.contains(type, "mpic")){
List<MemberPicture> memberPictureList = pictureService.getMemberPictureList(relatedid, tag, null, TagConstant.FLAG_PIC, Status.Y, formnum, maxnum);
picMapList.addAll(BeanUtil.getBeanMapList(memberPictureList, new String[]{"id","picturename"}));
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(picMapList));
}
//tag+id得到此电影或运动等视频
@RequestMapping("/subject/proxy/getVideoList.xhtml")
public String getVideoList(String tag, Long relatedid, Integer formnum, Integer maxnum, ModelMap model) {
if(StringUtils.isBlank(tag) || relatedid == null) return showJsonError(model, "参数错误!");
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 5;
List<Video> videoList = videoService.getVideoListByTag(tag, relatedid, formnum, maxnum);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(videoList));
}
//根据物品IDS得到物品
@RequestMapping("/subject/proxy/getGoodsListByGoodsId.xhtml")
public String getGoodsListByGoodsId(String goodsids, ModelMap model){
List<Long> idList = BeanUtil.getIdList(goodsids, ",");
if(idList.isEmpty()) return showJsonError(model, "参数错误!");
List<BaseGoods> goodsList = daoService.getObjectList(BaseGoods.class, idList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(BeanUtil.getBeanMapList(goodsList, new String[]{"id","goodsname","shortname","oriprice","unitprice","sales","allowaddnum","quantity","maxbuy","limg","fromtime","totime"})));
}
//根据条件得到活动
@RequestMapping("/subject/proxy/getActivity.xhtml")
public String getActivity(Long relatedid, String citycode, String type, Integer formnum, String order, String tag, Integer maxnum, ModelMap model){
if(StringUtils.isBlank(citycode)) citycode = "310000";
if(formnum == null) formnum = 0;
if(maxnum == null) maxnum = 5;
if(StringUtils.isBlank(type)) type = RemoteActivity.ATYPE_GEWA;
ErrorCode<List<RemoteActivity>> code = synchActivityService.getActivityListByOrder(citycode, type, RemoteActivity.TIME_CURRENT, null, null, tag, relatedid, order, formnum, maxnum);
if(code.isSuccess()){
List<RemoteActivity> activityList = code.getRetval();
List<Map> activityMapList = BeanUtil.getBeanMapList(activityList, new String[]{"id","title","address","clickedtimes","logo","startdate","enddate"});
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activityMapList));
}
return showJsonError(model, code.getMsg());
}
//根据 type、tag 查询资讯、剧照、视频
@RequestMapping("/subject/proxy/getInfoList.xhtml")
public String getInfoList(String type,String tag, Integer from, Integer max, ModelMap model){
if(from == null) from = 0;
if(max == null) max = 5;
Map params = new HashMap();
params.put(MongoData.ACTION_TYPE, type);
params.put(MongoData.ACTION_TAG, tag);
BasicDBObject query = new BasicDBObject();
query.put(QueryOperators.GT, 0);
params.put(MongoData.ACTION_ORDERNUM, query);
List<Map> list = mongoService.find(MongoData.NS_ACTIVITY_COMMON_PICTRUE, params, MongoData.ACTION_ORDERNUM, true, from, max);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(list));
}
//根据 type、tag 查询 数量
@RequestMapping("/subject/proxy/getPictureCount.xhtml")
public String getCheckPictureCount(String type,String tag, ModelMap model){
if(StringUtils.isBlank(type)) return showJsonError(model, "参数错误!");
Map params = new HashMap();
params.put(MongoData.ACTION_TYPE, type);
params.put(MongoData.ACTION_TAG, tag);
BasicDBObject query = new BasicDBObject();
query.put(QueryOperators.GT, 0);
params.put(MongoData.ACTION_ORDERNUM, query);
int count = mongoService.getCount(MongoData.NS_ACTIVITY_COMMON_PICTRUE, params);
return showJsonSuccess(model, count+"");
}
//根据用户ID得到用户信息(从缓存拿)
@RequestMapping("/subject/proxy/getMemberInfoList.xhtml")
public String getMemberInfoList(String ids, ModelMap model){
if(StringUtils.isBlank(ids)) return showJsonError(model, "参数错误!");
List<Long> idList = BeanUtil.getIdList(ids, ",");
addCacheMember(model, idList);
Map<Long, Map> map = (Map<Long, Map>) model.get("cacheMemberMap");
return showJsonSuccess(model, JsonUtils.writeObjectToJson(map));
}
//根据activityid查询活动
@RequestMapping("/subject/proxy/getActivityInfo.xhtml")
public String getActivityInfo(Long id, ModelMap model){
if(id == null) return showJsonError(model, "参数错误!");
ErrorCode<RemoteActivity> code = synchActivityService.getRemoteActivity(id);
if(code.isSuccess()){
RemoteActivity activity = code.getRetval();
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activity));
}
return showJsonError(model, code.getMsg());
}
//判断是否是disney用户
@RequestMapping("/subject/proxy/isDisneyMember.xhtml")
public String isDisneyMember(Long memberid, ModelMap model) {
Map params = new HashMap();
params.put("memberid", memberid);
Map memberMap = mongoService.findOne(MongoData.NS_DISNEY_MEMBER, params);
if(memberMap == null) return showJsonSuccess(model, "nodisney");
return showJsonSuccess(model);
}
//专题发送短信
@RequestMapping("/subject/proxy/sendMessage.xhtml")
public String sendMessage(String ztid, Long memberid, String mobile, String sendTime, String msgContent, String captchaId, String captcha, String hasCaptcha, String ip, ModelMap model){
if(memberid == null) return showJsonSuccess(model, "请先登录!");
if(!StringUtils.equals(hasCaptcha, Status.N)){
boolean isValidCaptcha = controllerService.validateCaptcha(captchaId, captcha, ip);
if(!isValidCaptcha) return showJsonError_CAPTCHA_ERROR(model);
}
if(!ValidateUtil.isMobile(mobile)) return showJsonError(model, "手机号码不能为空!");
if(StringUtils.isBlank(msgContent)) return showJsonError(model, "短信内容不能为空!");
if(VmUtils.getByteLength(msgContent) > 128) return showJsonError(model, "短信内容过长!");
boolean isSendMsg = StringUtils.isNotBlank(blogService.filterAllKey(msgContent));
String[] stimes = StringUtils.split(sendTime, ",");
if(stimes == null) return showJsonError(model, "参数错误,发送时间不能为空!");
for(String stime : stimes){
Timestamp st = DateUtil.parseTimestamp(stime);
SMSRecord sms = new SMSRecord(mobile);
if(isSendMsg){
sms.setStatus(SmsConstant.STATUS_FILTER);
}
if(StringUtils.isBlank(ztid)){
sms.setTradeNo("zt"+DateUtil.format(st, "yyyyMMdd"));
}else{
sms.setTradeNo("zt"+ztid);
}
sms.setContent(msgContent);
sms.setSendtime(st);
sms.setSmstype(SmsConstant.SMSTYPE_MANUAL);
sms.setValidtime(DateUtil.getLastTimeOfDay(st));
sms.setTag(TagConstant.TAG_ZHUANTI);
sms.setMemberid(memberid);
untransService.addMessage(sms);
}
return showJsonSuccess(model);
}
//得到推荐信息集合
@RequestMapping("/subject/proxy/getRecommendedListByPage.xhtml")
public String getRecommendedListByPage(String tag, String signname, String page, String parentid, String para, ModelMap model){
if(StringUtils.isBlank(tag) && StringUtils.isBlank(signname) || StringUtils.isBlank(para)) return showJsonSuccess(model);
String[] param = StringUtils.split(para ,",");
List<Map> dataMap = recommendService.getRecommendMap(tag, signname, parentid);
if(dataMap != null && StringUtils.isNotBlank(page)){
for(Map data : dataMap){
data.remove("id");
Object object = relateService.getRelatedObject(page, new Long(data.get(MongoData.ACTION_BOARDRELATEDID).toString().trim()));
if(object != null){
data.putAll(BeanUtil.getBeanMapWithKey(object, param));
}
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(dataMap));
}
//得到未知推荐信息集合
@RequestMapping("/subject/proxy/getRecommendedList.xhtml")
public String getRecommendedList(String tag, String signname, String parentid, ModelMap model){
if(StringUtils.isBlank(tag) && StringUtils.isBlank(signname)) return showJsonSuccess(model);
List<Map> dataMap = recommendService.getRecommendMap(tag, signname, parentid);
if(dataMap != null){
List<Long> activityIds = new ArrayList<Long>();
for(Map data : dataMap){
if(data.get("newsboard") == null) continue;
String type = data.get("newsboard")+"";
Long relatedid = new Long(data.get(MongoData.ACTION_BOARDRELATEDID)+"");
if(StringUtils.equals(type, "movie")){
Movie movie = daoService.getObject(Movie.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(movie, "moviename", "highlight", "director", "actors", "language", "videolen", "rclickedtimes", "boughtcount", "limg", "id"));
}else if(StringUtils.equals(type, "drama")){
Drama drama = daoService.getObject(Drama.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(drama, "dramaname", "highlight", "dramatype", "releasedate", "enddate", "clickedtimes", "boughtcount", "limg", "id"));
}else if(StringUtils.equals(type, "activity")){
activityIds.add(relatedid);
/*ErrorCode<RemoteActivity> code = synchActivityService.getRemoteActivity(relatedid);
if(code.isSuccess()){
RemoteActivity activity = code.getRetval();
data.putAll(BeanUtil.getBeanMapWithKey(activity, "title", "membername", "memberid", "address", "limg", "clickedtimes", "membercount", "id"));
}*/
}else if(StringUtils.equals(type, "gym")){
ErrorCode<RemoteGym> code = synchGymService.getRemoteGym(relatedid, true);
if(code.isSuccess()){
RemoteGym gym = code.getRetval();
data.putAll(BeanUtil.getBeanMapWithKey(gym, "name", "address", "clickedtimes", "limg", "content", "generalmarkedtimes", "id"));
}
}else if(StringUtils.equals(type, "sport")){
Sport sport = daoService.getObject(Sport.class, relatedid);
data.putAll(BeanUtil.getBeanMapWithKey(sport, "name", "address", "clickedtimes", "feature", "limg", "generalmarkedtimes", "id"));
}
}
//------------抽取在循环内调用http请求
if(!activityIds.isEmpty()){
ErrorCode<List<RemoteActivity>> activitysCode = synchActivityService.getRemoteActivityListByIds(activityIds);
if(activitysCode.isSuccess() && activitysCode.getRetval() != null){
for(Map data : dataMap){
if(data.get("newsboard") == null) continue;
String type = data.get("newsboard")+"";
Long relatedid = new Long(data.get(MongoData.ACTION_BOARDRELATEDID)+"");
if(StringUtils.equals(type, "activity")){
for(RemoteActivity activity : activitysCode.getRetval()){
if(activity.getId().equals(relatedid)){
data.putAll(BeanUtil.getBeanMapWithKey(activity, "title", "membername", "memberid", "address", "limg", "clickedtimes", "membercount", "id"));
break;
}
}
}
}
}
}
//-----------------------------------------
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(dataMap));
}
//得到抽奖奖品信息
@RequestMapping("/subject/proxy/getPrizeInfo.xhtml")
public String getPrizeInfo(String ids, ModelMap model){
if(StringUtils.isBlank(ids)) return showJsonError(model, "参数错误!");
List<Long> idList = BeanUtil.getIdList(ids, ",");
List<Prize> prizeList = daoService.getObjectList(Prize.class, idList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(BeanUtil.getBeanMapList(prizeList, new String[]{"id","pnumber","psendout","otype"})));
}
//disney活动专题
private static final List<String> tagList = Arrays.asList("wreckitralph");
//抽奖公用
@RequestMapping("/subject/proxy/clickDraw.xhtml")
public String clickDraw(Long memberid, String check, String gewatoken, String pointxy, String tag, String noLimitDraw, HttpServletRequest request, ModelMap model){
if(StringUtils.isBlank(tag)) return showJsonSuccess(model, "syserror");
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) return showJsonSuccess(model, "nologin");
Member member = daoService.getObject(Member.class, memberid);
if(member == null) return showJsonSuccess(model, "nologin");
if(tagList.contains(tag) && StringUtils.isBlank(gewatoken)){
Map params = new HashMap();
params.put("memberid", member.getId());
Map memberMap = mongoService.findOne(MongoData.NS_DISNEY_MEMBER, params);
if(memberMap == null) return showJsonSuccess(model, "nodsn");
}
MemberInfo memberInfo = daoService.getObject(MemberInfo.class, member.getId());
String opkey = tag + member.getId();
boolean allow = operationService.updateOperation(opkey, 10);
if(!allow) return showJsonSuccess(model, "frequent");
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null||!da.isJoin()) return showJsonSuccess(model, "nostart");
Timestamp cur = DateUtil.getCurFullTimestamp();
Integer num = 1;
Map<String, String> otherinfoMap = VmUtils.readJsonToMap(da.getOtherinfo());
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOBILE)) && !member.isBindMobile()) return showJsonSuccess(model, "nobindMobile");
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_EMAIL)) && !memberInfo.isFinishedTask(MemberConstant.TASK_CONFIRMREG)) return showJsonSuccess(model, "noemail");
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_TICKET)) && StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOVIEID))){
Long movieid = Long.parseLong(otherinfoMap.get(DrawActicityConstant.TASK_MOVIEID));
int pay = orderQueryService.getMemberOrderCountByMemberid(member.getId(), movieid);
if(pay == 0) return showJsonSuccess(model, "noticket");
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_MOREDRAW))){
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_HOUR))){
Timestamp startTime = DateUtil.addHour(cur,-Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_HOUR)));
List<WinnerInfo> winnerList = drawActivityService.getWinnerList(da.getId(), null, startTime, cur, "system", member.getId(), null, null, 0, 1);
if(winnerList.size() == 1) return showJsonSuccess(model, "nodrawcount");
Timestamp from = DateUtil.getCurTruncTimestamp();
Timestamp to = DateUtil.getMillTimestamp();
int today = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), from, to);
num = today + 1;
}else if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND))){
Date date = DateUtil.currentTime();
Timestamp startTime = DateUtil.getBeginTimestamp(date);
Timestamp endTime = DateUtil.getEndTimestamp(date);
Integer winnerCount = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), startTime, endTime);
Integer inviteCount = memberService.getInviteCountByMemberid(member.getId(), startTime, endTime);
if(inviteCount - winnerCount >= Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND))) num = inviteCount / Integer.parseInt(otherinfoMap.get(DrawActicityConstant.TASK_FRIEND));
}
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_WEIBO))){
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA, MemberConstant.SOURCE_QQ),member.getId());
if(VmUtils.isEmptyList(shareMemberList)) return showJsonSuccess(model, "noweibo");
int today = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), da.getStarttime(), da.getEndtime());
if(today > 0) return showJsonSuccess(model, "nocount");
}
if(StringUtils.isNotBlank(otherinfoMap.get(DrawActicityConstant.TASK_ONLYONE))){
int drawtimes = drawActivityService.getMemberWinnerCount(member.getId(), da.getId(), da.getStarttime(), da.getEndtime());
if(drawtimes > 0) return showJsonSuccess(model, "nocount");
}
if (!StringUtils.equals(noLimitDraw, "Y")) {
Integer count = drawActivityService.getCurDrawActivityNum(da, member.getId(), num);
if(count <= 0) return showJsonSuccess(model, "nodrawcount");
}
VersionCtl mvc = drawActivityService.gainMemberVc(""+member.getId());
try {
//FIXME:黄牛??
ErrorCode<WinnerInfo> ec = drawActivityService.baseClickDraw(da, mvc, false, member);
if(ec == null || !ec.isSuccess()) return showJsonSuccess(model, ec.getErrcode());
WinnerInfo winnerInfo = ec.getRetval();
if(winnerInfo == null) return showJsonSuccess(model, "syserror");
Prize prize = daoService.getObject(Prize.class, winnerInfo.getPrizeid());
if(prize == null) return showJsonSuccess(model, "syserror");
SMSRecord sms =drawActivityService.sendPrize(prize, winnerInfo, true);
if(sms !=null) untransService.sendMsgAtServer(sms, false);
Map otherinfo = VmUtils.readJsonToMap(prize.getOtherinfo());
if(otherinfo.get(DrawActicityConstant.TASK_WALA_CONTENT) != null){
String link = null;
if(otherinfo.get(DrawActicityConstant.TASK_WALA_LINK) != null){
link = otherinfo.get(DrawActicityConstant.TASK_WALA_LINK)+"";
link = "<a href=\""+link+"\" target=\"_blank\" rel=\"nofollow\">"+"链接地址"+"</a>";
}
String pointx = null, pointy = null;
if(StringUtils.isNotBlank(pointxy)){
List<String> pointList = Arrays.asList(StringUtils.split(pointxy, ":"));
if(pointList.size() == 2){
pointx = pointList.get(0);
pointy = pointList.get(1);
}
}
ErrorCode<Comment> result = commentService.addComment(member, TagConstant.TAG_TOPIC, null, otherinfo.get(DrawActicityConstant.TASK_WALA_CONTENT)+"", link, false, pointx, pointy, WebUtils.getRemoteIp(request));
if(result.isSuccess()) {
shareService.sendShareInfo("wala",result.getRetval().getId(), result.getRetval().getMemberid(), null);
}
}
return showJsonSuccess(model, "content="+prize.getPlevel()+"&ptype="+prize.getPtype()+"&prize="+prize.getOtype());
}catch(StaleObjectStateException e){
return showJsonSuccess(model, "syserror");
}catch(HibernateOptimisticLockingFailureException e){
return showJsonSuccess(model, "syserror");
}
}
//获取排片信息
@RequestMapping("/subject/proxy/getOpenplayInfo.xhtml")
public String getOpenplayInfo(Timestamp timeTo,String citycode,Long cinemaId, Long movieId,String edition, ModelMap model){
Timestamp timeFrom = DateUtil.getCurFullTimestamp();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
List<OpenPlayItem> list = openPlayService.getOpiList(citycode, cinemaId, movieId, timeFrom, timeTo, true);
for (OpenPlayItem opi: list) {
if(StringUtils.containsIgnoreCase(opi.getEdition(), edition)){
Map<String, Object> map = new HashMap<String, Object>();
map.put("mpid", opi.getMpid());
map.put("gewaprice", opi.getGewaprice());
map.put("costprice", opi.getCostprice());
map.put("playtime", opi.getPlaytime());
result.add(map);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
/**
* 007专题暂用查DMAX厅影片场次信息
*
* */
@RequestMapping("/subject/proxy/getOpenplaySpyInfo.xhtml")
public String getOpenplaySpyInfo(Timestamp timeTo,String citycode,Long cinemaId, Long movieId,Long roomId, ModelMap model){
Timestamp timeFrom = DateUtil.getCurFullTimestamp();
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
List<OpenPlayItem> list = openPlayService.getOpiList(citycode, cinemaId, movieId, timeFrom, timeTo, true);
for (OpenPlayItem opi: list) {
if(opi.getRoomid().equals(roomId)){
Map<String, Object> map = new HashMap<String, Object>();
map.put("mpid", opi.getMpid());
map.put("gewaprice", opi.getGewaprice());
map.put("costprice", opi.getCostprice());
map.put("playtime", opi.getPlaytime());
result.add(map);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
//根据城市ID得到城市的电影和影院
@RequestMapping("/subject/proxy/getCurCinemaAndMovieByCitycode.xhtml")
public String getCurCinemaAndMovieByCitycode(String citycodes, ModelMap model){
Map resultMap = new HashMap();
if(StringUtils.isNotBlank(citycodes)){
for(String citycode : StringUtils.split(citycodes, ",")){
Integer cinemaCount = mcpService.getTicketCinemaCount(citycode, null, null, null);
List<Long> movieIdList = mcpService.getCurMovieIdList(citycode);
resultMap.put("cinema"+citycode, cinemaCount);
resultMap.put("movie"+citycode, movieIdList.size());
}
}
return showJsonSuccess(model, JsonUtils.writeMapToJson(resultMap));
}
//根据城市ID得到城市的电影院
@RequestMapping("/subject/proxy/getCinemaByCitycode.xhtml")
public String getCinemaByCitycode(String citycodes, ModelMap model){
List resultList = new LinkedList();
if(StringUtils.isNotBlank(citycodes)){
for(String citycode : StringUtils.split(citycodes, ",")){
List<Cinema> cinemas = mcpService.getCinemaListByCitycode(citycode, 0, 100);
if(!cinemas.isEmpty()){
Map<String,List<Map>> resultMap = new HashMap<String,List<Map>>();
for(Cinema cinema : cinemas){
if(StringUtils.isNotBlank(cinema.getCountycode())){
List<Map> cinemaList = resultMap.get(cinema.getCountycode());
if(cinemaList == null){
cinemaList = new LinkedList<Map>();
resultMap.put(cinema.getCountycode(), cinemaList);
}
cinemaList.add(BeanUtil.getBeanMapWithKey(cinema,"id","name","countycode","countyname","citycode"));
}
}
resultList.add(resultMap);
}
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(resultList));
}
//保存投票信息
@RequestMapping("/subject/proxy/saveVote.xhtml")
public String saveVote(Long memberid, String tag, String itemid, Integer count, ModelMap model){
if(memberid == null) return showJsonSuccess(model, "请先登录!");
Map memberMap = commonVoteService.getSingleVote(tag, memberid, null);
if(memberMap == null){
memberMap = new HashMap();
memberMap.put("tag", tag);
memberMap.put("memberid", memberid);
memberMap.put(MongoData.SYSTEM_ID, ObjectId.uuid());
}
memberMap.put("addtime", DateUtil.getCurFullTimestampStr());
memberMap.put("itemid", itemid);
mongoService.saveOrUpdateMap(memberMap, MongoData.SYSTEM_ID, MongoData.NS_COMMON_VOTE);
vote(tag, itemid, count, model);
return showJsonSuccess(model);
}
//得到投票信息
@RequestMapping("/subject/proxy/getMemberVoteInfo.xhtml")
public String getMemberVoteInfo(Long memberid, String tag, String itemid, ModelMap model){
Map memberMap = commonVoteService.getSingleVote(tag, memberid, itemid);
return showJsonSuccess(model, JsonUtils.writeMapToJson(memberMap));
}
//得到票数
@RequestMapping("/subject/proxy/vote/movieList.xhtml")
public String votemovieList(String flag, ModelMap model){
List<Map> list = commonVoteService.getItemVoteList(flag);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(list));
}
// 得到最新投票人
@RequestMapping("/subject/proxy/getVoteInfo.xhtml")
public String getVoteInfo(String tag, Integer from, Integer maxnum, ModelMap model){
if(StringUtils.isBlank(tag)) return showJsonSuccess(model);
if(from == null) from = 0;
if(maxnum == null) maxnum = 20;
List<Map> result = commonVoteService.getVoteInfo(tag, from, maxnum);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
@RequestMapping("/subject/proxy/indexCommend.xhtml")
public String indexCommend(String cityCode,String signName,int from, int maxnum, ModelMap model){
if(maxnum > 50){
maxnum = 50;
}
List<GewaCommend> gewaCommends = commonService.getGewaCommendList(cityCode,signName, null, null, true, from, maxnum);
if(StringUtils.equals(SignName.INDEX_MOVIELIST, signName) || StringUtils.equals(SignName.INDEX_MOVIELIST_NEW, signName)){
RelatedHelper rh = new RelatedHelper();
commonService.initGewaCommendList("gcMovieList", rh, gewaCommends);
List<Map> maps = new LinkedList<Map>();
for(GewaCommend gewaCommend :gewaCommends) {
Map map = new HashMap();
Movie movie = (Movie)rh.getR1("gcMovieList",gewaCommend.getId());
map.put("id",movie.getId());
map.put("moviename", movie.getMoviename());
map.put("gmark",VmUtils.getLastMarkStar(movie, "general",markService.getMarkCountByTagRelatedid(gewaCommend.getTag(), gewaCommend.getRelatedid()),markService.getMarkdata(TagConstant.TAG_MOVIE)));
if(StringUtils.isNotBlank(gewaCommend.getLogo())){
map.put("logo", gewaCommend.getLogo());
}else{
map.put("logo", movie.getLimg());
}
map.put("edition", movie.getEdition());
map.put("hotvalue",movie.getHotvalue());
CityPrice cityPrice = moviePriceService.getCityPrice(gewaCommend.getRelatedid(), cityCode, TagConstant.TAG_MOVIE);
if(cityPrice != null){
map.put("cinemas",cityPrice.getCquantity());//播放影片影院数量
map.put("mpids",cityPrice.getQuantity());//影片排片数量
}else{
map.put("cinemas",0);
map.put("mpids",0);
}
maps.add(map);
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(maps));
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(gewaCommends));
}
//投票
private String vote(String tag, String itemid, Integer count, ModelMap model){
if(count == null) count = RandomUtils.randomInt(3)+3;
int support = commonVoteService.getSupportCount(tag, itemid);
commonVoteService.addCommonVote(tag, itemid, support+count);
return showJsonSuccess(model);
}
@RequestMapping("/subject/proxy/movieListByIds.xhtml")
public String movieListByIds(String movieids, ModelMap model){
if(movieids==null) return showJsonSuccess(model, "传递参数错误!");
List<Long> movieidList = BeanUtil.getIdList(movieids, ",");
List<Movie> movieList = daoService.getObjectList(Movie.class, movieidList);
List<Map> mapList = BeanUtil.getBeanMapList(movieList, "id","name","logo","moviename","highlight","director","actors", "language", "state","videolen","type");
for (int i = 0; i < mapList.size(); i++) {
MarkCountData markCount = markService.getMarkCountByTagRelatedid(TagConstant.TAG_MOVIE, Long.valueOf(mapList.get(i).get("id").toString()));
Integer general = VmUtils.getLastMarkStar(siftMovie(movieList,Long.valueOf(mapList.get(i).get("id").toString())), "general", markCount, markService.getMarkdata(TagConstant.TAG_MOVIE));
mapList.get(i).put("generalmark", general);//general / 10 + "." + general % 10;
}
model.put("movieList", mapList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(mapList));
}
private Movie siftMovie(List<Movie> movieList,Long id){
for (int i = 0; i < movieList.size(); i++) {
if (movieList.get(i).getId().equals(id)) {
return movieList.get(i);
}
}
return null;
}
@RequestMapping("/subject/proxy/activityListByIds.xhtml")
public String activityListByIds(String aids, ModelMap model){
if(aids == null) return showJsonError(model, "参数错误!");
List<Long> aidList = BeanUtil.getIdList(aids, ",");
ErrorCode<List<RemoteActivity>> code = synchActivityService.getRemoteActivityListByIds(aidList);
if(code.isSuccess()){
List<RemoteActivity> activityList = code.getRetval();
return showJsonSuccess(model, JsonUtils.writeObjectToJson(activityList));
}
return showJsonError(model, code.getMsg());
}
@RequestMapping("/subject/proxy/videoListBymid.xhtml")
public String videoListBymid(String movieId , ModelMap model){
List<Video> videoList = videoService.getVideoListByTag("movie", Long.valueOf(movieId), 0, 1000);
List<MemberPicture> memberVideoList = pictureService.getMemberPictureList(Long.valueOf(movieId), TagConstant.TAG_MOVIE, null, TagConstant.FLAG_VIDEO,
Status.Y, 0, 1000);
Map<String , List> videoMap =new HashMap<String, List>();
videoMap.put("videoList", videoList);
videoMap.put("memberVideoList", memberVideoList);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(videoMap));
}
@RequestMapping("/subject/proxy/commentListBymid.xhtml")
public String commentListBymid(Long memberId, Long movieId, String myOrder, String friend, Integer pageNo, String citycode , ModelMap model) {
Map<String, Object> map = new HashMap<String, Object>();
Movie movie = daoService.getObject(Movie.class, movieId);
if (movie == null)
return showJsonError(model, "电影不存在或已经删除!");
if (pageNo == null)
pageNo = 0;
int rowsPerPage = 10;
int first = rowsPerPage * pageNo;
List<Diary> diaryList = new ArrayList<Diary>();
if (StringUtils.isBlank(myOrder))
myOrder = "poohnum";//addtime
Member member = (Member)relateService.getRelatedObject("member", memberId);
if (StringUtils.isNotBlank(friend) && member != null) {
diaryList = diaryService.getFriendDiaryList(DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieId, member.getId(), first, rowsPerPage);
map.put("friend", true);
} else {
//rowsCount = diaryService.getDiaryCount(Diary.class, citycode, Diary.DIARY_TYPE_COMMENT, "movie", movieId);
diaryList = diaryService.getDiaryList(Diary.class, citycode, DiaryConstant.DIARY_TYPE_COMMENT, "movie", movieId, first, rowsPerPage, myOrder);
}
addCacheMember(model, ServiceHelper.getMemberIdListFromBeanList(diaryList));
map.put("diaryList", diaryList);
map.put("cacheMemberMap", model.get("cacheMemberMap"));
return showJsonSuccess(model, JsonUtils.writeObjectToJson(map));
}
@RequestMapping("/subject/proxy/winnerInfoList.xhtml")
public String winnerInfoList(String tag, int limit, String prizeType, ModelMap model){
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null) return showJsonError(model, "参数错误!");
if(StringUtils.isBlank(prizeType)) prizeType = "A,D,P,drama,remark,waibi";
List<Prize> pList = drawActivityService.getPrizeListByDid(da.getId(), StringUtils.split(prizeType, ","));
List<Long> pIdList = BeanUtil.getBeanPropertyList(pList,Long.class,"id",true);
List<WinnerInfo> infoList = drawActivityService.getWinnerList(da.getId(),pIdList, null , null, "system",null,null,null,0,limit);
List<Map> winnerMapList = BeanUtil.getBeanMapList(infoList, new String[]{"memberid", "nickname", "prizeid","addtime"});
for(Map info : winnerMapList){
Prize prize = daoService.getObject(Prize.class, Long.valueOf(info.get("prizeid")+""));
info.put("plevel", prize.getPlevel());
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(winnerMapList));
}
@RequestMapping("/subject/proxy/pictureListBymid.xhtml")
public String pictureListBymid(String movieId , ModelMap model){
if(StringUtils.isBlank(movieId)) return showJsonError(model, "noMovieId");
Movie movie = daoService.getObject(Movie.class, Long.valueOf(movieId));
if (movie == null)
return showJsonError(model, "该影片不存在或被删除!");
List<Picture> pictureList = pictureService.getPictureListByRelatedid(TagConstant.TAG_MOVIE, Long.valueOf(movieId), 0, 1000);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(pictureList));
}
@RequestMapping("/subject/proxy/recommendationSubject.xhtml")
public String recommendationSubject(String actName,String keywords,String desc,String pageURL,String flag,String userId,String check,ModelMap model){
String checkcode = StringUtil.md5(userId + "rcs!@#");
if(!StringUtils.equals(check, checkcode)) return showJsonSuccess(model, "nologin");
SpecialActivity specialActivity = new SpecialActivity("");
specialActivity.setActivityname(actName);
specialActivity.setSeokeywords(keywords);
specialActivity.setSeodescription(desc);
specialActivity.setWebsite(pageURL);
specialActivity.setFlag(flag);
try {
daoService.saveObject(specialActivity);
} catch (Exception e) {
return showJsonError(model, e.getMessage());
}
return showJsonSuccess(model,"发布成功!");
}
@RequestMapping("/subject/proxy/addDeliveryAddress.xhtml")
public String addDeliveryAddress(String memberid,String check,String tag, String realname, String email, String sex, String address,String mobile,ModelMap model){
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) return showJsonError(model, "nologin");
String opkey = memberid+"addDeliveryAddress";
boolean allow = operationService.updateOperation(opkey, 10, 20);
if(!allow) return showJsonError(model, "操作太频繁!");
if(StringUtils.isBlank(tag)) return showJsonError(model, "非法操作!");
if(StringUtils.isBlank(realname)) return showJsonError(model, "姓名不能为空!");
if(WebUtils.checkString(realname)) return showJsonError(model, "姓名中含有非法字符!");
if(StringUtils.isNotBlank(email)&&!ValidateUtil.isEmail(email)) return showJsonError(model, "邮箱格式错误!");
if(StringUtils.isNotBlank(sex)&&StringUtil.getByteLength(sex)>2) return showJsonError(model, "性别错误!");
if(StringUtils.isBlank(address)) return showJsonError(model, "地址内容不能为空!");
if(StringUtil.getByteLength(address)>400) return showJsonError(model, "地址内容过长!");
if(WebUtils.checkString(address)) return showJsonError(model, "地址中含有非法字符!");
if(!ValidateUtil.isMobile(mobile)) return showJsonError(model, "手机号码格式有误!");
Map winning = new HashMap();
winning.put(MongoData.ACTION_TAG, tag);
winning.put(MongoData.GEWA_CUP_MEMBERID, Long.valueOf(memberid));
mongoService.removeObjectList(MongoData.NS_WINNING_RECEIPT_INFO, winning);
winning.put(MongoData.SYSTEM_ID, System.currentTimeMillis() + StringUtil.getRandomString(5));
winning.put(MongoData.ACTION_ADDTIME, DateUtil.getCurFullTimestamp());
winning.put(MongoData.FIELD_REAL_NAME, realname);
winning.put(MongoData.FIELD_TELEPHONE, mobile);
winning.put(MongoData.FIELD_RECEIPT_ADDRESS, address);
if (StringUtils.isNotBlank(email)) {
winning.put(MongoData.FIELD_EMAIL, email);
}
if (StringUtils.isNotBlank(sex)) {
winning.put(MongoData.FIELD_SEX, sex);
}
mongoService.saveOrUpdateMap(winning, MongoData.SYSTEM_ID, MongoData.NS_WINNING_RECEIPT_INFO);
return showJsonSuccess(model,"success");
}
/**
* 上海电影艺术联盟获取排片数据
* @param citycode
* @param cinemaIds
* @param movieIds
* @param from
* @param maxnum
* @return
*/
@RequestMapping("/subject/proxy/getArtFilmAllianceOpi.xhtml")
public String getArtFilmAllianceOpi(String citycode,String cinemaIds, String movieIds, int from, int maxnum, ModelMap model){
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
if (from < 0) {
from = 0;
}
if (maxnum <= 0 || maxnum >= 200) {
maxnum = 200;
}
List<OpenPlayItem> opiList = openPlayService.getArtFilmAllianceOpi(citycode, cinemaIds, movieIds, from, maxnum);
result = BeanUtil.getBeanMapList(opiList, true);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(result));
}
//分享微博
@RequestMapping("/subject/proxy/shareInfo.xhtml")
public String sharesTicketInfo(Long memberid, String check, String content, String picurl, ModelMap model){
String checkcode = StringUtil.md5(memberid + "njmk5678");
if(!StringUtils.equals(check, checkcode)) {
return showJsonError(model, "请先登录!");
}
Member member = daoService.getObject(Member.class, memberid);
if(member == null) {
return showJsonError(model, "请先登录!");
}
if(StringUtils.isBlank(content)) {
return showJsonError(model, "分享内容不能为空!");
}
boolean allow = operationService.updateOperation("shareFilmFest" + member.getId(), OperationService.HALF_MINUTE, 5);
if(!allow) {
return showJsonError(model, "你操作过于频繁,请稍后再试!");
}
List<ShareMember> shareMemberList = shareService.getShareMemberByMemberid(Arrays.asList(MemberConstant.SOURCE_SINA), member.getId());
if(shareMemberList.isEmpty()) {
return showJsonError(model, "请先绑定微博!");
}
shareService.sendShareInfo("subject", null, member.getId(), content, picurl);
return showJsonSuccess(model);
}
//得到知道
@RequestMapping("/subject/proxy/getQuestionList.xhtml")
public String getQuestionList(String tag, Long relatedid, ModelMap model){
List<GewaQuestion> questionList = qaService.getQuestionByCategoryAndCategoryid(null, tag, relatedid, -1, -1);
return showJsonSuccess(model, JsonUtils.writeObjectToJson(questionList));
}
//得到知道的答案
@RequestMapping("/subject/proxy/getAnswerList.xhtml")
public String getQuestionList(String qids, Integer maxnum, ModelMap model){
if(maxnum == null) maxnum = 3;
Map<Long,List<GewaAnswer>> answersMap = new HashMap<Long,List<GewaAnswer>>();
String[] ids = StringUtils.split(qids, ",");
Long answerMemberid = qaService.getGewaraAnswerByMemberid();
if(ids != null){
for (String id : ids) {
int max = maxnum;
Long qid = Long.parseLong(id);
List<GewaAnswer> answers = new ArrayList<GewaAnswer>();
//先查找管理员的回复
List<GewaAnswer> ga = qaService.getAnswerListByQuestionAndMemId(0, 1, qid, answerMemberid);
if(ga!=null&&!ga.isEmpty()){
answers.add(ga.get(0));
max = 2;
}
List<GewaAnswer> gac = qaService.getAnswerListByQuestionId(0, max, qid);
answers.addAll(gac);
answersMap.put(qid, answers);
}
}
return showJsonSuccess(model, JsonUtils.writeObjectToJson(answersMap));
}
@RequestMapping("/subject/proxy/getMuOrderCount.xhtml")
public String getMuOrderCount(String memberids, Long relatedid, Timestamp fromtime, Timestamp totime, ModelMap model){
if(fromtime == null) fromtime = DateUtil.getMonthFirstDay(DateUtil.getCurFullTimestamp());
if(totime == null) totime = DateUtil.getCurFullTimestamp();
List<Long> idList = BeanUtil.getIdList(memberids, ",");
int count = orderQueryService.getMUOrderCountByMbrids(idList, relatedid, fromtime, totime);
return showJsonSuccess(model, count+"");
}
@RequestMapping("/subject/proxy/getMemberWinnerCount.xhtml")
public String getMemberWinnerCount(String tag, Long memberid, ModelMap model){
DrawActivity da = daoService.getObjectByUkey(DrawActivity.class, "tag", tag, true);
if(da == null || !da.isJoin() || memberid == null) return showJsonSuccess(model, "0");
int count = drawActivityService.getMemberWinnerCount(memberid, da.getId(), da.getStarttime(), da.getEndtime());
return showJsonSuccess(model, ""+count);
}
@RequestMapping("/subject/proxy/getMemberFirstTime.xhtml")
public String getMemberFirstTime(Long memberid, String citycode, ModelMap model){
Map<String , Object> firstInfo = new HashMap<String, Object>();
MemberInfo mi = daoService.getObject(MemberInfo.class, memberid);
firstInfo.put("addTime", mi.getAddtime());
Map map = mongoService.findOne(MongoData.NS_FIRSTORDER, MongoData.SYSTEM_ID, memberid);
if (map != null && map.get("ticket") != null) {
TicketOrder order = daoService.getObjectByUkey(TicketOrder.class, "tradeNo", map.get("ticket")+"");
if (order != null) {
firstInfo.put("orderTime", order.getCreatetime());
Movie movie = daoService.getObject(Movie.class, order.getMovieid());
firstInfo.put("movieName", movie.getName());
}
}
int movieCount = orderQueryService.getMemberTicketCountByMemberid(memberid, DateUtil.parseTimestamp("2012-11-22", "yyyy-MM-dd"), DateUtil.parseTimestamp("2013-11-28", "yyyy-MM-dd"), OrderConstant.STATUS_PAID_SUCCESS, citycode);
firstInfo.put("movieCount", movieCount);
return showJsonSuccess(model , JsonUtils.writeObjectToJson(firstInfo));
}
@RequestMapping("/subject/proxy/getColorBall.xhtml")
public String getColorBall(Long memberid,String mobile,String msgContent, ModelMap model) {
ErrorCode<SMSRecord> code = drawActivityService.getColorBall(memberid, mobile, msgContent);
if (!code.isSuccess()) {
return showJsonError(model, code.getErrcode());
}
daoService.saveObject(code.getRetval());
untransService.sendMsgAtServer(code.getRetval(), false);
return showJsonSuccess(model,"success");
}
@RequestMapping("/subject/proxy/getCouponCode.xhtml")
public String getCouponCode(Long memberid,String mobile,String msgContent, ModelMap model) {
ErrorCode<SMSRecord> code = drawActivityService.getCouponCode(memberid, mobile, msgContent);
if (!code.isSuccess()) {
return showJsonError(model, code.getErrcode());
}
daoService.saveObject(code.getRetval());
untransService.sendMsgAtServer(code.getRetval(), false);
return showJsonSuccess(model,"success");
}
} | 55,243 | 0.737116 | 0.733321 | 1,078 | 48.113174 | 36.424244 | 233 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.378479 | false | false | 4 |
fe5a69972a30329e24229885c8875c1967be7ade | 27,934,467,349,489 | 3ae3880d6577134c746a278a573e01ceda8a82fd | /feidao-service-migratory/src/main/java/com/feidao/platform/service/migratory/icebox/gridservice/InsertCaptcha.java | 24b835cc6edde2c6efb636c5062306f4219c9828 | [] | no_license | lixiawss/fd-j | https://github.com/lixiawss/fd-j | a517beb1ade3214ef608851aa407b28022665210 | 9dcafc863e2b5b5b0dd41052cb7ca1ca4fab7178 | refs/heads/master | 2018-01-01T07:09:04.812000 | 2016-07-12T04:19:19 | 2016-07-12T04:19:19 | 71,968,511 | 0 | 1 | null | true | 2016-10-26T05:10:50 | 2016-10-26T05:10:49 | 2016-07-14T02:57:48 | 2016-09-08T01:08:00 | 35,018 | 0 | 0 | 0 | null | null | null | package com.feidao.platform.service.migratory.icebox.gridservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feidao.platform.core.bean.Message;
import com.feidao.platform.service.data.icebox.gridservice.AbstractDataService;
import com.feidao.platform.service.migratory.serviceInterface.ICaptchaService;
import com.feidao.platform.service.migratory.serviceimpl.CaptchaServiceImpl;
public class InsertCaptcha extends AbstractDataService {
private static final Logger LOGGER = LoggerFactory
.getLogger(InsertCaptcha.class);
@Override
public String exec(Message msg) throws Exception {
try{
String result = "";
result = this.insertCaptcha(msg);
return result;
}catch(Exception e){
LOGGER.error(".exec()出错", e);
throw e;
}
}
public String insertCaptcha(Message msg) throws Exception {
try {
init(msg);
ICaptchaService captchaService = new CaptchaServiceImpl(msgNode, dbPoolInfo);
String result = captchaService.insert();
if(LOGGER.isDebugEnabled()){
LOGGER.debug(this.getClass().getName()+".insertCaptcha() = " + result);
}
return result;
} catch (Exception e) {
LOGGER.error("插入验证码服务出错", e);
throw e;
}
}
}
| UTF-8 | Java | 1,222 | java | InsertCaptcha.java | Java | [] | null | [] | package com.feidao.platform.service.migratory.icebox.gridservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feidao.platform.core.bean.Message;
import com.feidao.platform.service.data.icebox.gridservice.AbstractDataService;
import com.feidao.platform.service.migratory.serviceInterface.ICaptchaService;
import com.feidao.platform.service.migratory.serviceimpl.CaptchaServiceImpl;
public class InsertCaptcha extends AbstractDataService {
private static final Logger LOGGER = LoggerFactory
.getLogger(InsertCaptcha.class);
@Override
public String exec(Message msg) throws Exception {
try{
String result = "";
result = this.insertCaptcha(msg);
return result;
}catch(Exception e){
LOGGER.error(".exec()出错", e);
throw e;
}
}
public String insertCaptcha(Message msg) throws Exception {
try {
init(msg);
ICaptchaService captchaService = new CaptchaServiceImpl(msgNode, dbPoolInfo);
String result = captchaService.insert();
if(LOGGER.isDebugEnabled()){
LOGGER.debug(this.getClass().getName()+".insertCaptcha() = " + result);
}
return result;
} catch (Exception e) {
LOGGER.error("插入验证码服务出错", e);
throw e;
}
}
}
| 1,222 | 0.745833 | 0.744167 | 44 | 26.272728 | 25.967081 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.977273 | false | false | 4 |
b0dbd9387d703ce0b95530d353e47f2f489455b8 | 32,813,550,201,067 | e95318ca12571cf2ed7109250d15b8919aec1977 | /hahaxueche/src/main/java/com/hahaxueche/ui/adapter/findCoach/ReviewAdapter.java | 434d98997920a1d5d9b7829b2cbde6155a2b84f9 | [] | no_license | XiaosongTech/hahaxueche-android | https://github.com/XiaosongTech/hahaxueche-android | 91a0ea82404ef65c1298609e1d36c9c297f85b04 | ae7886f57d975f542356581f2685ec3f456c4cdf | refs/heads/master | 2021-06-18T04:24:55.028000 | 2017-07-01T04:10:12 | 2017-07-01T04:10:12 | 49,932,832 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hahaxueche.ui.adapter.findCoach;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hahaxueche.R;
import com.hahaxueche.model.user.coach.Review;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by wangshirui on 2016/10/8.
*/
public class ReviewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Review> mReviewList;
public ReviewAdapter(Context context, ArrayList<Review> reviewArrayList) {
inflater = LayoutInflater.from(context);
mReviewList = reviewArrayList;
}
@Override
public int getCount() {
return mReviewList.size();
}
@Override
public Object getItem(int position) {
return mReviewList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(R.layout.adapter_review, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
Review review = mReviewList.get(position);
holder.ivAvatar.setImageURI(review.reviewer.avatar);
holder.tvName.setText(review.reviewer.name);
holder.tvDate.setText(review.updated_at.substring(0, 10));
float reviewerRating = 0;
if (!TextUtils.isEmpty(review.rating)) {
reviewerRating = Float.parseFloat(review.rating);
}
if (reviewerRating > 5) {
reviewerRating = 5;
}
holder.rbScore.setRating(reviewerRating);
holder.tvComment.setText(review.comment);
return convertView;
}
static class ViewHolder {
@BindView(R.id.iv_avatar)
SimpleDraweeView ivAvatar;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_date)
TextView tvDate;
@BindView(R.id.rb_score)
RatingBar rbScore;
@BindView(R.id.tv_comment)
TextView tvComment;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
| UTF-8 | Java | 2,590 | java | ReviewAdapter.java | Java | [
{
"context": "import butterknife.ButterKnife;\n\n/**\n * Created by wangshirui on 2016/10/8.\n */\n\npublic class ReviewAdapter ext",
"end": 545,
"score": 0.9994937777519226,
"start": 535,
"tag": "USERNAME",
"value": "wangshirui"
}
] | null | [] | package com.hahaxueche.ui.adapter.findCoach;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hahaxueche.R;
import com.hahaxueche.model.user.coach.Review;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by wangshirui on 2016/10/8.
*/
public class ReviewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<Review> mReviewList;
public ReviewAdapter(Context context, ArrayList<Review> reviewArrayList) {
inflater = LayoutInflater.from(context);
mReviewList = reviewArrayList;
}
@Override
public int getCount() {
return mReviewList.size();
}
@Override
public Object getItem(int position) {
return mReviewList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(R.layout.adapter_review, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
Review review = mReviewList.get(position);
holder.ivAvatar.setImageURI(review.reviewer.avatar);
holder.tvName.setText(review.reviewer.name);
holder.tvDate.setText(review.updated_at.substring(0, 10));
float reviewerRating = 0;
if (!TextUtils.isEmpty(review.rating)) {
reviewerRating = Float.parseFloat(review.rating);
}
if (reviewerRating > 5) {
reviewerRating = 5;
}
holder.rbScore.setRating(reviewerRating);
holder.tvComment.setText(review.comment);
return convertView;
}
static class ViewHolder {
@BindView(R.id.iv_avatar)
SimpleDraweeView ivAvatar;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_date)
TextView tvDate;
@BindView(R.id.rb_score)
RatingBar rbScore;
@BindView(R.id.tv_comment)
TextView tvComment;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
| 2,590 | 0.66139 | 0.656371 | 92 | 27.152174 | 20.058575 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543478 | false | false | 4 |
cce23b15da77a6bf9eb3adaa1bf1cb60165158bc | 27,642,409,582,221 | 2be5f06ebefc5d6960ea29f382ec522dea1922e7 | /projeto_novo/sorrisosystem/src/br/com/project/bean/view/AgendamentosBeanView_old.java | 823e4bfce4f1cc7ae6b2f98726163ccaea6e5751 | [] | no_license | jlcjj/sorrisosystem | https://github.com/jlcjj/sorrisosystem | 49a8ae8cc56ef6c2191172c8307fad270fbfb4c6 | 030c063e1665678f072182a8be8f9510050de535 | refs/heads/master | 2020-05-31T09:39:22.758000 | 2019-10-09T17:53:10 | 2019-10-09T17:53:10 | 190,216,759 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.project.bean.view;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import br.com.framework.interfac.crud.InterfaceCrud;
import br.com.project.bean.geral.BeanManagedViewAbstract;
import br.com.project.carregamento.lazy.CarregamentoLazyListForObject;
import br.com.project.geral.controller.AgendamentosController;
import br.com.project.model.classes.Agendamentos;
@Controller
@Scope(value="session")
@ManagedBean(name = "agendamentosBeanView")
public class AgendamentosBeanView_old extends BeanManagedViewAbstract {
/**
*
*/
private static final long serialVersionUID = 1L;
private String url = "/cadastro/cad_agendamentos.jsf?faces-redirect=true";
private String urlFind = "/cadastro/find_agendamentos.jsf?faces-redirect=true";
private Agendamentos objetoSelecionado = new Agendamentos();
private CarregamentoLazyListForObject<Agendamentos> list = new CarregamentoLazyListForObject<Agendamentos>();
@Override
public StreamedContent getArquivoReport() throws Exception {
super.setNomeRelatorioJasper("report_agendamentos");
super.setNomeRelatorioSaida("report_agendamentos");
super.setListDataBeanCollectionReport(agendamentosController.findList(getClassImplement()));
return super.getArquivoReport();
}
public CarregamentoLazyListForObject<Agendamentos> getList() throws Exception {
return list;
}
protected Class<Agendamentos> getClassImplement() {
return Agendamentos.class;
}
@Override
public String save() throws Exception {
//System.out.println(objetoSelecionado.getNomeMedico());
objetoSelecionado = agendamentosController.merge(objetoSelecionado);
novo();
return "";
}
@Override
public void saveEdit() throws Exception {
// TODO Auto-generated method stub
saveNotReturn();
}
@Override
public void saveNotReturn() throws Exception {
list.clean();
objetoSelecionado = agendamentosController.merge(objetoSelecionado);
list.add(objetoSelecionado);
objetoSelecionado = new Agendamentos();
sucesso();
}
@Override
public String novo() throws Exception {
setarVariaveisNulas();
return url;
}
@Override
public void setarVariaveisNulas() throws Exception {
list.clean();
objetoSelecionado = new Agendamentos();
}
@Override
public String editar() throws Exception {
list.clean();
return url;
}
@Override
public void excluir() throws Exception {
// TODO Auto-generated method stub
objetoSelecionado = (Agendamentos) agendamentosController.getSession()
.get(getClassImplement(), objetoSelecionado.getAgendamento_id());
agendamentosController.delete(objetoSelecionado);
list.remove(objetoSelecionado);
novo();
sucesso();
}
@Autowired
private AgendamentosController agendamentosController;
public Agendamentos getObjetoSelecionado() {
return objetoSelecionado;
}
public void setObjetoSelecionado(Agendamentos objetoSelecionado) {
this.objetoSelecionado = objetoSelecionado;
}
@Override
public String redirecionarFindEntidade() throws Exception {
setarVariaveisNulas();
return urlFind;
}
@Override
protected InterfaceCrud<Agendamentos> getController() {
return agendamentosController;
}
public List<SelectItem> getAgendados() throws Exception{
return agendamentosController.getListAgendados();
}
@Override
public void consultarEntidade() throws Exception {
objetoSelecionado = new Agendamentos();
list.clean();
list.setTotalRegistroConsulta(super.totalRegistroConsulta(), super.SqlLazyQuery());
}
@Override
public String condicaoAndParaPesquisa() throws Exception {
// TODO Auto-generated method stub
return "";
}
@Override
public void saveNotReturnHorario() throws Exception {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 4,008 | java | AgendamentosBeanView_old.java | Java | [] | null | [] | package br.com.project.bean.view;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.model.SelectItem;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import br.com.framework.interfac.crud.InterfaceCrud;
import br.com.project.bean.geral.BeanManagedViewAbstract;
import br.com.project.carregamento.lazy.CarregamentoLazyListForObject;
import br.com.project.geral.controller.AgendamentosController;
import br.com.project.model.classes.Agendamentos;
@Controller
@Scope(value="session")
@ManagedBean(name = "agendamentosBeanView")
public class AgendamentosBeanView_old extends BeanManagedViewAbstract {
/**
*
*/
private static final long serialVersionUID = 1L;
private String url = "/cadastro/cad_agendamentos.jsf?faces-redirect=true";
private String urlFind = "/cadastro/find_agendamentos.jsf?faces-redirect=true";
private Agendamentos objetoSelecionado = new Agendamentos();
private CarregamentoLazyListForObject<Agendamentos> list = new CarregamentoLazyListForObject<Agendamentos>();
@Override
public StreamedContent getArquivoReport() throws Exception {
super.setNomeRelatorioJasper("report_agendamentos");
super.setNomeRelatorioSaida("report_agendamentos");
super.setListDataBeanCollectionReport(agendamentosController.findList(getClassImplement()));
return super.getArquivoReport();
}
public CarregamentoLazyListForObject<Agendamentos> getList() throws Exception {
return list;
}
protected Class<Agendamentos> getClassImplement() {
return Agendamentos.class;
}
@Override
public String save() throws Exception {
//System.out.println(objetoSelecionado.getNomeMedico());
objetoSelecionado = agendamentosController.merge(objetoSelecionado);
novo();
return "";
}
@Override
public void saveEdit() throws Exception {
// TODO Auto-generated method stub
saveNotReturn();
}
@Override
public void saveNotReturn() throws Exception {
list.clean();
objetoSelecionado = agendamentosController.merge(objetoSelecionado);
list.add(objetoSelecionado);
objetoSelecionado = new Agendamentos();
sucesso();
}
@Override
public String novo() throws Exception {
setarVariaveisNulas();
return url;
}
@Override
public void setarVariaveisNulas() throws Exception {
list.clean();
objetoSelecionado = new Agendamentos();
}
@Override
public String editar() throws Exception {
list.clean();
return url;
}
@Override
public void excluir() throws Exception {
// TODO Auto-generated method stub
objetoSelecionado = (Agendamentos) agendamentosController.getSession()
.get(getClassImplement(), objetoSelecionado.getAgendamento_id());
agendamentosController.delete(objetoSelecionado);
list.remove(objetoSelecionado);
novo();
sucesso();
}
@Autowired
private AgendamentosController agendamentosController;
public Agendamentos getObjetoSelecionado() {
return objetoSelecionado;
}
public void setObjetoSelecionado(Agendamentos objetoSelecionado) {
this.objetoSelecionado = objetoSelecionado;
}
@Override
public String redirecionarFindEntidade() throws Exception {
setarVariaveisNulas();
return urlFind;
}
@Override
protected InterfaceCrud<Agendamentos> getController() {
return agendamentosController;
}
public List<SelectItem> getAgendados() throws Exception{
return agendamentosController.getListAgendados();
}
@Override
public void consultarEntidade() throws Exception {
objetoSelecionado = new Agendamentos();
list.clean();
list.setTotalRegistroConsulta(super.totalRegistroConsulta(), super.SqlLazyQuery());
}
@Override
public String condicaoAndParaPesquisa() throws Exception {
// TODO Auto-generated method stub
return "";
}
@Override
public void saveNotReturnHorario() throws Exception {
// TODO Auto-generated method stub
}
}
| 4,008 | 0.773703 | 0.773453 | 165 | 23.290909 | 25.691885 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.424242 | false | false | 4 |
e6dd126ddf148a779f132406b01adb2e070a2cc4 | 3,427,383,922,946 | 95e944448000c08dd3d6915abb468767c9f29d3c | /sources/com/bytedance/android/live/core/p148d/C3168a.java | c463dc2a60ec6b3087e102faf8f432942dd1da82 | [] | no_license | xrealm/tiktok-src | https://github.com/xrealm/tiktok-src | 261b1faaf7b39d64bb7cb4106dc1a35963bd6868 | 90f305b5f981d39cfb313d75ab231326c9fca597 | refs/heads/master | 2022-11-12T06:43:07.401000 | 2020-07-04T20:21:12 | 2020-07-04T20:21:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bytedance.android.live.core.p148d;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: com.bytedance.android.live.core.d.a */
public class C3168a {
/* renamed from: a */
public static void m11982a(JSONObject jSONObject, String str, float f) {
try {
jSONObject.put(str, (double) f);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11983a(JSONObject jSONObject, String str, long j) {
try {
jSONObject.put(str, j);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11984a(JSONObject jSONObject, String str, String str2) {
try {
jSONObject.put(str, str2);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11985a(JSONObject jSONObject, String str, JSONObject jSONObject2) {
try {
jSONObject.put(str, jSONObject2);
} catch (JSONException unused) {
}
}
}
| UTF-8 | Java | 1,071 | java | C3168a.java | Java | [] | null | [] | package com.bytedance.android.live.core.p148d;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: com.bytedance.android.live.core.d.a */
public class C3168a {
/* renamed from: a */
public static void m11982a(JSONObject jSONObject, String str, float f) {
try {
jSONObject.put(str, (double) f);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11983a(JSONObject jSONObject, String str, long j) {
try {
jSONObject.put(str, j);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11984a(JSONObject jSONObject, String str, String str2) {
try {
jSONObject.put(str, str2);
} catch (JSONException unused) {
}
}
/* renamed from: a */
public static void m11985a(JSONObject jSONObject, String str, JSONObject jSONObject2) {
try {
jSONObject.put(str, jSONObject2);
} catch (JSONException unused) {
}
}
}
| 1,071 | 0.595705 | 0.56676 | 39 | 26.461538 | 24.080896 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.487179 | false | false | 4 |
c542fdbbaede4fd9de300c174058a675886817b3 | 10,428,180,611,064 | 2fd9d77d529e9b90fd077d0aa5ed2889525129e3 | /DecompiledViberSrc/app/src/main/java/com/my/target/dw.java | f4c10c260881d021f11224a08464eea7da03b006 | [] | no_license | cga2351/code | https://github.com/cga2351/code | 703f5d49dc3be45eafc4521e931f8d9d270e8a92 | 4e35fb567d359c252c2feca1e21b3a2a386f2bdb | refs/heads/master | 2021-07-08T15:11:06.299000 | 2021-05-06T13:22:21 | 2021-05-06T13:22:21 | 60,314,071 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.my.target;
import android.os.Build.VERSION;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class dw extends ds
{
public dw(String paramString, String[] paramArrayOfString, int paramInt)
throws JSONException
{
super("start");
this.a.put("format", paramString);
this.a.put("orientation", paramInt);
this.a.put("rotation", false);
JSONArray localJSONArray;
if ((paramArrayOfString != null) && (paramArrayOfString.length > 0))
{
if (Build.VERSION.SDK_INT < 19)
break label101;
localJSONArray = new JSONArray(paramArrayOfString);
}
while (true)
{
JSONObject localJSONObject = new JSONObject();
localJSONObject.put("excludeBanners", localJSONArray);
this.a.put("filter", localJSONObject);
return;
label101: localJSONArray = new JSONArray();
int j = paramArrayOfString.length;
while (i < j)
{
localJSONArray.put(paramArrayOfString[i]);
i++;
}
}
}
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar
* Qualified Name: com.my.target.dw
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 1,256 | java | dw.java | Java | [] | null | [] | package com.my.target;
import android.os.Build.VERSION;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class dw extends ds
{
public dw(String paramString, String[] paramArrayOfString, int paramInt)
throws JSONException
{
super("start");
this.a.put("format", paramString);
this.a.put("orientation", paramInt);
this.a.put("rotation", false);
JSONArray localJSONArray;
if ((paramArrayOfString != null) && (paramArrayOfString.length > 0))
{
if (Build.VERSION.SDK_INT < 19)
break label101;
localJSONArray = new JSONArray(paramArrayOfString);
}
while (true)
{
JSONObject localJSONObject = new JSONObject();
localJSONObject.put("excludeBanners", localJSONArray);
this.a.put("filter", localJSONObject);
return;
label101: localJSONArray = new JSONArray();
int j = paramArrayOfString.length;
while (i < j)
{
localJSONArray.put(paramArrayOfString[i]);
i++;
}
}
}
}
/* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar
* Qualified Name: com.my.target.dw
* JD-Core Version: 0.6.2
*/ | 1,256 | 0.628981 | 0.611465 | 44 | 26.59091 | 22.368116 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613636 | false | false | 4 |
0d1fe0eeb3ca23438694044395a1c004d7ad96f6 | 7,567,732,434,511 | 58d83b50c25c417546529606a7a247dc6ed52c4d | /src/nomutable/Entregable6.java | 1dda69cd35d59e5c1735eb90dc11a31fbba98b9d | [] | no_license | UrielAngeles/UrielAP_Lenguajes | https://github.com/UrielAngeles/UrielAP_Lenguajes | c9b5e1798905e7ea2141e87eed485bec1e24c269 | 9b2ea8bc9e6089443dfe55c74d2a9f32096cd38f | refs/heads/master | 2021-08-24T04:09:37.004000 | 2017-12-08T01:40:25 | 2017-12-08T01:40:25 | 103,201,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 nomutable;
/**
*
* @author Uridrack7
*/
public class Entregable6 {
public static void main(String[] args) {
int u[]={10,-2,7,11};
System.out.println("El tamano es: "+u.length);
System.out.println("En el indice 3 esta "+u[2]);
int[]r={1,6,11,19};
int []i=new int[4];
i[0]=-9;
i[1]=7;
i[2]=10;
i[3]=11;
//Vamos a iterar el arreglo i usando un ciclo for
for (int j=0; j<i.length; j++){
System.out.println(i[j]);
}
//Aqui veremos el ciclo for mejorado
for(int numero:i){
System.out.println("Mejorado "+numero);
}
String mensaje="Entregable6 Uridrack7";
byte []e= mensaje.getBytes();
System.out.println("tamaño "+e.length);
String codificado="";
for (byte l:e){
System.out.println("El byte es: "+l);
codificado=codificado+l;
}
System.out.println("el mensaje codificado es: ");
System.out.println(codificado);
}
}
| UTF-8 | Java | 1,424 | java | Entregable6.java | Java | [
{
"context": "r.\r\n */\r\npackage nomutable;\r\n\r\n/**\r\n *\r\n * @author Uridrack7\r\n */\r\npublic class Entregable6 {\r\n public ",
"end": 241,
"score": 0.9969109892845154,
"start": 232,
"tag": "USERNAME",
"value": "Uridrack7"
}
] | null | [] | /*
* 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 nomutable;
/**
*
* @author Uridrack7
*/
public class Entregable6 {
public static void main(String[] args) {
int u[]={10,-2,7,11};
System.out.println("El tamano es: "+u.length);
System.out.println("En el indice 3 esta "+u[2]);
int[]r={1,6,11,19};
int []i=new int[4];
i[0]=-9;
i[1]=7;
i[2]=10;
i[3]=11;
//Vamos a iterar el arreglo i usando un ciclo for
for (int j=0; j<i.length; j++){
System.out.println(i[j]);
}
//Aqui veremos el ciclo for mejorado
for(int numero:i){
System.out.println("Mejorado "+numero);
}
String mensaje="Entregable6 Uridrack7";
byte []e= mensaje.getBytes();
System.out.println("tamaño "+e.length);
String codificado="";
for (byte l:e){
System.out.println("El byte es: "+l);
codificado=codificado+l;
}
System.out.println("el mensaje codificado es: ");
System.out.println(codificado);
}
}
| 1,424 | 0.486297 | 0.465214 | 44 | 30.34091 | 20.512682 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704545 | false | false | 4 |
4c6ebe222bc86bf30ed2074977d6e4c217417f62 | 22,204,980,974,452 | 2115eee30e98c44dce97b50fab01fa40fea82eaf | /Apartado1/Ejercicio2i1.java | 7ad135703133b867af5f83decb15a3c63b4bd545 | [] | no_license | NoelMillan/ejercicios-java | https://github.com/NoelMillan/ejercicios-java | ef413513a219a823b20ccef3b913249cc49ae8ce | 4d0877c917d08a42fbf5393092934bbe1ab9db13 | refs/heads/main | 2023-01-07T22:00:35.665000 | 2020-11-10T09:44:07 | 2020-11-10T09:44:07 | 303,810,513 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Nombre, Dirección y Número Tlf
*
* @author Noel Millán Rebollo
*/
public class Ejercicio2i1 {
public static void main(String[] args) {
System.out.println("Noel Millán Rebollo");
System.out.println("Avenida Puerros");
System.out.println("660392827");
}
}
| UTF-8 | Java | 291 | java | Ejercicio2i1.java | Java | [
{
"context": "**\n * Nombre, Dirección y Número Tlf\n *\n * @author Noel Millán Rebollo\n */\npublic class Ejercicio2i1 {\n public static v",
"end": 71,
"score": 0.999901533126831,
"start": 52,
"tag": "NAME",
"value": "Noel Millán Rebollo"
},
{
"context": "oid main(String[] args) {\n System.out.println(\"Noel Millán Rebollo\");\n System.out.println(\"Avenida Puerros\");\n ",
"end": 190,
"score": 0.9999013543128967,
"start": 171,
"tag": "NAME",
"value": "Noel Millán Rebollo"
}
] | null | [] | /**
* Nombre, Dirección y Número Tlf
*
* @author <NAME>
*/
public class Ejercicio2i1 {
public static void main(String[] args) {
System.out.println("<NAME>");
System.out.println("Avenida Puerros");
System.out.println("660392827");
}
}
| 263 | 0.658537 | 0.620209 | 12 | 22.5 | 17.394922 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
6e5491b209a7f441c26cc71867416ee1f4069ddd | 28,630,252,049,760 | 50ce0f0f218917662e9f66cfcb6c6fa351a015d3 | /FrontEnd/app/src/androidTest/java/com/group17/teddysbrochure/MainActivityTest.java | b824871d4b97caf317735a77a302601cfd4d1d7f | [] | no_license | daniellevert/Teddys-Brochure | https://github.com/daniellevert/Teddys-Brochure | 8aeb1e47d89a946e35cee3f291b388b6c0768401 | 9395416b515ae931206c84efc8e51ec1f2d25e77 | refs/heads/main | 2023-08-21T07:03:15.174000 | 2021-09-24T00:37:48 | 2021-09-24T00:37:48 | 403,799,024 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.group17.teddysbrochure;
import android.widget.ListView;
import androidx.test.espresso.action.TypeTextAction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mainActivity = new ActivityTestRule<>(MainActivity.class);
@Before
public void beginMainActivity() throws InterruptedException {
mainActivity.getActivity().getSupportFragmentManager().beginTransaction();
Thread.sleep(1000);
}
@Test
public void testDisplayBottomNavigation() {
onView(withId(R.id.nav_home)).check(matches(isDisplayed()));
onView(withId(R.id.nav_maps)).check(matches(isDisplayed()));
onView(withId(R.id.nav_explore)).check(matches(isDisplayed()));
onView(withId(R.id.nav_reviews)).check(matches(isDisplayed()));
onView(withId(R.id.nav_history)).check(matches(isDisplayed()));
}
@Test
public void testHomeClickBottomNav() {
onView(withId(R.id.nav_home)).perform(click());
onView(withId(R.id.home_page)).check(matches(isDisplayed()));
}
@Test
public void testMapsClickBottomNav() {
onView(withId(R.id.nav_maps)).perform(click());
onView(withId(R.id.fullMapsComponent)).check(matches(isDisplayed()));
}
@Test
public void testExploreClickBottomNav() {
onView(withId(R.id.nav_explore)).perform(click());
onView(withId(R.id.explore_page)).check(matches(isDisplayed()));
}
@Test
public void testReviewsClickBottomNav() {
onView(withId(R.id.nav_reviews)).perform(click());
onView(withId(R.id.reviews_page)).check(matches(isDisplayed()));
}
@Test
public void testHistoryClickBottomNav() {
onView(withId(R.id.nav_history)).perform(click());
onView(withId(R.id.history_page)).check(matches(isDisplayed()));
}
@Test
public void testOpenSearch() {
onView(withId(R.id.search_icon)).perform(click());
onView(withId(R.id.searchParkWrapper)).check(matches(isDisplayed()));
}
// TODO: @Test
// public void testSearchTyping() {
// onView(withId(R.id.search_icon)).perform(click());
// onView(withId(R.id.searchParkWrapper)).perform(click());
// }
@Test
public void testDisplayParksSearch() {
onView(withId(R.id.search_icon)).perform(click());
onView(withId(R.id.my_list)).check(matches(isDisplayed()));
}
// TODO: @Test
// public void testSwitchParks() {
//
// onView(withId(R.id.search_icon)).perform(click());
// onView(withId(R.id.my_list)).perform(click());
// }
}
| UTF-8 | Java | 3,232 | java | MainActivityTest.java | Java | [] | null | [] | package com.group17.teddysbrochure;
import android.widget.ListView;
import androidx.test.espresso.action.TypeTextAction;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mainActivity = new ActivityTestRule<>(MainActivity.class);
@Before
public void beginMainActivity() throws InterruptedException {
mainActivity.getActivity().getSupportFragmentManager().beginTransaction();
Thread.sleep(1000);
}
@Test
public void testDisplayBottomNavigation() {
onView(withId(R.id.nav_home)).check(matches(isDisplayed()));
onView(withId(R.id.nav_maps)).check(matches(isDisplayed()));
onView(withId(R.id.nav_explore)).check(matches(isDisplayed()));
onView(withId(R.id.nav_reviews)).check(matches(isDisplayed()));
onView(withId(R.id.nav_history)).check(matches(isDisplayed()));
}
@Test
public void testHomeClickBottomNav() {
onView(withId(R.id.nav_home)).perform(click());
onView(withId(R.id.home_page)).check(matches(isDisplayed()));
}
@Test
public void testMapsClickBottomNav() {
onView(withId(R.id.nav_maps)).perform(click());
onView(withId(R.id.fullMapsComponent)).check(matches(isDisplayed()));
}
@Test
public void testExploreClickBottomNav() {
onView(withId(R.id.nav_explore)).perform(click());
onView(withId(R.id.explore_page)).check(matches(isDisplayed()));
}
@Test
public void testReviewsClickBottomNav() {
onView(withId(R.id.nav_reviews)).perform(click());
onView(withId(R.id.reviews_page)).check(matches(isDisplayed()));
}
@Test
public void testHistoryClickBottomNav() {
onView(withId(R.id.nav_history)).perform(click());
onView(withId(R.id.history_page)).check(matches(isDisplayed()));
}
@Test
public void testOpenSearch() {
onView(withId(R.id.search_icon)).perform(click());
onView(withId(R.id.searchParkWrapper)).check(matches(isDisplayed()));
}
// TODO: @Test
// public void testSearchTyping() {
// onView(withId(R.id.search_icon)).perform(click());
// onView(withId(R.id.searchParkWrapper)).perform(click());
// }
@Test
public void testDisplayParksSearch() {
onView(withId(R.id.search_icon)).perform(click());
onView(withId(R.id.my_list)).check(matches(isDisplayed()));
}
// TODO: @Test
// public void testSwitchParks() {
//
// onView(withId(R.id.search_icon)).perform(click());
// onView(withId(R.id.my_list)).perform(click());
// }
}
| 3,232 | 0.690285 | 0.687809 | 98 | 31.979591 | 28.236603 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418367 | false | false | 4 |
f71f95dd870d01afb08ec8f45571fbe61de96f56 | 28,630,252,052,227 | 1f2b3ffa4c9664d0c0200e37da4125b95b8b3f85 | /src/main/java/com/ds/mapper/AdminMapper.java | 21b29b1a67038a0c77e67abfc479f5024125553d | [] | no_license | LeeGu-hun/dowajo | https://github.com/LeeGu-hun/dowajo | 6e7b8e316e00044dc276e6fabcd9282b0163f8ae | f82d903128a947539b0efcad111fb22478f2927e | refs/heads/master | 2023-01-13T14:02:43.629000 | 2020-11-17T05:33:54 | 2020-11-17T05:33:54 | 301,915,228 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ds.mapper;
import java.util.List;
import com.ds.domain.AuthVO;
import com.ds.domain.Criteria;
import com.ds.domain.QuestionsVO;
import com.ds.domain.UserVO;
public interface AdminMapper {
//학생, 선생님 문의 사항
public List<QuestionsVO> getQueList(Criteria cri);
public int getTotalCount(Criteria cri);
public void main_regist(QuestionsVO vo);
//QnA 답글
public int QnA_update(QuestionsVO vo);
//관리자 문의 사항
public List<QuestionsVO> getQueList2(Criteria cri);
public int getTotalCount2(Criteria cri);
//관리자 등록
public void admin_regist(UserVO vo);
public void admin_registAuth(AuthVO auth);
//선생님 등록
public void teacher_regist(UserVO vo);
public void teacher_registAuth(AuthVO auth);
//아이디 중복 체크
public String duplicateId(String user_id);
//상세 보기
public UserVO read(int user_no);
public QuestionsVO main_read(int qa_no);
//삭제
public int delete(int user_id);
public int main_delete(int qa_no);
//학생, 교사, 관리자 전체 수
public int getUserTypeTotal(Criteria cri);
//학생, 교사, 관리자 전체 목록
public List<UserVO> getUserTypeList(Criteria cri);
public boolean upHit(int qa_no);
public UserVO user_read(String user_id); //사용자 정보보기
public int user_update(UserVO vo); //회원정보 업데이트
public int user_delete(Long user_no); //사용자 삭제
}
| UTF-8 | Java | 1,480 | java | AdminMapper.java | Java | [] | null | [] | package com.ds.mapper;
import java.util.List;
import com.ds.domain.AuthVO;
import com.ds.domain.Criteria;
import com.ds.domain.QuestionsVO;
import com.ds.domain.UserVO;
public interface AdminMapper {
//학생, 선생님 문의 사항
public List<QuestionsVO> getQueList(Criteria cri);
public int getTotalCount(Criteria cri);
public void main_regist(QuestionsVO vo);
//QnA 답글
public int QnA_update(QuestionsVO vo);
//관리자 문의 사항
public List<QuestionsVO> getQueList2(Criteria cri);
public int getTotalCount2(Criteria cri);
//관리자 등록
public void admin_regist(UserVO vo);
public void admin_registAuth(AuthVO auth);
//선생님 등록
public void teacher_regist(UserVO vo);
public void teacher_registAuth(AuthVO auth);
//아이디 중복 체크
public String duplicateId(String user_id);
//상세 보기
public UserVO read(int user_no);
public QuestionsVO main_read(int qa_no);
//삭제
public int delete(int user_id);
public int main_delete(int qa_no);
//학생, 교사, 관리자 전체 수
public int getUserTypeTotal(Criteria cri);
//학생, 교사, 관리자 전체 목록
public List<UserVO> getUserTypeList(Criteria cri);
public boolean upHit(int qa_no);
public UserVO user_read(String user_id); //사용자 정보보기
public int user_update(UserVO vo); //회원정보 업데이트
public int user_delete(Long user_no); //사용자 삭제
}
| 1,480 | 0.704407 | 0.702888 | 54 | 22.370371 | 18.476507 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.388889 | false | false | 4 |
220677024cb3e4fb279056b28f954f0d289fc132 | 14,628,658,676,126 | 2403b45082d3380ddc4b117135dfe37b317f5490 | /fr.inria.diverse.swhModel.generator/xtend-gen/fr/inria/diverse/swhModel/generator/aspects/ImportAspect.java | 27bca254cb1d4c035263e90a7ca58f20a808013d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | RomainLefeuvre/DatasetBuilder | https://github.com/RomainLefeuvre/DatasetBuilder | 1bb30f72513ff81fdfd6e7624c18ffb7d404a982 | 80648785603e49b43eb1c451389210e7fbea36fb | refs/heads/master | 2023-05-31T11:59:03.843000 | 2023-02-20T18:11:05 | 2023-02-20T18:11:05 | 580,346,138 | 4 | 0 | null | false | 2023-02-19T09:10:44 | 2022-12-20T10:34:59 | 2023-01-26T17:27:00 | 2023-02-19T09:10:43 | 42,314 | 1 | 0 | 0 | Java | false | false | package fr.inria.diverse.swhModel.generator.aspects;
import fr.inria.diverse.k3.al.annotationprocessor.Aspect;
import org.eclipse.ocl.pivot.Import;
@Aspect(className = Import.class)
@SuppressWarnings("all")
public class ImportAspect extends NamedElementAspect {
}
| UTF-8 | Java | 266 | java | ImportAspect.java | Java | [] | null | [] | package fr.inria.diverse.swhModel.generator.aspects;
import fr.inria.diverse.k3.al.annotationprocessor.Aspect;
import org.eclipse.ocl.pivot.Import;
@Aspect(className = Import.class)
@SuppressWarnings("all")
public class ImportAspect extends NamedElementAspect {
}
| 266 | 0.815789 | 0.81203 | 9 | 28.555555 | 22.341347 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
0295d49f910c9ffa9eadc6e62ea15bc9dd0859d0 | 17,171,279,302,259 | f5b750a888a7c956ec8606e82114d3b0317008e6 | /src/by/homework2/FirstTaskHW2.java | c246f07bfeb78297808b95b6d0e274f7d69f6728 | [] | no_license | pokach021/homeWork | https://github.com/pokach021/homeWork | ec693eee79e844f3e25371ee300ff8702e9cbe57 | 7d9319628b72fa9ae5e51c25119a06bd6c727d6b | refs/heads/main | 2023-01-23T19:54:26.021000 | 2020-11-20T20:40:24 | 2020-11-20T20:40:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.homework2;
import java.util.Scanner;
public class FirstTaskHW2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter pyramid size:");
int size = scanner.nextInt();
int[][] pyramid = new int[size][size];
int step = 0;
if (size % 2 != 0) {
while (step <= size / 2) {
for (int i = step; i < pyramid.length - step; i++) {
for (int j = step; j < pyramid.length - step; j++) {
pyramid[i][j] = step + 1;
}
}
step++;
}
} else {
while (step < size / 2) {
for (int i = step; i < pyramid.length - step; i++) {
for (int j = step; j < pyramid.length - step; j++) {
pyramid[i][j] = step + 1;
}
}
step++;
}
}
for (int i = 0; i < pyramid.length; i++) {
System.out.println();
for (int j = 0; j < pyramid[i].length; j++) {
System.out.print(pyramid[i][j] + "\t");
}
}
}
}
| UTF-8 | Java | 1,235 | java | FirstTaskHW2.java | Java | [] | null | [] | package by.homework2;
import java.util.Scanner;
public class FirstTaskHW2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter pyramid size:");
int size = scanner.nextInt();
int[][] pyramid = new int[size][size];
int step = 0;
if (size % 2 != 0) {
while (step <= size / 2) {
for (int i = step; i < pyramid.length - step; i++) {
for (int j = step; j < pyramid.length - step; j++) {
pyramid[i][j] = step + 1;
}
}
step++;
}
} else {
while (step < size / 2) {
for (int i = step; i < pyramid.length - step; i++) {
for (int j = step; j < pyramid.length - step; j++) {
pyramid[i][j] = step + 1;
}
}
step++;
}
}
for (int i = 0; i < pyramid.length; i++) {
System.out.println();
for (int j = 0; j < pyramid[i].length; j++) {
System.out.print(pyramid[i][j] + "\t");
}
}
}
}
| 1,235 | 0.398381 | 0.389474 | 38 | 31.5 | 20.647097 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657895 | false | false | 4 |
517c68ec12934a51f17780b43628b7fbf0bcc265 | 24,816,321,084,789 | 264664784a7e213cbb7bad9879a78269ee77428a | /app/src/main/java/com/cxzy/xxjg/utils/ConstantsUtil.java | 9a76c64d43206285a760e03799846e73b6bf9486 | [] | no_license | langrenqing214/xuexiaojianguan | https://github.com/langrenqing214/xuexiaojianguan | cd0593b58aec4d32c2b1345ea23a4f45bf775e82 | 5108b7c7dcea77a9382175e7df546ae7f81ae90c | refs/heads/master | 2020-03-22T21:18:59.308000 | 2018-08-27T15:36:44 | 2018-08-27T15:36:44 | 140,676,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cxzy.xxjg.utils;
/**
* Created by demo on 2018/8/20.
*/
public class ConstantsUtil {
public static final String AUTH_LOGIN_STATUS_SUCCESS = "auth_login_status_success";
}
| UTF-8 | Java | 191 | java | ConstantsUtil.java | Java | [
{
"context": "package com.cxzy.xxjg.utils;\n\n/**\n * Created by demo on 2018/8/20.\n */\n\npublic class ConstantsUtil {\n ",
"end": 52,
"score": 0.997786819934845,
"start": 48,
"tag": "USERNAME",
"value": "demo"
}
] | null | [] | package com.cxzy.xxjg.utils;
/**
* Created by demo on 2018/8/20.
*/
public class ConstantsUtil {
public static final String AUTH_LOGIN_STATUS_SUCCESS = "auth_login_status_success";
}
| 191 | 0.712042 | 0.675393 | 9 | 20.222221 | 26.873274 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 4 |
5408576b20fe8b29ccc35c4a458d11e472d635af | 25,958,782,387,394 | f7770e21f34ef093eb78dae21fd9bde99b6e9011 | /src/main/java/com/hengyuan/hicash/service/query/AppAgainBasicInfo.java | 7d14af17bc1b1ee56d14d1817a8440ce9e6987af | [] | no_license | webvul/HicashAppService | https://github.com/webvul/HicashAppService | 9ac8e50c00203df0f4666cd81c108a7f14a3e6e0 | abf27908f537979ef26dfac91406c1869867ec50 | refs/heads/master | 2020-03-22T19:58:41.549000 | 2017-12-26T08:30:04 | 2017-12-26T08:30:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hengyuan.hicash.service.query;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.hengyuan.hicash.constant.ResultCodes;
import com.hengyuan.hicash.domain.service.user.AppAgainBasicService;
import com.hengyuan.hicash.parameters.request.user.AppAgainBasicReq;
import com.hengyuan.hicash.parameters.request.user.AppAgainBasicResp;
import com.hengyuan.hicash.service.validate.query.AppAgainBasicVal;
import com.hengyuan.hicash.utils.RecordUtils;
import com.hengyuan.hicash.utils.ResourceUtils;
/**
*
* @author wangliang
* @date 2017年8月22日 上午10:23:01
*/
@WebServlet("/AppAgainBasicInfo")
public class AppAgainBasicInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(AppAgainBasicInfo.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AppAgainBasicReq appAgainBasicReq = new AppAgainBasicReq();
AppAgainBasicResp appAgainBasicResp = new AppAgainBasicResp();
appAgainBasicReq.setAppTempNo(request.getParameter("appTempNo"));
RecordUtils.writeRequest(logger, request, appAgainBasicReq);
AppAgainBasicVal appAgainBasicVal = new AppAgainBasicVal(appAgainBasicReq);
String resultCode = appAgainBasicVal.validate();
if(!ResultCodes.NORMAL.equals(resultCode)){
appAgainBasicResp.setResultCode(resultCode);
}else{
AppAgainBasicService appAgainBasicService = new AppAgainBasicService();
appAgainBasicResp = (AppAgainBasicResp)appAgainBasicService.responseValue(appAgainBasicReq);
}
appAgainBasicResp.setResultMsg(ResourceUtils.getString(appAgainBasicResp.getResultCode()));
RecordUtils.writeResponse(logger, null, appAgainBasicResp);
response.getWriter().write(appAgainBasicResp.toJson());
}
}
| UTF-8 | Java | 2,238 | java | AppAgainBasicInfo.java | Java | [
{
"context": "an.hicash.utils.ResourceUtils;\n\n/**\n * \n * @author wangliang\n * @date 2017年8月22日 上午10:23:01\n */\n@WebServlet(\"/",
"end": 768,
"score": 0.9795762300491333,
"start": 759,
"tag": "USERNAME",
"value": "wangliang"
}
] | null | [] | package com.hengyuan.hicash.service.query;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.hengyuan.hicash.constant.ResultCodes;
import com.hengyuan.hicash.domain.service.user.AppAgainBasicService;
import com.hengyuan.hicash.parameters.request.user.AppAgainBasicReq;
import com.hengyuan.hicash.parameters.request.user.AppAgainBasicResp;
import com.hengyuan.hicash.service.validate.query.AppAgainBasicVal;
import com.hengyuan.hicash.utils.RecordUtils;
import com.hengyuan.hicash.utils.ResourceUtils;
/**
*
* @author wangliang
* @date 2017年8月22日 上午10:23:01
*/
@WebServlet("/AppAgainBasicInfo")
public class AppAgainBasicInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(AppAgainBasicInfo.class);
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AppAgainBasicReq appAgainBasicReq = new AppAgainBasicReq();
AppAgainBasicResp appAgainBasicResp = new AppAgainBasicResp();
appAgainBasicReq.setAppTempNo(request.getParameter("appTempNo"));
RecordUtils.writeRequest(logger, request, appAgainBasicReq);
AppAgainBasicVal appAgainBasicVal = new AppAgainBasicVal(appAgainBasicReq);
String resultCode = appAgainBasicVal.validate();
if(!ResultCodes.NORMAL.equals(resultCode)){
appAgainBasicResp.setResultCode(resultCode);
}else{
AppAgainBasicService appAgainBasicService = new AppAgainBasicService();
appAgainBasicResp = (AppAgainBasicResp)appAgainBasicService.responseValue(appAgainBasicReq);
}
appAgainBasicResp.setResultMsg(ResourceUtils.getString(appAgainBasicResp.getResultCode()));
RecordUtils.writeResponse(logger, null, appAgainBasicResp);
response.getWriter().write(appAgainBasicResp.toJson());
}
}
| 2,238 | 0.814632 | 0.807899 | 63 | 34.365078 | 28.784531 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.603175 | false | false | 4 |
7a795c71e566c22012a156bdcf3d220e12af0da7 | 13,374,528,183,869 | a25ffce70545f7a6afeb58e5c70eb24a17426318 | /jbm-cluster/jbm-cluster-platform/jbm-cluster-platform-center/src/main/java/com/jbm/cluster/center/controller/GatewayIpLimitApiController.java | 91e17b8bd9cf517e9795d7bc2ad2db7ca2f2c6d3 | [
"Apache-2.0"
] | permissive | numen06/JBM | https://github.com/numen06/JBM | 4b3b2158f8199957c6e1500ab05ae5aca375a98f | 827df87659e9392d73897753142271ab1e573974 | refs/heads/7.1 | 2023-08-31T15:35:34.579000 | 2023-08-23T01:12:01 | 2023-08-23T01:12:01 | 160,906,536 | 10 | 9 | Apache-2.0 | false | 2023-04-14T19:31:19 | 2018-12-08T05:16:32 | 2023-01-31T17:08:15 | 2023-04-14T19:31:18 | 64,469 | 5 | 8 | 4 | Java | false | false | package com.jbm.cluster.center.controller;
import com.jbm.cluster.api.entitys.gateway.GatewayIpLimitApi;
import com.jbm.cluster.center.service.GatewayIpLimitApiService;
import com.jbm.framework.mvc.web.MasterDataCollection;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: wesley.zhang
* @Create: 2020-02-25 03:57:09
*/
@RestController
@RequestMapping("/gatewayIpLimitApi")
public class GatewayIpLimitApiController extends MasterDataCollection<GatewayIpLimitApi, GatewayIpLimitApiService> {
} | UTF-8 | Java | 589 | java | GatewayIpLimitApiController.java | Java | [
{
"context": "b.bind.annotation.RestController;\n\n/**\n * @Author: wesley.zhang\n * @Create: 2020-02-25 03:57:09\n */\n@RestControll",
"end": 380,
"score": 0.7959674000740051,
"start": 368,
"tag": "NAME",
"value": "wesley.zhang"
}
] | null | [] | package com.jbm.cluster.center.controller;
import com.jbm.cluster.api.entitys.gateway.GatewayIpLimitApi;
import com.jbm.cluster.center.service.GatewayIpLimitApiService;
import com.jbm.framework.mvc.web.MasterDataCollection;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: wesley.zhang
* @Create: 2020-02-25 03:57:09
*/
@RestController
@RequestMapping("/gatewayIpLimitApi")
public class GatewayIpLimitApiController extends MasterDataCollection<GatewayIpLimitApi, GatewayIpLimitApiService> {
} | 589 | 0.831918 | 0.808149 | 16 | 35.875 | 31.693602 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 4 |
9624b85472df773ec6fe5242d979f0e03baa4735 | 12,292,196,466,141 | f110ce3d12092b2ba44ab307a630c4f40efcad32 | /src/main/java/com.hbcd/testscript/commonplatform_mobile/borderfree/Scen_B12261_Display_All_Shipping_Methods.java | 560d539cbd578a726dce8f18fbcfe6f0ec7126b3 | [] | no_license | rahullodha85/ta-banner-tests | https://github.com/rahullodha85/ta-banner-tests | db1dafe02110b44e0f32c2ce262869dfa2ae7dbd | 02dbf6bcd96c9b34adb17c19e133537f1213c287 | refs/heads/master | 2021-01-25T09:45:37.800000 | 2017-06-09T16:39:04 | 2017-06-09T16:39:04 | 93,874,921 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hbcd.testscript.commonplatform_mobile.borderfree;
import com.hbcd.banner.mobile.saks.validations.ValidateHome;
import com.hbcd.banner.mobile.saks.validations.ValidateShipping;
import com.hbcd.banner.validations.s5a.ValidateRs;
import com.hbcd.banner.validations.s5a.ValidateShippingBilling;
import com.hbcd.base.ScenarioChkout;
import com.hbcd.base.ScenarioMobileSaks;
import com.hbcd.banner.mobile.saks.pages.mProductDetailPage;
import com.hbcd.commonbanner.base.pages.SearchFunction;
/**
* Created by vevinmoza on 11/16/15.
*/
public class Scen_B12261_Display_All_Shipping_Methods extends ScenarioMobileSaks {
public void executeScript() throws Exception {
/*
Scenario: Display All Available Shipping Methods
(Reference notation #2 in attachment: International_ShippingPage_Mobile_ToBe.png)
GIVEN that I’m an international customer on the shipping page
WHEN the page loads
THEN display all available shipping methods
AND give me the option to pay my duties and taxes now or upon delivery
*/
// nav.ChangeCountry("United Kingdom");
// ValidateHome.hasCountryChanged("www.saksfifthavenue.com/static/images/flags/GB.gif");
nav.ChangeCountry("India");
nav.SearchFor("");
pdp.AddToBag();
pdp.EnterBag();
bag.CheckOut();
lgn.LoginWith("user@s5a.com");
shp.AddShippingAddress(false, dataObject.getAddress1(), dataObject.getState(), dataObject.getCity(), dataObject.getZipCode(),true);
ValidateShipping.hasShippingMethods(3);
ValidateShipping.hasOptionDutyFreeAndTaxes();
}
}
| UTF-8 | Java | 1,631 | java | Scen_B12261_Display_All_Shipping_Methods.java | Java | [
{
"context": "nner.base.pages.SearchFunction;\n\n/**\n * Created by vevinmoza on 11/16/15.\n */\npublic class Scen_B12261_Display",
"end": 527,
"score": 0.9996775388717651,
"start": 518,
"tag": "USERNAME",
"value": "vevinmoza"
},
{
"context": ");\n bag.CheckOut();\n lgn.LoginWith(\"user@s5a.com\");\n shp.AddShippingAddress(false, dataObje",
"end": 1371,
"score": 0.9999164342880249,
"start": 1359,
"tag": "EMAIL",
"value": "user@s5a.com"
}
] | null | [] | package com.hbcd.testscript.commonplatform_mobile.borderfree;
import com.hbcd.banner.mobile.saks.validations.ValidateHome;
import com.hbcd.banner.mobile.saks.validations.ValidateShipping;
import com.hbcd.banner.validations.s5a.ValidateRs;
import com.hbcd.banner.validations.s5a.ValidateShippingBilling;
import com.hbcd.base.ScenarioChkout;
import com.hbcd.base.ScenarioMobileSaks;
import com.hbcd.banner.mobile.saks.pages.mProductDetailPage;
import com.hbcd.commonbanner.base.pages.SearchFunction;
/**
* Created by vevinmoza on 11/16/15.
*/
public class Scen_B12261_Display_All_Shipping_Methods extends ScenarioMobileSaks {
public void executeScript() throws Exception {
/*
Scenario: Display All Available Shipping Methods
(Reference notation #2 in attachment: International_ShippingPage_Mobile_ToBe.png)
GIVEN that I’m an international customer on the shipping page
WHEN the page loads
THEN display all available shipping methods
AND give me the option to pay my duties and taxes now or upon delivery
*/
// nav.ChangeCountry("United Kingdom");
// ValidateHome.hasCountryChanged("www.saksfifthavenue.com/static/images/flags/GB.gif");
nav.ChangeCountry("India");
nav.SearchFor("");
pdp.AddToBag();
pdp.EnterBag();
bag.CheckOut();
lgn.LoginWith("<EMAIL>");
shp.AddShippingAddress(false, dataObject.getAddress1(), dataObject.getState(), dataObject.getCity(), dataObject.getZipCode(),true);
ValidateShipping.hasShippingMethods(3);
ValidateShipping.hasOptionDutyFreeAndTaxes();
}
}
| 1,626 | 0.739104 | 0.728668 | 43 | 36.837208 | 31.573414 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false | 4 |
0eeafe28574c772fa7353d0920ff10069ebfa71a | 14,963,666,121,646 | a5dd07390debf19e1a53e791e0e6dbc4433567e2 | /nested_scroller/src/main/java/com/mrh/nested_scroller/child/NestedBody.java | cf4f40d1044dfce60d0606cc5c40ecad3b36231c | [] | no_license | Wuxiaonai/StickyTabLayout | https://github.com/Wuxiaonai/StickyTabLayout | 6d1aa5bc854ea8890c63d7a787fa9a31ae83fb72 | 99687cb68644f647cda27e760a7fe290465fb5f0 | refs/heads/master | 2020-12-05T03:48:52.414000 | 2019-12-18T11:36:41 | 2019-12-18T11:36:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mrh.nested_scroller.child;
/**
* 嵌套滑动 Body
* Created by haoxinlei on 2019-12-07.
*/
public interface NestedBody {
}
| UTF-8 | Java | 140 | java | NestedBody.java | Java | [
{
"context": "ed_scroller.child;\n\n/**\n * 嵌套滑动 Body\n * Created by haoxinlei on 2019-12-07.\n */\npublic interface NestedBody {\n",
"end": 80,
"score": 0.9995203018188477,
"start": 71,
"tag": "USERNAME",
"value": "haoxinlei"
}
] | null | [] | package com.mrh.nested_scroller.child;
/**
* 嵌套滑动 Body
* Created by haoxinlei on 2019-12-07.
*/
public interface NestedBody {
}
| 140 | 0.704545 | 0.643939 | 8 | 15.5 | 15.692355 | 38 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 4 |
e2eace31329621113730e4e90fae4097c91051be | 14,963,666,125,562 | d20a6ec2e19cb372b2662f193225f66b52ba9122 | /src/shop/ShowPage.java | dfe132f57e4cd9fb0784c8459a8d80cfb217dc2d | [] | no_license | sleephu/Shopping-Cart---Session-exercise | https://github.com/sleephu/Shopping-Cart---Session-exercise | 520d99aa90b428e37e489302bf94fc75634e8319 | 453b261ee0f0d73ea72817d5fcc62e2891ccf28f | refs/heads/master | 2020-04-13T02:52:10.332000 | 2014-10-09T22:43:13 | 2014-10-09T22:43:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package shop;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ShowPage")
public class ShowPage extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowPage() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// CatalogPage currentPage =
// CatalogPageLookUp.getCatalogPage((request.getParameter("type")));
// request.setAttribute("pages", currentPage);
// String address;
String currentPage= request.getParameter("type");
// if (currentPage == null) {
// address = "UnknownPages.jsp";
// } else if (currentPage.equals("Books")) {
// CatalogItem[] items = {
// new CatalogItem("01","Java Servlet Programming", 29.95),
// new CatalogItem("02","Oracle Database Programming",48.95),
// new CatalogItem("03","System Analysis and Design With UML",14.95),
// new CatalogItem("04","Object Oriented Software engineering",35.99),
// new CatalogItem("05","Java Web Services",27.99)};
// address = "showPage.jsp";
// address = "book.jsp";//It can also use this!~^_^~.
// } else if (currentPage.equals("Music")) {
// CatalogItem[] items = {
// new CatalogItem("06","I'm Going to Tell You a Secret By Madonna",26.99),
// new CatalogItem("07","Baby one more time By Brienty Spears",10.95),
// new CatalogItem("08","Justified By Justin Timberlake",9.97),
// new CatalogItem("09","Loose By Nelly Furtado",13.98),
// new CatalogItem("10","Gold Digger By Kanye West",27.99)};
// address = "music.jsp?title=huahua";
// address = "music.jsp";
// address = "showPage.jsp";
// } else {
// CatalogItem[] items = {
// new CatalogItem("11","Apple Mac Pro with 13.3' Display",1299.99),
// new CatalogItem("12","Asus Laptop With Centrino 2 Black",945.95),
// new CatalogItem("13","HP Pavilion Laptop With Centrino 2 DV7",1199.95),
// new CatalogItem("14","Toshiba Satellite Laptop With Centrino 2-Copper",899.99),
// new CatalogItem("15","Sony VAIO Laptop With Core 2 Duo Cosmopolitan Pink",799.99)};
// address = "showPage.jsp";
// address = "computer.jsp";
// }
// request.setAttribute("a", "huahua");
// request.setAttribute("type",currentPage);
if(currentPage !=null){
request.setAttribute("type", currentPage);
RequestDispatcher dispatcher =
request.getRequestDispatcher("showPage.jsp");
dispatcher.forward(request, response);
}
};
// CatalogItem[] items = {
// new CatalogItem("01","Java Servlet Programming", 29.95),
// new CatalogItem("02","Oracle Database Programming",48.95),
// new CatalogItem("03","System Analysis and Design With UML",14.95),
// new CatalogItem("04","Object Oriented Software engineering",35.99),
// new CatalogItem("05","Java Web Services",27.99),
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
| UTF-8 | Java | 3,911 | java | ShowPage.java | Java | [
{
"context": " new CatalogItem(\"07\",\"Baby one more time By Brienty Spears\",10.95),\n//\t\t\t \t\t new CatalogItem",
"end": 1847,
"score": 0.6249114274978638,
"start": 1841,
"tag": "NAME",
"value": "rienty"
},
{
"context": "atalogItem(\"07\",\"Baby one more time By Brienty Spears\",10.95),\n//\t\t\t \t\t new CatalogItem(\"08\",\"",
"end": 1854,
"score": 0.5749244689941406,
"start": 1851,
"tag": "NAME",
"value": "ars"
},
{
"context": "\t\t\t \t\t new CatalogItem(\"08\",\"Justified By Justin Timberlake\",9.97),\n//\t\t\t \t\t new CatalogItem(\"09\",\"L",
"end": 1934,
"score": 0.9998906850814819,
"start": 1917,
"tag": "NAME",
"value": "Justin Timberlake"
},
{
"context": ",\n//\t\t\t \t\t new CatalogItem(\"09\",\"Loose By Nelly Furtado\",13.98),\n//\t\t\t \t\t new CatalogItem(\"10\",\"",
"end": 2005,
"score": 0.9991741180419922,
"start": 1992,
"tag": "NAME",
"value": "Nelly Furtado"
}
] | null | [] | package shop;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ShowPage")
public class ShowPage extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowPage() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// CatalogPage currentPage =
// CatalogPageLookUp.getCatalogPage((request.getParameter("type")));
// request.setAttribute("pages", currentPage);
// String address;
String currentPage= request.getParameter("type");
// if (currentPage == null) {
// address = "UnknownPages.jsp";
// } else if (currentPage.equals("Books")) {
// CatalogItem[] items = {
// new CatalogItem("01","Java Servlet Programming", 29.95),
// new CatalogItem("02","Oracle Database Programming",48.95),
// new CatalogItem("03","System Analysis and Design With UML",14.95),
// new CatalogItem("04","Object Oriented Software engineering",35.99),
// new CatalogItem("05","Java Web Services",27.99)};
// address = "showPage.jsp";
// address = "book.jsp";//It can also use this!~^_^~.
// } else if (currentPage.equals("Music")) {
// CatalogItem[] items = {
// new CatalogItem("06","I'm Going to Tell You a Secret By Madonna",26.99),
// new CatalogItem("07","Baby one more time By Brienty Spears",10.95),
// new CatalogItem("08","Justified By <NAME>",9.97),
// new CatalogItem("09","Loose By <NAME>",13.98),
// new CatalogItem("10","Gold Digger By Kanye West",27.99)};
// address = "music.jsp?title=huahua";
// address = "music.jsp";
// address = "showPage.jsp";
// } else {
// CatalogItem[] items = {
// new CatalogItem("11","Apple Mac Pro with 13.3' Display",1299.99),
// new CatalogItem("12","Asus Laptop With Centrino 2 Black",945.95),
// new CatalogItem("13","HP Pavilion Laptop With Centrino 2 DV7",1199.95),
// new CatalogItem("14","Toshiba Satellite Laptop With Centrino 2-Copper",899.99),
// new CatalogItem("15","Sony VAIO Laptop With Core 2 Duo Cosmopolitan Pink",799.99)};
// address = "showPage.jsp";
// address = "computer.jsp";
// }
// request.setAttribute("a", "huahua");
// request.setAttribute("type",currentPage);
if(currentPage !=null){
request.setAttribute("type", currentPage);
RequestDispatcher dispatcher =
request.getRequestDispatcher("showPage.jsp");
dispatcher.forward(request, response);
}
};
// CatalogItem[] items = {
// new CatalogItem("01","Java Servlet Programming", 29.95),
// new CatalogItem("02","Oracle Database Programming",48.95),
// new CatalogItem("03","System Analysis and Design With UML",14.95),
// new CatalogItem("04","Object Oriented Software engineering",35.99),
// new CatalogItem("05","Java Web Services",27.99),
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request,response);
}
}
| 3,893 | 0.619023 | 0.584505 | 97 | 39.319588 | 31.005003 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.237113 | false | false | 4 |
49a8036f8352d9f7b9ba77871f9c5fb56b5711c9 | 29,274,497,147,665 | 627ffdda3213454c292643ad275fd2d71aa71310 | /JieLinkDevOpsServer/src/main/java/com/jieshun/devopsserver/controller/package-info.java | b3585fe3b67736adf66bc65f23f497698e6826d3 | [
"Apache-2.0"
] | permissive | loveraindeme/JieLink.DevOps | https://github.com/loveraindeme/JieLink.DevOps | 399b1b1a2818433f9fd3f5b40deedf845c9b60e9 | 1927f740ea1a671e32d921b1b2a7a61ded9d5257 | refs/heads/master | 2023-08-27T21:29:42.283000 | 2021-11-13T07:46:00 | 2021-11-13T07:46:00 | 418,384,008 | 0 | 0 | Apache-2.0 | true | 2021-11-13T07:46:01 | 2021-10-18T07:07:11 | 2021-11-13T07:42:47 | 2021-11-13T07:46:00 | 20,392 | 0 | 0 | 0 | C# | false | false | package com.jieshun.devopsserver.controller; | UTF-8 | Java | 44 | java | package-info.java | Java | [] | null | [] | package com.jieshun.devopsserver.controller; | 44 | 0.886364 | 0.886364 | 1 | 44 | 0 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
a04a1e0fb0478cfb3674e7c96fe0dc76466d9eef | 7,301,444,451,511 | c063f941a02efb6e29ea9bce19cb2030a47bdbb9 | /app/src/main/java/com/monresto/acidlabs/monresto/UI/Main/MainActivity.java | 3fdcdb08e90e971384b2013b04f78811db43840c | [
"MIT"
] | permissive | IsmailZe/HuaweiMonresto | https://github.com/IsmailZe/HuaweiMonresto | 3fc86fa25b4720d483379c72ac4ec1efb1a8cdcc | 91014430d53b966cfbac71944af698ff339ba7c3 | refs/heads/master | 2023-02-19T08:06:44.193000 | 2021-01-22T20:21:59 | 2021-01-22T20:21:59 | 332,047,473 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.monresto.acidlabs.monresto.UI.Main;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.android.volley.VolleyError;
import com.facebook.appevents.AppEventsConstants;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.monresto.acidlabs.monresto.Config;
import com.monresto.acidlabs.monresto.GPSTracker;
import com.monresto.acidlabs.monresto.Model.Address;
import com.monresto.acidlabs.monresto.Model.Restaurant;
import com.monresto.acidlabs.monresto.Model.Semsem;
import com.monresto.acidlabs.monresto.Model.ShoppingCart;
import com.monresto.acidlabs.monresto.Model.Speciality;
import com.monresto.acidlabs.monresto.Model.User;
import com.monresto.acidlabs.monresto.ObjectSerializer;
import com.monresto.acidlabs.monresto.PlacePickerDialog;
import com.monresto.acidlabs.monresto.R;
import com.monresto.acidlabs.monresto.Service.Restaurant.RestaurantAsyncResponse;
import com.monresto.acidlabs.monresto.Service.Restaurant.RestaurantService;
import com.monresto.acidlabs.monresto.Service.User.UserAsyncResponse;
import com.monresto.acidlabs.monresto.Service.User.UserService;
import com.monresto.acidlabs.monresto.UI.Cart.CartActivity;
import com.monresto.acidlabs.monresto.UI.Profile.ProfileActivity;
import com.monresto.acidlabs.monresto.UI.User.LoginActivity;
import com.monresto.acidlabs.monresto.UI.User.SelectAddressActivity;
import com.monresto.acidlabs.monresto.Utilities;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseSequence;
import uk.co.deanwild.materialshowcaseview.ShowcaseConfig;
//Testing fetch information from api
public class MainActivity extends AppCompatActivity implements RestaurantAsyncResponse, UserAsyncResponse, SwipeRefreshLayout.OnRefreshListener, MaterialSearchBar.OnSearchActionListener {
@BindView(R.id.home_profile_icon)
ImageView home_profile_icon;
@BindView(R.id.home_close)
ImageView home_close;
@BindView(R.id.stores_recyclerview)
RecyclerView stores_recyclerview;
@BindView(R.id.restaurants_swiper)
SwipeRefreshLayout restaurants_swiper;
@BindView(R.id.status_restaurants)
ConstraintLayout status_restaurants;
@BindView(R.id.cart_frame)
FrameLayout cart_frame;
@BindView(R.id.cart_quantity)
TextView cart_quantity;
@BindView(R.id.cart_total)
TextView cart_total;
@BindView(R.id.deliveryLabel)
TextView deliveryLabel;
@BindView(R.id.change_address_container)
LinearLayout change_address_container;
GPSTracker gpsTracker;
Geocoder geocoder;
boolean list_init = false;
private ArrayList<Restaurant> searchList;
private ArrayList<Speciality> specialities;
private boolean firstResume;
private FusedLocationProviderClient mFusedLocationClient;
private UserService userService;
private RestaurantService service;
private RecyclerViewAdapter recyclerViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
restaurants_swiper.setOnRefreshListener(this);
stores_recyclerview.setNestedScrollingEnabled(false);
firstResume = true;
init();
}
public void init() {
gpsTracker = new GPSTracker(this);
service = new RestaurantService(this);
userService = new UserService(this);
List<android.location.Address> addresses;
geocoder = new Geocoder(this);
service.getDetails(251);
try {
if (User.getInstance() != null && User.getInstance().getSelectedAddress() != null)
deliveryLabel.setText(User.getInstance().getSelectedAddress().getAdresse());
else {
addresses = geocoder.getFromLocation(Semsem.getLat(), Semsem.getLon(), 3);
if (addresses != null && !addresses.isEmpty()) {
deliveryLabel.setText(addresses.get(0).getAddressLine(0));
if (deliveryLabel.getText().equals(""))
deliveryLabel.setText("Adresse inconnue");
} else
deliveryLabel.setText("Adresse inconnue");
}
} catch (IOException e) {
e.printStackTrace();
}
if (getIntent().getStringExtra("serviceType") != null) {
service.getRestoByRubrique(Semsem.getLat(), Semsem.getLon(), getIntent().getStringExtra("serviceType"));
// service.getRestoByRubrique(33.824944f, 8.396075f, getIntent().getStringExtra("serviceType"));
} else
service.getAll(Semsem.getLat(), Semsem.getLon());
// service.getAll(33.82f, 8.39f);
service.getSpecialities();
stores_recyclerview.setLayoutManager(new LinearLayoutManager(this));
change_address_container.setOnClickListener(e -> {
if (User.getInstance() != null) {
Intent intent = new Intent(this, SelectAddressActivity.class);
startActivity(intent);
}
});
home_profile_icon.setOnClickListener(view -> {
Intent intent;
if (User.getInstance() == null)
intent = new Intent(this, LoginActivity.class);
else
intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
});
cart_frame.setOnClickListener(view -> {
Intent intent;
intent = new Intent(this, CartActivity.class);
startActivity(intent);
});
home_close.setOnClickListener(view -> {
finish();
});
}
@Override
public void onListReceived(ArrayList<Restaurant> restaurantList, int status) {
Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "resto");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, restaurantList.toString());
Config.logger.logEvent("Rechercher",
restaurantList.size(),
params);
Semsem.getInstance().setRestaurants(restaurantList);
if (ShoppingCart.getInstance() != null && !ShoppingCart.getInstance().isEmpty())
updateHomeCart();
if (ShoppingCart.getInstance() != null && Semsem.getInstance().findRestaurant(ShoppingCart.getInstance().getRestoID()) == null) {
ShoppingCart.getInstance().clear();
updateHomeCart();
}
if (!restaurantList.isEmpty()) {
try {
if (ShoppingCart.getInstance() != null && ShoppingCart.getInstance().getCartSubTotal() > 0) {
cart_frame.setVisibility(View.VISIBLE);
} else {
cart_frame.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
restaurants_swiper.setVisibility(View.VISIBLE);
status_restaurants.setVisibility(View.INVISIBLE);
populateRecyclerView(restaurantList);
if (status == 10) {
Utilities.statusUnavailable(this, "Suite à une forte demande, cette zone est fermée", status_restaurants, restaurants_swiper);
}
if (!list_init) {
//Load saved shopping cart
SharedPreferences sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
String serialItems;
if (sharedPreferences.contains("items")) {
serialItems = sharedPreferences.getString("items", "");
ShoppingCart shoppingCart = (ShoppingCart) ObjectSerializer.deserialize(serialItems);
if (shoppingCart != null && Semsem.getInstance().findRestaurant(shoppingCart.getRestoID()) != null) {
ShoppingCart.setInstance((ShoppingCart) ObjectSerializer.deserialize(serialItems));
updateHomeCart();
}
}
list_init = true;
}
} else {
Utilities.statusChangerUnavailable(this, "Aucun restaurant trouvé", status_restaurants, restaurants_swiper);
}
ShowcaseConfig configs = new ShowcaseConfig();
configs.setDelay(500);
configs.setMaskColor(Color.BLACK);
// half second between each showcase view
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, "2");
sequence.setConfig(configs);
sequence.addSequenceItem(change_address_container,
"Vous pouvez changer de position rapidement", "SUIVANT");
if (cart_frame.isShown())
sequence.addSequenceItem(cart_frame,
"Accédez au panier fluidement", "COMPRIS");
sequence.start();
}
@Override
public void onSpecialitiesReceived(ArrayList<Speciality> specialities) {
this.specialities = specialities;
if (recyclerViewAdapter == null)
recyclerViewAdapter = new RecyclerViewAdapter(this);
recyclerViewAdapter.setSpecialities(specialities);
}
@Override
public void onServerDown() {
Utilities.statusChanger(this, R.layout.fragment_breakdown, status_restaurants, restaurants_swiper);
}
@Override
public void onServerHighDemand() {
Utilities.statusChanger(this, R.layout.fragment_highdemand, status_restaurants, restaurants_swiper);
}
@Override
public void onNoRestaurantsFound() {
Utilities.statusChanger(this, R.layout.fragment_unavailable, status_restaurants, restaurants_swiper);
}
@Override
public void onError(VolleyError error) {
}
public void populateRecyclerView(ArrayList<Restaurant> restaurantList) {
if (recyclerViewAdapter == null)
recyclerViewAdapter = new RecyclerViewAdapter(this, restaurantList);
else recyclerViewAdapter.setRestaurants(restaurantList);
stores_recyclerview.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
@Override
public void onRefresh() {
if (getIntent().getStringExtra("serviceType") != null) {
service.getRestoByRubrique(Semsem.getLat(), Semsem.getLon(), getIntent().getStringExtra("serviceType"));
} else
service.getAll(Semsem.getLat(), Semsem.getLon());
restaurants_swiper.setRefreshing(false);
}
@Override
public void onBackPressed() {
finish();
/*
//// SCROLL TO TOP, APPARENTLY NOT LIKED BY EVERYONE...
LinearLayoutManager layoutManager = (LinearLayoutManager) stores_recyclerview.getLayoutManager();
assert layoutManager != null;
if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
super.onBackPressed();
} else {
stores_recyclerview.smoothScrollToPosition(0);
}*/
}
@Override
protected void onResume() {
super.onResume();
if (firstResume) {
firstResume = false;
Semsem.locationChanged = false;
} else {
if (Semsem.locationChanged) {
Semsem.locationChanged = false;
Utilities.statusChanger(this, R.layout.fragment_loading, status_restaurants, restaurants_swiper);
cart_frame.setVisibility(View.INVISIBLE);
service.getAll(Semsem.getLat(), Semsem.getLon());
service.getSpecialities();
List<android.location.Address> addresses;
geocoder = new Geocoder(this);
try {
if (User.getInstance() != null && User.getInstance().getSelectedAddress() != null)
deliveryLabel.setText(User.getInstance().getSelectedAddress().getAdresse());
else {
addresses = geocoder.getFromLocation(Semsem.getLat(), Semsem.getLon(), 3);
if (addresses != null && !addresses.isEmpty()) {
deliveryLabel.setText(addresses.get(0).getAddressLine(0));
if (deliveryLabel.getText().equals(""))
deliveryLabel.setText("Adresse inconnue");
} else
deliveryLabel.setText("Adresse inconnue");
}
} catch (IOException e) {
e.printStackTrace();
}
}
updateHomeCart();
}
}
@Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
onRefresh();
}
@Override
public void onSearchConfirmed(CharSequence text) {
searchList = new ArrayList<>();
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getName().toLowerCase().contains(text.toString().toLowerCase())) {
searchList.add(restaurant);
}
}
if (!searchList.isEmpty()) {
populateRecyclerView(searchList);
try {
Utilities.hideKeyboard(this);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Aucune donnée trouvée", Toast.LENGTH_SHORT).show();
try {
Utilities.hideKeyboard(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void searchWithSpeciality(Speciality speciality) {
ArrayList<Restaurant> searchList = new ArrayList<>();
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
for (Speciality currSpeciality : restaurant.getSpecialities()) {
if (currSpeciality.getTitle().equals(speciality.getTitle()))
searchList.add(restaurant);
}
}
populateRecyclerView(searchList);
}
public void searchWithFilter(int filter) {
ArrayList<Restaurant> searchList = new ArrayList<>();
switch (filter) {
case Semsem.FILTER_OPEN: {
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getState().toLowerCase().equals("open"))
searchList.add(restaurant);
}
}
break;
case Semsem.FILTER_PROMO: {
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getWithPromotion() != 0)
searchList.add(restaurant);
}
}
break;
case Semsem.FILTER_NOTE: {
searchList = Restaurant.sort(Semsem.getInstance().getRestaurants(), (e1, e2) -> e1.getRate() > e2.getRate() ? -1 : 1);
}
break;
case Semsem.FILTER_TIME: {
searchList = Restaurant.sort(Semsem.getInstance().getRestaurants(), (e1, e2) -> e1.getEstimatedTime() - e2.getEstimatedTime());
}
break;
}
populateRecyclerView(searchList);
}
public void resetRecyclerView() {
populateRecyclerView(Semsem.getInstance().getRestaurants());
}
@Override
public void onButtonClicked(int buttonCode) {
}
@SuppressLint("SetTextI18n")
public void updateHomeCart() {
cart_quantity.setText(String.valueOf(ShoppingCart.getInstance().getItems().size()));
DecimalFormat dec = new DecimalFormat("#0.00");
cart_total.setText(dec.format(ShoppingCart.getInstance().getCartSubTotal()) + " DT");
try {
if (ShoppingCart.getInstance().getCartSubTotal() == 0) {
cart_frame.setVisibility(View.GONE);
} else {
cart_frame.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void onUserLogin(User user) {
userService.getDetails(user.getId(), true);
}
@Override
public void onUserDetailsReceived(User user) {
userService.getAddress(User.getInstance().getId());
}
@Override
public void onAddressListReceived(ArrayList<Address> addresses) {
if (User.getInstance() != null)
User.getInstance().setAddresses(addresses);
Intent intent = new Intent(this, SelectAddressActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Config.REQUEST_CODE_FILTER_SELECT && data != null) {
int filter = data.getIntExtra("filter", 0);
searchWithFilter(filter);
}
}
}
}
| UTF-8 | Java | 17,959 | java | MainActivity.java | Java | [] | null | [] | package com.monresto.acidlabs.monresto.UI.Main;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.android.volley.VolleyError;
import com.facebook.appevents.AppEventsConstants;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.monresto.acidlabs.monresto.Config;
import com.monresto.acidlabs.monresto.GPSTracker;
import com.monresto.acidlabs.monresto.Model.Address;
import com.monresto.acidlabs.monresto.Model.Restaurant;
import com.monresto.acidlabs.monresto.Model.Semsem;
import com.monresto.acidlabs.monresto.Model.ShoppingCart;
import com.monresto.acidlabs.monresto.Model.Speciality;
import com.monresto.acidlabs.monresto.Model.User;
import com.monresto.acidlabs.monresto.ObjectSerializer;
import com.monresto.acidlabs.monresto.PlacePickerDialog;
import com.monresto.acidlabs.monresto.R;
import com.monresto.acidlabs.monresto.Service.Restaurant.RestaurantAsyncResponse;
import com.monresto.acidlabs.monresto.Service.Restaurant.RestaurantService;
import com.monresto.acidlabs.monresto.Service.User.UserAsyncResponse;
import com.monresto.acidlabs.monresto.Service.User.UserService;
import com.monresto.acidlabs.monresto.UI.Cart.CartActivity;
import com.monresto.acidlabs.monresto.UI.Profile.ProfileActivity;
import com.monresto.acidlabs.monresto.UI.User.LoginActivity;
import com.monresto.acidlabs.monresto.UI.User.SelectAddressActivity;
import com.monresto.acidlabs.monresto.Utilities;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseSequence;
import uk.co.deanwild.materialshowcaseview.ShowcaseConfig;
//Testing fetch information from api
public class MainActivity extends AppCompatActivity implements RestaurantAsyncResponse, UserAsyncResponse, SwipeRefreshLayout.OnRefreshListener, MaterialSearchBar.OnSearchActionListener {
@BindView(R.id.home_profile_icon)
ImageView home_profile_icon;
@BindView(R.id.home_close)
ImageView home_close;
@BindView(R.id.stores_recyclerview)
RecyclerView stores_recyclerview;
@BindView(R.id.restaurants_swiper)
SwipeRefreshLayout restaurants_swiper;
@BindView(R.id.status_restaurants)
ConstraintLayout status_restaurants;
@BindView(R.id.cart_frame)
FrameLayout cart_frame;
@BindView(R.id.cart_quantity)
TextView cart_quantity;
@BindView(R.id.cart_total)
TextView cart_total;
@BindView(R.id.deliveryLabel)
TextView deliveryLabel;
@BindView(R.id.change_address_container)
LinearLayout change_address_container;
GPSTracker gpsTracker;
Geocoder geocoder;
boolean list_init = false;
private ArrayList<Restaurant> searchList;
private ArrayList<Speciality> specialities;
private boolean firstResume;
private FusedLocationProviderClient mFusedLocationClient;
private UserService userService;
private RestaurantService service;
private RecyclerViewAdapter recyclerViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
restaurants_swiper.setOnRefreshListener(this);
stores_recyclerview.setNestedScrollingEnabled(false);
firstResume = true;
init();
}
public void init() {
gpsTracker = new GPSTracker(this);
service = new RestaurantService(this);
userService = new UserService(this);
List<android.location.Address> addresses;
geocoder = new Geocoder(this);
service.getDetails(251);
try {
if (User.getInstance() != null && User.getInstance().getSelectedAddress() != null)
deliveryLabel.setText(User.getInstance().getSelectedAddress().getAdresse());
else {
addresses = geocoder.getFromLocation(Semsem.getLat(), Semsem.getLon(), 3);
if (addresses != null && !addresses.isEmpty()) {
deliveryLabel.setText(addresses.get(0).getAddressLine(0));
if (deliveryLabel.getText().equals(""))
deliveryLabel.setText("Adresse inconnue");
} else
deliveryLabel.setText("Adresse inconnue");
}
} catch (IOException e) {
e.printStackTrace();
}
if (getIntent().getStringExtra("serviceType") != null) {
service.getRestoByRubrique(Semsem.getLat(), Semsem.getLon(), getIntent().getStringExtra("serviceType"));
// service.getRestoByRubrique(33.824944f, 8.396075f, getIntent().getStringExtra("serviceType"));
} else
service.getAll(Semsem.getLat(), Semsem.getLon());
// service.getAll(33.82f, 8.39f);
service.getSpecialities();
stores_recyclerview.setLayoutManager(new LinearLayoutManager(this));
change_address_container.setOnClickListener(e -> {
if (User.getInstance() != null) {
Intent intent = new Intent(this, SelectAddressActivity.class);
startActivity(intent);
}
});
home_profile_icon.setOnClickListener(view -> {
Intent intent;
if (User.getInstance() == null)
intent = new Intent(this, LoginActivity.class);
else
intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
});
cart_frame.setOnClickListener(view -> {
Intent intent;
intent = new Intent(this, CartActivity.class);
startActivity(intent);
});
home_close.setOnClickListener(view -> {
finish();
});
}
@Override
public void onListReceived(ArrayList<Restaurant> restaurantList, int status) {
Bundle params = new Bundle();
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "resto");
params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, restaurantList.toString());
Config.logger.logEvent("Rechercher",
restaurantList.size(),
params);
Semsem.getInstance().setRestaurants(restaurantList);
if (ShoppingCart.getInstance() != null && !ShoppingCart.getInstance().isEmpty())
updateHomeCart();
if (ShoppingCart.getInstance() != null && Semsem.getInstance().findRestaurant(ShoppingCart.getInstance().getRestoID()) == null) {
ShoppingCart.getInstance().clear();
updateHomeCart();
}
if (!restaurantList.isEmpty()) {
try {
if (ShoppingCart.getInstance() != null && ShoppingCart.getInstance().getCartSubTotal() > 0) {
cart_frame.setVisibility(View.VISIBLE);
} else {
cart_frame.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
restaurants_swiper.setVisibility(View.VISIBLE);
status_restaurants.setVisibility(View.INVISIBLE);
populateRecyclerView(restaurantList);
if (status == 10) {
Utilities.statusUnavailable(this, "Suite à une forte demande, cette zone est fermée", status_restaurants, restaurants_swiper);
}
if (!list_init) {
//Load saved shopping cart
SharedPreferences sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
String serialItems;
if (sharedPreferences.contains("items")) {
serialItems = sharedPreferences.getString("items", "");
ShoppingCart shoppingCart = (ShoppingCart) ObjectSerializer.deserialize(serialItems);
if (shoppingCart != null && Semsem.getInstance().findRestaurant(shoppingCart.getRestoID()) != null) {
ShoppingCart.setInstance((ShoppingCart) ObjectSerializer.deserialize(serialItems));
updateHomeCart();
}
}
list_init = true;
}
} else {
Utilities.statusChangerUnavailable(this, "Aucun restaurant trouvé", status_restaurants, restaurants_swiper);
}
ShowcaseConfig configs = new ShowcaseConfig();
configs.setDelay(500);
configs.setMaskColor(Color.BLACK);
// half second between each showcase view
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, "2");
sequence.setConfig(configs);
sequence.addSequenceItem(change_address_container,
"Vous pouvez changer de position rapidement", "SUIVANT");
if (cart_frame.isShown())
sequence.addSequenceItem(cart_frame,
"Accédez au panier fluidement", "COMPRIS");
sequence.start();
}
@Override
public void onSpecialitiesReceived(ArrayList<Speciality> specialities) {
this.specialities = specialities;
if (recyclerViewAdapter == null)
recyclerViewAdapter = new RecyclerViewAdapter(this);
recyclerViewAdapter.setSpecialities(specialities);
}
@Override
public void onServerDown() {
Utilities.statusChanger(this, R.layout.fragment_breakdown, status_restaurants, restaurants_swiper);
}
@Override
public void onServerHighDemand() {
Utilities.statusChanger(this, R.layout.fragment_highdemand, status_restaurants, restaurants_swiper);
}
@Override
public void onNoRestaurantsFound() {
Utilities.statusChanger(this, R.layout.fragment_unavailable, status_restaurants, restaurants_swiper);
}
@Override
public void onError(VolleyError error) {
}
public void populateRecyclerView(ArrayList<Restaurant> restaurantList) {
if (recyclerViewAdapter == null)
recyclerViewAdapter = new RecyclerViewAdapter(this, restaurantList);
else recyclerViewAdapter.setRestaurants(restaurantList);
stores_recyclerview.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
@Override
public void onRefresh() {
if (getIntent().getStringExtra("serviceType") != null) {
service.getRestoByRubrique(Semsem.getLat(), Semsem.getLon(), getIntent().getStringExtra("serviceType"));
} else
service.getAll(Semsem.getLat(), Semsem.getLon());
restaurants_swiper.setRefreshing(false);
}
@Override
public void onBackPressed() {
finish();
/*
//// SCROLL TO TOP, APPARENTLY NOT LIKED BY EVERYONE...
LinearLayoutManager layoutManager = (LinearLayoutManager) stores_recyclerview.getLayoutManager();
assert layoutManager != null;
if (layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
super.onBackPressed();
} else {
stores_recyclerview.smoothScrollToPosition(0);
}*/
}
@Override
protected void onResume() {
super.onResume();
if (firstResume) {
firstResume = false;
Semsem.locationChanged = false;
} else {
if (Semsem.locationChanged) {
Semsem.locationChanged = false;
Utilities.statusChanger(this, R.layout.fragment_loading, status_restaurants, restaurants_swiper);
cart_frame.setVisibility(View.INVISIBLE);
service.getAll(Semsem.getLat(), Semsem.getLon());
service.getSpecialities();
List<android.location.Address> addresses;
geocoder = new Geocoder(this);
try {
if (User.getInstance() != null && User.getInstance().getSelectedAddress() != null)
deliveryLabel.setText(User.getInstance().getSelectedAddress().getAdresse());
else {
addresses = geocoder.getFromLocation(Semsem.getLat(), Semsem.getLon(), 3);
if (addresses != null && !addresses.isEmpty()) {
deliveryLabel.setText(addresses.get(0).getAddressLine(0));
if (deliveryLabel.getText().equals(""))
deliveryLabel.setText("Adresse inconnue");
} else
deliveryLabel.setText("Adresse inconnue");
}
} catch (IOException e) {
e.printStackTrace();
}
}
updateHomeCart();
}
}
@Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
onRefresh();
}
@Override
public void onSearchConfirmed(CharSequence text) {
searchList = new ArrayList<>();
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getName().toLowerCase().contains(text.toString().toLowerCase())) {
searchList.add(restaurant);
}
}
if (!searchList.isEmpty()) {
populateRecyclerView(searchList);
try {
Utilities.hideKeyboard(this);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "Aucune donnée trouvée", Toast.LENGTH_SHORT).show();
try {
Utilities.hideKeyboard(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void searchWithSpeciality(Speciality speciality) {
ArrayList<Restaurant> searchList = new ArrayList<>();
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
for (Speciality currSpeciality : restaurant.getSpecialities()) {
if (currSpeciality.getTitle().equals(speciality.getTitle()))
searchList.add(restaurant);
}
}
populateRecyclerView(searchList);
}
public void searchWithFilter(int filter) {
ArrayList<Restaurant> searchList = new ArrayList<>();
switch (filter) {
case Semsem.FILTER_OPEN: {
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getState().toLowerCase().equals("open"))
searchList.add(restaurant);
}
}
break;
case Semsem.FILTER_PROMO: {
for (Restaurant restaurant : Semsem.getInstance().getRestaurants()) {
if (restaurant.getWithPromotion() != 0)
searchList.add(restaurant);
}
}
break;
case Semsem.FILTER_NOTE: {
searchList = Restaurant.sort(Semsem.getInstance().getRestaurants(), (e1, e2) -> e1.getRate() > e2.getRate() ? -1 : 1);
}
break;
case Semsem.FILTER_TIME: {
searchList = Restaurant.sort(Semsem.getInstance().getRestaurants(), (e1, e2) -> e1.getEstimatedTime() - e2.getEstimatedTime());
}
break;
}
populateRecyclerView(searchList);
}
public void resetRecyclerView() {
populateRecyclerView(Semsem.getInstance().getRestaurants());
}
@Override
public void onButtonClicked(int buttonCode) {
}
@SuppressLint("SetTextI18n")
public void updateHomeCart() {
cart_quantity.setText(String.valueOf(ShoppingCart.getInstance().getItems().size()));
DecimalFormat dec = new DecimalFormat("#0.00");
cart_total.setText(dec.format(ShoppingCart.getInstance().getCartSubTotal()) + " DT");
try {
if (ShoppingCart.getInstance().getCartSubTotal() == 0) {
cart_frame.setVisibility(View.GONE);
} else {
cart_frame.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void onUserLogin(User user) {
userService.getDetails(user.getId(), true);
}
@Override
public void onUserDetailsReceived(User user) {
userService.getAddress(User.getInstance().getId());
}
@Override
public void onAddressListReceived(ArrayList<Address> addresses) {
if (User.getInstance() != null)
User.getInstance().setAddresses(addresses);
Intent intent = new Intent(this, SelectAddressActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Config.REQUEST_CODE_FILTER_SELECT && data != null) {
int filter = data.getIntExtra("filter", 0);
searchWithFilter(filter);
}
}
}
}
| 17,959 | 0.634323 | 0.631092 | 475 | 36.795788 | 30.393532 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.591579 | false | false | 4 |
612dfd9e91290dbb83f99002b269252147224f21 | 34,153,579,947,079 | b1c6b6fda9a40b9ae1d1811db13d90d6bb38bb1a | /src/com/asiainfo/crm/ssm/segment/common/SegSqlBuilder.java | c95b1b7ff113a36cefd2fb8e7a0c7aa6e5e127d9 | [] | no_license | feiniaoying/Inet | https://github.com/feiniaoying/Inet | e7ef42ca9578f463d11e0faca2308afa0804019e | 5cb1918f7ba03024dc3b20aa32254abb2f3ec2fd | refs/heads/master | 2016-06-06T20:48:56.142000 | 2016-03-05T14:50:58 | 2016-03-05T14:50:58 | 53,204,179 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author Ethan Huang
* AisiaInfo. ChengDu Branch
* 下午04:02:14 2012-4-6
*/
package com.asiainfo.crm.ssm.segment.common;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import com.ai.appframe2.util.StringUtils;
import com.asiainfo.crm.ssm.campaign.ivalues.IBOSsmCampSegmentRelValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMarketSegmentValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMarketingTargetValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMktTgtImpLogValue;
/**
*
*
*/
public class SegSqlBuilder {
/**
* 返回根据市场细分ID查询营销目标sql
* @param marketSegmentId
* @param createDate
* @param map
* @param sql
* @return
*/
public static String getMktTgtBySegIdSql(long marketSegmentId,
Timestamp createDate, HashMap map) {
String sql = "MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID";
map.put("MARKET_SEGMENT_ID", marketSegmentId);
map.put("SEG_CREATE_DATE", createDate);
return sql;
}
/**
* 返回根据营销目标id查询目标属性sql
* @param mktTgtId
* @param createDate
* @param map
* @return
*/
public static String getMktTgtAttrByTgtId(long mktTgtId,
Timestamp createDate, HashMap map) {
String sql = "MKT_TGT_ID = :MKT_TGT_ID";
map.put("MKT_TGT_ID", mktTgtId);
map.put("SEG_CREATE_DATE", createDate);//分表
return sql;
}
/**
* 拼接市场细分查询条件sql
* @param sb
* @param map
* @param segId
* @param segName
* @param segCate
* @param state
* @param segType
* @param time
*/
public static void createCondition(StringBuffer sb, HashMap map,
String segId, String segName, String segCate, String state,
String segType, String time,String cityId) {
if(!StringUtils.emptyString(segId)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentId).append(" like :SEG_ID");
map.put("SEG_ID", new StringBuffer("%").append(segId.trim()).append("%").toString());
// map.put("S_QnrId", new StringBuffer("%").append(qnrId.trim()).append("%"));
}
if(!StringUtils.emptyString(segName)){
sb.append(" and upper(").append(IBOSsmMarketSegmentValue.S_MarketSegmentName).append( ") like :S_MarketSegmentName");
map.put("S_MarketSegmentName", new StringBuffer("%").append(segName.trim().toUpperCase()).append("%").toString());
}
if(!StringUtils.emptyString(segCate)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentCategory).append( " = :S_MarketSegmentCategory");
map.put("S_MarketSegmentCategory", segCate);
}
if(!StringUtils.emptyString(state)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_State).append( " = :S_State");
map.put("S_State", state);
}
if(!StringUtils.emptyString(segType)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentType).append( " = :S_MarketSegmentType");
map.put("S_MarketSegmentType", segType);
}
if(!StringUtils.emptyString(time)){
sb.append(" and sysdate between EFFECTIVE_DATE and EXPIRE_DATE ");
}
sb.append(" and state <>'10F'");
sb.append(" order by done_date desc");
}
/**
* 拼接营销目标临时表查询条件
* @param sb
* @param map
* @param segId
* @param batchId
* @param number
* @param state
*/
public static void createLogCondition(StringBuffer sb, HashMap map,
String segId, String batchId, String number, String state) {
if(!StringUtils.emptyString(segId)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_MarketSegmentId).append("=:S_MarketSegmentId");
map.put("S_MarketSegmentId", segId);
}
if(!StringUtils.emptyString(batchId)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_ImportBatchId).append("=:S_ImportBatchId");
map.put("S_ImportBatchId", batchId);
}
if(!StringUtils.emptyString(number)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_AccessNumber).append("=:S_AccessNumber");
map.put("S_AccessNumber", number.trim());
}
if(!StringUtils.emptyString(state)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_State).append("=:S_State");
map.put("S_State", state);
}
}
/**
* 根据营销活动id返回对应市场细分信息sql
* @param mktCampId
* @param map
* @return
*/
public static String getSegRelSql(String mktCampId, HashMap map) {
StringBuffer sb = new StringBuffer();
sb.append("select * from SSM_MARKET_SEGMENT r1 left join SSM_CAMP_SEGMENT_REL r2 on r1.market_segment_id = r2.market_segment_id where r2.").append(IBOSsmCampSegmentRelValue.S_MktCampId).append(" = :MKT_CAMP_ID");
map.put("MKT_CAMP_ID", mktCampId);
return sb.toString();
}
/**
* 拼接根据市场细分id查询营销目标Sql
* @param object
* @param parse
* @param tar
* @return
*/
public static String getMktTgtSqlBySegId(long segId, Date segCreateDate,
HashMap tar) {
StringBuffer sb = new StringBuffer(" 1=1 ");
sb.append(" and ").append(IBOSsmMarketingTargetValue.S_MarketSegmentId).append(" =:MARKET_SEGMENT_ID");
tar.put("MARKET_SEGMENT_ID", segId);
tar.put("SEG_CREATE_DATE", segCreateDate);
return sb.toString();
}
/**
* 返回根据市场细分id和号码查询营销目标sql
* @param segId
* @param accessNumber
* @param segCreateDate
* @param map
* @return
*/
public static String getMktTgtBySegIdAndNumberSql(String segId,
String accessNumber, String segCreateDate, HashMap map) throws Exception{
StringBuffer where = new StringBuffer(" 1=1 ");
if(segId!=null&&!segId.equals("")&&!segId.equals("0")){
where.append("and ").append(IBOSsmMarketingTargetValue.S_MarketSegmentId).append(" = :MARKET_SEGMENT_ID");
map.put("MARKET_SEGMENT_ID", segId);
}
if(accessNumber!=null&&!accessNumber.equals("")&&!accessNumber.equals("0")){
where.append(" and ").append(IBOSsmMarketingTargetValue.S_AccessNumber).append(" = :ACCESS_NUMBER");
map.put("ACCESS_NUMBER", accessNumber);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
map.put("SEG_CREATE_DATE", sdf.parse(segCreateDate));
return where.toString();
}
/**
* 返回根据市场细分id和批次id查询营销目标临时表sql
* @param segId
* @param batchId
* @param segCreateDate
* @param map
* @return
*/
public static String getTarLogBySegIdAndBatchId(String segId,
String batchId, Timestamp segCreateDate, HashMap map) {
String sql = " MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID and IMPORT_BATCH_ID = :IMPORT_BATCH_ID";
map.put("MARKET_SEGMENT_ID", segId);
map.put("IMPORT_BATCH_ID", batchId);//仅查询出临时表中此批次的导入数据
map.put("SEG_CREATE_DATE", segCreateDate);//分表需要
return sql;
}
/**
* 根据营销活动ID返回细分关系SQL
* @param campId
* @param map
* @return
*/
public static String getSegRelSqlByCampId(String campId, HashMap map) {
String sql = " MKT_CAMP_ID = :MKT_CAMP_ID";
map.put("MKT_CAMP_ID", campId);
return sql;
}
/**
* @param phone
* @param segmentId
* @param segCreateDate
* @param map
* @return
*/
public static String gethasTgtInSegSql(String phone, String segmentId,
Timestamp segCreateDate, HashMap map) {
String sql = "ACCESS_NUMBER = :ACCESS_NUMBER and MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID and STATE = '10A'";
map.put("ACCESS_NUMBER", phone);
map.put("MARKET_SEGMENT_ID", segmentId);
map.put("SEG_CREATE_DATE", segCreateDate);
return sql;
}
}
| GB18030 | Java | 7,441 | java | SegSqlBuilder.java | Java | [
{
"context": "/**\n * @author Ethan Huang\n * AisiaInfo. ChengDu Branch\n * 下午04:02:14 2012-4",
"end": 27,
"score": 0.9998419880867004,
"start": 16,
"tag": "NAME",
"value": "Ethan Huang"
}
] | null | [] | /**
* @author <NAME>
* AisiaInfo. ChengDu Branch
* 下午04:02:14 2012-4-6
*/
package com.asiainfo.crm.ssm.segment.common;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import com.ai.appframe2.util.StringUtils;
import com.asiainfo.crm.ssm.campaign.ivalues.IBOSsmCampSegmentRelValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMarketSegmentValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMarketingTargetValue;
import com.asiainfo.crm.ssm.segment.ivalues.IBOSsmMktTgtImpLogValue;
/**
*
*
*/
public class SegSqlBuilder {
/**
* 返回根据市场细分ID查询营销目标sql
* @param marketSegmentId
* @param createDate
* @param map
* @param sql
* @return
*/
public static String getMktTgtBySegIdSql(long marketSegmentId,
Timestamp createDate, HashMap map) {
String sql = "MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID";
map.put("MARKET_SEGMENT_ID", marketSegmentId);
map.put("SEG_CREATE_DATE", createDate);
return sql;
}
/**
* 返回根据营销目标id查询目标属性sql
* @param mktTgtId
* @param createDate
* @param map
* @return
*/
public static String getMktTgtAttrByTgtId(long mktTgtId,
Timestamp createDate, HashMap map) {
String sql = "MKT_TGT_ID = :MKT_TGT_ID";
map.put("MKT_TGT_ID", mktTgtId);
map.put("SEG_CREATE_DATE", createDate);//分表
return sql;
}
/**
* 拼接市场细分查询条件sql
* @param sb
* @param map
* @param segId
* @param segName
* @param segCate
* @param state
* @param segType
* @param time
*/
public static void createCondition(StringBuffer sb, HashMap map,
String segId, String segName, String segCate, String state,
String segType, String time,String cityId) {
if(!StringUtils.emptyString(segId)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentId).append(" like :SEG_ID");
map.put("SEG_ID", new StringBuffer("%").append(segId.trim()).append("%").toString());
// map.put("S_QnrId", new StringBuffer("%").append(qnrId.trim()).append("%"));
}
if(!StringUtils.emptyString(segName)){
sb.append(" and upper(").append(IBOSsmMarketSegmentValue.S_MarketSegmentName).append( ") like :S_MarketSegmentName");
map.put("S_MarketSegmentName", new StringBuffer("%").append(segName.trim().toUpperCase()).append("%").toString());
}
if(!StringUtils.emptyString(segCate)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentCategory).append( " = :S_MarketSegmentCategory");
map.put("S_MarketSegmentCategory", segCate);
}
if(!StringUtils.emptyString(state)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_State).append( " = :S_State");
map.put("S_State", state);
}
if(!StringUtils.emptyString(segType)){
sb.append(" and ").append(IBOSsmMarketSegmentValue.S_MarketSegmentType).append( " = :S_MarketSegmentType");
map.put("S_MarketSegmentType", segType);
}
if(!StringUtils.emptyString(time)){
sb.append(" and sysdate between EFFECTIVE_DATE and EXPIRE_DATE ");
}
sb.append(" and state <>'10F'");
sb.append(" order by done_date desc");
}
/**
* 拼接营销目标临时表查询条件
* @param sb
* @param map
* @param segId
* @param batchId
* @param number
* @param state
*/
public static void createLogCondition(StringBuffer sb, HashMap map,
String segId, String batchId, String number, String state) {
if(!StringUtils.emptyString(segId)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_MarketSegmentId).append("=:S_MarketSegmentId");
map.put("S_MarketSegmentId", segId);
}
if(!StringUtils.emptyString(batchId)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_ImportBatchId).append("=:S_ImportBatchId");
map.put("S_ImportBatchId", batchId);
}
if(!StringUtils.emptyString(number)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_AccessNumber).append("=:S_AccessNumber");
map.put("S_AccessNumber", number.trim());
}
if(!StringUtils.emptyString(state)){
sb.append(" and ").append(IBOSsmMktTgtImpLogValue.S_State).append("=:S_State");
map.put("S_State", state);
}
}
/**
* 根据营销活动id返回对应市场细分信息sql
* @param mktCampId
* @param map
* @return
*/
public static String getSegRelSql(String mktCampId, HashMap map) {
StringBuffer sb = new StringBuffer();
sb.append("select * from SSM_MARKET_SEGMENT r1 left join SSM_CAMP_SEGMENT_REL r2 on r1.market_segment_id = r2.market_segment_id where r2.").append(IBOSsmCampSegmentRelValue.S_MktCampId).append(" = :MKT_CAMP_ID");
map.put("MKT_CAMP_ID", mktCampId);
return sb.toString();
}
/**
* 拼接根据市场细分id查询营销目标Sql
* @param object
* @param parse
* @param tar
* @return
*/
public static String getMktTgtSqlBySegId(long segId, Date segCreateDate,
HashMap tar) {
StringBuffer sb = new StringBuffer(" 1=1 ");
sb.append(" and ").append(IBOSsmMarketingTargetValue.S_MarketSegmentId).append(" =:MARKET_SEGMENT_ID");
tar.put("MARKET_SEGMENT_ID", segId);
tar.put("SEG_CREATE_DATE", segCreateDate);
return sb.toString();
}
/**
* 返回根据市场细分id和号码查询营销目标sql
* @param segId
* @param accessNumber
* @param segCreateDate
* @param map
* @return
*/
public static String getMktTgtBySegIdAndNumberSql(String segId,
String accessNumber, String segCreateDate, HashMap map) throws Exception{
StringBuffer where = new StringBuffer(" 1=1 ");
if(segId!=null&&!segId.equals("")&&!segId.equals("0")){
where.append("and ").append(IBOSsmMarketingTargetValue.S_MarketSegmentId).append(" = :MARKET_SEGMENT_ID");
map.put("MARKET_SEGMENT_ID", segId);
}
if(accessNumber!=null&&!accessNumber.equals("")&&!accessNumber.equals("0")){
where.append(" and ").append(IBOSsmMarketingTargetValue.S_AccessNumber).append(" = :ACCESS_NUMBER");
map.put("ACCESS_NUMBER", accessNumber);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
map.put("SEG_CREATE_DATE", sdf.parse(segCreateDate));
return where.toString();
}
/**
* 返回根据市场细分id和批次id查询营销目标临时表sql
* @param segId
* @param batchId
* @param segCreateDate
* @param map
* @return
*/
public static String getTarLogBySegIdAndBatchId(String segId,
String batchId, Timestamp segCreateDate, HashMap map) {
String sql = " MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID and IMPORT_BATCH_ID = :IMPORT_BATCH_ID";
map.put("MARKET_SEGMENT_ID", segId);
map.put("IMPORT_BATCH_ID", batchId);//仅查询出临时表中此批次的导入数据
map.put("SEG_CREATE_DATE", segCreateDate);//分表需要
return sql;
}
/**
* 根据营销活动ID返回细分关系SQL
* @param campId
* @param map
* @return
*/
public static String getSegRelSqlByCampId(String campId, HashMap map) {
String sql = " MKT_CAMP_ID = :MKT_CAMP_ID";
map.put("MKT_CAMP_ID", campId);
return sql;
}
/**
* @param phone
* @param segmentId
* @param segCreateDate
* @param map
* @return
*/
public static String gethasTgtInSegSql(String phone, String segmentId,
Timestamp segCreateDate, HashMap map) {
String sql = "ACCESS_NUMBER = :ACCESS_NUMBER and MARKET_SEGMENT_ID = :MARKET_SEGMENT_ID and STATE = '10A'";
map.put("ACCESS_NUMBER", phone);
map.put("MARKET_SEGMENT_ID", segmentId);
map.put("SEG_CREATE_DATE", segCreateDate);
return sql;
}
}
| 7,436 | 0.696341 | 0.692416 | 233 | 29.613733 | 31.189938 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.961373 | false | false | 4 |
80198c26fb297d4189f466a28ead499f0c4ba905 | 29,351,806,514,453 | 11a1190578ed1a44caeadef1f422597be9be69f5 | /forest/CPLibrary/Utilities/osmutils/.svn/text-base/StreetsPreprocessorTask.java.svn-base | c9ce23dd763c349015f94d646e15fa106eb6dc53 | [] | no_license | guaguakai/intrusionGame | https://github.com/guaguakai/intrusionGame | 29e685d3287d83ec09ffcaf03b4fb7f4acf757bd | a6925e00432e59cb02c65a60fdac3381d97bb364 | refs/heads/master | 2022-01-08T09:01:15.573000 | 2018-11-12T00:14:05 | 2018-11-12T00:14:05 | 154,755,856 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package osmutils;
import java.util.List;
import org.openstreetmap.osm.data.MemoryDataSet;
import org.openstreetmap.osm.data.Selector;
import org.openstreetmap.osmosis.core.domain.v0_6.Way;
//TODO RFCT komentar tridy
public class StreetsPreprocessorTask implements OsmImportTask,OsmWaySink {
private GraphBuilder builder;
public StreetsPreprocessorTask(GraphBuilder builder) {
this.builder = builder;
}
public void finish() {
builder.extractLargestConnectedComponent();
}
public Selector getSelector() {
TagFilter filter = new TagFilter();
filter.addIncludedTag("highway", "*");
filter.addExcludedTag("area", "yes");
// Do not include paths
filter.addExcludedTag("highway", "path");
filter.addExcludedTag("highway", "cycleway");
filter.addExcludedTag("highway", "footway");
filter.addExcludedTag("highway", "bridleway");
filter.addExcludedTag("highway", "byway");
filter.addExcludedTag("highway", "steps");
filter.addExcludedTag("highway", "pedestrian");
filter.addExcludedTag("highway", "track");
return new TagSelector(filter,false, true, false, true);
}
public void sink(Way way, MemoryDataSet dataset) {
OsmInterpreter interpreter = new OsmInterpreter(dataset);
List<ExtPath> paths = interpreter.interpret(way);
for (ExtPath path : paths) {
builder.add(path);
}
}
}
| UTF-8 | Java | 1,354 | StreetsPreprocessorTask.java.svn-base | Java | [] | null | [] | package osmutils;
import java.util.List;
import org.openstreetmap.osm.data.MemoryDataSet;
import org.openstreetmap.osm.data.Selector;
import org.openstreetmap.osmosis.core.domain.v0_6.Way;
//TODO RFCT komentar tridy
public class StreetsPreprocessorTask implements OsmImportTask,OsmWaySink {
private GraphBuilder builder;
public StreetsPreprocessorTask(GraphBuilder builder) {
this.builder = builder;
}
public void finish() {
builder.extractLargestConnectedComponent();
}
public Selector getSelector() {
TagFilter filter = new TagFilter();
filter.addIncludedTag("highway", "*");
filter.addExcludedTag("area", "yes");
// Do not include paths
filter.addExcludedTag("highway", "path");
filter.addExcludedTag("highway", "cycleway");
filter.addExcludedTag("highway", "footway");
filter.addExcludedTag("highway", "bridleway");
filter.addExcludedTag("highway", "byway");
filter.addExcludedTag("highway", "steps");
filter.addExcludedTag("highway", "pedestrian");
filter.addExcludedTag("highway", "track");
return new TagSelector(filter,false, true, false, true);
}
public void sink(Way way, MemoryDataSet dataset) {
OsmInterpreter interpreter = new OsmInterpreter(dataset);
List<ExtPath> paths = interpreter.interpret(way);
for (ExtPath path : paths) {
builder.add(path);
}
}
}
| 1,354 | 0.730428 | 0.728951 | 55 | 23.618181 | 22.026836 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.927273 | false | false | 4 |
|
b61f91916a94f0df94386c837a572b4b50a14c2f | 34,926,674,057,419 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/9/9_a6eba54056d53f7999a4a809613ea7c3fe006f15/SpectrumInMemory/9_a6eba54056d53f7999a4a809613ea7c3fe006f15_SpectrumInMemory_s.java | d8ae236ba3b6fc512fa3a60464c99bb86552726a | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package org.dawnsci.spectrum.ui.file;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.trace.ITrace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import uk.ac.diamond.scisoft.analysis.dataset.IDataset;
import uk.ac.diamond.scisoft.analysis.io.LoaderFactory;
public class SpectrumInMemory extends AbstractSpectrumFile implements ISpectrumFile {
Map<String,IDataset> datasets;
private String name;
private String longName;
public SpectrumInMemory(String longName, String name,IDataset xDataset ,Collection<IDataset> yDatasets, IPlottingSystem system) {
this.system = system;
this.name = name;
this.longName = longName;
datasets = new HashMap<String, IDataset>();
yDatasetNames = new ArrayList<String>(yDatasets.size());
useAxisDataset = false;
if (xDataset != null) {
useAxisDataset = true;
String dsName = xDataset.getName();
if (dsName == null) dsName = "xData";
datasets.put(dsName, xDataset);
xDatasetName = dsName;
}
//TODO make more robust to the same dataset names
int i = 0;
for (IDataset dataset : yDatasets) {
String dsName = dataset.getName();
if (dsName == null) dsName = "yData" + i;
datasets.put(dsName, dataset);
yDatasetNames.add(dsName);
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
@Override
public Collection<String> getDataNames() {
return getDatasetNames();
}
@Override
public IDataset getDataset(String name) {
return datasets.get(name);
}
@Override
public IDataset getxDataset() {
return datasets.get(xDatasetName);
}
@Override
public List<IDataset> getyDatasets() {
List<IDataset> sets = new ArrayList<IDataset>();
for (String name : yDatasetNames) {
sets.add(datasets.get(name));
}
return sets;
}
@Override
public String getxDatasetName() {
// TODO Auto-generated method stub
return xDatasetName;
}
@Override
public boolean contains(String datasetName) {
for (String name : datasets.keySet()) {
if (datasetName.equals(name)) return true;
}
return false;
}
public void plotAll() {
//not slow, doesnt need to be a job but the mutex keeps the plotting order
Job job = new Job("Plot all") {
@Override
protected IStatus run(IProgressMonitor monitor) {
IDataset x = null;
if (useAxisDataset) x = getxDataset();
List<IDataset> list = getyDatasets();
List<IDataset> copy = new ArrayList<IDataset>(list.size());
List<String> names = new ArrayList<String>(list.size());
for (IDataset ds : list) copy.add(ds);
for (int i= 0; i < copy.size(); i++) {
names.add( copy.get(i).getName());
if (copy.get(i).getRank() != 1) {
copy.set(i,reduceTo1D(x, copy.get(i)));
}
copy.get(i).setName(getTraceName(copy.get(i).getName()));
}
List<ITrace> traces = system.updatePlot1D(x, getyDatasets(), null);
for (int i = 0; i < traces.size();i++) {
traceMap.put(yDatasetNames.get(i), traces.get(i));
}
for (int i= 0; i < copy.size(); i++) {
list.get(i).setName(names.get(i));
}
return Status.OK_STATUS;
}
};
job.setRule(mutex);
job.schedule();
}
protected void addToPlot(final String name) {
if (traceMap.containsKey(name)) return;
Job job = new Job("Add to plot") {
@Override
protected IStatus run(IProgressMonitor monitor) {
IDataset x = null;
if (useAxisDataset) x = getxDataset();
IDataset set = datasets.get(name);
String oldName = set.getName();
if (set.getRank() != 1) set = reduceTo1D(x, set);
set.setName(getTraceName(set.getName()));
if (set != null) {
List<ITrace> traces = system.updatePlot1D(x, Arrays.asList(new IDataset[] {set}), null);
traceMap.put(name, traces.get(0));
}
set.setName(oldName);
return Status.OK_STATUS;
}
};
job.setRule(mutex);
job.schedule();
}
@Override
public String getLongName() {
return longName;
}
@Override
public List<String> getPossibleAxisNames() {
return getDatasetNames();
}
@Override
public List<String> getMatchingDatasets(int size) {
// TODO Auto-generated method stub
return getDatasetNames();
}
private List<String> getDatasetNames() {
List<String> col = new ArrayList<String>(datasets.size());
for (String key : datasets.keySet()) {
col.add(key);
}
return col;
}
@Override
protected String getTraceName(String name) {
// TODO Auto-generated method stub
return this.name + " : " + name;
}
@Override
public boolean canBeSaved() {
return true;
}
}
| UTF-8 | Java | 5,060 | java | 9_a6eba54056d53f7999a4a809613ea7c3fe006f15_SpectrumInMemory_s.java | Java | [] | null | [] | package org.dawnsci.spectrum.ui.file;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.trace.ITrace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import uk.ac.diamond.scisoft.analysis.dataset.IDataset;
import uk.ac.diamond.scisoft.analysis.io.LoaderFactory;
public class SpectrumInMemory extends AbstractSpectrumFile implements ISpectrumFile {
Map<String,IDataset> datasets;
private String name;
private String longName;
public SpectrumInMemory(String longName, String name,IDataset xDataset ,Collection<IDataset> yDatasets, IPlottingSystem system) {
this.system = system;
this.name = name;
this.longName = longName;
datasets = new HashMap<String, IDataset>();
yDatasetNames = new ArrayList<String>(yDatasets.size());
useAxisDataset = false;
if (xDataset != null) {
useAxisDataset = true;
String dsName = xDataset.getName();
if (dsName == null) dsName = "xData";
datasets.put(dsName, xDataset);
xDatasetName = dsName;
}
//TODO make more robust to the same dataset names
int i = 0;
for (IDataset dataset : yDatasets) {
String dsName = dataset.getName();
if (dsName == null) dsName = "yData" + i;
datasets.put(dsName, dataset);
yDatasetNames.add(dsName);
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
@Override
public Collection<String> getDataNames() {
return getDatasetNames();
}
@Override
public IDataset getDataset(String name) {
return datasets.get(name);
}
@Override
public IDataset getxDataset() {
return datasets.get(xDatasetName);
}
@Override
public List<IDataset> getyDatasets() {
List<IDataset> sets = new ArrayList<IDataset>();
for (String name : yDatasetNames) {
sets.add(datasets.get(name));
}
return sets;
}
@Override
public String getxDatasetName() {
// TODO Auto-generated method stub
return xDatasetName;
}
@Override
public boolean contains(String datasetName) {
for (String name : datasets.keySet()) {
if (datasetName.equals(name)) return true;
}
return false;
}
public void plotAll() {
//not slow, doesnt need to be a job but the mutex keeps the plotting order
Job job = new Job("Plot all") {
@Override
protected IStatus run(IProgressMonitor monitor) {
IDataset x = null;
if (useAxisDataset) x = getxDataset();
List<IDataset> list = getyDatasets();
List<IDataset> copy = new ArrayList<IDataset>(list.size());
List<String> names = new ArrayList<String>(list.size());
for (IDataset ds : list) copy.add(ds);
for (int i= 0; i < copy.size(); i++) {
names.add( copy.get(i).getName());
if (copy.get(i).getRank() != 1) {
copy.set(i,reduceTo1D(x, copy.get(i)));
}
copy.get(i).setName(getTraceName(copy.get(i).getName()));
}
List<ITrace> traces = system.updatePlot1D(x, getyDatasets(), null);
for (int i = 0; i < traces.size();i++) {
traceMap.put(yDatasetNames.get(i), traces.get(i));
}
for (int i= 0; i < copy.size(); i++) {
list.get(i).setName(names.get(i));
}
return Status.OK_STATUS;
}
};
job.setRule(mutex);
job.schedule();
}
protected void addToPlot(final String name) {
if (traceMap.containsKey(name)) return;
Job job = new Job("Add to plot") {
@Override
protected IStatus run(IProgressMonitor monitor) {
IDataset x = null;
if (useAxisDataset) x = getxDataset();
IDataset set = datasets.get(name);
String oldName = set.getName();
if (set.getRank() != 1) set = reduceTo1D(x, set);
set.setName(getTraceName(set.getName()));
if (set != null) {
List<ITrace> traces = system.updatePlot1D(x, Arrays.asList(new IDataset[] {set}), null);
traceMap.put(name, traces.get(0));
}
set.setName(oldName);
return Status.OK_STATUS;
}
};
job.setRule(mutex);
job.schedule();
}
@Override
public String getLongName() {
return longName;
}
@Override
public List<String> getPossibleAxisNames() {
return getDatasetNames();
}
@Override
public List<String> getMatchingDatasets(int size) {
// TODO Auto-generated method stub
return getDatasetNames();
}
private List<String> getDatasetNames() {
List<String> col = new ArrayList<String>(datasets.size());
for (String key : datasets.keySet()) {
col.add(key);
}
return col;
}
@Override
protected String getTraceName(String name) {
// TODO Auto-generated method stub
return this.name + " : " + name;
}
@Override
public boolean canBeSaved() {
return true;
}
}
| 5,060 | 0.651581 | 0.649407 | 207 | 23.439613 | 21.449749 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.26087 | false | false | 4 |
942119a4c08668a9c47bc81a86813a1808904527 | 34,926,674,056,776 | ff7e66f1d7829a6aaa10f64851edfe077083f912 | /src/main/java/com/talent/Controller/ForegroController.java | 8b80ba9eb761e5626938d314dbbfcdf8d3d08e06 | [] | no_license | burterfly/talentMaven | https://github.com/burterfly/talentMaven | bc0508185fd47624160dfab1a8bc46a7e61153b2 | 34f36dcf8f1e7bc45ce9c79c6a9072531cbb9844 | refs/heads/master | 2020-12-29T13:11:30.816000 | 2020-02-18T11:27:26 | 2020-02-18T11:27:26 | 238,618,420 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.talent.Controller;
import com.talent.entity.*;
import com.talent.service.TalentService;
import com.talent.service.businessService;
import com.talent.service.foregroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping(value = {"/foregro"})
public class ForegroController {
@Autowired
private businessService businessservice;
@Autowired
private TalentService talentservice;
@Autowired
private foregroService foregroservice;
@RequestMapping(value = {"/businesslogin"})
public String businesslogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
System.out.println(username);
System.out.println(password);
business user =businessservice.businesslogin(username,password);
if(user != null){
Integer bid=user.getBid();
session.setAttribute("bid", bid);
return "redirect:/business/listBusiness?bid="+bid;
}
return "foregro/loginError";
}
@RequestMapping(value = {"/talentlogin"})
public String talentlogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
talent user =talentservice.talentlogin(username,password);
if(user != null){
Integer tid=user.getTid();
session.setAttribute("tid", tid);
return "redirect:/talent/listTalent?tid="+tid;
}
return "foregro/loginError";
}
@RequestMapping(value = {"/stafflogin"})
public String stafflogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
staff user =foregroservice.stafflogin(username,password);
if(user != null){
return "redirect:/staff/User";
}
return "foregro/loginError";
}
@RequestMapping(value ="/toregister", method = RequestMethod.GET)
public String toregister(HttpSession session){
return "foregro/register";
}
@RequestMapping(value ="/talentregister")
public String talentregister(@RequestParam("Tusername") String Tusername,
@RequestParam("Tpassword") String Tpassword,
@RequestParam("Tname") String Tname,
@RequestParam("Tage") Integer Tage,
@RequestParam("Tsex") String Tsex,
@RequestParam("Tcer") String Tcer,
@RequestParam("Tedu") String Tedu,
@RequestParam("Tpro") String Tpro) {
talent talent=new talent();
talent.setTusername(Tusername);
talent.setTpassword(Tpassword);
talent.setTname(Tname);
talent.setTage(Tage);
talent.setTsex(Tsex);
talent.setTcer(Tcer);
talent.setTedu(Tedu);
talent.setTpro(Tpro);
System.out.println("ok");
talentservice.talentregister(talent);
return "foregro/login";
}
@RequestMapping(value ="/businessregister")
public String businessregister(@RequestParam("Busername") String Busername,
@RequestParam("Bpassword") String Bpassword,
@RequestParam("Bname") String Bname,
@RequestParam("Baddress") String Baddress,
@RequestParam("Btime") String Btime,
@RequestParam("Bservice") String Bservice) {
business business=new business();
business.setBusername(Busername);
business.setBpassword(Bpassword);
business.setBname(Bname);
business.setBaddress(Baddress);
business.setBtime(Btime);
business.setBservice(Bservice);
System.out.println("ok");
businessservice.businessregister(business);
return "foregro/login";
}
@RequestMapping(value ="/toindex", method = RequestMethod.GET)
public String toindex(){
return "foregro/index";
}
@RequestMapping(value ="/toabout", method = RequestMethod.GET)
public String toabout(){
return "foregro/about";
}
@RequestMapping(value ="/toalbum")
public String toalbum(Model model)
{
List<business> listalbum = businessservice.listAllBusiness();
model.addAttribute("listalbum", listalbum);
System.out.println(listalbum.size());
return "foregro/album";
}
@RequestMapping(value ="/toalbum_detail")
public String toalbum_detail(Integer bid,Model model){
System.out.println(bid+"细节");
business listbusiness=businessservice.listBusiness(bid);
model.addAttribute("listbusiness", listbusiness);
return "foregro/album_detail";
}
@RequestMapping(value ="/toarticle_details")
public String toarticle_details(Model model){
List<experience> listallpublic=foregroservice.listallpublic();
for (int i = 0; i < listallpublic.size(); i++) {
String name;
String address;
Integer j=listallpublic.get(i).getBid();
name = businessservice.listBusiness(j).getBname();
address = businessservice.listBusiness(j).getBaddress();
listallpublic.get(i).setBname(name);
listallpublic.get(i).setEother(address);
}
model.addAttribute("listallpublic", listallpublic);
return "foregro/article_details";
}
@RequestMapping(value ="/toarticle", method = RequestMethod.GET)
public String toarticle(){
return "foregro/article";
}
@RequestMapping(value ="/toarticle_detail", method = RequestMethod.GET)
public String toarticle_detail(){
return "foregro/article_detail";
}
@RequestMapping(value ="/tocomment", method = RequestMethod.GET)
public String tocomment(){
return "foregro/comment";
}
@RequestMapping(value ="/tocontact", method = RequestMethod.GET)
public String tocontract(){
return "foregro/contact";
}
@RequestMapping(value ="/toproduct", method = RequestMethod.GET)
public String toproduct(){
return "foregro/product";
}
}
| UTF-8 | Java | 6,940 | java | ForegroController.java | Java | [
{
"context": ")\n public String talentregister(@RequestParam(\"Tusername\") String Tusername,\n ",
"end": 2748,
"score": 0.8257960677146912,
"start": 2747,
"tag": "USERNAME",
"value": "T"
},
{
"context": "g talentregister(@RequestParam(\"Tusername\") String Tusername,\n @Reques",
"end": 2767,
"score": 0.8117251992225647,
"start": 2766,
"tag": "USERNAME",
"value": "T"
},
{
"context": "t=new talent();\n talent.setTusername(Tusername);\n talent.setTpassword(Tpassword);\n ",
"end": 3353,
"score": 0.9104425311088562,
"start": 3344,
"tag": "USERNAME",
"value": "Tusername"
},
{
"context": "ame(Tusername);\n talent.setTpassword(Tpassword);\n talent.setTname(Tname);\n ",
"end": 3399,
"score": 0.8267350196838379,
"start": 3390,
"tag": "PASSWORD",
"value": "Tpassword"
},
{
"context": " public String businessregister(@RequestParam(\"Busername\") String Busername,\n ",
"end": 3850,
"score": 0.5149721503257751,
"start": 3849,
"tag": "USERNAME",
"value": "B"
},
{
"context": "businessregister(@RequestParam(\"Busername\") String Busername,\n @Reques",
"end": 3869,
"score": 0.5765591859817505,
"start": 3868,
"tag": "USERNAME",
"value": "B"
},
{
"context": "ess=new business();\n business.setBusername(Busername);\n business.setBpassword(Bpassword);\n ",
"end": 4332,
"score": 0.8986631631851196,
"start": 4323,
"tag": "USERNAME",
"value": "Busername"
}
] | null | [] | package com.talent.Controller;
import com.talent.entity.*;
import com.talent.service.TalentService;
import com.talent.service.businessService;
import com.talent.service.foregroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping(value = {"/foregro"})
public class ForegroController {
@Autowired
private businessService businessservice;
@Autowired
private TalentService talentservice;
@Autowired
private foregroService foregroservice;
@RequestMapping(value = {"/businesslogin"})
public String businesslogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
System.out.println(username);
System.out.println(password);
business user =businessservice.businesslogin(username,password);
if(user != null){
Integer bid=user.getBid();
session.setAttribute("bid", bid);
return "redirect:/business/listBusiness?bid="+bid;
}
return "foregro/loginError";
}
@RequestMapping(value = {"/talentlogin"})
public String talentlogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
talent user =talentservice.talentlogin(username,password);
if(user != null){
Integer tid=user.getTid();
session.setAttribute("tid", tid);
return "redirect:/talent/listTalent?tid="+tid;
}
return "foregro/loginError";
}
@RequestMapping(value = {"/stafflogin"})
public String stafflogin(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session){
staff user =foregroservice.stafflogin(username,password);
if(user != null){
return "redirect:/staff/User";
}
return "foregro/loginError";
}
@RequestMapping(value ="/toregister", method = RequestMethod.GET)
public String toregister(HttpSession session){
return "foregro/register";
}
@RequestMapping(value ="/talentregister")
public String talentregister(@RequestParam("Tusername") String Tusername,
@RequestParam("Tpassword") String Tpassword,
@RequestParam("Tname") String Tname,
@RequestParam("Tage") Integer Tage,
@RequestParam("Tsex") String Tsex,
@RequestParam("Tcer") String Tcer,
@RequestParam("Tedu") String Tedu,
@RequestParam("Tpro") String Tpro) {
talent talent=new talent();
talent.setTusername(Tusername);
talent.setTpassword(<PASSWORD>);
talent.setTname(Tname);
talent.setTage(Tage);
talent.setTsex(Tsex);
talent.setTcer(Tcer);
talent.setTedu(Tedu);
talent.setTpro(Tpro);
System.out.println("ok");
talentservice.talentregister(talent);
return "foregro/login";
}
@RequestMapping(value ="/businessregister")
public String businessregister(@RequestParam("Busername") String Busername,
@RequestParam("Bpassword") String Bpassword,
@RequestParam("Bname") String Bname,
@RequestParam("Baddress") String Baddress,
@RequestParam("Btime") String Btime,
@RequestParam("Bservice") String Bservice) {
business business=new business();
business.setBusername(Busername);
business.setBpassword(Bpassword);
business.setBname(Bname);
business.setBaddress(Baddress);
business.setBtime(Btime);
business.setBservice(Bservice);
System.out.println("ok");
businessservice.businessregister(business);
return "foregro/login";
}
@RequestMapping(value ="/toindex", method = RequestMethod.GET)
public String toindex(){
return "foregro/index";
}
@RequestMapping(value ="/toabout", method = RequestMethod.GET)
public String toabout(){
return "foregro/about";
}
@RequestMapping(value ="/toalbum")
public String toalbum(Model model)
{
List<business> listalbum = businessservice.listAllBusiness();
model.addAttribute("listalbum", listalbum);
System.out.println(listalbum.size());
return "foregro/album";
}
@RequestMapping(value ="/toalbum_detail")
public String toalbum_detail(Integer bid,Model model){
System.out.println(bid+"细节");
business listbusiness=businessservice.listBusiness(bid);
model.addAttribute("listbusiness", listbusiness);
return "foregro/album_detail";
}
@RequestMapping(value ="/toarticle_details")
public String toarticle_details(Model model){
List<experience> listallpublic=foregroservice.listallpublic();
for (int i = 0; i < listallpublic.size(); i++) {
String name;
String address;
Integer j=listallpublic.get(i).getBid();
name = businessservice.listBusiness(j).getBname();
address = businessservice.listBusiness(j).getBaddress();
listallpublic.get(i).setBname(name);
listallpublic.get(i).setEother(address);
}
model.addAttribute("listallpublic", listallpublic);
return "foregro/article_details";
}
@RequestMapping(value ="/toarticle", method = RequestMethod.GET)
public String toarticle(){
return "foregro/article";
}
@RequestMapping(value ="/toarticle_detail", method = RequestMethod.GET)
public String toarticle_detail(){
return "foregro/article_detail";
}
@RequestMapping(value ="/tocomment", method = RequestMethod.GET)
public String tocomment(){
return "foregro/comment";
}
@RequestMapping(value ="/tocontact", method = RequestMethod.GET)
public String tocontract(){
return "foregro/contact";
}
@RequestMapping(value ="/toproduct", method = RequestMethod.GET)
public String toproduct(){
return "foregro/product";
}
}
| 6,941 | 0.61707 | 0.616926 | 181 | 37.320442 | 23.605577 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.646409 | false | false | 4 |
cfe5d2d6ded715bc52d457310d22d29834f7ea77 | 3,143,916,116,279 | 8fce1bb1907d1ec58761a5c2ad68f0ba967dac8a | /src/DataBaseOperations/DBManagementAdmin.java | 0972a9615f4f15348d74bd0cf148839ce643120d | [
"Apache-2.0"
] | permissive | kodluyoruz-deneme/KeepHTML | https://github.com/kodluyoruz-deneme/KeepHTML | 5addfe38ed214096839e048e06c37cc524823ee2 | 0da588b9a128443ca74d798aa461d1409b632677 | refs/heads/main | 2023-06-10T03:20:55.876000 | 2021-06-23T15:10:47 | 2021-06-23T15:10:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 DataBaseOperations;
import com.mysql.cj.protocol.Resultset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import signup.DbHelper;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import java.sql.*;
import java.util.Date;
/**
*
* @author RECEP
*/
public class DBManagementAdmin {
DbHelper dbHelper = new DbHelper();
Statement statement = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet resultSet;
JTable table = new JTable();
JTable tableTemplates = new JTable();
DefaultTableModel tblModel;
DefaultTableModel tblModelTemplates;
DBManagementUser dbManagementUser = new DBManagementUser();
public DBManagementAdmin()
{
}
//CONNECTION
//Veri Tabanı Bağlantı Açma
private void openConnection()
{
try{
// if(connection.isClosed())
//{
connection = dbHelper.getConnection();
statement = connection.createStatement();
// }
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
}
//Veri Tabanı Bağlantı Kapatma
private void closeConnection()
{
try {
connection.close();
} catch (SQLException ex) {
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
}
//INSERT, UPDATE, DELETE, DISPLAY
//KULLANICI
//Kullanıcı Ekleme
public int addUser(String username, String password, int isAdmin)
{
openConnection();
try{
statement.executeUpdate("INSERT INTO users (username,password,isAdmin) VALUES('"
+ username + "','"
+ password + "',"
+ isAdmin + ")");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Ekleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Güncelleme
public int updateUser(String username, String password, String newUsername)
{
openConnection();
try{
statement.executeUpdate("UPDATE users SET username='" + newUsername +"'," + "password='" + password + "' WHERE username='" + username +"'");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Güncelleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Silme
public int deleteUser(String username)
{
openConnection();
try{
statement.executeUpdate("DELETE FROM users WHERE username='" + username + "'");
return 1;
}
catch(SQLException ex)
{
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Silme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Listeleme
public void displayUsers(JTable jTable, String search)
{
jTable.setModel(new DefaultTableModel(null,new String[]{"Kullanıcı Adı","Parola"}));
jTable.getColumnModel().getColumn(1).setMinWidth(0);
jTable.getColumnModel().getColumn(1).setMaxWidth(0);
jTable.getColumnModel().getColumn(1).setPreferredWidth(0);
table = jTable;
openConnection();
try{
resultSet = statement.executeQuery("SELECT * FROM users WHERE username LIKE \"%"
+ search + "%\" AND isAdmin != 1");
while(resultSet.next()){
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String data [] = {username,password};
tblModel = (DefaultTableModel)jTable.getModel();
tblModel.addRow(data);
}
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
finally
{
closeConnection();
}
}
//TEMPLATE
//Template Ekleme
public int addTemplate(String templateName, String templatePath, JLabel label)
{
openConnection();
try{
preparedStatement = connection.prepareStatement("INSERT INTO templates (templateName,templatePath) VALUES('"
+ templateName + "','"
+ templatePath + "')");
preparedStatement.executeUpdate();
//Labela fotoğraf ekleme
ImageIcon imgThisImg = new ImageIcon(templatePath);
label.setIcon(imgThisImg);
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Template Ekleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
catch(Exception exception)
{
System.out.println("Exception Hatası: " + exception.getMessage());
System.out.println("Exception Code: " + exception.getCause());
Date now = new Date();
dbManagementUser.callStoredError(exception.getClass().getName(), -1,exception.getMessage(),now.toString());
return 0;
}
finally
{
closeConnection();
}
}
//Template Güncelleme
public int updateTemplate(String templateName, String templatePath, JLabel label, int ID)
{
openConnection();
try{
statement.executeUpdate("UPDATE templates SET templateName='" + templateName +"'," + "templatePath='" + templatePath + "' WHERE templateID=" + ID +"");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Template Güncelleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
catch(Exception exception)
{
System.out.println("Exception Hatası: "+exception.getMessage());
System.out.println("Exception Code: "+ exception.getCause());
Date now = new Date();
dbManagementUser.callStoredError(exception.getClass().getName(), -1,exception.getMessage(),now.toString());
return 0;
}
finally
{
closeConnection();
}
}
//Template Silme
public int deleteTemplate(int ID)
{
openConnection();
try{
statement.executeUpdate("DELETE FROM templates WHERE templateID=" + ID);
return 1;
}
catch(SQLException ex)
{
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Silme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Template Listeleme
public void displayTemplates(JTable jTable, String search)
{
jTable.setModel(new DefaultTableModel(null,new String[]{"Liste Numarası","Template Adı","Uzantısı"}));
jTable.getColumnModel().getColumn(0).setMinWidth(100);
jTable.getColumnModel().getColumn(0).setMaxWidth(100);
jTable.getColumnModel().getColumn(0).setPreferredWidth(100);
jTable.getColumnModel().getColumn(1).setMinWidth(200);
jTable.getColumnModel().getColumn(1).setMaxWidth(200);
jTable.getColumnModel().getColumn(1).setPreferredWidth(200);
tableTemplates = jTable;
openConnection();
try{
resultSet = statement.executeQuery("SELECT * FROM templates WHERE templateName LIKE \"%"
+ search + "%\"");
while(resultSet.next()){
String templateID = resultSet.getString("templateID");
String templateName = resultSet.getString("templateName");
String templatePath = resultSet.getString("templatePath");
String data [] = {templateID, templateName,templatePath};
tblModelTemplates = (DefaultTableModel)jTable.getModel();
tblModelTemplates.addRow(data);
}
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
finally
{
closeConnection();
}
}
//TextField Op.
//TextField Reset
public void resetFields(ArrayList<JTextField> fields)
{
for(JTextField field : fields)
{
field.setText("");
}
}
//TextField Fill
public void fillFieldsUser(JTextField username, JPasswordField password)
{
username.setText(tblModel.getValueAt(table.getSelectedRow(), 0).toString());
password.setText(tblModel.getValueAt(table.getSelectedRow(), 1).toString());
}
public void fillFieldsTemplate(JTextField templatePath, JTextField templateName)
{
templatePath.setText(tblModelTemplates.getValueAt(tableTemplates.getSelectedRow(), 2).toString());
templateName.setText(tblModelTemplates.getValueAt(tableTemplates.getSelectedRow(), 1).toString());
}
}
| UTF-8 | Java | 11,337 | java | DBManagementAdmin.java | Java | [
{
"context": "va.sql.*;\nimport java.util.Date;\n/**\n *\n * @author RECEP\n */\npublic class DBManagementAdmin {\n\n DbHelpe",
"end": 741,
"score": 0.9990547299385071,
"start": 736,
"tag": "USERNAME",
"value": "RECEP"
},
{
"context": " //INSERT, UPDATE, DELETE, DISPLAY\n \n //KULLANICI\n //Kullanıcı Ekleme \n public int addUser(S",
"end": 2207,
"score": 0.6813085675239563,
"start": 2200,
"tag": "NAME",
"value": "ULLANIC"
},
{
"context": ".executeUpdate(\"UPDATE users SET username='\" + newUsername +\"',\" + \"password='\" + password + \"' WHERE userna",
"end": 3239,
"score": 0.9361131191253662,
"start": 3231,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "T username='\" + newUsername +\"',\" + \"password='\" + password + \"' WHERE username='\" + username +\"'\");\n ",
"end": 3271,
"score": 0.9973623156547546,
"start": 3263,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " String username = resultSet.getString(\"username\");\n String password = resultSet.ge",
"end": 5086,
"score": 0.7232328057289124,
"start": 5078,
"tag": "USERNAME",
"value": "username"
}
] | null | [] | /*
* 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 DataBaseOperations;
import com.mysql.cj.protocol.Resultset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import signup.DbHelper;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import java.sql.*;
import java.util.Date;
/**
*
* @author RECEP
*/
public class DBManagementAdmin {
DbHelper dbHelper = new DbHelper();
Statement statement = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet resultSet;
JTable table = new JTable();
JTable tableTemplates = new JTable();
DefaultTableModel tblModel;
DefaultTableModel tblModelTemplates;
DBManagementUser dbManagementUser = new DBManagementUser();
public DBManagementAdmin()
{
}
//CONNECTION
//Veri Tabanı Bağlantı Açma
private void openConnection()
{
try{
// if(connection.isClosed())
//{
connection = dbHelper.getConnection();
statement = connection.createStatement();
// }
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
}
//Veri Tabanı Bağlantı Kapatma
private void closeConnection()
{
try {
connection.close();
} catch (SQLException ex) {
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
}
//INSERT, UPDATE, DELETE, DISPLAY
//KULLANICI
//Kullanıcı Ekleme
public int addUser(String username, String password, int isAdmin)
{
openConnection();
try{
statement.executeUpdate("INSERT INTO users (username,password,isAdmin) VALUES('"
+ username + "','"
+ password + "',"
+ isAdmin + ")");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Ekleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Güncelleme
public int updateUser(String username, String password, String newUsername)
{
openConnection();
try{
statement.executeUpdate("UPDATE users SET username='" + newUsername +"'," + "password='" + <PASSWORD> + "' WHERE username='" + username +"'");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Güncelleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Silme
public int deleteUser(String username)
{
openConnection();
try{
statement.executeUpdate("DELETE FROM users WHERE username='" + username + "'");
return 1;
}
catch(SQLException ex)
{
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Silme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Kullanıcı Listeleme
public void displayUsers(JTable jTable, String search)
{
jTable.setModel(new DefaultTableModel(null,new String[]{"Kullanıcı Adı","Parola"}));
jTable.getColumnModel().getColumn(1).setMinWidth(0);
jTable.getColumnModel().getColumn(1).setMaxWidth(0);
jTable.getColumnModel().getColumn(1).setPreferredWidth(0);
table = jTable;
openConnection();
try{
resultSet = statement.executeQuery("SELECT * FROM users WHERE username LIKE \"%"
+ search + "%\" AND isAdmin != 1");
while(resultSet.next()){
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String data [] = {username,password};
tblModel = (DefaultTableModel)jTable.getModel();
tblModel.addRow(data);
}
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
finally
{
closeConnection();
}
}
//TEMPLATE
//Template Ekleme
public int addTemplate(String templateName, String templatePath, JLabel label)
{
openConnection();
try{
preparedStatement = connection.prepareStatement("INSERT INTO templates (templateName,templatePath) VALUES('"
+ templateName + "','"
+ templatePath + "')");
preparedStatement.executeUpdate();
//Labela fotoğraf ekleme
ImageIcon imgThisImg = new ImageIcon(templatePath);
label.setIcon(imgThisImg);
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Template Ekleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
catch(Exception exception)
{
System.out.println("Exception Hatası: " + exception.getMessage());
System.out.println("Exception Code: " + exception.getCause());
Date now = new Date();
dbManagementUser.callStoredError(exception.getClass().getName(), -1,exception.getMessage(),now.toString());
return 0;
}
finally
{
closeConnection();
}
}
//Template Güncelleme
public int updateTemplate(String templateName, String templatePath, JLabel label, int ID)
{
openConnection();
try{
statement.executeUpdate("UPDATE templates SET templateName='" + templateName +"'," + "templatePath='" + templatePath + "' WHERE templateID=" + ID +"");
return 1;
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Template Güncelleme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
catch(Exception exception)
{
System.out.println("Exception Hatası: "+exception.getMessage());
System.out.println("Exception Code: "+ exception.getCause());
Date now = new Date();
dbManagementUser.callStoredError(exception.getClass().getName(), -1,exception.getMessage(),now.toString());
return 0;
}
finally
{
closeConnection();
}
}
//Template Silme
public int deleteTemplate(int ID)
{
openConnection();
try{
statement.executeUpdate("DELETE FROM templates WHERE templateID=" + ID);
return 1;
}
catch(SQLException ex)
{
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
System.out.println("Kayıt Silme Başarısız!");
dbHelper.showErrorMessage(ex);
return 0;
}
finally
{
closeConnection();
}
}
//Template Listeleme
public void displayTemplates(JTable jTable, String search)
{
jTable.setModel(new DefaultTableModel(null,new String[]{"Liste Numarası","Template Adı","Uzantısı"}));
jTable.getColumnModel().getColumn(0).setMinWidth(100);
jTable.getColumnModel().getColumn(0).setMaxWidth(100);
jTable.getColumnModel().getColumn(0).setPreferredWidth(100);
jTable.getColumnModel().getColumn(1).setMinWidth(200);
jTable.getColumnModel().getColumn(1).setMaxWidth(200);
jTable.getColumnModel().getColumn(1).setPreferredWidth(200);
tableTemplates = jTable;
openConnection();
try{
resultSet = statement.executeQuery("SELECT * FROM templates WHERE templateName LIKE \"%"
+ search + "%\"");
while(resultSet.next()){
String templateID = resultSet.getString("templateID");
String templateName = resultSet.getString("templateName");
String templatePath = resultSet.getString("templatePath");
String data [] = {templateID, templateName,templatePath};
tblModelTemplates = (DefaultTableModel)jTable.getModel();
tblModelTemplates.addRow(data);
}
}
catch(SQLException ex){
Date now = new Date();
dbManagementUser.callStoredError(ex.getClass().getName(), ex.getErrorCode(),ex.getMessage(),now.toString());
dbHelper.showErrorMessage(ex);
}
finally
{
closeConnection();
}
}
//TextField Op.
//TextField Reset
public void resetFields(ArrayList<JTextField> fields)
{
for(JTextField field : fields)
{
field.setText("");
}
}
//TextField Fill
public void fillFieldsUser(JTextField username, JPasswordField password)
{
username.setText(tblModel.getValueAt(table.getSelectedRow(), 0).toString());
password.setText(tblModel.getValueAt(table.getSelectedRow(), 1).toString());
}
public void fillFieldsTemplate(JTextField templatePath, JTextField templateName)
{
templatePath.setText(tblModelTemplates.getValueAt(tableTemplates.getSelectedRow(), 2).toString());
templateName.setText(tblModelTemplates.getValueAt(tableTemplates.getSelectedRow(), 1).toString());
}
}
| 11,339 | 0.586302 | 0.581783 | 323 | 33.941177 | 30.95487 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.681115 | false | false | 4 |
ab5de4c78a0bacb602469815b86e48ca204f4dad | 3,143,916,115,569 | f3cbd988bb572e4ccfbf3b098ae0be2f7055af53 | /BigNo.java | 7d94fb1adb5f9dc23e8bffee7babb0a834bff020 | [] | no_license | supreetshm947/practicealgo | https://github.com/supreetshm947/practicealgo | bad8eee232b2a09c7d759b8b02005e67cf2a2c29 | 15f293f04497ec58dd6e88b6d2557d414b0d9c32 | refs/heads/master | 2021-06-28T12:40:38.502000 | 2017-09-14T05:39:59 | 2017-09-14T05:39:59 | 103,490,315 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.math.BigInteger;
public class BigNo {
public static void main(String s[]) {
BigInteger pref = new BigInteger("1123111600000000000000") ;
String suff = "1116";
BigInteger no = new BigInteger(pref.toString()+suff+"00");
BigInteger currHigh = new BigInteger(pref.toString()+suff+"99");
BigInteger ninetySeven = new BigInteger("97");
BigInteger mod = no.mod(ninetySeven);
no = no.subtract(mod).add(ninetySeven);
BigInteger highNo = new BigInteger("1123111999999999999999111699");
while(no.compareTo(highNo)==-1) {
if(no.compareTo(currHigh)==1) {
pref = pref.add(new BigInteger("1"));
no = new BigInteger(pref.toString()+suff+"00");
currHigh = new BigInteger(pref.toString()+suff+"99");
mod = no.mod(ninetySeven);
no = no.subtract(mod).add(ninetySeven);;
}
System.out.println(no);
no = no.add(ninetySeven);
}
}
}
| UTF-8 | Java | 881 | java | BigNo.java | Java | [] | null | [] | import java.math.BigInteger;
public class BigNo {
public static void main(String s[]) {
BigInteger pref = new BigInteger("1123111600000000000000") ;
String suff = "1116";
BigInteger no = new BigInteger(pref.toString()+suff+"00");
BigInteger currHigh = new BigInteger(pref.toString()+suff+"99");
BigInteger ninetySeven = new BigInteger("97");
BigInteger mod = no.mod(ninetySeven);
no = no.subtract(mod).add(ninetySeven);
BigInteger highNo = new BigInteger("1123111999999999999999111699");
while(no.compareTo(highNo)==-1) {
if(no.compareTo(currHigh)==1) {
pref = pref.add(new BigInteger("1"));
no = new BigInteger(pref.toString()+suff+"00");
currHigh = new BigInteger(pref.toString()+suff+"99");
mod = no.mod(ninetySeven);
no = no.subtract(mod).add(ninetySeven);;
}
System.out.println(no);
no = no.add(ninetySeven);
}
}
}
| 881 | 0.679909 | 0.603859 | 27 | 31.629629 | 21.480652 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.777778 | false | false | 4 |
5b8209e3a1abcc2a42ea2cc5c58dc5b6c2027e2c | 9,028,021,268,951 | 8f74dd5e339aeef01ac3ebcdcd289b19980c23bb | /lab_rab_3/src/by/bsuir/carrental/dao/DaoFactory.java | 9005b716e6153cd2d523bc21c0ea6f44a68a4ec3 | [] | no_license | Liberator007/epam_labs | https://github.com/Liberator007/epam_labs | 56783d5f65f2726bb5e93717b5340d895289eaf5 | 4b4d5fdf38761d36c3bc5e07a4793baf4e9ce5ee | refs/heads/master | 2022-04-01T00:15:32.047000 | 2019-12-15T23:53:27 | 2019-12-15T23:53:27 | 209,012,398 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.bsuir.carrental.dao;
import by.bsuir.carrental.dao.CarDao.CarDAO;
public class DaoFactory {
private static CarDAO carDAO = new CarDAO();
public static CarDAO getCarDAO()
{
return carDAO;
}
}
| UTF-8 | Java | 230 | java | DaoFactory.java | Java | [] | null | [] | package by.bsuir.carrental.dao;
import by.bsuir.carrental.dao.CarDao.CarDAO;
public class DaoFactory {
private static CarDAO carDAO = new CarDAO();
public static CarDAO getCarDAO()
{
return carDAO;
}
}
| 230 | 0.682609 | 0.682609 | 13 | 16.692308 | 17.617231 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.307692 | false | false | 4 |
1ae3d8b5ecabb6a4ecb2d45a254892ec7afbe161 | 21,062,519,634,879 | ccbe1d51475823da9c8040df27aad75ee3b5d579 | /src/com/company6/Bank.java | 2957b316631ffec3b426b54bb7301bc8dead3018 | [] | no_license | sirangithub/schoolwork | https://github.com/sirangithub/schoolwork | 2f5cbf904e6b5bbd7cea77103e2a87c82e443e53 | aaa67f8be7f11586adf24bc877239b06058e8cad | refs/heads/master | 2020-05-30T19:19:34.621000 | 2019-06-04T06:47:00 | 2019-06-04T06:47:00 | 189,921,425 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company6;
public class Bank {
private String account;
private double balance;
public Bank(String account,double balance){
this.account=account;
this.balance=balance;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "账户:"+account+"余额:"+balance;
}
public synchronized void saveAccount(){
double balance=getBalance();
double balance1=Math.random()*10000;
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
balance=balance+balance1;
setBalance(balance);
System.out.println(getAccount()+"存入:"+balance1+"账户余额:"+balance);
}
public synchronized void drawAccount(){
double balance=getBalance();
double balance2=Math.random()*10000;
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}if(balance2<balance){
balance=balance-balance2;
setBalance(balance);
System.out.println(getAccount()+"取出:"+balance2+"账户余额:"+balance);
}else {System.out.println(getAccount()+"余额不足");}
}
}
| UTF-8 | Java | 1,519 | java | Bank.java | Java | [] | null | [] | package com.company6;
public class Bank {
private String account;
private double balance;
public Bank(String account,double balance){
this.account=account;
this.balance=balance;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
@Override
public String toString() {
return "账户:"+account+"余额:"+balance;
}
public synchronized void saveAccount(){
double balance=getBalance();
double balance1=Math.random()*10000;
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
balance=balance+balance1;
setBalance(balance);
System.out.println(getAccount()+"存入:"+balance1+"账户余额:"+balance);
}
public synchronized void drawAccount(){
double balance=getBalance();
double balance2=Math.random()*10000;
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}if(balance2<balance){
balance=balance-balance2;
setBalance(balance);
System.out.println(getAccount()+"取出:"+balance2+"账户余额:"+balance);
}else {System.out.println(getAccount()+"余额不足");}
}
}
| 1,519 | 0.59661 | 0.580339 | 51 | 27.921568 | 16.730673 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509804 | false | false | 4 |
20e1e48d045411e261b9809c5f3f69afb438f19d | 23,261,542,899,551 | 6c927e442e0c8c4620477d0f206f089ef0244746 | /src/main/java/snippet/web/project/repositories/LanguageRepository.java | 8ff03e45139f93f8f02696c4a4440c6070d3da8d | [] | no_license | NinaSimic/Snippet-Web-project | https://github.com/NinaSimic/Snippet-Web-project | 1fbd2ad2e6b7a8e303e824f0ddff7c36326b7ca3 | a934f072c3ecccec931fb81086b331a348747c52 | refs/heads/master | 2021-01-18T19:34:45.929000 | 2017-09-10T01:07:20 | 2017-09-10T01:07:20 | 100,534,617 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package snippet.web.project.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import snippet.web.project.model.Language;
import java.util.List;
public interface LanguageRepository extends JpaRepository<Language, Long> {
Language findByName(String name);
}
| UTF-8 | Java | 291 | java | LanguageRepository.java | Java | [] | null | [] | package snippet.web.project.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import snippet.web.project.model.Language;
import java.util.List;
public interface LanguageRepository extends JpaRepository<Language, Long> {
Language findByName(String name);
}
| 291 | 0.814433 | 0.814433 | 12 | 23.25 | 26.074013 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
8ba446a59f6111e9c31105de45cdd72a4c737e8e | 35,244,501,638,126 | 6c2a5995d202113a3a846e17a9ddc138ba0788bb | /icore/src/main/java/com/beautifullife/core/network/Retrofit/RetrofitManager.java | 1b914b7ce119aa75c45ea0fd16862f1d494a006a | [] | no_license | yzbzz/icore | https://github.com/yzbzz/icore | 47ebd7fef0212295cc7bf9c3b82cbea9df9dcee5 | 5fa793e3586e6b412b407682273ca0bedf6473da | refs/heads/master | 2020-12-31T02:22:18.201000 | 2016-01-12T03:35:58 | 2016-01-12T03:35:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.beautifullife.core.network.Retrofit;
import android.content.Context;
import com.beautifullife.core.network.okhttp.OKHttpManager;
import com.beautifullife.core.network.okhttp.response.ResponseHandlerInterface;
import com.beautifullife.core.rx.schedulers.AndroidSchedulers;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request.Builder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.functions.Action1;
public class RetrofitManager {
public static void createOKhttpClient() {
OkHttpClient okhttpClient = OKHttpManager.getInstance().getOkHttpClient().clone();
}
public static <T> void get(Context context, Call<T> repos, String url, HashMap<String, String> params, String md5Param, boolean isEncode, ResponseHandlerInterface responseHandlerInterface) throws Exception {
Interceptor interceptor = new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain arg0) throws IOException {
Builder newRequest = arg0.request().newBuilder();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("versionName", "1.0");
headers.put("platform", "android");
if (headers != null) {
for (Map.Entry<String, String> param : headers.entrySet()) {
newRequest.addHeader(param.getKey(), param.getValue());
}
}
return arg0.proceed(newRequest.build());
}
};
OkHttpClient okhttpClient = OKHttpManager.getInstance().getOkHttpClient().clone();
okhttpClient.interceptors().add(interceptor);
//RXjava
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(okhttpClient).build();
repos.enqueue(new Callback<T>() {
@Override
public void onResponse(retrofit.Response<T> paramResponse, Retrofit paramRetrofit) {
//404 paramResponse.errorBody().string()
Observable.just(paramResponse).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<retrofit.Response<T>>() {
@Override
public void call(retrofit.Response<T> arg0) {
arg0.body();
}
});
}
@Override
public void onFailure(Throwable paramThrowable) {
}
});
}
}
| UTF-8 | Java | 2,855 | java | RetrofitManager.java | Java | [] | null | [] | package com.beautifullife.core.network.Retrofit;
import android.content.Context;
import com.beautifullife.core.network.okhttp.OKHttpManager;
import com.beautifullife.core.network.okhttp.response.ResponseHandlerInterface;
import com.beautifullife.core.rx.schedulers.AndroidSchedulers;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request.Builder;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.functions.Action1;
public class RetrofitManager {
public static void createOKhttpClient() {
OkHttpClient okhttpClient = OKHttpManager.getInstance().getOkHttpClient().clone();
}
public static <T> void get(Context context, Call<T> repos, String url, HashMap<String, String> params, String md5Param, boolean isEncode, ResponseHandlerInterface responseHandlerInterface) throws Exception {
Interceptor interceptor = new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain arg0) throws IOException {
Builder newRequest = arg0.request().newBuilder();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("versionName", "1.0");
headers.put("platform", "android");
if (headers != null) {
for (Map.Entry<String, String> param : headers.entrySet()) {
newRequest.addHeader(param.getKey(), param.getValue());
}
}
return arg0.proceed(newRequest.build());
}
};
OkHttpClient okhttpClient = OKHttpManager.getInstance().getOkHttpClient().clone();
okhttpClient.interceptors().add(interceptor);
//RXjava
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(okhttpClient).build();
repos.enqueue(new Callback<T>() {
@Override
public void onResponse(retrofit.Response<T> paramResponse, Retrofit paramRetrofit) {
//404 paramResponse.errorBody().string()
Observable.just(paramResponse).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<retrofit.Response<T>>() {
@Override
public void call(retrofit.Response<T> arg0) {
arg0.body();
}
});
}
@Override
public void onFailure(Throwable paramThrowable) {
}
});
}
}
| 2,855 | 0.655692 | 0.651138 | 72 | 38.652779 | 40.708706 | 211 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 4 |
ef6e30fce2d8d8a2321289ed045ab532c4af82be | 20,392,504,760,684 | c5ea0e1565028698d823cf78c25a945f2545f515 | /analysis-core/src/main/java/org/mappinganalysis/model/functions/decomposition/simsort/SimSortVertexCentricIteration.java | aa8a8bab219242dbb7c60f13e7b9c305e57d17a5 | [] | no_license | freeclimbing/mapping-analysis | https://github.com/freeclimbing/mapping-analysis | 3485b4a02596b1e404360e9557f44649aebce6cc | 643ac0e1cb0ae81fee52f32c513535a093a960a6 | refs/heads/master | 2021-03-30T20:59:39.892000 | 2018-03-12T11:03:05 | 2018-03-12T11:03:05 | 124,872,631 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.mappinganalysis.model.functions.decomposition.simsort;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAlgorithm;
import org.apache.flink.graph.Vertex;
import org.apache.log4j.Logger;
import org.mappinganalysis.model.ObjectMap;
/**
* Execute SimSort procedure based on vertex-centric-iteration
*/
public class SimSortVertexCentricIteration
implements GraphAlgorithm<Long, ObjectMap, ObjectMap, Graph<Long, ObjectMap, ObjectMap>> {
private static final Logger LOG = Logger.getLogger(SimSort.class);
private final ExecutionEnvironment env;
private final Double minSimilarity;
public SimSortVertexCentricIteration(Double minSimilarity, ExecutionEnvironment env) {
this.minSimilarity = minSimilarity;
this.env = env;
}
@Override
public Graph<Long, ObjectMap, ObjectMap> run(
Graph<Long, ObjectMap, ObjectMap> graph) throws Exception {
// set solution set unmanaged in order to reduce out of memory exception on non-cluster setup
// aggParameters.setSolutionSetUnmanagedMemory(true);
DataSet<Vertex<Long, SimSortVertexTuple>> workingVertices = graph
.getUndirected()
.run(new SimSortInputGraphCreator(env))
.runVertexCentricIteration(new SimSortComputeFunction(minSimilarity),
new SimSortMessageCombiner(),
Integer.MAX_VALUE)
.getVertices();
DataSet<Vertex<Long, ObjectMap>> resultingVertices = graph
.getVertices()
.join(workingVertices)
.where(0)
.equalTo(0)
.with((vertex, workingVertex) -> {
// LOG.info("v: " + vertex.toString() + " wv: " + workingVertex.toString());
vertex.getValue().setHashCcId(workingVertex.getValue().getHash());
if (workingVertex.getValue().getOldHash() != Long.MIN_VALUE) {
vertex.getValue().setOldHashCcId(workingVertex.getValue().getOldHash());
}
vertex.getValue().setVertexStatus(workingVertex.getValue().isActive());
return vertex;
})
.returns(new TypeHint<Vertex<Long, ObjectMap>>() {});
return Graph.fromDataSet(resultingVertices, graph.getEdges(), env);
}
}
| UTF-8 | Java | 2,325 | java | SimSortVertexCentricIteration.java | Java | [] | null | [] | package org.mappinganalysis.model.functions.decomposition.simsort;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.graph.Graph;
import org.apache.flink.graph.GraphAlgorithm;
import org.apache.flink.graph.Vertex;
import org.apache.log4j.Logger;
import org.mappinganalysis.model.ObjectMap;
/**
* Execute SimSort procedure based on vertex-centric-iteration
*/
public class SimSortVertexCentricIteration
implements GraphAlgorithm<Long, ObjectMap, ObjectMap, Graph<Long, ObjectMap, ObjectMap>> {
private static final Logger LOG = Logger.getLogger(SimSort.class);
private final ExecutionEnvironment env;
private final Double minSimilarity;
public SimSortVertexCentricIteration(Double minSimilarity, ExecutionEnvironment env) {
this.minSimilarity = minSimilarity;
this.env = env;
}
@Override
public Graph<Long, ObjectMap, ObjectMap> run(
Graph<Long, ObjectMap, ObjectMap> graph) throws Exception {
// set solution set unmanaged in order to reduce out of memory exception on non-cluster setup
// aggParameters.setSolutionSetUnmanagedMemory(true);
DataSet<Vertex<Long, SimSortVertexTuple>> workingVertices = graph
.getUndirected()
.run(new SimSortInputGraphCreator(env))
.runVertexCentricIteration(new SimSortComputeFunction(minSimilarity),
new SimSortMessageCombiner(),
Integer.MAX_VALUE)
.getVertices();
DataSet<Vertex<Long, ObjectMap>> resultingVertices = graph
.getVertices()
.join(workingVertices)
.where(0)
.equalTo(0)
.with((vertex, workingVertex) -> {
// LOG.info("v: " + vertex.toString() + " wv: " + workingVertex.toString());
vertex.getValue().setHashCcId(workingVertex.getValue().getHash());
if (workingVertex.getValue().getOldHash() != Long.MIN_VALUE) {
vertex.getValue().setOldHashCcId(workingVertex.getValue().getOldHash());
}
vertex.getValue().setVertexStatus(workingVertex.getValue().isActive());
return vertex;
})
.returns(new TypeHint<Vertex<Long, ObjectMap>>() {});
return Graph.fromDataSet(resultingVertices, graph.getEdges(), env);
}
}
| 2,325 | 0.712688 | 0.711398 | 61 | 37.114754 | 29.168306 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672131 | false | false | 4 |
5097ad31b574e26758307097bd0d030f634f49fc | 6,390,911,398,835 | 73d5a79a8355899960001844bcec5a41206d4deb | /A1-echo-server-java/EchoClient/src/com/anindyaspaul/Receiver.java | 45d87b20b8b721db17174c98b6b410f6212c4b15 | [] | no_license | anindyaspaul/distributed-systems-lab | https://github.com/anindyaspaul/distributed-systems-lab | 365316e1a3b748e2c5a91eb325605a1f87fee3e8 | b3c48ab5095a3d691db03e30dc6b6f53e9f13c52 | refs/heads/master | 2020-03-02T22:56:12.805000 | 2016-10-31T17:48:23 | 2016-10-31T17:48:23 | 64,637,585 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.anindyaspaul;
import java.io.*;
import java.net.*;
public class Receiver implements Runnable {
DataInputStream inputStream;
Receiver(Socket _socket) throws Exception {
inputStream = new DataInputStream(_socket.getInputStream());
}
@Override
public void run() {
while(true) {
try {
String message = inputStream.readUTF();
System.out.println("[Server]: " + message);
} catch (Exception e) {
}
}
}
} | UTF-8 | Java | 446 | java | Receiver.java | Java | [] | null | [] | package com.anindyaspaul;
import java.io.*;
import java.net.*;
public class Receiver implements Runnable {
DataInputStream inputStream;
Receiver(Socket _socket) throws Exception {
inputStream = new DataInputStream(_socket.getInputStream());
}
@Override
public void run() {
while(true) {
try {
String message = inputStream.readUTF();
System.out.println("[Server]: " + message);
} catch (Exception e) {
}
}
}
} | 446 | 0.67713 | 0.67713 | 25 | 16.879999 | 18.049532 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.56 | false | false | 4 |
5868e14cbf2f277c30387d7d66fd5268ece066ba | 8,375,186,285,360 | 50fa8b4b464ac2c14851ad0e018aaeab0934a1ba | /src/pickone/medium/MinSwap801.java | bf15c1f3013cdaa4254a83b5cb7339e055f37805 | [] | no_license | Lying9/leetcode | https://github.com/Lying9/leetcode | 7940668f39a4709169153f621aa08435c6ebeb2f | f7ed54b3f08df4ab7a6878f8b039b1b2d2591e37 | refs/heads/master | 2020-04-01T07:06:02.137000 | 2020-03-29T03:56:09 | 2020-03-29T03:56:09 | 152,976,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pickone.medium;
import sun.font.TrueTypeFont;
/**
* Created by ying on 2018/11/5.
*/
public class MinSwap801 {
public static void main(String[] args) {
/* int[] A = {1,3,5,4};
int[] B ={1,2,3,7};*/
int[] A = {0,7,8,10,10,11,12,13,19,18};
int[] B ={4,4,5,7,11,14,15,16,17,20};
System.out.println(minSwap(A,B));
for (int i:A)
System.out.print(i+"\t");
System.out.println();
for (int i:B)
System.out.print(i+"\t");
}
public static int minSwap(int[] A, int[] B) {
if(A.length == 0 || B.length == 0)
return 0;
int[] swap = new int[A.length]; //第i个元素表示 AB中第i个元素交换 从0到i的最小交换次数
int[] keep = new int[A.length]; //第i个元素表示 AB中第i个元素不交换 从0到i的最小交换次数
swap[0] = 1;
keep[0] = 0;
for (int i = 1; i <A.length ; i++) {
swap[i] = keep[i] = Integer.MAX_VALUE;
if(A[i]>A[i-1] && B[i]>B[i-1]){ //满足AB不交换的条件
swap[i] = swap[i-1]+1; //AB的第i个元素如果交换 则i-1也必须交换
keep[i] = keep[i-1]; //AB的第i个元素如果不交换,则i-1也不交换
}
if(A[i]>B[i-1] && B[i]>A[i-1]){ //满足AB交换的条件
keep[i]=Math.min(keep[i],swap[i-1]); //如果第i个元素不交换 则i-1元素必须交换
swap[i]=Math.min(swap[i],keep[i-1]+1); //如果第i个元素交换 则i-1元素不交换且加上这一次的交换
}
}
return Math.min(keep[A.length-1],swap[A.length-1]);
}
}
| UTF-8 | Java | 1,735 | java | MinSwap801.java | Java | [
{
"context": "\n\nimport sun.font.TrueTypeFont;\n\n/**\n * Created by ying on 2018/11/5.\n */\npublic class MinSwap801 {\n\n ",
"end": 78,
"score": 0.9962139129638672,
"start": 74,
"tag": "USERNAME",
"value": "ying"
}
] | null | [] | package pickone.medium;
import sun.font.TrueTypeFont;
/**
* Created by ying on 2018/11/5.
*/
public class MinSwap801 {
public static void main(String[] args) {
/* int[] A = {1,3,5,4};
int[] B ={1,2,3,7};*/
int[] A = {0,7,8,10,10,11,12,13,19,18};
int[] B ={4,4,5,7,11,14,15,16,17,20};
System.out.println(minSwap(A,B));
for (int i:A)
System.out.print(i+"\t");
System.out.println();
for (int i:B)
System.out.print(i+"\t");
}
public static int minSwap(int[] A, int[] B) {
if(A.length == 0 || B.length == 0)
return 0;
int[] swap = new int[A.length]; //第i个元素表示 AB中第i个元素交换 从0到i的最小交换次数
int[] keep = new int[A.length]; //第i个元素表示 AB中第i个元素不交换 从0到i的最小交换次数
swap[0] = 1;
keep[0] = 0;
for (int i = 1; i <A.length ; i++) {
swap[i] = keep[i] = Integer.MAX_VALUE;
if(A[i]>A[i-1] && B[i]>B[i-1]){ //满足AB不交换的条件
swap[i] = swap[i-1]+1; //AB的第i个元素如果交换 则i-1也必须交换
keep[i] = keep[i-1]; //AB的第i个元素如果不交换,则i-1也不交换
}
if(A[i]>B[i-1] && B[i]>A[i-1]){ //满足AB交换的条件
keep[i]=Math.min(keep[i],swap[i-1]); //如果第i个元素不交换 则i-1元素必须交换
swap[i]=Math.min(swap[i],keep[i-1]+1); //如果第i个元素交换 则i-1元素不交换且加上这一次的交换
}
}
return Math.min(keep[A.length-1],swap[A.length-1]);
}
}
| 1,735 | 0.477966 | 0.425763 | 45 | 31.777779 | 25.271757 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.2 | false | false | 4 |
227a213f16f3c918eecc18f1af45f3c4713de69a | 34,626,026,352,566 | cbbe662e46ab70a131bbcd8f8ba8452db38037a6 | /src/LinuxThesis/Operator/OperatorSetup/OperatorStartup.java | bee8fabd5bfed7e3687836c4a8ae972e202e894f | [
"Apache-2.0"
] | permissive | patrik999/adaptive-stream-reasoning-monitoring | https://github.com/patrik999/adaptive-stream-reasoning-monitoring | 11191d68bfa4ae1a03d58dc8c7154ca84118ae44 | 7bbfa1a394e0127e0c4ea670a632be216c83faea | refs/heads/master | 2022-04-21T10:42:56.107000 | 2020-04-25T16:19:11 | 2020-04-25T16:19:11 | 248,282,960 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package OperatorSetup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import Model.CmThread;
import Model.ConnectedStreamReasoner;
import Model.EventThread;
import Model.LupsRule;
import Model.UmThread;
import util.Printer;
public class OperatorStartup {
public static int exp=2;
public static int test=3;
static final int CM_PORT = 1977;
static final int UM_PORT = 1978;
static final int EVENT_PORT = 1980;
public static List<ConnectedStreamReasoner> openConnections = new ArrayList<ConnectedStreamReasoner>();
public static void main(String args[]) throws IOException {
ConnectedStreamReasoner sr0 = new ConnectedStreamReasoner();
sr0.srID = 0;
assignLupsRules(sr0);
openConnections.add(sr0);
Printer.SetStartTime(LocalDateTime.now());
Printer.CustomPrint("Started server Program");
ServerSocket cm_ServerSocket = null;
ServerSocket um_ServerSocket = null;
ServerSocket event_ServerSocket = null;
try {
cm_ServerSocket = new ServerSocket(CM_PORT);
um_ServerSocket = new ServerSocket(UM_PORT);
event_ServerSocket = new ServerSocket(EVENT_PORT);
} catch (IOException e) {
e.printStackTrace();
}
CreateCMReceiver(cm_ServerSocket);
CreateUMReceiver(um_ServerSocket);
CreateEventReceiver(event_ServerSocket);
BufferedReader consoleBr = new BufferedReader(new InputStreamReader(System.in));
while (true) {
// BroadCastToCommunicationManagers(consoleBr.readLine());
BroadCastToUpdateMangers(consoleBr.readLine());
}
}
// Launches a thread whos job it is to listen for incoming Update Manager
// connection requests.
// When one is detected, a new thread is launched that will deal with messages
// coming from that Update Manager.
public static void CreateUMReceiver(ServerSocket serverSocket) {
Runnable umServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new UmThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, null, t, null));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().umThread = t;
}
}
}
};
Thread umThread = new Thread(umServer);
umThread.start();
Printer.CustomPrint("Started um Receiver Thread");
}
public static void CreateCMReceiver(ServerSocket serverSocket) {
Runnable cmServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new CmThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, t, null, null));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().cmThread = t;
}
}
}
};
Thread cmThread = new Thread(cmServer);
cmThread.start();
Printer.CustomPrint("Started cm Receiver Thread");
}
public static void CreateEventReceiver(ServerSocket serverSocket) {
Runnable eventServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new EventThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, null, null, t));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().eventThread = t;
}
}
}
};
Thread eventChannelThread = new Thread(eventServer);
eventChannelThread.start();
Printer.CustomPrint("Started Event Channel Receiver Thread");
}
public static void assignLupsRules(ConnectedStreamReasoner sr0) {
//Exp1Test1
if(exp==1 && test==1) {
sr0.lupsRules.add(new LupsRule("execute rule editPredicateCommunication(0,push,false,0) when trafficJam(l34)"));
}
//Exp1Test2
if(exp==1 && test==2) {
//manually input: interfaceCommand(addException^-1^0^0^[(0,[l20])]^push^false^0)
}
//Exp2Test1
if(exp==2 && test==1) {
sr0.lupsRules.add(new LupsRule("disable for -1 rule trafficCount when prideParade(l34)"));
sr0.lupsRules.add(new LupsRule("enable for -1 rule trafficCount when prideParadeEnd(l34)"));
}
//Exp2Test2
if(exp==2 && test==2) {
sr0.lupsRules.add(new LupsRule("execute for 60 rule editParameterValue(0,001.00) when trafficJam(l20)"));
}
//Exp2Test3
if(exp==2 && test==3) {
sr0.lupsRules.add(new LupsRule("assert for 15 rule hasSignalGroup(L,T) :- &sql2[\"SELECT a,b FROM object_role_assertion WHERE object_role=151\"](L,T). when trafficJam(l20)"));
sr0.lupsRules.add(new LupsRule("assert for 15 rule trafficLighState(T,S) :- &sql2[\"SELECT DISTINCT ON (iid) iid, x FROM v_signalstate_mrel WHERE tp > 0 ORDER BY iid, tp DESC\"](T,S). when trafficJam(l20)"));
sr0.lupsRules.add(new LupsRule("assert for 15 rule @wsSend(\"trafficLightState(\",T,\",\",S,\")\") :- hasSignalGroup(L,T), trafficLighState(T,S). when trafficJam(l20)"));
}
}
public static void BroadCastToCommunicationManagers(String message) {
for (ConnectedStreamReasoner sr : openConnections) {
((CmThread) sr.cmThread).pushMessage(message);
}
}
public static void BroadCastToUpdateMangers(String message) {
for (ConnectedStreamReasoner sr : openConnections) {
((UmThread) sr.umThread).pushMessage(message);
}
}
}
| UTF-8 | Java | 6,173 | java | OperatorStartup.java | Java | [] | null | [] | package OperatorSetup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import Model.CmThread;
import Model.ConnectedStreamReasoner;
import Model.EventThread;
import Model.LupsRule;
import Model.UmThread;
import util.Printer;
public class OperatorStartup {
public static int exp=2;
public static int test=3;
static final int CM_PORT = 1977;
static final int UM_PORT = 1978;
static final int EVENT_PORT = 1980;
public static List<ConnectedStreamReasoner> openConnections = new ArrayList<ConnectedStreamReasoner>();
public static void main(String args[]) throws IOException {
ConnectedStreamReasoner sr0 = new ConnectedStreamReasoner();
sr0.srID = 0;
assignLupsRules(sr0);
openConnections.add(sr0);
Printer.SetStartTime(LocalDateTime.now());
Printer.CustomPrint("Started server Program");
ServerSocket cm_ServerSocket = null;
ServerSocket um_ServerSocket = null;
ServerSocket event_ServerSocket = null;
try {
cm_ServerSocket = new ServerSocket(CM_PORT);
um_ServerSocket = new ServerSocket(UM_PORT);
event_ServerSocket = new ServerSocket(EVENT_PORT);
} catch (IOException e) {
e.printStackTrace();
}
CreateCMReceiver(cm_ServerSocket);
CreateUMReceiver(um_ServerSocket);
CreateEventReceiver(event_ServerSocket);
BufferedReader consoleBr = new BufferedReader(new InputStreamReader(System.in));
while (true) {
// BroadCastToCommunicationManagers(consoleBr.readLine());
BroadCastToUpdateMangers(consoleBr.readLine());
}
}
// Launches a thread whos job it is to listen for incoming Update Manager
// connection requests.
// When one is detected, a new thread is launched that will deal with messages
// coming from that Update Manager.
public static void CreateUMReceiver(ServerSocket serverSocket) {
Runnable umServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new UmThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, null, t, null));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().umThread = t;
}
}
}
};
Thread umThread = new Thread(umServer);
umThread.start();
Printer.CustomPrint("Started um Receiver Thread");
}
public static void CreateCMReceiver(ServerSocket serverSocket) {
Runnable cmServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new CmThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, t, null, null));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().cmThread = t;
}
}
}
};
Thread cmThread = new Thread(cmServer);
cmThread.start();
Printer.CustomPrint("Started cm Receiver Thread");
}
public static void CreateEventReceiver(ServerSocket serverSocket) {
Runnable eventServer = new Runnable() {
public void run() {
Socket socket = null;
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
Thread t = new EventThread(socket);
t.start();
if (openConnections.stream().noneMatch(x -> x.srID == 0)) {
openConnections.add(new ConnectedStreamReasoner(0, null, null, t));
} else {
openConnections.stream().filter(x -> x.srID == 0).findFirst().get().eventThread = t;
}
}
}
};
Thread eventChannelThread = new Thread(eventServer);
eventChannelThread.start();
Printer.CustomPrint("Started Event Channel Receiver Thread");
}
public static void assignLupsRules(ConnectedStreamReasoner sr0) {
//Exp1Test1
if(exp==1 && test==1) {
sr0.lupsRules.add(new LupsRule("execute rule editPredicateCommunication(0,push,false,0) when trafficJam(l34)"));
}
//Exp1Test2
if(exp==1 && test==2) {
//manually input: interfaceCommand(addException^-1^0^0^[(0,[l20])]^push^false^0)
}
//Exp2Test1
if(exp==2 && test==1) {
sr0.lupsRules.add(new LupsRule("disable for -1 rule trafficCount when prideParade(l34)"));
sr0.lupsRules.add(new LupsRule("enable for -1 rule trafficCount when prideParadeEnd(l34)"));
}
//Exp2Test2
if(exp==2 && test==2) {
sr0.lupsRules.add(new LupsRule("execute for 60 rule editParameterValue(0,001.00) when trafficJam(l20)"));
}
//Exp2Test3
if(exp==2 && test==3) {
sr0.lupsRules.add(new LupsRule("assert for 15 rule hasSignalGroup(L,T) :- &sql2[\"SELECT a,b FROM object_role_assertion WHERE object_role=151\"](L,T). when trafficJam(l20)"));
sr0.lupsRules.add(new LupsRule("assert for 15 rule trafficLighState(T,S) :- &sql2[\"SELECT DISTINCT ON (iid) iid, x FROM v_signalstate_mrel WHERE tp > 0 ORDER BY iid, tp DESC\"](T,S). when trafficJam(l20)"));
sr0.lupsRules.add(new LupsRule("assert for 15 rule @wsSend(\"trafficLightState(\",T,\",\",S,\")\") :- hasSignalGroup(L,T), trafficLighState(T,S). when trafficJam(l20)"));
}
}
public static void BroadCastToCommunicationManagers(String message) {
for (ConnectedStreamReasoner sr : openConnections) {
((CmThread) sr.cmThread).pushMessage(message);
}
}
public static void BroadCastToUpdateMangers(String message) {
for (ConnectedStreamReasoner sr : openConnections) {
((UmThread) sr.umThread).pushMessage(message);
}
}
}
| 6,173 | 0.668233 | 0.651871 | 186 | 31.188171 | 32.736191 | 211 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.005376 | false | false | 4 |
7aaa38ce6d2d5a96acbc42a994251bd9e94055c7 | 13,477,607,437,838 | 9a1cdd3ddd753d7d9f860b3d76e75a3b005613e1 | /PbResponsibilityListDao.java | 34ef134ea559c224d3fcc5aa25a3822acde9fe75 | [] | no_license | L0ngxhn/ResponsibilityList | https://github.com/L0ngxhn/ResponsibilityList | f1e80bc41c2d175ee90275ac0c86e3736165c0b3 | 95a4872c0b37fc5a5e77117d2b7ae3bf236fa637 | refs/heads/master | 2020-03-18T03:56:34.601000 | 2018-05-21T12:03:17 | 2018-05-21T12:03:17 | 134,263,262 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cl.ipb.web.dao.pb;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.cl.ipb.common.Page;
import com.cl.ipb.web.dao.BaseDao;
import com.cl.ipb.web.model.pb.PbProject;
import com.cl.ipb.web.model.pb.PbResponsibilityList;
@Repository
public class PbResponsibilityListDao extends BaseDao<PbResponsibilityList>{
//某个机构所拥有的的清单列表
public PbResponsibilityList getListById( String id) {
String hql = "from PbResponsibilityList rl where rl.id = ?";//
return get(hql,id);
}
//根据清单名称、清单责任类型(下拉菜单)、适用组织机构类别(下拉菜单、数字字典),两表关联查询(pb_responsibility_type and pb_responsibility_list)
//查询条件已完善
public Page getListByPartyUnitIdAnd(Page page, String id,Map<String,String> conditions) {
StringBuffer hql = new StringBuffer("from PbResponsibilityList rl where rl.delFlag='0' ");
if(!id.equals("")){
hql.append("and rl.ownerUnit.id ='"+id+"'");
}
if (conditions.get("listName").length()>0) {
hql.append(" and rl.name like '%");
hql.append(conditions.get("listName") + "%'");
}
if(conditions.get("type").length()>0){
hql.append("and rl.type.name ='" + conditions.get("type") + "'");
}
if(conditions.get("unitType").length()>0){
hql.append("and rl.unitType ='" + conditions.get("unitType") + "'");
}
if(conditions.get("year").length()>0){
hql.append("and rl.year ='" + conditions.get("year") + "'");
}
return findPage(page, hql.toString(), null);
}
//显示某个项目的清单列表
public List<PbResponsibilityList> getListsByProjrctId(String projectId) {
String hql = "from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
return find(hql, null);
}
//获取某个项目的清单分值
public Float getPointsByProjectId(String projectId) {
String hql = "select sum(rl.points) from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
Object o = findListByHql(hql).get(0);
return Float.valueOf(o==null?"0":o.toString());
}
//获取某个项目的清单数量
public int getCountByProjectId(String projectId) {
String hql = "select count(rl.id) from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
Object o = findListByHql(hql).get(0);
return Integer.valueOf(o==null?"0":o.toString());
}
public void del(PbResponsibilityList pbResponsibilityList){
pbResponsibilityList.setDelFlag(1);
this.update(pbResponsibilityList);
}
/**
* 根据条件查询列表
* @param id
* @param conditions
* @return
*/
public List<PbResponsibilityList> listByDotDot(String ownerPartId,Map<String,String> conditions){
StringBuffer hql = new StringBuffer("from PbResponsibilityList rl where rl.delFlag='0' and rl.ownerUnit.id ='"+ownerPartId+"'");
//模糊搜索
if (conditions.get("listName") !=null && conditions.get("listName").length()>0) {
hql.append(" and rl.name like '%");
hql.append(conditions.get("listName") + "%'");
}
//责任类型 数据自典value
if(conditions.get("type") !=null && conditions.get("type").length()>0){
System.out.println(conditions.get("type"));
hql.append("and rl.type.name ='" + conditions.get("type") + "'");
}
//适用机构类型 数据自典Id
if( conditions.get("unitType") !=null && conditions.get("unitType").length()>0){
hql.append("and rl.unitType ='" + conditions.get("unitType") + "'");
}
//执行年份
if(conditions.get("year") !=null && conditions.get("year").length()>0){
hql.append("and rl.year ='" + conditions.get("year") + "'");
}
//履责类型 :1机构 2人员
if(conditions.get("objectType") !=null && conditions.get("objectType").length()>0){
hql.append("and rl.objectType='"+conditions.get("objectType")+"'");
}
//人员履责类型 数据自典id
if(conditions.get("member_responsibility_type") !=null && conditions.get("member_responsibility_type").length()>0){
hql.append("and rl.member_responsibility_type='"+conditions.get("member_responsibility_type")+"'");
}
//责任层级
if(conditions.get("level") !=null && conditions.get("level").length()>0){
hql.append("and rl.level='"+conditions.get("level")+"'");
}
System.out.println(hql.toString());
return findListByHql(hql.toString());
}
}
| UTF-8 | Java | 4,756 | java | PbResponsibilityListDao.java | Java | [] | null | [] | package com.cl.ipb.web.dao.pb;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.cl.ipb.common.Page;
import com.cl.ipb.web.dao.BaseDao;
import com.cl.ipb.web.model.pb.PbProject;
import com.cl.ipb.web.model.pb.PbResponsibilityList;
@Repository
public class PbResponsibilityListDao extends BaseDao<PbResponsibilityList>{
//某个机构所拥有的的清单列表
public PbResponsibilityList getListById( String id) {
String hql = "from PbResponsibilityList rl where rl.id = ?";//
return get(hql,id);
}
//根据清单名称、清单责任类型(下拉菜单)、适用组织机构类别(下拉菜单、数字字典),两表关联查询(pb_responsibility_type and pb_responsibility_list)
//查询条件已完善
public Page getListByPartyUnitIdAnd(Page page, String id,Map<String,String> conditions) {
StringBuffer hql = new StringBuffer("from PbResponsibilityList rl where rl.delFlag='0' ");
if(!id.equals("")){
hql.append("and rl.ownerUnit.id ='"+id+"'");
}
if (conditions.get("listName").length()>0) {
hql.append(" and rl.name like '%");
hql.append(conditions.get("listName") + "%'");
}
if(conditions.get("type").length()>0){
hql.append("and rl.type.name ='" + conditions.get("type") + "'");
}
if(conditions.get("unitType").length()>0){
hql.append("and rl.unitType ='" + conditions.get("unitType") + "'");
}
if(conditions.get("year").length()>0){
hql.append("and rl.year ='" + conditions.get("year") + "'");
}
return findPage(page, hql.toString(), null);
}
//显示某个项目的清单列表
public List<PbResponsibilityList> getListsByProjrctId(String projectId) {
String hql = "from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
return find(hql, null);
}
//获取某个项目的清单分值
public Float getPointsByProjectId(String projectId) {
String hql = "select sum(rl.points) from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
Object o = findListByHql(hql).get(0);
return Float.valueOf(o==null?"0":o.toString());
}
//获取某个项目的清单数量
public int getCountByProjectId(String projectId) {
String hql = "select count(rl.id) from PbResponsibilityList rl where rl.id in("
+ "select pr.pbResponsibilityList.id from PbProjectResponsibility pr where pr.pbProject.id='"+projectId+"')";
Object o = findListByHql(hql).get(0);
return Integer.valueOf(o==null?"0":o.toString());
}
public void del(PbResponsibilityList pbResponsibilityList){
pbResponsibilityList.setDelFlag(1);
this.update(pbResponsibilityList);
}
/**
* 根据条件查询列表
* @param id
* @param conditions
* @return
*/
public List<PbResponsibilityList> listByDotDot(String ownerPartId,Map<String,String> conditions){
StringBuffer hql = new StringBuffer("from PbResponsibilityList rl where rl.delFlag='0' and rl.ownerUnit.id ='"+ownerPartId+"'");
//模糊搜索
if (conditions.get("listName") !=null && conditions.get("listName").length()>0) {
hql.append(" and rl.name like '%");
hql.append(conditions.get("listName") + "%'");
}
//责任类型 数据自典value
if(conditions.get("type") !=null && conditions.get("type").length()>0){
System.out.println(conditions.get("type"));
hql.append("and rl.type.name ='" + conditions.get("type") + "'");
}
//适用机构类型 数据自典Id
if( conditions.get("unitType") !=null && conditions.get("unitType").length()>0){
hql.append("and rl.unitType ='" + conditions.get("unitType") + "'");
}
//执行年份
if(conditions.get("year") !=null && conditions.get("year").length()>0){
hql.append("and rl.year ='" + conditions.get("year") + "'");
}
//履责类型 :1机构 2人员
if(conditions.get("objectType") !=null && conditions.get("objectType").length()>0){
hql.append("and rl.objectType='"+conditions.get("objectType")+"'");
}
//人员履责类型 数据自典id
if(conditions.get("member_responsibility_type") !=null && conditions.get("member_responsibility_type").length()>0){
hql.append("and rl.member_responsibility_type='"+conditions.get("member_responsibility_type")+"'");
}
//责任层级
if(conditions.get("level") !=null && conditions.get("level").length()>0){
hql.append("and rl.level='"+conditions.get("level")+"'");
}
System.out.println(hql.toString());
return findListByHql(hql.toString());
}
}
| 4,756 | 0.668393 | 0.66389 | 113 | 37.309734 | 34.050217 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.256637 | false | false | 4 |
f557946e1433a5b6464d7caf805159e1ee58acba | 21,199,958,629,720 | 78354044deae527de861fc6449d658f952776556 | /src/main/java/com/cjw/yolonote/service/NoteBookService.java | 186ab791b2f3b650fc2b614d0d357c388dda4c53 | [] | no_license | WYUSIG/YoloNote | https://github.com/WYUSIG/YoloNote | 4a1638dc9c75c750a863b3dda79da4fc95e8cfc4 | 2e9c81f94ea030e5fefd420ad352475315436fb2 | refs/heads/master | 2020-09-27T04:41:32.136000 | 2019-12-20T09:53:13 | 2019-12-20T09:53:13 | 226,432,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cjw.yolonote.service;
/**
* @ClassName NoteBookService
* @Description: TODO
* @Author 陈家婉
* @Date 2019/12/17 0017
* @Version V1.0
**/
public interface NoteBookService {
}
| UTF-8 | Java | 196 | java | NoteBookService.java | Java | [
{
"context": " NoteBookService\n * @Description: TODO\n * @Author 陈家婉\n * @Date 2019/12/17 0017\n * @Version V1.0\n **/\npu",
"end": 105,
"score": 0.9997649788856506,
"start": 102,
"tag": "NAME",
"value": "陈家婉"
}
] | null | [] | package com.cjw.yolonote.service;
/**
* @ClassName NoteBookService
* @Description: TODO
* @Author 陈家婉
* @Date 2019/12/17 0017
* @Version V1.0
**/
public interface NoteBookService {
}
| 196 | 0.694737 | 0.621053 | 11 | 16.272728 | 12.314743 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.090909 | false | false | 4 |
de5b6acc013884c0200fb05c4326b1de18bbd600 | 19,430,432,051,653 | 319310d814b2d94ce76c9cb768acc4faf751c842 | /apps/VOSSystemManager/src/main/java/il/co/vor/SystemManager/ServicesTableModel.java | 892e3cf6195fa842dbef5680d574588f3a41803a | [] | no_license | AvrahamBabkoff/vor | https://github.com/AvrahamBabkoff/vor | 1a6108b969fe9885f0fe55e4fb61cfbc7a140e6e | 59d8ca1df48856d4ef80a04a7916e0e6c0989cee | refs/heads/master | 2022-12-09T11:07:57.963000 | 2019-06-19T05:50:47 | 2019-06-19T05:50:47 | 192,471,060 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package il.co.vor.SystemManager;
import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.table.AbstractTableModel;
import il.co.vor.DalConfigObjects.Service;
import il.co.vor.common.Enums.ServiceType;
import il.co.vor.defines.Constants;
@SuppressWarnings("serial")
public class ServicesTableModel extends AbstractTableModel {
private List<ServiceUIWraper> m_servicesData = null;
private String[] m_serviceTypeNames = null;
private String[] m_columnNames = null;
private Icon m_errorIcon = null;
private Icon m_successIcon = null;
public ServicesTableModel() {
m_errorIcon = new ImageIcon(getClass().getResource(Constants.ERROR_IMAGE_PATH));
m_successIcon = new ImageIcon(getClass().getResource(Constants.SUCCESS_IMAGE_PATH));
m_columnNames = new String[9];
m_columnNames[Constants.SERVICE_ID_COLUMN_NUMBER] = Constants.SERVICE_ID_COLUMN_NAME;
m_columnNames[Constants.SERVICE_TYPE_NAME_COLUMN_NUMBER] = Constants.SERVICE_TYPE_NAME_COLUMN_NAME;
m_columnNames[Constants.SERVICE_NAME_COLUMN_NUMBER] = Constants.SERVICE_NAME_COLUMN_NAME;
m_columnNames[Constants.SERVICE_DESCRIPTION_COLUMN_NUMBER] = Constants.SERVICE_DESCRIPTION_COLUMN_NAME;
m_columnNames[Constants.SERVICE_ADDRESS_IP_COLUMN_NUMBER] = Constants.SERVICE_ADDRESS_IP_COLUMN_NAME;
m_columnNames[Constants.SERVICE_PORT_COLUMN_NUMBER] = Constants.SERVICE_PORT_COLUMN_NAME;
m_columnNames[Constants.SERVICE_STATUS_COLUMN_NUMBER] = Constants.SERVICE_STATUS_COLUMN_NAME;
m_columnNames[Constants.SERVICE_LOG_LEVEL_NUMBER] = Constants.SERVICE_LOG_LEVEL_NAME;
m_columnNames[Constants.SITE_NAME_COLUMN_NUMBER] = Constants.SITE_NAME_COLUMN_NAME;
m_serviceTypeNames = new String[ServiceType.values().length];
int index = 0;
for (ServiceType type : ServiceType.values()) {
m_serviceTypeNames[index++] = type.toString();
}
}
public int GetStatusColumnNumber() {
return Constants.SERVICE_STATUS_COLUMN_NUMBER;
}
public int GetLogLevelColumnNumber() {
return Constants.SERVICE_LOG_LEVEL_NUMBER;
}
public void updateServices(List<ServiceUIWraper> _servicesData) {
m_servicesData = _servicesData;
}
@Override
public String getColumnName(int column) {
return m_columnNames[column];
}
@Override
public int getColumnCount() {
return m_columnNames.length;
}
@Override
public int getRowCount() {
return ((null != m_servicesData) ? m_servicesData.size() : 0);
}
@Override
public Object getValueAt(int row, int column) {
Object serviceAttribute = null;
if (null != m_servicesData)
{
ServiceUIWraper serviceObjectWrapper = m_servicesData.get(row);
Service serviceObject = serviceObjectWrapper.getService();
switch(column) {
case Constants.SERVICE_ID_COLUMN_NUMBER: serviceAttribute = String.valueOf(serviceObject.getServiceId()); break;
case Constants.SERVICE_TYPE_NAME_COLUMN_NUMBER: serviceAttribute = m_serviceTypeNames[serviceObject.getServiceType()]; break;
case Constants.SERVICE_NAME_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceName(); break;
case Constants.SERVICE_DESCRIPTION_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceDescription(); break;
case Constants.SERVICE_ADDRESS_IP_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceAddressIp(); break;
case Constants.SERVICE_PORT_COLUMN_NUMBER: serviceAttribute = String.valueOf(serviceObject.getServiceAddressPort()); break;
case Constants.SERVICE_STATUS_COLUMN_NUMBER: serviceAttribute = (serviceObjectWrapper.isActive()) ? m_successIcon: m_errorIcon; break;
case Constants.SERVICE_LOG_LEVEL_NUMBER: serviceAttribute = serviceObjectWrapper.getLogLevel(); break;
case Constants.SITE_NAME_COLUMN_NUMBER: serviceAttribute = serviceObjectWrapper.getSiteName(); break;
default: break;
}
}
return serviceAttribute;
}
}
| UTF-8 | Java | 4,171 | java | ServicesTableModel.java | Java | [] | null | [] | package il.co.vor.SystemManager;
import java.util.List;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.table.AbstractTableModel;
import il.co.vor.DalConfigObjects.Service;
import il.co.vor.common.Enums.ServiceType;
import il.co.vor.defines.Constants;
@SuppressWarnings("serial")
public class ServicesTableModel extends AbstractTableModel {
private List<ServiceUIWraper> m_servicesData = null;
private String[] m_serviceTypeNames = null;
private String[] m_columnNames = null;
private Icon m_errorIcon = null;
private Icon m_successIcon = null;
public ServicesTableModel() {
m_errorIcon = new ImageIcon(getClass().getResource(Constants.ERROR_IMAGE_PATH));
m_successIcon = new ImageIcon(getClass().getResource(Constants.SUCCESS_IMAGE_PATH));
m_columnNames = new String[9];
m_columnNames[Constants.SERVICE_ID_COLUMN_NUMBER] = Constants.SERVICE_ID_COLUMN_NAME;
m_columnNames[Constants.SERVICE_TYPE_NAME_COLUMN_NUMBER] = Constants.SERVICE_TYPE_NAME_COLUMN_NAME;
m_columnNames[Constants.SERVICE_NAME_COLUMN_NUMBER] = Constants.SERVICE_NAME_COLUMN_NAME;
m_columnNames[Constants.SERVICE_DESCRIPTION_COLUMN_NUMBER] = Constants.SERVICE_DESCRIPTION_COLUMN_NAME;
m_columnNames[Constants.SERVICE_ADDRESS_IP_COLUMN_NUMBER] = Constants.SERVICE_ADDRESS_IP_COLUMN_NAME;
m_columnNames[Constants.SERVICE_PORT_COLUMN_NUMBER] = Constants.SERVICE_PORT_COLUMN_NAME;
m_columnNames[Constants.SERVICE_STATUS_COLUMN_NUMBER] = Constants.SERVICE_STATUS_COLUMN_NAME;
m_columnNames[Constants.SERVICE_LOG_LEVEL_NUMBER] = Constants.SERVICE_LOG_LEVEL_NAME;
m_columnNames[Constants.SITE_NAME_COLUMN_NUMBER] = Constants.SITE_NAME_COLUMN_NAME;
m_serviceTypeNames = new String[ServiceType.values().length];
int index = 0;
for (ServiceType type : ServiceType.values()) {
m_serviceTypeNames[index++] = type.toString();
}
}
public int GetStatusColumnNumber() {
return Constants.SERVICE_STATUS_COLUMN_NUMBER;
}
public int GetLogLevelColumnNumber() {
return Constants.SERVICE_LOG_LEVEL_NUMBER;
}
public void updateServices(List<ServiceUIWraper> _servicesData) {
m_servicesData = _servicesData;
}
@Override
public String getColumnName(int column) {
return m_columnNames[column];
}
@Override
public int getColumnCount() {
return m_columnNames.length;
}
@Override
public int getRowCount() {
return ((null != m_servicesData) ? m_servicesData.size() : 0);
}
@Override
public Object getValueAt(int row, int column) {
Object serviceAttribute = null;
if (null != m_servicesData)
{
ServiceUIWraper serviceObjectWrapper = m_servicesData.get(row);
Service serviceObject = serviceObjectWrapper.getService();
switch(column) {
case Constants.SERVICE_ID_COLUMN_NUMBER: serviceAttribute = String.valueOf(serviceObject.getServiceId()); break;
case Constants.SERVICE_TYPE_NAME_COLUMN_NUMBER: serviceAttribute = m_serviceTypeNames[serviceObject.getServiceType()]; break;
case Constants.SERVICE_NAME_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceName(); break;
case Constants.SERVICE_DESCRIPTION_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceDescription(); break;
case Constants.SERVICE_ADDRESS_IP_COLUMN_NUMBER: serviceAttribute = serviceObject.getServiceAddressIp(); break;
case Constants.SERVICE_PORT_COLUMN_NUMBER: serviceAttribute = String.valueOf(serviceObject.getServiceAddressPort()); break;
case Constants.SERVICE_STATUS_COLUMN_NUMBER: serviceAttribute = (serviceObjectWrapper.isActive()) ? m_successIcon: m_errorIcon; break;
case Constants.SERVICE_LOG_LEVEL_NUMBER: serviceAttribute = serviceObjectWrapper.getLogLevel(); break;
case Constants.SITE_NAME_COLUMN_NUMBER: serviceAttribute = serviceObjectWrapper.getSiteName(); break;
default: break;
}
}
return serviceAttribute;
}
}
| 4,171 | 0.710141 | 0.709422 | 98 | 40.561226 | 40.108288 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.397959 | false | false | 4 |
1737203d705edc58e1143cdc7aaea9412d6d2420 | 21,457,656,612,033 | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-900-Files/boiler-To-Generate-900-Files/syncregions-900Files/BoilerActuator5909.java | a7d58cbb3ad5ccea2479e1b3c3a7f2621b0ec2b2 | [] | no_license | soha500/EglSync | https://github.com/soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464000 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | false | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | 2019-04-15T09:03:54 | 2019-05-31T11:34:01 | 87 | 0 | 0 | 0 | Java | false | false | package syncregions;
public class BoilerActuator5909 {
public execute(int temperatureDifference5909, boolean boilerStatus5909) {
//sync _bfpnGUbFEeqXnfGWlV5909, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| UTF-8 | Java | 263 | java | BoilerActuator5909.java | Java | [] | null | [] | package syncregions;
public class BoilerActuator5909 {
public execute(int temperatureDifference5909, boolean boilerStatus5909) {
//sync _bfpnGUbFEeqXnfGWlV5909, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| 263 | 0.749049 | 0.688213 | 13 | 19.23077 | 24.729782 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.230769 | false | false | 4 |
15d38d0facc0bc6008cf42cafd18f98d0f42dfc4 | 33,706,903,387,196 | db9c6a12076c7c96765b9448247d7feb0cb9a2b2 | /chain/chain-shop/src/main/java/net/onlineshop/services/manage/cases/dao/impl/CasesDaoImpl.java | c1ff8f96a4053445cf784a80a12aeda9fdba27d7 | [] | no_license | wangbing234/qkkj | https://github.com/wangbing234/qkkj | d1730bbf89fa0e1d84a4a3bacdf3400b502d7cf5 | dc4f5b70b8e801e8d430c00636569040f2599e54 | refs/heads/master | 2020-12-02T18:14:30.271000 | 2017-07-07T08:50:27 | 2017-07-07T08:50:27 | 96,497,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.onlineshop.services.manage.cases.dao.impl;
import java.util.List;
import net.onlineshop.core.dao.BaseDao;
import net.onlineshop.core.dao.page.PagerModel;
import net.onlineshop.services.manage.cases.bean.Cases;
import net.onlineshop.services.manage.cases.dao.CasesDao;
public class CasesDaoImpl implements CasesDao {
private BaseDao dao;
public void setDao(BaseDao dao) {
this.dao = dao;
}
public PagerModel selectPageList(Cases e) {
return dao.selectPageList("manage.cases.selectPageList", "manage.cases.selectPageCount", e);
}
public List selectList(Cases e) {
return dao.selectList("manage.cases.selectList", e);
}
public Cases selectOne(Cases e) {
return (Cases) dao.selectOne("manage.cases.selectOne", e);
}
public int delete(Cases e) {
return dao.delete("manage.cases.delete", e);
}
public int update(Cases e) {
return dao.update("manage.cases.update", e);
}
public int deletes(String[] ids) {
Cases e = new Cases();
for (int i = 0; i < ids.length; i++) {
e.setId(ids[i]);
delete(e);
}
return 0;
}
public int insert(Cases e) {
return dao.insert("manage.cases.insert", e);
}
public int deleteById(int id) {
return dao.delete("manage.cases.deleteById", id);
}
@Override
public Cases selectById(String id) {
return (Cases) dao.selectOne("manage.cases.selectById", id);
}
}
| UTF-8 | Java | 1,354 | java | CasesDaoImpl.java | Java | [] | null | [] | package net.onlineshop.services.manage.cases.dao.impl;
import java.util.List;
import net.onlineshop.core.dao.BaseDao;
import net.onlineshop.core.dao.page.PagerModel;
import net.onlineshop.services.manage.cases.bean.Cases;
import net.onlineshop.services.manage.cases.dao.CasesDao;
public class CasesDaoImpl implements CasesDao {
private BaseDao dao;
public void setDao(BaseDao dao) {
this.dao = dao;
}
public PagerModel selectPageList(Cases e) {
return dao.selectPageList("manage.cases.selectPageList", "manage.cases.selectPageCount", e);
}
public List selectList(Cases e) {
return dao.selectList("manage.cases.selectList", e);
}
public Cases selectOne(Cases e) {
return (Cases) dao.selectOne("manage.cases.selectOne", e);
}
public int delete(Cases e) {
return dao.delete("manage.cases.delete", e);
}
public int update(Cases e) {
return dao.update("manage.cases.update", e);
}
public int deletes(String[] ids) {
Cases e = new Cases();
for (int i = 0; i < ids.length; i++) {
e.setId(ids[i]);
delete(e);
}
return 0;
}
public int insert(Cases e) {
return dao.insert("manage.cases.insert", e);
}
public int deleteById(int id) {
return dao.delete("manage.cases.deleteById", id);
}
@Override
public Cases selectById(String id) {
return (Cases) dao.selectOne("manage.cases.selectById", id);
}
}
| 1,354 | 0.711965 | 0.710487 | 58 | 22.344828 | 22.762304 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.465517 | false | false | 4 |
640c908eb74e925b0a9f89216099b7e6a1e50669 | 2,181,843,393,003 | 4c84171d0e54f2a1612b688cd06d1723dbd997ff | /src/main/java/com/findat/service/UserService.java | d7622c4b6f57a84900f74c6dce39311bf77db983 | [] | no_license | jorgegueyer/findat-app | https://github.com/jorgegueyer/findat-app | beab0243cf69848b53470f3e3dda4ddc484f4aee | 851c889bb612d3cb3d1a804803a8fc71b40fe7b8 | refs/heads/master | 2021-06-09T07:57:11.131000 | 2020-01-23T12:05:04 | 2020-01-23T12:05:04 | 150,277,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.findat.service;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.findat.model.User;
import com.findat.model.UserList;
public class UserService {
List<User> userList = UserList.getInstance();
public List<User> getAllUsers() {
return userList;
}
public List<User> searchUsersByName(String name) {
Comparator<User> groupByComparator = Comparator.comparing(User::getName)
.thenComparing(User::getLastName);
List<User> result = userList
.stream()
.filter(e -> e.getName().equalsIgnoreCase(name) || e.getLastName().equalsIgnoreCase(name))
.sorted(groupByComparator)
.collect(Collectors.toList()); //terminal operation
return result;
}
public User getUser(long id) throws Exception {
Optional<User> match = userList.stream()
.filter(e -> e.getId() == id)
.findFirst(); //terminal operation
if (match.isPresent()) return match.get();
else throw new Exception("The User id " + id + " not found");
}
public long addUser(User user) {
userList.add(user);
return user.getId();
}
public boolean updateUser(User customer) {
int matchIdx = 0;
Optional<User> match = userList.stream()
.filter(c -> c.getId() == customer.getId())
.findFirst();
if (match.isPresent()) {
matchIdx = userList.indexOf(match.get());
userList.set(matchIdx, customer);
return true;
} else {
return false;
}
}
public boolean deleteUser(long id) {
Predicate<User> user = e -> e.getId() == id;
if (userList.removeIf(user)) {
return true;
} else {
return false;
}
}
}
| UTF-8 | Java | 2,036 | java | UserService.java | Java | [] | null | [] | package com.findat.service;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import com.findat.model.User;
import com.findat.model.UserList;
public class UserService {
List<User> userList = UserList.getInstance();
public List<User> getAllUsers() {
return userList;
}
public List<User> searchUsersByName(String name) {
Comparator<User> groupByComparator = Comparator.comparing(User::getName)
.thenComparing(User::getLastName);
List<User> result = userList
.stream()
.filter(e -> e.getName().equalsIgnoreCase(name) || e.getLastName().equalsIgnoreCase(name))
.sorted(groupByComparator)
.collect(Collectors.toList()); //terminal operation
return result;
}
public User getUser(long id) throws Exception {
Optional<User> match = userList.stream()
.filter(e -> e.getId() == id)
.findFirst(); //terminal operation
if (match.isPresent()) return match.get();
else throw new Exception("The User id " + id + " not found");
}
public long addUser(User user) {
userList.add(user);
return user.getId();
}
public boolean updateUser(User customer) {
int matchIdx = 0;
Optional<User> match = userList.stream()
.filter(c -> c.getId() == customer.getId())
.findFirst();
if (match.isPresent()) {
matchIdx = userList.indexOf(match.get());
userList.set(matchIdx, customer);
return true;
} else {
return false;
}
}
public boolean deleteUser(long id) {
Predicate<User> user = e -> e.getId() == id;
if (userList.removeIf(user)) {
return true;
} else {
return false;
}
}
}
| 2,036 | 0.562377 | 0.561886 | 68 | 28.941177 | 23.078436 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 4 |
d57384bd047fa2916a5a068e4cf9392be4c58ed5 | 2,181,843,395,097 | 5552158836965cc8442947438deef73e43205647 | /SonAEs-LPIII/src/java/banco/ProcessoDAO.java | 0d5df859e54309a1292e95d8e69b4dc0a48f8352 | [] | no_license | Fernando-7/Temporario | https://github.com/Fernando-7/Temporario | 02cef64545befa53662df02e1556b85ef2f03fc0 | 55d4a81915e7ea8169874939088adfa27c5a0684 | refs/heads/master | 2017-11-02T16:54:45.642000 | 2017-07-07T14:23:30 | 2017-07-07T14:23:30 | 96,545,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 banco;
import classes.*;
import java.sql.*;
import java.util.*;
/**
*
* @author Icaro
*/
public class ProcessoDAO {
private Connection conn;
public ArrayList<Processo> pesquisar(Processo P){
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "select * FROM processo";
query += " WHERE processo.matricula = '" + P.getMatricula()+"'";
query += " ORDER BY processo.numProcesso asc";
Statement stm = conn.createStatement();
ResultSet resultado = stm.executeQuery(query);
ArrayList< Processo > listaProcesso = new ArrayList< Processo >();
while(resultado.next()){
listaProcesso.add(new Processo(resultado.getInt("numProcesso"), resultado.getString("matricula"), resultado.getString("status"), resultado.getInt("tempo")));
}
stm.close();
conn.close();
return listaProcesso;
}catch(Exception e){
throw new RuntimeException(e);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
public void adicionar(Processo P) throws ClassNotFoundException {
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "insert into processo ";
query += "(numProcesso,matricula,status,tempo, descricao) ";
query += "values (?,?,?,?,?)";
PreparedStatement stm = conn.prepareStatement(query);
stm.setInt(1, P.getNumProcesso());
stm.setString(2, P.getMatricula());
stm.setString(3, P.getStatus());
stm.setInt(4, P.getTempo());
stm.setString(5, P.getDescricao());
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException(e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException(e);
}
}
public void alterar(Processo P) throws ClassNotFoundException{
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "update sistema_integracao.processo ";
query += "set status = ?,tempo = ?, descricao = ?";
query += "where numProcesso = " + P.getNumProcesso();
PreparedStatement stm = conn.prepareStatement(query);
stm.setString(1, P.getStatus());
stm.setInt(2, P.getTempo());
stm.setString(3, P.getDescricao());
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException (e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException (e);
}
}
public void remover(Processo P) throws ClassNotFoundException{
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "delete from sistema_integracao.processo ";
query += "where numProcesso = " + P.getNumProcesso();
PreparedStatement stm = conn.prepareStatement(query);
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException(e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException(e);
}
}
public Processo pesquisarID(Processo P){
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "select * FROM processo";
query += " WHERE processo.numProcesso = '" + P.getNumProcesso()+"'";
query += " ORDER BY processo.numProcesso asc";
Statement stm = conn.createStatement();
ResultSet resultado = stm.executeQuery(query);
Processo pro = null;
while(resultado.next()){
pro = new Processo(resultado.getInt("numProcesso"), resultado.getString("matricula"), resultado.getString("status"), resultado.getInt("tempo"), resultado.getString("descricao"));
}
stm.close();
conn.close();
return pro;
}catch(Exception e){
throw new RuntimeException(e);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
| UTF-8 | Java | 5,055 | java | ProcessoDAO.java | Java | [
{
"context": " java.sql.*;\nimport java.util.*;\n/**\n *\n * @author Icaro\n */\npublic class ProcessoDAO {\n private Co",
"end": 280,
"score": 0.9989614486694336,
"start": 275,
"tag": "NAME",
"value": "Icaro"
}
] | null | [] | /*
* 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 banco;
import classes.*;
import java.sql.*;
import java.util.*;
/**
*
* @author Icaro
*/
public class ProcessoDAO {
private Connection conn;
public ArrayList<Processo> pesquisar(Processo P){
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "select * FROM processo";
query += " WHERE processo.matricula = '" + P.getMatricula()+"'";
query += " ORDER BY processo.numProcesso asc";
Statement stm = conn.createStatement();
ResultSet resultado = stm.executeQuery(query);
ArrayList< Processo > listaProcesso = new ArrayList< Processo >();
while(resultado.next()){
listaProcesso.add(new Processo(resultado.getInt("numProcesso"), resultado.getString("matricula"), resultado.getString("status"), resultado.getInt("tempo")));
}
stm.close();
conn.close();
return listaProcesso;
}catch(Exception e){
throw new RuntimeException(e);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
public void adicionar(Processo P) throws ClassNotFoundException {
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "insert into processo ";
query += "(numProcesso,matricula,status,tempo, descricao) ";
query += "values (?,?,?,?,?)";
PreparedStatement stm = conn.prepareStatement(query);
stm.setInt(1, P.getNumProcesso());
stm.setString(2, P.getMatricula());
stm.setString(3, P.getStatus());
stm.setInt(4, P.getTempo());
stm.setString(5, P.getDescricao());
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException(e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException(e);
}
}
public void alterar(Processo P) throws ClassNotFoundException{
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "update sistema_integracao.processo ";
query += "set status = ?,tempo = ?, descricao = ?";
query += "where numProcesso = " + P.getNumProcesso();
PreparedStatement stm = conn.prepareStatement(query);
stm.setString(1, P.getStatus());
stm.setInt(2, P.getTempo());
stm.setString(3, P.getDescricao());
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException (e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException (e);
}
}
public void remover(Processo P) throws ClassNotFoundException{
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "delete from sistema_integracao.processo ";
query += "where numProcesso = " + P.getNumProcesso();
PreparedStatement stm = conn.prepareStatement(query);
stm.execute();
stm.close();
}catch(Exception e){
throw new RuntimeException(e);
}
conn.close();
}catch(RuntimeException | SQLException e){
throw new RuntimeException(e);
}
}
public Processo pesquisarID(Processo P){
try{
this.conn = new ConnectionFactory().getConnection();
try{
String query = "select * FROM processo";
query += " WHERE processo.numProcesso = '" + P.getNumProcesso()+"'";
query += " ORDER BY processo.numProcesso asc";
Statement stm = conn.createStatement();
ResultSet resultado = stm.executeQuery(query);
Processo pro = null;
while(resultado.next()){
pro = new Processo(resultado.getInt("numProcesso"), resultado.getString("matricula"), resultado.getString("status"), resultado.getInt("tempo"), resultado.getString("descricao"));
}
stm.close();
conn.close();
return pro;
}catch(Exception e){
throw new RuntimeException(e);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
| 5,055 | 0.518892 | 0.51731 | 148 | 33.155407 | 30.586985 | 198 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.094595 | false | false | 4 |
925c353494901f1da8a825bd8116fa3d4b8b1702 | 17,815,524,349,335 | 3ef35a9e8c40be49ccb14977fe44f100d87157aa | /src/DanLiLanHanShi/Test.java | 89afcee1b5e75927312baa6d91b47bfe3d57fe4e | [] | no_license | wfengg/Designer | https://github.com/wfengg/Designer | 9aae0afe92dbee84f5309f66c6a3f0675d6c081c | b46339c04747099e34fe088536f21a8cde6e430d | refs/heads/master | 2020-03-26T21:29:59.805000 | 2018-08-20T08:54:24 | 2018-08-20T08:54:24 | 145,392,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DanLiLanHanShi;
public class Test {
private static Test test = null;
private Test(){};
public static synchronized Test getTest(){
if(test==null){
test = new Test();
}
return test;
}
}
| UTF-8 | Java | 249 | java | Test.java | Java | [] | null | [] | package DanLiLanHanShi;
public class Test {
private static Test test = null;
private Test(){};
public static synchronized Test getTest(){
if(test==null){
test = new Test();
}
return test;
}
}
| 249 | 0.554217 | 0.554217 | 15 | 15.6 | 14.351771 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
4879a13dc2192088ef6c54ee2be046112121b33d | 25,821,343,389,615 | 906ea8cbc4f98a05c8c72d61f1043ada9fcc64b6 | /Programacion 4/Clase2019/Parcial Final/viveros_parcial_final/src/CRUD/CrudVivero.java | 9a1341d7b2d173dfaa967a9a7f9b708af711122e | [] | no_license | santiagoSSAA/Universidad | https://github.com/santiagoSSAA/Universidad | 89ebb03583a6e6455c8bf5a31f88d24ff97fed8f | c9d2680f2d91d2a47c7e2983ce64421deefc4d9f | refs/heads/master | 2020-08-06T06:39:32.583000 | 2020-05-07T15:07:31 | 2020-05-07T15:07:31 | 212,872,465 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package CRUD;
import java.util.ArrayList;
import java.util.Scanner;
import MODEL.Vivero;
import MODEL.Productor;
public class CrudVivero {
public static Vivero CrearVivero(Productor productor) {
if(productor != null) {
Vivero vivero = new Vivero();
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE NOMBRE DEL VIVERO: ");
vivero.setNombreVivero(keyboard.next());
System.out.print("INGRESE DEPARTAMENTO: ");
vivero.setDepartamento(keyboard.next());
System.out.print("INGRESE MUNICIPIO: ");
vivero.setMunicipio(keyboard.next());
productor.addListaVivero(vivero);
return vivero;
}
System.out.println("Productor no encontrado");
return null;
}
public static void mostrarVivero(Vivero vivero) {
System.out.println("Nombre del vivero: " + vivero.getNombre());
System.out.println("Departamento: " + vivero.getDepartamento());
System.out.println("Municipio: " + vivero.getMunicipio());
}
public static Vivero buscarVivero(ArrayList<Vivero> listaViveros) {
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE NOMBRE DEL VIVERO: ");
String nombreVivero = keyboard.next();
for(Vivero vivero : listaViveros) {
if(vivero.getNombreVivero() != null && vivero.getNombreVivero().equals(nombreVivero)) {
return vivero;
}
}
return null;
}
public static ArrayList<Vivero> borrarVivero(ArrayList<Vivero> listaViveros){
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE EL NOMBRE DEL VIVERO: ");
String nombreVivero = keyboard.next();
if(nombreVivero != null) {
listaViveros.removeIf(viveroBorrar -> viveroBorrar.getNombreVivero().equals(nombreVivero));
}
return listaViveros;
}
}
| UTF-8 | Java | 1,764 | java | CrudVivero.java | Java | [] | null | [] | package CRUD;
import java.util.ArrayList;
import java.util.Scanner;
import MODEL.Vivero;
import MODEL.Productor;
public class CrudVivero {
public static Vivero CrearVivero(Productor productor) {
if(productor != null) {
Vivero vivero = new Vivero();
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE NOMBRE DEL VIVERO: ");
vivero.setNombreVivero(keyboard.next());
System.out.print("INGRESE DEPARTAMENTO: ");
vivero.setDepartamento(keyboard.next());
System.out.print("INGRESE MUNICIPIO: ");
vivero.setMunicipio(keyboard.next());
productor.addListaVivero(vivero);
return vivero;
}
System.out.println("Productor no encontrado");
return null;
}
public static void mostrarVivero(Vivero vivero) {
System.out.println("Nombre del vivero: " + vivero.getNombre());
System.out.println("Departamento: " + vivero.getDepartamento());
System.out.println("Municipio: " + vivero.getMunicipio());
}
public static Vivero buscarVivero(ArrayList<Vivero> listaViveros) {
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE NOMBRE DEL VIVERO: ");
String nombreVivero = keyboard.next();
for(Vivero vivero : listaViveros) {
if(vivero.getNombreVivero() != null && vivero.getNombreVivero().equals(nombreVivero)) {
return vivero;
}
}
return null;
}
public static ArrayList<Vivero> borrarVivero(ArrayList<Vivero> listaViveros){
Scanner keyboard = new Scanner(System.in);
System.out.print("INGRESE EL NOMBRE DEL VIVERO: ");
String nombreVivero = keyboard.next();
if(nombreVivero != null) {
listaViveros.removeIf(viveroBorrar -> viveroBorrar.getNombreVivero().equals(nombreVivero));
}
return listaViveros;
}
}
| 1,764 | 0.704082 | 0.704082 | 63 | 27 | 25.295084 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.174603 | false | false | 4 |
4fbc4150360e67be629a0a0777ec1494c2d5b433 | 23,888,608,134,945 | afddd8e7c37d94249af89ec8d0982ed9da5a052c | /pim-parent/pim-web/src/main/java/com/sinux/modules/auth/service/PimDataAuthService.java | 738c34e8c1f1886c19e61a816b10640b23e184e5 | [] | no_license | honcur/learngit | https://github.com/honcur/learngit | 22ace3d532c039b6328150e518f47e9bd2f8cb77 | 10fee51597444cf9dea7982b3abfbe2fc558ad2d | refs/heads/master | 2020-03-22T19:19:34.176000 | 2018-07-31T10:35:23 | 2018-07-31T10:35:23 | 140,520,794 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright © 2015-2020 <a href="http://www.sinux.com.cn/">JFusion</a> All rights reserved.
*/
package com.sinux.modules.auth.service;
import java.util.*;
import com.sinux.core.persistence.Page;
import com.sinux.core.utils.IdGen;
import com.sinux.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.sinux.core.persistence.BatchEntity;
import com.sinux.core.service.BaseCrudService;
import com.sinux.modules.auth.entity.PimDataAuth;
import com.sinux.modules.auth.dao.PimDataAuthDao;
import javax.mail.search.SearchTerm;
/**
* 数据权限Service
*
* @author lf
* @version 2018-07-30
*/
@Service
public class PimDataAuthService extends BaseCrudService<PimDataAuthDao, PimDataAuth> {
/**
* * @Description: 保存数据权限
* * @author lf
* * @date 2018/7/30 10:32
*
*/
@Transactional
public void saveDataAuth(List<PimDataAuth> pimDataAuths) {
Set<String> userIds = new HashSet<>();
if (pimDataAuths != null) {
for (PimDataAuth pimDataAuth : pimDataAuths) {
pimDataAuth.setId(IdGen.uuid());
pimDataAuth.setCreateDate(new Date());
userIds.add(pimDataAuth.getUserId());
}
}
//先删除后保存
dao.deleteAuthDatas(userIds);
dao.insertAuthDatas(pimDataAuths);
}
/**
* * @Description: 分页获取数据权限
* * @author lf
* * @date 2018/7/30 13:17
*
*/
public Page<PimDataAuth> findAuthDataByPage(Page<PimDataAuth> pageDto) throws IllegalAccessException, InstantiationException {
return this.findPage(pageDto, PimDataAuth.class);
}
/**
* @Description: 批量删除数据权限 通过UserId
* @author lf
* @date 2018/7/30 13:27
*/
public void deleteDataAuth(List<PimDataAuth> pimDataAuths) {
Set<String> userIds = new HashSet<>();
if(pimDataAuths !=null){
for (PimDataAuth pimDataAuth : pimDataAuths){
userIds.add(pimDataAuth.getUserId());
}
}
dao.deleteAuthDatas(userIds);
}
} | UTF-8 | Java | 2,383 | java | PimDataAuthService.java | Java | [
{
"context": "arch.SearchTerm;\n\n/**\n * 数据权限Service\n *\n * @author lf\n * @version 2018-07-30\n */\n@Service\npublic class ",
"end": 788,
"score": 0.9809064865112305,
"start": 786,
"tag": "USERNAME",
"value": "lf"
},
{
"context": " * * @Description: 保存数据权限\n * * @author lf\n * * @date 2018/7/30 10:32\n *\n */\n ",
"end": 974,
"score": 0.9732598066329956,
"start": 972,
"tag": "USERNAME",
"value": "lf"
},
{
"context": " * * @Description: 分页获取数据权限\n * * @author lf\n * * @date 2018/7/30 13:17\n *\n */\n ",
"end": 1598,
"score": 0.9776567816734314,
"start": 1596,
"tag": "USERNAME",
"value": "lf"
},
{
"context": " * @Description: 批量删除数据权限 通过UserId\n * @author lf\n * @date 2018/7/30 13:27\n */\n public",
"end": 1909,
"score": 0.9972607493400574,
"start": 1907,
"tag": "USERNAME",
"value": "lf"
}
] | null | [] | /**
* Copyright © 2015-2020 <a href="http://www.sinux.com.cn/">JFusion</a> All rights reserved.
*/
package com.sinux.modules.auth.service;
import java.util.*;
import com.sinux.core.persistence.Page;
import com.sinux.core.utils.IdGen;
import com.sinux.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.sinux.core.persistence.BatchEntity;
import com.sinux.core.service.BaseCrudService;
import com.sinux.modules.auth.entity.PimDataAuth;
import com.sinux.modules.auth.dao.PimDataAuthDao;
import javax.mail.search.SearchTerm;
/**
* 数据权限Service
*
* @author lf
* @version 2018-07-30
*/
@Service
public class PimDataAuthService extends BaseCrudService<PimDataAuthDao, PimDataAuth> {
/**
* * @Description: 保存数据权限
* * @author lf
* * @date 2018/7/30 10:32
*
*/
@Transactional
public void saveDataAuth(List<PimDataAuth> pimDataAuths) {
Set<String> userIds = new HashSet<>();
if (pimDataAuths != null) {
for (PimDataAuth pimDataAuth : pimDataAuths) {
pimDataAuth.setId(IdGen.uuid());
pimDataAuth.setCreateDate(new Date());
userIds.add(pimDataAuth.getUserId());
}
}
//先删除后保存
dao.deleteAuthDatas(userIds);
dao.insertAuthDatas(pimDataAuths);
}
/**
* * @Description: 分页获取数据权限
* * @author lf
* * @date 2018/7/30 13:17
*
*/
public Page<PimDataAuth> findAuthDataByPage(Page<PimDataAuth> pageDto) throws IllegalAccessException, InstantiationException {
return this.findPage(pageDto, PimDataAuth.class);
}
/**
* @Description: 批量删除数据权限 通过UserId
* @author lf
* @date 2018/7/30 13:27
*/
public void deleteDataAuth(List<PimDataAuth> pimDataAuths) {
Set<String> userIds = new HashSet<>();
if(pimDataAuths !=null){
for (PimDataAuth pimDataAuth : pimDataAuths){
userIds.add(pimDataAuth.getUserId());
}
}
dao.deleteAuthDatas(userIds);
}
} | 2,383 | 0.654945 | 0.633407 | 78 | 28.179487 | 25.678358 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.358974 | false | false | 4 |
de6b1ef4d8184755aa5c59f92ef9e851fafdb650 | 11,278,584,133,099 | 8d144e8027d449cd9261dd05f745a3662f1ef8a1 | /src/com/github/manasg/logging/RemoteAppender.java | 372f4a9c852f182d64405f5827ec063a4994865c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | manasg/AmonLogging | https://github.com/manasg/AmonLogging | 03aec22522a59b37fd78b1af54e118cfa6d3d379 | 2dcd0d2d0df89abd736f2465f24379e13d4ffd8b | refs/heads/master | 2021-01-10T21:24:58.684000 | 2012-08-30T19:53:32 | 2012-08-30T19:53:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.manasg.logging;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
public class RemoteAppender extends AppenderSkeleton {
protected String destination = "localhost:2464";
protected String environment = "unknown_env";
protected String hostname = "";
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
private String getDestinationURL() {
StringBuffer sb = new StringBuffer();
sb.append("http://").append(this.destination).append("/api/log");
return sb.toString();
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public RemoteAppender() {
// default
this.setThreshold(Level.WARN);
// try to get the IP/hostname
try {
this.hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
this.hostname = "unknown";
}
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(LoggingEvent arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(getDestinationURL());
try {
String payload = AmonPayload.AmonPayloadJson(arg0,getEnvironment(),hostname);
httpPost.setEntity(new StringEntity(payload));
httpPost.setHeader("Content-type", "application/json");
HttpResponse response2 = httpclient.execute(httpPost);
//System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} catch (Exception e) {
} finally {
httpPost.releaseConnection();
}
}
}
| UTF-8 | Java | 2,750 | java | RemoteAppender.java | Java | [
{
"context": "package com.github.manasg.logging;\n\nimport java.net.InetAddress;\nimport jav",
"end": 25,
"score": 0.870256245136261,
"start": 19,
"tag": "USERNAME",
"value": "manasg"
}
] | null | [] | package com.github.manasg.logging;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
public class RemoteAppender extends AppenderSkeleton {
protected String destination = "localhost:2464";
protected String environment = "unknown_env";
protected String hostname = "";
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
private String getDestinationURL() {
StringBuffer sb = new StringBuffer();
sb.append("http://").append(this.destination).append("/api/log");
return sb.toString();
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public RemoteAppender() {
// default
this.setThreshold(Level.WARN);
// try to get the IP/hostname
try {
this.hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
this.hostname = "unknown";
}
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(LoggingEvent arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(getDestinationURL());
try {
String payload = AmonPayload.AmonPayloadJson(arg0,getEnvironment(),hostname);
httpPost.setEntity(new StringEntity(payload));
httpPost.setHeader("Content-type", "application/json");
HttpResponse response2 = httpclient.execute(httpPost);
//System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} catch (Exception e) {
} finally {
httpPost.releaseConnection();
}
}
}
| 2,750 | 0.646545 | 0.641455 | 105 | 25.190475 | 22.198711 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 4 |
a84ba21c37ba343a777707fae6e81d1b49c6dab4 | 11,278,584,132,092 | 1f34d1b09603164331bcf14a9ab8187912f47bdd | /app/src/main/java/com/ornoiragency/chacks/models/Chat.java | 27be46007a794f8c09d886b62db93b62ea68d62c | [] | no_license | OrnoirAgency/Chacks | https://github.com/OrnoirAgency/Chacks | 597b81c604e9e709695ba21bc4a5ca9a05656c02 | fac773579df38fe5ec2e4cc7d8f1325b1280d0f3 | refs/heads/master | 2022-12-17T14:29:39.831000 | 2020-09-08T13:24:29 | 2020-09-08T13:24:29 | 293,817,686 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ornoiragency.chacks.models;
import androidx.annotation.Keep;
import com.google.firebase.database.DataSnapshot;
import java.io.Serializable;
import java.util.ArrayList;
@Keep public class Chat {
private String sender;
private String receiver;
private String message,pdf,docFile,imageFile,
audio,video,videoLegend,videoCover,
messageVideoDuration,fileName,fileType,
type,messageId,timestamp,
audioDuration,audioFile;
private boolean isseen;
private ArrayList<String> mediaUrlList = new ArrayList<>();
public Chat() {}
public Chat(String sender, String receiver, String message, String pdf, String docFile, String imageFile,
String audio, String video, String videoLegend, String videoCover, String messageVideoDuration,
String fileName, String fileType, String type, String messageId,
String timestamp, String audioDuration, String audioFile, boolean isseen, ArrayList<String> mediaUrlList) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.pdf = pdf;
this.docFile = docFile;
this.imageFile = imageFile;
this.audio = audio;
this.video = video;
this.videoLegend = videoLegend;
this.videoCover = videoCover;
this.messageVideoDuration = messageVideoDuration;
this.fileName = fileName;
this.fileType = fileType;
this.type = type;
this.messageId = messageId;
this.timestamp = timestamp;
this.audioDuration = audioDuration;
this.audioFile = audioFile;
this.isseen = isseen;
this.mediaUrlList = mediaUrlList;
}
public void parseObject(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String str4 = "media";
if (dataSnapshot.child(str4).getChildrenCount() > 0) {
for (DataSnapshot mediaSnapshot : dataSnapshot.child(str4).getChildren()) {
this.mediaUrlList.add(mediaSnapshot.getValue().toString());
}
}
}
}
public ArrayList<String> getMediaUrlList() {
return this.mediaUrlList;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getMessageVideoDuration() {
return messageVideoDuration;
}
public void setMessageVideoDuration(String messageVideoDuration) {
this.messageVideoDuration = messageVideoDuration;
}
public String getAudioDuration() {
return audioDuration;
}
public void setAudioDuration(String audioDuration) {
this.audioDuration = audioDuration;
}
public String getAudioFile() {
return audioFile;
}
public void setAudioFile(String audioFile) {
this.audioFile = audioFile;
}
public String getVideoCover() {
return videoCover;
}
public void setVideoCover(String videoCover) {
this.videoCover = videoCover;
}
public String getVideoLegend() {
return videoLegend;
}
public void setVideoLegend(String videoLegend) {
this.videoLegend = videoLegend;
}
public void setMediaUrlList(ArrayList<String> mediaUrlList) {
this.mediaUrlList = mediaUrlList;
}
public String getImageFile() {
return imageFile;
}
public void setImageFile(String imageFile) {
this.imageFile = imageFile;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDocFile() {
return docFile;
}
public void setDocFile(String docFile) {
this.docFile = docFile;
}
public String getPdf() {
return pdf;
}
public void setPdf(String pdf) {
this.pdf = pdf;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
}
| UTF-8 | Java | 5,325 | java | Chat.java | Java | [] | null | [] | package com.ornoiragency.chacks.models;
import androidx.annotation.Keep;
import com.google.firebase.database.DataSnapshot;
import java.io.Serializable;
import java.util.ArrayList;
@Keep public class Chat {
private String sender;
private String receiver;
private String message,pdf,docFile,imageFile,
audio,video,videoLegend,videoCover,
messageVideoDuration,fileName,fileType,
type,messageId,timestamp,
audioDuration,audioFile;
private boolean isseen;
private ArrayList<String> mediaUrlList = new ArrayList<>();
public Chat() {}
public Chat(String sender, String receiver, String message, String pdf, String docFile, String imageFile,
String audio, String video, String videoLegend, String videoCover, String messageVideoDuration,
String fileName, String fileType, String type, String messageId,
String timestamp, String audioDuration, String audioFile, boolean isseen, ArrayList<String> mediaUrlList) {
this.sender = sender;
this.receiver = receiver;
this.message = message;
this.pdf = pdf;
this.docFile = docFile;
this.imageFile = imageFile;
this.audio = audio;
this.video = video;
this.videoLegend = videoLegend;
this.videoCover = videoCover;
this.messageVideoDuration = messageVideoDuration;
this.fileName = fileName;
this.fileType = fileType;
this.type = type;
this.messageId = messageId;
this.timestamp = timestamp;
this.audioDuration = audioDuration;
this.audioFile = audioFile;
this.isseen = isseen;
this.mediaUrlList = mediaUrlList;
}
public void parseObject(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String str4 = "media";
if (dataSnapshot.child(str4).getChildrenCount() > 0) {
for (DataSnapshot mediaSnapshot : dataSnapshot.child(str4).getChildren()) {
this.mediaUrlList.add(mediaSnapshot.getValue().toString());
}
}
}
}
public ArrayList<String> getMediaUrlList() {
return this.mediaUrlList;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getMessageVideoDuration() {
return messageVideoDuration;
}
public void setMessageVideoDuration(String messageVideoDuration) {
this.messageVideoDuration = messageVideoDuration;
}
public String getAudioDuration() {
return audioDuration;
}
public void setAudioDuration(String audioDuration) {
this.audioDuration = audioDuration;
}
public String getAudioFile() {
return audioFile;
}
public void setAudioFile(String audioFile) {
this.audioFile = audioFile;
}
public String getVideoCover() {
return videoCover;
}
public void setVideoCover(String videoCover) {
this.videoCover = videoCover;
}
public String getVideoLegend() {
return videoLegend;
}
public void setVideoLegend(String videoLegend) {
this.videoLegend = videoLegend;
}
public void setMediaUrlList(ArrayList<String> mediaUrlList) {
this.mediaUrlList = mediaUrlList;
}
public String getImageFile() {
return imageFile;
}
public void setImageFile(String imageFile) {
this.imageFile = imageFile;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDocFile() {
return docFile;
}
public void setDocFile(String docFile) {
this.docFile = docFile;
}
public String getPdf() {
return pdf;
}
public void setPdf(String pdf) {
this.pdf = pdf;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isIsseen() {
return isseen;
}
public void setIsseen(boolean isseen) {
this.isseen = isseen;
}
}
| 5,325 | 0.621408 | 0.620657 | 225 | 22.666666 | 22.153204 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.471111 | false | false | 4 |
aa75cf0e6c29fe17fa61646d047412c5007da4eb | 5,025,111,782,655 | 6ceaf894526a5995cc23b8130af4ea61c0de348a | /src/com/pk/PasswordGenerator.java | 0c8623efaccf7fd7107eeb6b703d884135ef5ea7 | [] | no_license | PankajKumarBehera123/prnk-pwd | https://github.com/PankajKumarBehera123/prnk-pwd | 78052e973216f2f8809c4b36bd9fcbce33e7c628 | 86910626692c5568dd54dfe067cdf1216a237fe5 | refs/heads/master | 2023-04-26T09:47:14.392000 | 2021-05-28T15:40:48 | 2021-05-28T15:40:48 | 371,747,383 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pk;
import com.pk.exception.InvalidMobileNumberException;
import com.pk.exception.InvalidSpecialCharacterException;
import com.pk.exception.InvalidUserNameException;
public class PasswordGenerator {
public static String generatePwd(String mobNo, String name, char specialChar) {
StringBuilder pwd = null;
if (mobNo == null || mobNo.length() != 10 || mobNo.contains(" ")) {
throw new InvalidMobileNumberException("Please Enter 10 digits mobile number..!!");
}
pwd = new StringBuilder();
for (int i = mobNo.length() - 1; i >= 6; i--) {
pwd.append(mobNo.charAt(i));
}
pwd.reverse();
if (specialChar == '#' || specialChar == '$') {
pwd.append(specialChar);
} else {
throw new InvalidSpecialCharacterException(specialChar + " is not allowed, Pease Enter either # or $ ");
}
if (name == null || name.length() < 3 || name.contains(" ")) {
throw new InvalidUserNameException("Please enter valid name, which must have atleast 3 or more characters");
}
for (int i = 0; i < 3; i++) {
pwd.append(name.charAt(i));
}
return pwd.toString();
}
public static void main(String[] args) {
String pwd = generatePwd("8789456518", "priyanka", '#');
System.out.println("Generated Password is :" + pwd);
}
}
| UTF-8 | Java | 1,260 | java | PasswordGenerator.java | Java | [
{
"context": "main(String[] args) {\n\t\tString pwd = generatePwd(\"8789456518\", \"priyanka\", '#');\n\t\tSystem.out.println(\"Generat",
"end": 1178,
"score": 0.9965968132019043,
"start": 1168,
"tag": "PASSWORD",
"value": "8789456518"
},
{
"context": "args) {\n\t\tString pwd = generatePwd(\"8789456518\", \"priyanka\", '#');\n\t\tSystem.out.println(\"Generated Password ",
"end": 1190,
"score": 0.9952571988105774,
"start": 1182,
"tag": "PASSWORD",
"value": "priyanka"
}
] | null | [] | package com.pk;
import com.pk.exception.InvalidMobileNumberException;
import com.pk.exception.InvalidSpecialCharacterException;
import com.pk.exception.InvalidUserNameException;
public class PasswordGenerator {
public static String generatePwd(String mobNo, String name, char specialChar) {
StringBuilder pwd = null;
if (mobNo == null || mobNo.length() != 10 || mobNo.contains(" ")) {
throw new InvalidMobileNumberException("Please Enter 10 digits mobile number..!!");
}
pwd = new StringBuilder();
for (int i = mobNo.length() - 1; i >= 6; i--) {
pwd.append(mobNo.charAt(i));
}
pwd.reverse();
if (specialChar == '#' || specialChar == '$') {
pwd.append(specialChar);
} else {
throw new InvalidSpecialCharacterException(specialChar + " is not allowed, Pease Enter either # or $ ");
}
if (name == null || name.length() < 3 || name.contains(" ")) {
throw new InvalidUserNameException("Please enter valid name, which must have atleast 3 or more characters");
}
for (int i = 0; i < 3; i++) {
pwd.append(name.charAt(i));
}
return pwd.toString();
}
public static void main(String[] args) {
String pwd = generatePwd("<PASSWORD>", "<PASSWORD>", '#');
System.out.println("Generated Password is :" + pwd);
}
}
| 1,262 | 0.674603 | 0.65873 | 42 | 29 | 30.714508 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.190476 | false | false | 4 |
f32e6f2cf8d61ca1a82eef1abf375957a00e5381 | 17,463,337,078,444 | 5a99dfebceb46367b7af476eabbadeba605bf21b | /pet-online-shop-backend/src/main/java/com/sazonov/mainonlineshop/MainonlineshopApplication.java | a79ad40ff99cd99ed95bb092ac422f4762cdda3e | [] | no_license | Andrea04172004/pet-online-shop | https://github.com/Andrea04172004/pet-online-shop | 77d36f4568f8698f5578fe647ac87bd610f93f2f | c6afb4f805ea800d966d9939cfd09a2d972f0ccb | refs/heads/master | 2023-09-02T11:39:09.085000 | 2021-11-10T11:13:35 | 2021-11-10T11:13:35 | 426,591,409 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sazonov.mainonlineshop;
import com.sazonov.mainonlineshop.enums.OrderStatus;
import com.sazonov.mainonlineshop.enums.ProductLabel;
import com.sazonov.mainonlineshop.repository.*;
import com.sazonov.mainonlineshop.shopentity.*;
import com.sazonov.mainonlineshop.enums.Roles;
import com.sazonov.mainonlineshop.userentity.AddressEntity;
import com.sazonov.mainonlineshop.userentity.CreditCardEntity;
import com.sazonov.mainonlineshop.userentity.UserEntity;
import com.sazonov.mainonlineshop.utils.UserGenerator;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.sql.DataSource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
@SpringBootApplication()
public class MainonlineshopApplication {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
public static void main(String[] args) {
SpringApplication.run(MainonlineshopApplication.class, args);
}
@Bean
CommandLineRunner init(UserRepository userRepository, OrderRepository orderRepository, CreditCardRepository creditCardRepository,
AddressRepository addressRepository, DiscountRepository discountRepository, AttachmentRepository attachmentRepository,
CartRepository cartRepository, CategoryRepository categoryRepository, PaymentRepository paymentRepository,
ProductRepository productRepository, PasswordEncoder passwordEncoder, LineItemRepository lineItemRepository,
WishListRepository wishListRepository) {
return args -> {
UserEntity userEntity = new UserEntity();
Set<CreditCardEntity> creditCardEntitiesAdmin = new HashSet<>();
CreditCardEntity creditCardEntity4 = CreditCardEntity.builder()
.cardNumber("1111-1111-1111-1111")
.expirationDate("2022")
.cardType("VISA")
.build();
creditCardRepository.save(creditCardEntity4);
CreditCardEntity creditCardEntity5 = CreditCardEntity.builder()
.cardNumber("2222-2222-2222-2222")
.expirationDate("2022")
.cardType("Master Card")
.build();
creditCardRepository.save(creditCardEntity5);
CreditCardEntity creditCardEntity6 = CreditCardEntity.builder()
.cardNumber("3333-3333-3333-3333")
.expirationDate("2022")
.cardType("American Express")
.build();
creditCardRepository.save(creditCardEntity6);
creditCardEntitiesAdmin.add(creditCardEntity4);
creditCardEntitiesAdmin.add(creditCardEntity5);
creditCardEntitiesAdmin.add(creditCardEntity6);
creditCardRepository.saveAll(creditCardEntitiesAdmin);
UserEntity admin = UserEntity.builder()
.email("admin@mail.com")
.password(passwordEncoder.encode("123"))
.firstName("admin")
.lastName("adminov")
.phoneList(userEntity.addPhone("+38 068 2 864 111"))
.phoneList(userEntity.addPhone("+38 068 2 864 222"))
.phoneList(userEntity.addPhone("+38 068 2 864 333"))
.phoneList(userEntity.addPhone("+38 068 2 864 444"))
.phoneList(userEntity.addPhone("+38 068 2 864 555"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_ADMIN.name())
.build();
userRepository.save(admin);
AddressEntity addressEntity6 = AddressEntity.builder()
.city("Stol")
.street("Ruchka street")
.buildingNumber("1122")
.apartmentNumber("33f")
.build();
addressRepository.save(addressEntity6);
AddressEntity addressEntity7 = AddressEntity.builder()
.city("voda")
.street("kran Street")
.buildingNumber("8961")
.apartmentNumber("91h")
.build();
addressRepository.save(addressEntity7);
AddressEntity addressEntity8 = AddressEntity.builder()
.city("dohovka")
.street("lodka street")
.buildingNumber("182")
.apartmentNumber("53c")
.build();
addressRepository.save(addressEntity8);
Set<AddressEntity> addressEntitySet = new HashSet<>();
addressEntitySet.add(addressEntity6);
addressEntitySet.add(addressEntity7);
addressEntitySet.add(addressEntity8);
addressRepository.saveAll(addressEntitySet);
admin.setAddressEntitySet(addressEntitySet);
userRepository.save(admin);
CreditCardEntity creditCardEntity1 = CreditCardEntity.builder()
.cardNumber("4024007161952808")
.cardType("VISA GOLD")
.expirationDate("08-11-2020").build();
CreditCardEntity creditCardEntity2 = CreditCardEntity.builder()
.cardNumber("5293553709949443")
.cardType("MASTER CARD")
.expirationDate("08-11-2020").build();
CreditCardEntity creditCardEntity3 = CreditCardEntity.builder()
.cardNumber("376893368247957")
.cardType("VISA")
.expirationDate("08-11-2020").build();
creditCardRepository.save(creditCardEntity1);
creditCardRepository.save(creditCardEntity2);
creditCardRepository.save(creditCardEntity3);
Set<CreditCardEntity> creditCardEntities = new HashSet<>();
creditCardEntities.add(creditCardEntity1);
creditCardEntities.add(creditCardEntity2);
creditCardEntities.add(creditCardEntity3);
admin.setCreditCardEntitySet(creditCardEntitiesAdmin);
userRepository.save(admin);
UserEntity andrewKachmar = UserEntity.builder()
.email("andrew@mail.com")
.password("$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu")
.firstName("andrew")
.lastName("kachmar")
.phoneList(userEntity.addPhone("+38 068 2 864 864"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.creditCardEntitySet(creditCardEntities)
.build();
userRepository.save(andrewKachmar);
UserEntity manager = UserEntity.builder()
.email("manager@mail.com")
.password("$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu")
.firstName("manager")
.lastName("managerov")
.phoneList(userEntity.addPhone("+27 124 6 342 123"))
//.phoneNumber("+27 124 6 342 123")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_MANAGER.name())
.build();
userRepository.save(manager);
UserEntity testUser = UserEntity.builder()
.email("testUser@gmail.com")
.password("$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu")
.firstName("Tommy")
.lastName("Tester")
.phoneList(userEntity.addPhone("+27 777 7 777 666"))
.phoneList(userEntity.addPhone("+27 777 7 777 777"))
//.phoneNumber("+27 124 6 342 123")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.build();
userRepository.save(testUser);
UserEntity kirillSazonov = UserEntity.builder()
.email("kirill@mail.com")
.password("$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu")
.firstName("kirill")
.lastName("sazonov")
.phoneList(userEntity.addPhone("+38 068 2 999 777"))
.phoneList(userEntity.addPhone("+27 777 7 777 888"))
.phoneList(userEntity.addPhone("+27 777 7 777 999"))
.phoneList(userEntity.addPhone("+27 777 7 777 000"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_ADMIN.name())
.build();
userRepository.save(kirillSazonov);
AddressEntity addressEntity3 = AddressEntity.builder()
.city("Katok")
.street("Buhanka street")
.buildingNumber("3214")
.apartmentNumber("21z")
.build();
addressRepository.save(addressEntity3);
AddressEntity addressEntity4 = AddressEntity.builder()
.city("Shalash")
.street("Derevo Street")
.buildingNumber("2239")
.apartmentNumber("2c")
.build();
addressRepository.save(addressEntity4);
AddressEntity addressEntity5 = AddressEntity.builder()
.city("Bashmak")
.street("tarelka street")
.buildingNumber("6691")
.apartmentNumber("88a")
.build();
addressRepository.save(addressEntity5);
Set<AddressEntity> addressEntityKirillSet = new HashSet<>();
addressEntityKirillSet.add(addressEntity3);
addressEntityKirillSet.add(addressEntity4);
addressEntityKirillSet.add(addressEntity5);
addressRepository.saveAll(addressEntityKirillSet);
kirillSazonov.setAddressEntitySet(addressEntityKirillSet);
userRepository.save(kirillSazonov);
for (int i = 0; i < 4; i++) {
UserEntity requestGenerateCustomers = UserEntity.builder()
.email(UserGenerator.setEmailAddress())
.password(passwordEncoder.encode(UserGenerator.setPassword()))
.firstName(UserGenerator.setFirstName())
.lastName(UserGenerator.setLastName())
.phoneList(userEntity.addPhone(UserGenerator.setPhoneNumber()))
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.build();
userRepository.save(requestGenerateCustomers);
}
CategoryEntity generalCategory = CategoryEntity.builder()
.name("GeneralCategory")
.productSet(new HashSet<>())
.build();
categoryRepository.save(generalCategory);
CategoryEntity fruit = CategoryEntity.builder()
.name("fruit")
.build();
CategoryEntity vegetable = CategoryEntity.builder()
.name("vegetable")
.build();
CategoryEntity meat = CategoryEntity.builder()
.name("meat")
.build();
categoryRepository.save(fruit);
categoryRepository.save(vegetable);
categoryRepository.save(meat);
CategoryEntity appleCategory = CategoryEntity.builder()
.name("appleCategory")
.productSet(new HashSet<>())
.build();
categoryRepository.save(appleCategory);
Set<CategoryEntity> subCategories = Set.of(appleCategory);
//fruit.setSubCategories(subCategories);
categoryRepository.save(fruit);
List<String> images = new LinkedList<>();
images.add("https://eshop.elit.ua/imgbank/Image/masljniy_filtr.jpg");
images.add("https://bezdor4x4.com.ua/uploads/content/2018/12/19/source/3-27388x.jpg");
List<String> images2 = new LinkedList<>();
images2.add("https://dvizhok.su/assets/images/resources/15187/ysilennoe-sceplenue.jpg");
images2.add("https://kitaec.ua/upload/iblock/e08/Kupplung_smart_451_m.JPG");
List<String> images3 = new LinkedList<>();
images3.add("https://a.d-cd.net/b3a86d4s-960.jpg");
images3.add("https://d1350.com/wa-data/public/shop/products/06/80/118006/images/56013/56013.750@2x.jpg");
ProductEntity apple = ProductEntity.builder()
.name("apple")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.quantity(12)
.productLabel(ProductLabel.NEW)
.category(appleCategory)
.build();
ProductEntity apple1 = ProductEntity.builder()
.name("apple1")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.quantity(13)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity apple2 = ProductEntity.builder()
.name("apple2")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.quantity(56)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity apple3 = ProductEntity.builder()
.name("apple3")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.quantity(122)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity tomato = ProductEntity.builder()
.name("tomato")
.price(2.22)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.quantity(100)
.productLabel(ProductLabel.NEW)
.category(vegetable)
.build();
ProductEntity pork = ProductEntity.builder()
.name("pork1")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork1 = ProductEntity.builder()
.name("pork2")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork2 = ProductEntity.builder()
.name("pork3")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork3 = ProductEntity.builder()
.name("pork4")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
productRepository.save(apple);
productRepository.save(apple1);
productRepository.save(apple2);
productRepository.save(apple3);
productRepository.save(tomato);
productRepository.save(pork);
productRepository.save(pork1);
productRepository.save(pork2);
productRepository.save(pork3);
appleCategory.getProductSet().add(apple);
categoryRepository.save(appleCategory);
AddressEntity addressEntity = AddressEntity.builder()
.apartmentNumber("56")
.buildingNumber("23")
.city("Tylchin")
.street("Joid").build();
addressRepository.save(addressEntity);
DiscountEntity discountEntity = DiscountEntity.builder()
.expiration(LocalDateTime.now())
.percent(12).build();
discountRepository.save(discountEntity);
LineItemEntity lineItemEntity1 = LineItemEntity.builder()
.quantity(2)
.product(pork)
.build();
LineItemEntity lineItemEntity2 = LineItemEntity.builder()
.quantity(1)
.product(pork1)
.build();
LineItemEntity lineItemEntity3 = LineItemEntity.builder()
.quantity(2)
.product(pork3)
.build();
lineItemRepository.save(lineItemEntity1);
lineItemRepository.save(lineItemEntity2);
lineItemRepository.save(lineItemEntity3);
List<LineItemEntity> lines = new LinkedList<>();
lines.add(lineItemEntity1);
lines.add(lineItemEntity2);
lines.add(lineItemEntity3);
AttachmentEntity attachmentEntity1 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test").build();
AttachmentEntity attachmentEntity2 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test1").build();
AttachmentEntity attachmentEntity3 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test2").build();
attachmentRepository.save(attachmentEntity1);
attachmentRepository.save(attachmentEntity2);
attachmentRepository.save(attachmentEntity3);
PaymentEntity paymentEntity1 = PaymentEntity.builder()
.isCash(false)
.amount("2232")
.clientName("Oleg")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity1).build();
PaymentEntity paymentEntity2 = PaymentEntity.builder()
.isCash(false)
.amount("100")
.clientName("Dima")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity2).build();
PaymentEntity paymentEntity3 = PaymentEntity.builder()
.isCash(true)
.amount("23")
.clientName("Max")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity3).build();
paymentRepository.save(paymentEntity1);
paymentRepository.save(paymentEntity2);
paymentRepository.save(paymentEntity3);
List<PaymentEntity> paymentEntities1 = new LinkedList<>();
paymentEntities1.add(paymentEntity1);
paymentEntities1.add(paymentEntity2);
paymentEntities1.add(paymentEntity3);
OrderEntity order1 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.NEW)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(lines)
.paymentEntity(paymentEntities1).build();
orderRepository.save(order1);
OrderEntity order2 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.CLOSED)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order2);
OrderEntity order3 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.PAID)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order3);
OrderEntity order4 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.UNPAID)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order4);
Set<OrderEntity> orderEntities = new HashSet<>();
orderEntities.add(order1);
orderEntities.add(order2);
orderEntities.add(order3);
orderRepository.saveAll(orderEntities);
admin.setOrderEntitySet(orderEntities);
userRepository.save(admin);
List<ProductEntity> productEntities = new LinkedList<>();
productEntities.add(apple);
productEntities.add(apple1);
productEntities.add(apple2);
productEntities.add(apple3);
List<ProductEntity> productEntities2 = new LinkedList<>();
productEntities2.add(pork);
productEntities2.add(pork1);
productEntities2.add(pork2);
productEntities2.add(pork3);
WishListEntity wishListEntity = WishListEntity.builder()
.id(1)
.title("Products")
.productEntities(productEntities).build();
wishListRepository.save(wishListEntity);
WishListEntity wishListEntity2 = WishListEntity.builder()
.id(2)
.title("Items")
.productEntities(productEntities2).build();
wishListRepository.save(wishListEntity2);
Set<WishListEntity> wishListEntities = new HashSet<>();
wishListEntities.add(wishListEntity);
wishListEntities.add(wishListEntity2);
admin.setWishListEntities(wishListEntities);
userRepository.save(admin);
};
}
}
| UTF-8 | Java | 26,104 | java | MainonlineshopApplication.java | Java | [
{
"context": " UserEntity.builder()\n .email(\"admin@mail.com\")\n .password(passwordEncoder.e",
"end": 3901,
"score": 0.9999241828918457,
"start": 3887,
"tag": "EMAIL",
"value": "admin@mail.com"
},
{
"context": " .password(passwordEncoder.encode(\"123\"))\n .firstName(\"admin\")\n ",
"end": 3961,
"score": 0.9986772537231445,
"start": 3958,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "er.encode(\"123\"))\n .firstName(\"admin\")\n .lastName(\"adminov\")\n ",
"end": 4002,
"score": 0.9927591681480408,
"start": 3997,
"tag": "NAME",
"value": "admin"
},
{
"context": "firstName(\"admin\")\n .lastName(\"adminov\")\n .phoneList(userEntity.addPh",
"end": 4043,
"score": 0.9996274709701538,
"start": 4036,
"tag": "NAME",
"value": "adminov"
},
{
"context": "serRepository.save(admin);\n\n UserEntity andrewKachmar = UserEntity.builder()\n ",
"end": 7417,
"score": 0.767577052116394,
"start": 7414,
"tag": "NAME",
"value": "and"
},
{
"context": "epository.save(admin);\n\n UserEntity andrewKachmar = UserEntity.builder()\n .email",
"end": 7427,
"score": 0.9402388334274292,
"start": 7417,
"tag": "USERNAME",
"value": "rewKachmar"
},
{
"context": " UserEntity.builder()\n .email(\"andrew@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.",
"end": 7494,
"score": 0.9999229311943054,
"start": 7479,
"tag": "EMAIL",
"value": "andrew@mail.com"
},
{
"context": "l(\"andrew@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu\")\n .firstName(\"andrew\")\n ",
"end": 7588,
"score": 0.9993270039558411,
"start": 7528,
"tag": "PASSWORD",
"value": "$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu"
},
{
"context": "FaSsiTUIl.TCrFu\")\n .firstName(\"andrew\")\n .lastName(\"kachmar\")\n ",
"end": 7629,
"score": 0.9995524883270264,
"start": 7623,
"tag": "NAME",
"value": "andrew"
},
{
"context": "irstName(\"andrew\")\n .lastName(\"kachmar\")\n .phoneList(userEntity.addPh",
"end": 7670,
"score": 0.9996325969696045,
"start": 7663,
"tag": "NAME",
"value": "kachmar"
},
{
"context": " .build();\n\n userRepository.save(andrewKachmar);\n\n\n UserEntity manager = UserE",
"end": 8253,
"score": 0.6947809457778931,
"start": 8250,
"tag": "NAME",
"value": "rew"
},
{
"context": ".build();\n\n userRepository.save(andrewKachmar);\n\n\n UserEntity manager = UserEntity.b",
"end": 8260,
"score": 0.643485426902771,
"start": 8254,
"tag": "NAME",
"value": "achmar"
},
{
"context": " UserEntity.builder()\n .email(\"manager@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.",
"end": 8363,
"score": 0.9999240636825562,
"start": 8347,
"tag": "EMAIL",
"value": "manager@mail.com"
},
{
"context": "(\"manager@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu\")\n .firstName(\"manager\")\n ",
"end": 8457,
"score": 0.9993425607681274,
"start": 8397,
"tag": "PASSWORD",
"value": "$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu"
},
{
"context": "FaSsiTUIl.TCrFu\")\n .firstName(\"manager\")\n .lastName(\"managerov\")\n ",
"end": 8499,
"score": 0.7103797197341919,
"start": 8492,
"tag": "NAME",
"value": "manager"
},
{
"context": "rstName(\"manager\")\n .lastName(\"managerov\")\n .phoneList(userEntity.addPh",
"end": 8542,
"score": 0.9934112429618835,
"start": 8533,
"tag": "NAME",
"value": "managerov"
},
{
"context": " UserEntity.builder()\n .email(\"testUser@gmail.com\")\n .password(\"$2a$10$PrI5Gk9L.",
"end": 9148,
"score": 0.9999208450317383,
"start": 9130,
"tag": "EMAIL",
"value": "testUser@gmail.com"
},
{
"context": "testUser@gmail.com\")\n .password(\"$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu\")\n .firstName(\"Tommy\")\n ",
"end": 9242,
"score": 0.9989008903503418,
"start": 9182,
"tag": "PASSWORD",
"value": "$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu"
},
{
"context": "FaSsiTUIl.TCrFu\")\n .firstName(\"Tommy\")\n .lastName(\"Tester\")\n ",
"end": 9282,
"score": 0.9997671246528625,
"start": 9277,
"tag": "NAME",
"value": "Tommy"
},
{
"context": "firstName(\"Tommy\")\n .lastName(\"Tester\")\n .phoneList(userEntity.addPh",
"end": 9322,
"score": 0.9968767762184143,
"start": 9316,
"tag": "NAME",
"value": "Tester"
},
{
"context": "epository.save(testUser);\n\n\n UserEntity kirillSazonov = UserEntity.builder()\n .email",
"end": 9938,
"score": 0.6267693638801575,
"start": 9925,
"tag": "USERNAME",
"value": "kirillSazonov"
},
{
"context": " UserEntity.builder()\n .email(\"kirill@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.",
"end": 10005,
"score": 0.9999284744262695,
"start": 9990,
"tag": "EMAIL",
"value": "kirill@mail.com"
},
{
"context": "l(\"kirill@mail.com\")\n .password(\"$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu\")\n .firstName(\"kirill\")\n ",
"end": 10099,
"score": 0.9993280172348022,
"start": 10039,
"tag": "PASSWORD",
"value": "$2a$10$PrI5Gk9L.tSZiW9FXhTS8O8Mz9E97k2FZbFvGFFaSsiTUIl.TCrFu"
},
{
"context": "FaSsiTUIl.TCrFu\")\n .firstName(\"kirill\")\n .lastName(\"sazonov\")\n ",
"end": 10140,
"score": 0.9987664222717285,
"start": 10134,
"tag": "NAME",
"value": "kirill"
},
{
"context": "irstName(\"kirill\")\n .lastName(\"sazonov\")\n .phoneList(userEntity.addPh",
"end": 10181,
"score": 0.9997463226318359,
"start": 10174,
"tag": "NAME",
"value": "sazonov"
},
{
"context": "EmailAddress())\n .password(passwordEncoder.encode(UserGenerator.setPassword()))\n ",
"end": 12540,
"score": 0.8697426319122314,
"start": 12532,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "roductEntity.builder()\n .name(\"pork2\")\n .price(3.33)\n ",
"end": 17544,
"score": 0.697616457939148,
"start": 17540,
"tag": "NAME",
"value": "pork"
},
{
"context": "roductEntity.builder()\n .name(\"pork3\")\n .price(3.33)\n ",
"end": 17922,
"score": 0.8238477110862732,
"start": 17921,
"tag": "NAME",
"value": "p"
},
{
"context": "roductEntity.builder()\n .name(\"pork4\")\n .price(3.33)\n ",
"end": 18307,
"score": 0.6897989511489868,
"start": 18303,
"tag": "NAME",
"value": "pork"
},
{
"context": " .amount(\"2232\")\n .clientName(\"Oleg\")\n .dateTime(LocalDateTime.now",
"end": 21468,
"score": 0.9995710849761963,
"start": 21464,
"tag": "NAME",
"value": "Oleg"
},
{
"context": " .amount(\"100\")\n .clientName(\"Dima\")\n .dateTime(LocalDateTime.now",
"end": 21763,
"score": 0.99959796667099,
"start": 21759,
"tag": "NAME",
"value": "Dima"
},
{
"context": " .amount(\"23\")\n .clientName(\"Max\")\n .dateTime(LocalDateTime.now",
"end": 22055,
"score": 0.9998466372489929,
"start": 22052,
"tag": "NAME",
"value": "Max"
}
] | null | [] | package com.sazonov.mainonlineshop;
import com.sazonov.mainonlineshop.enums.OrderStatus;
import com.sazonov.mainonlineshop.enums.ProductLabel;
import com.sazonov.mainonlineshop.repository.*;
import com.sazonov.mainonlineshop.shopentity.*;
import com.sazonov.mainonlineshop.enums.Roles;
import com.sazonov.mainonlineshop.userentity.AddressEntity;
import com.sazonov.mainonlineshop.userentity.CreditCardEntity;
import com.sazonov.mainonlineshop.userentity.UserEntity;
import com.sazonov.mainonlineshop.utils.UserGenerator;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.sql.DataSource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
@SpringBootApplication()
public class MainonlineshopApplication {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
public static void main(String[] args) {
SpringApplication.run(MainonlineshopApplication.class, args);
}
@Bean
CommandLineRunner init(UserRepository userRepository, OrderRepository orderRepository, CreditCardRepository creditCardRepository,
AddressRepository addressRepository, DiscountRepository discountRepository, AttachmentRepository attachmentRepository,
CartRepository cartRepository, CategoryRepository categoryRepository, PaymentRepository paymentRepository,
ProductRepository productRepository, PasswordEncoder passwordEncoder, LineItemRepository lineItemRepository,
WishListRepository wishListRepository) {
return args -> {
UserEntity userEntity = new UserEntity();
Set<CreditCardEntity> creditCardEntitiesAdmin = new HashSet<>();
CreditCardEntity creditCardEntity4 = CreditCardEntity.builder()
.cardNumber("1111-1111-1111-1111")
.expirationDate("2022")
.cardType("VISA")
.build();
creditCardRepository.save(creditCardEntity4);
CreditCardEntity creditCardEntity5 = CreditCardEntity.builder()
.cardNumber("2222-2222-2222-2222")
.expirationDate("2022")
.cardType("Master Card")
.build();
creditCardRepository.save(creditCardEntity5);
CreditCardEntity creditCardEntity6 = CreditCardEntity.builder()
.cardNumber("3333-3333-3333-3333")
.expirationDate("2022")
.cardType("American Express")
.build();
creditCardRepository.save(creditCardEntity6);
creditCardEntitiesAdmin.add(creditCardEntity4);
creditCardEntitiesAdmin.add(creditCardEntity5);
creditCardEntitiesAdmin.add(creditCardEntity6);
creditCardRepository.saveAll(creditCardEntitiesAdmin);
UserEntity admin = UserEntity.builder()
.email("<EMAIL>")
.password(passwordEncoder.encode("123"))
.firstName("admin")
.lastName("adminov")
.phoneList(userEntity.addPhone("+38 068 2 864 111"))
.phoneList(userEntity.addPhone("+38 068 2 864 222"))
.phoneList(userEntity.addPhone("+38 068 2 864 333"))
.phoneList(userEntity.addPhone("+38 068 2 864 444"))
.phoneList(userEntity.addPhone("+38 068 2 864 555"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_ADMIN.name())
.build();
userRepository.save(admin);
AddressEntity addressEntity6 = AddressEntity.builder()
.city("Stol")
.street("Ruchka street")
.buildingNumber("1122")
.apartmentNumber("33f")
.build();
addressRepository.save(addressEntity6);
AddressEntity addressEntity7 = AddressEntity.builder()
.city("voda")
.street("kran Street")
.buildingNumber("8961")
.apartmentNumber("91h")
.build();
addressRepository.save(addressEntity7);
AddressEntity addressEntity8 = AddressEntity.builder()
.city("dohovka")
.street("lodka street")
.buildingNumber("182")
.apartmentNumber("53c")
.build();
addressRepository.save(addressEntity8);
Set<AddressEntity> addressEntitySet = new HashSet<>();
addressEntitySet.add(addressEntity6);
addressEntitySet.add(addressEntity7);
addressEntitySet.add(addressEntity8);
addressRepository.saveAll(addressEntitySet);
admin.setAddressEntitySet(addressEntitySet);
userRepository.save(admin);
CreditCardEntity creditCardEntity1 = CreditCardEntity.builder()
.cardNumber("4024007161952808")
.cardType("VISA GOLD")
.expirationDate("08-11-2020").build();
CreditCardEntity creditCardEntity2 = CreditCardEntity.builder()
.cardNumber("5293553709949443")
.cardType("MASTER CARD")
.expirationDate("08-11-2020").build();
CreditCardEntity creditCardEntity3 = CreditCardEntity.builder()
.cardNumber("376893368247957")
.cardType("VISA")
.expirationDate("08-11-2020").build();
creditCardRepository.save(creditCardEntity1);
creditCardRepository.save(creditCardEntity2);
creditCardRepository.save(creditCardEntity3);
Set<CreditCardEntity> creditCardEntities = new HashSet<>();
creditCardEntities.add(creditCardEntity1);
creditCardEntities.add(creditCardEntity2);
creditCardEntities.add(creditCardEntity3);
admin.setCreditCardEntitySet(creditCardEntitiesAdmin);
userRepository.save(admin);
UserEntity andrewKachmar = UserEntity.builder()
.email("<EMAIL>")
.password("<PASSWORD>")
.firstName("andrew")
.lastName("kachmar")
.phoneList(userEntity.addPhone("+38 068 2 864 864"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.creditCardEntitySet(creditCardEntities)
.build();
userRepository.save(andrewKachmar);
UserEntity manager = UserEntity.builder()
.email("<EMAIL>")
.password("<PASSWORD>")
.firstName("manager")
.lastName("managerov")
.phoneList(userEntity.addPhone("+27 124 6 342 123"))
//.phoneNumber("+27 124 6 342 123")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_MANAGER.name())
.build();
userRepository.save(manager);
UserEntity testUser = UserEntity.builder()
.email("<EMAIL>")
.password("<PASSWORD>")
.firstName("Tommy")
.lastName("Tester")
.phoneList(userEntity.addPhone("+27 777 7 777 666"))
.phoneList(userEntity.addPhone("+27 777 7 777 777"))
//.phoneNumber("+27 124 6 342 123")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.build();
userRepository.save(testUser);
UserEntity kirillSazonov = UserEntity.builder()
.email("<EMAIL>")
.password("<PASSWORD>")
.firstName("kirill")
.lastName("sazonov")
.phoneList(userEntity.addPhone("+38 068 2 999 777"))
.phoneList(userEntity.addPhone("+27 777 7 777 888"))
.phoneList(userEntity.addPhone("+27 777 7 777 999"))
.phoneList(userEntity.addPhone("+27 777 7 777 000"))
// .phoneNumber("+38 068 2 864 864")// setLocation("uk")
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_ADMIN.name())
.build();
userRepository.save(kirillSazonov);
AddressEntity addressEntity3 = AddressEntity.builder()
.city("Katok")
.street("Buhanka street")
.buildingNumber("3214")
.apartmentNumber("21z")
.build();
addressRepository.save(addressEntity3);
AddressEntity addressEntity4 = AddressEntity.builder()
.city("Shalash")
.street("Derevo Street")
.buildingNumber("2239")
.apartmentNumber("2c")
.build();
addressRepository.save(addressEntity4);
AddressEntity addressEntity5 = AddressEntity.builder()
.city("Bashmak")
.street("tarelka street")
.buildingNumber("6691")
.apartmentNumber("88a")
.build();
addressRepository.save(addressEntity5);
Set<AddressEntity> addressEntityKirillSet = new HashSet<>();
addressEntityKirillSet.add(addressEntity3);
addressEntityKirillSet.add(addressEntity4);
addressEntityKirillSet.add(addressEntity5);
addressRepository.saveAll(addressEntityKirillSet);
kirillSazonov.setAddressEntitySet(addressEntityKirillSet);
userRepository.save(kirillSazonov);
for (int i = 0; i < 4; i++) {
UserEntity requestGenerateCustomers = UserEntity.builder()
.email(UserGenerator.setEmailAddress())
.password(<PASSWORD>Encoder.encode(UserGenerator.setPassword()))
.firstName(UserGenerator.setFirstName())
.lastName(UserGenerator.setLastName())
.phoneList(userEntity.addPhone(UserGenerator.setPhoneNumber()))
.active(true)
.created(LocalDate.now())
.updated(LocalDate.now())
.lastVisit(LocalDate.now())
.cartEntity(cartRepository.save(new CartEntity()))
.role(Roles.ROLE_CUSTOMER.name())
.build();
userRepository.save(requestGenerateCustomers);
}
CategoryEntity generalCategory = CategoryEntity.builder()
.name("GeneralCategory")
.productSet(new HashSet<>())
.build();
categoryRepository.save(generalCategory);
CategoryEntity fruit = CategoryEntity.builder()
.name("fruit")
.build();
CategoryEntity vegetable = CategoryEntity.builder()
.name("vegetable")
.build();
CategoryEntity meat = CategoryEntity.builder()
.name("meat")
.build();
categoryRepository.save(fruit);
categoryRepository.save(vegetable);
categoryRepository.save(meat);
CategoryEntity appleCategory = CategoryEntity.builder()
.name("appleCategory")
.productSet(new HashSet<>())
.build();
categoryRepository.save(appleCategory);
Set<CategoryEntity> subCategories = Set.of(appleCategory);
//fruit.setSubCategories(subCategories);
categoryRepository.save(fruit);
List<String> images = new LinkedList<>();
images.add("https://eshop.elit.ua/imgbank/Image/masljniy_filtr.jpg");
images.add("https://bezdor4x4.com.ua/uploads/content/2018/12/19/source/3-27388x.jpg");
List<String> images2 = new LinkedList<>();
images2.add("https://dvizhok.su/assets/images/resources/15187/ysilennoe-sceplenue.jpg");
images2.add("https://kitaec.ua/upload/iblock/e08/Kupplung_smart_451_m.JPG");
List<String> images3 = new LinkedList<>();
images3.add("https://a.d-cd.net/b3a86d4s-960.jpg");
images3.add("https://d1350.com/wa-data/public/shop/products/06/80/118006/images/56013/56013.750@2x.jpg");
ProductEntity apple = ProductEntity.builder()
.name("apple")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.quantity(12)
.productLabel(ProductLabel.NEW)
.category(appleCategory)
.build();
ProductEntity apple1 = ProductEntity.builder()
.name("apple1")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.quantity(13)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity apple2 = ProductEntity.builder()
.name("apple2")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.quantity(56)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity apple3 = ProductEntity.builder()
.name("apple3")
.price(1.11)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.quantity(122)
.productLabel(ProductLabel.NEW)
.category(fruit)
.build();
ProductEntity tomato = ProductEntity.builder()
.name("tomato")
.price(2.22)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.quantity(100)
.productLabel(ProductLabel.NEW)
.category(vegetable)
.build();
ProductEntity pork = ProductEntity.builder()
.name("pork1")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork1 = ProductEntity.builder()
.name("pork2")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork2 = ProductEntity.builder()
.name("pork3")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images2)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
ProductEntity pork3 = ProductEntity.builder()
.name("pork4")
.price(3.33)
.expirationDate(LocalDate.now().plusDays(100))
.image(images3)
.productLabel(ProductLabel.NEW)
.quantity(18)
.category(meat)
.build();
productRepository.save(apple);
productRepository.save(apple1);
productRepository.save(apple2);
productRepository.save(apple3);
productRepository.save(tomato);
productRepository.save(pork);
productRepository.save(pork1);
productRepository.save(pork2);
productRepository.save(pork3);
appleCategory.getProductSet().add(apple);
categoryRepository.save(appleCategory);
AddressEntity addressEntity = AddressEntity.builder()
.apartmentNumber("56")
.buildingNumber("23")
.city("Tylchin")
.street("Joid").build();
addressRepository.save(addressEntity);
DiscountEntity discountEntity = DiscountEntity.builder()
.expiration(LocalDateTime.now())
.percent(12).build();
discountRepository.save(discountEntity);
LineItemEntity lineItemEntity1 = LineItemEntity.builder()
.quantity(2)
.product(pork)
.build();
LineItemEntity lineItemEntity2 = LineItemEntity.builder()
.quantity(1)
.product(pork1)
.build();
LineItemEntity lineItemEntity3 = LineItemEntity.builder()
.quantity(2)
.product(pork3)
.build();
lineItemRepository.save(lineItemEntity1);
lineItemRepository.save(lineItemEntity2);
lineItemRepository.save(lineItemEntity3);
List<LineItemEntity> lines = new LinkedList<>();
lines.add(lineItemEntity1);
lines.add(lineItemEntity2);
lines.add(lineItemEntity3);
AttachmentEntity attachmentEntity1 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test").build();
AttachmentEntity attachmentEntity2 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test1").build();
AttachmentEntity attachmentEntity3 = AttachmentEntity.builder()
.created(LocalDateTime.now())
.content("It cost a fortune")
.name("Test2").build();
attachmentRepository.save(attachmentEntity1);
attachmentRepository.save(attachmentEntity2);
attachmentRepository.save(attachmentEntity3);
PaymentEntity paymentEntity1 = PaymentEntity.builder()
.isCash(false)
.amount("2232")
.clientName("Oleg")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity1).build();
PaymentEntity paymentEntity2 = PaymentEntity.builder()
.isCash(false)
.amount("100")
.clientName("Dima")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity2).build();
PaymentEntity paymentEntity3 = PaymentEntity.builder()
.isCash(true)
.amount("23")
.clientName("Max")
.dateTime(LocalDateTime.now())
.attachmentEntity(attachmentEntity3).build();
paymentRepository.save(paymentEntity1);
paymentRepository.save(paymentEntity2);
paymentRepository.save(paymentEntity3);
List<PaymentEntity> paymentEntities1 = new LinkedList<>();
paymentEntities1.add(paymentEntity1);
paymentEntities1.add(paymentEntity2);
paymentEntities1.add(paymentEntity3);
OrderEntity order1 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.NEW)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(lines)
.paymentEntity(paymentEntities1).build();
orderRepository.save(order1);
OrderEntity order2 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.CLOSED)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order2);
OrderEntity order3 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.PAID)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order3);
OrderEntity order4 = OrderEntity.builder()
.created(LocalDate.now())
.status(OrderStatus.UNPAID)
.orderPrice(1000)
.discountEntity(discountEntity)
.addressEntity(addressEntity)
.userEntity(admin)
.lineItemEntitySet(new LinkedList<>())
.paymentEntity(new LinkedList<>()).build();
orderRepository.save(order4);
Set<OrderEntity> orderEntities = new HashSet<>();
orderEntities.add(order1);
orderEntities.add(order2);
orderEntities.add(order3);
orderRepository.saveAll(orderEntities);
admin.setOrderEntitySet(orderEntities);
userRepository.save(admin);
List<ProductEntity> productEntities = new LinkedList<>();
productEntities.add(apple);
productEntities.add(apple1);
productEntities.add(apple2);
productEntities.add(apple3);
List<ProductEntity> productEntities2 = new LinkedList<>();
productEntities2.add(pork);
productEntities2.add(pork1);
productEntities2.add(pork2);
productEntities2.add(pork3);
WishListEntity wishListEntity = WishListEntity.builder()
.id(1)
.title("Products")
.productEntities(productEntities).build();
wishListRepository.save(wishListEntity);
WishListEntity wishListEntity2 = WishListEntity.builder()
.id(2)
.title("Items")
.productEntities(productEntities2).build();
wishListRepository.save(wishListEntity2);
Set<WishListEntity> wishListEntities = new HashSet<>();
wishListEntities.add(wishListEntity);
wishListEntities.add(wishListEntity2);
admin.setWishListEntities(wishListEntities);
userRepository.save(admin);
};
}
}
| 25,863 | 0.540683 | 0.512565 | 634 | 40.1735 | 24.619274 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.334385 | false | false | 4 |
c7c2ff492c10d31e3b57c5c6f1d5821f8d6e03f5 | 29,927,332,137,099 | ecfe827ed9bf67371cdade1c98254c676ec3514c | /src/test/java/com/npaw/service/balancer/servlets/ServicioTest.java | 5a13785e2834fa4ac7242cd4f488b56594928aa1 | [] | no_license | xeviff/balancer-service | https://github.com/xeviff/balancer-service | 15b3b537fb9ce5681dfddd8f6cd71e9c1a2d56fe | d51bfa75f7957c05cb1c608f0421271e612c0f31 | refs/heads/main | 2023-08-28T11:12:31.991000 | 2021-11-04T15:32:24 | 2021-11-04T15:32:24 | 424,647,269 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.npaw.service.balancer.servlets;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import com.npaw.service.balancer.config.ConfigManager;
import com.npaw.service.balancer.model.DeviceConfiguration;
class ServicioTest {
DecimalFormat df = new DecimalFormat("###.##");
static ConfigManager configM;
@BeforeAll
static void init() throws Exception {
configM = ConfigManager.getInstance();
}
@RepeatedTest(10)
@DisplayName("Load Balance Test (xTimes) >> multiple calls, 1% margin error allowed")
void loadBalanceTest1 () throws Exception {
//given
int callN = 1000000;
byte cluster1LoadDef = 30;
byte cluster2LoadDef = 70;
byte errMrgn = 1; //%
String account = "clienteA";
String device = "XBox";
String cluster1 = "clusterA.com";
String cluster2 = "clusterB.com";
DeviceConfiguration deviceInfo = configM.getDevice(account, device);
//when
String[] balancedResult = new String[callN];
for (int i=0 ; i<callN ; i++) {
String cluster = deviceInfo.getBalancing().nextRequest();
balancedResult[i]=cluster;
}
//then
List<String> resultList = Arrays.asList(balancedResult);
int cluster1Count = Collections.frequency(resultList, cluster1);
int cluster2Count = Collections.frequency(resultList, cluster2);
float cluster1Balance = calcPer100(cluster1Count,callN);
float cluster2Balance = calcPer100(cluster2Count,callN);
String headerLog = MessageFormat.format("Balancing test made for {2} calls, account {0} and device {1}.",
account, device, callN);
System.out.println();
System.out.println(headerLog);
System.out.println("Balanced to cluster1Balance: "+printPercent(cluster1Balance));
System.out.println("Balanced to cluster2Balance: "+printPercent(cluster2Balance));
System.out.println("Error margin: "+printPercent(cluster1Balance-(float)cluster1LoadDef));
// System.out.println("Error margin 2: "+printPercent(cluster2Balance-(float)cluster2LoadDef));
assertAll(
() -> assertTrue(isValueInAllowedErrMargin(cluster1Balance, cluster1LoadDef, errMrgn)),
() -> assertTrue(isValueInAllowedErrMargin(cluster2Balance, cluster2LoadDef, errMrgn))
);
}
private float calcPer100 (int amount, int total) {
float perc = amount*(float)100/(float)total;
return perc;
}
private boolean isValueInAllowedErrMargin (float value, byte defined, byte margin) {
float mgn = (float)margin;
float def = (float)defined;
return value >= def-mgn && value <= def+mgn;
}
private String printPercent (float value) {
return df.format(value)+" %";
}
}
| UTF-8 | Java | 2,895 | java | ServicioTest.java | Java | [
{
"context": "= 70;\n\t\tbyte errMrgn = 1; //%\n\t\tString account = \"clienteA\";\n\t\tString device = \"XBox\";\n\t\tString cluster1 = \"",
"end": 1046,
"score": 0.8882105350494385,
"start": 1038,
"tag": "USERNAME",
"value": "clienteA"
}
] | null | [] | package com.npaw.service.balancer.servlets;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import com.npaw.service.balancer.config.ConfigManager;
import com.npaw.service.balancer.model.DeviceConfiguration;
class ServicioTest {
DecimalFormat df = new DecimalFormat("###.##");
static ConfigManager configM;
@BeforeAll
static void init() throws Exception {
configM = ConfigManager.getInstance();
}
@RepeatedTest(10)
@DisplayName("Load Balance Test (xTimes) >> multiple calls, 1% margin error allowed")
void loadBalanceTest1 () throws Exception {
//given
int callN = 1000000;
byte cluster1LoadDef = 30;
byte cluster2LoadDef = 70;
byte errMrgn = 1; //%
String account = "clienteA";
String device = "XBox";
String cluster1 = "clusterA.com";
String cluster2 = "clusterB.com";
DeviceConfiguration deviceInfo = configM.getDevice(account, device);
//when
String[] balancedResult = new String[callN];
for (int i=0 ; i<callN ; i++) {
String cluster = deviceInfo.getBalancing().nextRequest();
balancedResult[i]=cluster;
}
//then
List<String> resultList = Arrays.asList(balancedResult);
int cluster1Count = Collections.frequency(resultList, cluster1);
int cluster2Count = Collections.frequency(resultList, cluster2);
float cluster1Balance = calcPer100(cluster1Count,callN);
float cluster2Balance = calcPer100(cluster2Count,callN);
String headerLog = MessageFormat.format("Balancing test made for {2} calls, account {0} and device {1}.",
account, device, callN);
System.out.println();
System.out.println(headerLog);
System.out.println("Balanced to cluster1Balance: "+printPercent(cluster1Balance));
System.out.println("Balanced to cluster2Balance: "+printPercent(cluster2Balance));
System.out.println("Error margin: "+printPercent(cluster1Balance-(float)cluster1LoadDef));
// System.out.println("Error margin 2: "+printPercent(cluster2Balance-(float)cluster2LoadDef));
assertAll(
() -> assertTrue(isValueInAllowedErrMargin(cluster1Balance, cluster1LoadDef, errMrgn)),
() -> assertTrue(isValueInAllowedErrMargin(cluster2Balance, cluster2LoadDef, errMrgn))
);
}
private float calcPer100 (int amount, int total) {
float perc = amount*(float)100/(float)total;
return perc;
}
private boolean isValueInAllowedErrMargin (float value, byte defined, byte margin) {
float mgn = (float)margin;
float def = (float)defined;
return value >= def-mgn && value <= def+mgn;
}
private String printPercent (float value) {
return df.format(value)+" %";
}
}
| 2,895 | 0.744041 | 0.724352 | 87 | 32.275864 | 28.119896 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.149425 | false | false | 4 |
d58329fbd149d58f7d6725a28434124ffa8a398c | 24,988,119,771,879 | e1d21bfd5783cbb8320806dfb42128fa9bb0b0bc | /src/main/java/com/coreos/appc/S3AciRepository.java | 2b6f7626feddee9852d3fe1662139af2d750224d | [
"Apache-2.0"
] | permissive | justinsb/appc-java | https://github.com/justinsb/appc-java | bb274d02c96ce1db793d9d8edfed7cba4df963de | 5f68d919aaee266e39a09a2eb242f3fe8491d913 | refs/heads/master | 2016-09-06T08:16:19.554000 | 2015-05-05T04:03:20 | 2015-05-05T04:03:20 | 33,824,787 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coreos.appc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import org.slf4j.Logger;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.google.common.base.Strings;
public class S3AciRepository extends AciRepository {
final AmazonS3 s3;
final String bucketName;
final String prefix;
public boolean updateLatest = true;
public boolean makePublic = true;
public S3AciRepository(AmazonS3 s3, String bucketName, String prefix) {
this.s3 = s3;
this.bucketName = bucketName;
this.prefix = prefix;
}
@Override
public void push(AciImageInfo imageInfo, File image, byte[] signature, Logger log) {
String imageKey = buildKey(imageInfo, "aci");
{
log.info("Uploading image to {}/{}", bucketName, imageKey);
PutObjectRequest request = new PutObjectRequest(bucketName, imageKey, image);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
s3.putObject(request);
}
String signatureKey = buildKey(imageInfo, "aci.asc");
if (signature != null) {
InputStream contents = new ByteArrayInputStream(signature);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(signature.length);
PutObjectRequest request = new PutObjectRequest(bucketName, signatureKey, contents, metadata);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
log.info("Uploading signature to {}/{}", bucketName, signatureKey);
s3.putObject(request);
}
if (updateLatest) {
String tag = "latest";
log.info("Setting up redirect for {}", tag);
String tagKey = buildKey(imageInfo, "aci", tag);
String redirectTo = "/" + imageKey;
createRedirect(tagKey, redirectTo);
}
if (updateLatest && signature != null) {
String tag = "latest";
log.info("Setting up signature redirect for {}", tag);
String tagSignatureKey = buildKey(imageInfo, "aci.asc", tag);
//
// InputStream contents = new ByteArrayInputStream(signature);
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentLength(signature.length);
// PutObjectRequest request = new PutObjectRequest(bucketName, tagSignatureKey, contents,
// metadata);
// if (makePublic) {
// request.withCannedAcl(CannedAccessControlList.PublicRead);
// }
// log.info("Uploading signature to {}/{}", bucketName, tagSignatureKey);
// s3.putObject(request);
String redirectTo = "/" + signatureKey;
createRedirect(tagSignatureKey, redirectTo);
}
}
private void createRedirect(String fromKey, String redirectTo) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
metadata.setHeader("x-amz-website-redirect-location", redirectTo);
PutObjectRequest request = new PutObjectRequest(bucketName, fromKey, new ByteArrayInputStream(
new byte[0]), metadata);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
s3.putObject(request);
}
private String buildKey(AciImageInfo imageInfo, String extension) {
String version = imageInfo.version;
if (Strings.isNullOrEmpty(version)) {
version = AciImageInfo.DEFAULT_VERSION;
}
return buildKey(imageInfo, extension, version);
}
private String buildKey(AciImageInfo imageInfo, String extension, String version) {
String baseKey = prefix;
if (Strings.isNullOrEmpty(baseKey)) {
baseKey = "";
} else if (!baseKey.endsWith("/")) {
baseKey += "/";
}
String name = imageInfo.name;
if (Strings.isNullOrEmpty(name)) {
throw new IllegalArgumentException("name is required");
}
String os = imageInfo.os;
if (Strings.isNullOrEmpty(os)) {
os = AciImageInfo.DEFAULT_OS;
}
String arch = imageInfo.arch;
if (Strings.isNullOrEmpty(arch)) {
arch = AciImageInfo.DEFAULT_ARCH;
}
// key += name + "-" + version + "-" + os + "-" + arch + "." + ext;
String key = baseKey + os + "/" + arch + "/" + name + "-" + version + "." + extension;
return key;
}
} | UTF-8 | Java | 4,401 | java | S3AciRepository.java | Java | [
{
"context": " String tagSignatureKey = buildKey(imageInfo, \"aci.asc\", tag);\n //\n // InputStream contents = ",
"end": 2211,
"score": 0.702216386795044,
"start": 2204,
"tag": "KEY",
"value": "aci.asc"
}
] | null | [] | package com.coreos.appc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import org.slf4j.Logger;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.google.common.base.Strings;
public class S3AciRepository extends AciRepository {
final AmazonS3 s3;
final String bucketName;
final String prefix;
public boolean updateLatest = true;
public boolean makePublic = true;
public S3AciRepository(AmazonS3 s3, String bucketName, String prefix) {
this.s3 = s3;
this.bucketName = bucketName;
this.prefix = prefix;
}
@Override
public void push(AciImageInfo imageInfo, File image, byte[] signature, Logger log) {
String imageKey = buildKey(imageInfo, "aci");
{
log.info("Uploading image to {}/{}", bucketName, imageKey);
PutObjectRequest request = new PutObjectRequest(bucketName, imageKey, image);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
s3.putObject(request);
}
String signatureKey = buildKey(imageInfo, "aci.asc");
if (signature != null) {
InputStream contents = new ByteArrayInputStream(signature);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(signature.length);
PutObjectRequest request = new PutObjectRequest(bucketName, signatureKey, contents, metadata);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
log.info("Uploading signature to {}/{}", bucketName, signatureKey);
s3.putObject(request);
}
if (updateLatest) {
String tag = "latest";
log.info("Setting up redirect for {}", tag);
String tagKey = buildKey(imageInfo, "aci", tag);
String redirectTo = "/" + imageKey;
createRedirect(tagKey, redirectTo);
}
if (updateLatest && signature != null) {
String tag = "latest";
log.info("Setting up signature redirect for {}", tag);
String tagSignatureKey = buildKey(imageInfo, "aci.asc", tag);
//
// InputStream contents = new ByteArrayInputStream(signature);
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentLength(signature.length);
// PutObjectRequest request = new PutObjectRequest(bucketName, tagSignatureKey, contents,
// metadata);
// if (makePublic) {
// request.withCannedAcl(CannedAccessControlList.PublicRead);
// }
// log.info("Uploading signature to {}/{}", bucketName, tagSignatureKey);
// s3.putObject(request);
String redirectTo = "/" + signatureKey;
createRedirect(tagSignatureKey, redirectTo);
}
}
private void createRedirect(String fromKey, String redirectTo) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
metadata.setHeader("x-amz-website-redirect-location", redirectTo);
PutObjectRequest request = new PutObjectRequest(bucketName, fromKey, new ByteArrayInputStream(
new byte[0]), metadata);
if (makePublic) {
request.withCannedAcl(CannedAccessControlList.PublicRead);
}
s3.putObject(request);
}
private String buildKey(AciImageInfo imageInfo, String extension) {
String version = imageInfo.version;
if (Strings.isNullOrEmpty(version)) {
version = AciImageInfo.DEFAULT_VERSION;
}
return buildKey(imageInfo, extension, version);
}
private String buildKey(AciImageInfo imageInfo, String extension, String version) {
String baseKey = prefix;
if (Strings.isNullOrEmpty(baseKey)) {
baseKey = "";
} else if (!baseKey.endsWith("/")) {
baseKey += "/";
}
String name = imageInfo.name;
if (Strings.isNullOrEmpty(name)) {
throw new IllegalArgumentException("name is required");
}
String os = imageInfo.os;
if (Strings.isNullOrEmpty(os)) {
os = AciImageInfo.DEFAULT_OS;
}
String arch = imageInfo.arch;
if (Strings.isNullOrEmpty(arch)) {
arch = AciImageInfo.DEFAULT_ARCH;
}
// key += name + "-" + version + "-" + os + "-" + arch + "." + ext;
String key = baseKey + os + "/" + arch + "/" + name + "-" + version + "." + extension;
return key;
}
} | 4,401 | 0.677346 | 0.672802 | 138 | 30.89855 | 26.830734 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782609 | false | false | 4 |
4adc3bb3c63a593ef61069a1daac0e59fec9bf3f | 3,779,571,274,538 | a66b179bde211463fa91ac3845efefdff56dfdfe | /src/easy/ValidParentheses.java | be1360a140983a0184221faf54bf60902010b9ff | [] | no_license | MrGeekr/LeetCodeDiary | https://github.com/MrGeekr/LeetCodeDiary | 271553bf81d357b2c6d5736a269dcbd7f05b07b2 | 2c3280ee31f7af9b7104cf3d0a1e992352735a9e | refs/heads/master | 2020-06-25T06:43:08.757000 | 2020-01-08T07:41:19 | 2020-01-08T07:41:19 | 199,233,524 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package easy;
import java.util.HashMap;
import java.util.Stack;
/**
* Created by MrGeekr.
* Date : 2019/11/29.
* Description :
* 20. 有效的括号
* 难度
* 简单
*
* 1214
*
*
* 收藏
*
* 分享
* 切换为英文
* 关注
* 通过次数
*
* 160,393
*
* 提交次数
*
* 399,623
* 描述
* 评论
* 题解New
* 历史
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 注意空字符串可被认为是有效字符串。
*
* 示例 1:
*
* 输入: "()"
* 输出: true
* 示例 2:
*
* 输入: "()[]{}"
* 输出: true
* 示例 3:
*
* 输入: "(]"
* 输出: false
* 示例 4:
*
* 输入: "([)]"
* 输出: false
* 示例 5:
*
* 输入: "{[]}"
* 输出: true
*/
public class ValidParentheses {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
//用HashMap存放符号的对应关系,右括号放在key,因为要到用右括号来对比栈中的左括号
HashMap<Character,Character> map=new HashMap<>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
for (int i = 0; i <s.length() ; i++) {
char c=s.charAt(i);
if (!map.containsKey(c)){
stack.push(c);
}else {
//要注意栈为空的情况,否则异常
if (stack.isEmpty()){
return false;
}
char temp=stack.pop();
if (temp!=map.get(c)){
return false;
}
}
}
return stack.isEmpty();
}
}
| UTF-8 | Java | 1,793 | java | ValidParentheses.java | Java | [
{
"context": "ashMap;\nimport java.util.Stack;\n\n/**\n * Created by MrGeekr.\n * Date : 2019/11/29.\n * Description :\n * 20. 有效",
"end": 91,
"score": 0.9996007680892944,
"start": 84,
"tag": "USERNAME",
"value": "MrGeekr"
}
] | null | [] | package easy;
import java.util.HashMap;
import java.util.Stack;
/**
* Created by MrGeekr.
* Date : 2019/11/29.
* Description :
* 20. 有效的括号
* 难度
* 简单
*
* 1214
*
*
* 收藏
*
* 分享
* 切换为英文
* 关注
* 通过次数
*
* 160,393
*
* 提交次数
*
* 399,623
* 描述
* 评论
* 题解New
* 历史
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 注意空字符串可被认为是有效字符串。
*
* 示例 1:
*
* 输入: "()"
* 输出: true
* 示例 2:
*
* 输入: "()[]{}"
* 输出: true
* 示例 3:
*
* 输入: "(]"
* 输出: false
* 示例 4:
*
* 输入: "([)]"
* 输出: false
* 示例 5:
*
* 输入: "{[]}"
* 输出: true
*/
public class ValidParentheses {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
//用HashMap存放符号的对应关系,右括号放在key,因为要到用右括号来对比栈中的左括号
HashMap<Character,Character> map=new HashMap<>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
for (int i = 0; i <s.length() ; i++) {
char c=s.charAt(i);
if (!map.containsKey(c)){
stack.push(c);
}else {
//要注意栈为空的情况,否则异常
if (stack.isEmpty()){
return false;
}
char temp=stack.pop();
if (temp!=map.get(c)){
return false;
}
}
}
return stack.isEmpty();
}
}
| 1,793 | 0.43817 | 0.415297 | 88 | 14.897727 | 13.82935 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.261364 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.