blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ed54241a772d9e3ccfd2bbf08f8a9b4b53f63e9 | b6199abe08586e153408063afa96a6e4f40be1aa | /Desktop/ClassScheduleSearch/src/sample/LoginController.java | eb4870984b615befc4902e4fc941e27963ea7aea | [] | no_license | mikeshprd/testt | 3aa2a61740512b2dc8235ae2ae9a51bd28437e09 | 4b29104b350e4e19bc2126af4412880e8bc10725 | refs/heads/master | 2021-05-09T20:13:28.198902 | 2018-03-14T21:12:44 | 2018-03-14T21:12:44 | 118,681,639 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,028 | java | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class LoginController {
@FXML
public TextField campusId, password;
@FXML
public Button loginB;
@FXML
public Label userPassWrong;
java.sql.Connection conn = null;
ResultSet rs = null;
Statement st;
@FXML
public void Login(ActionEvent event) throws Exception{
try {
if (!campusId.getText().isEmpty() && !password.getText().isEmpty()) {
String user = campusId.getText();
String pass = password.getText();
conn = DriverManager.getConnection("jdbc:sqlite:UpdatedDB.db");
st = (Statement) conn.createStatement();
rs = st.executeQuery("SELECT * FROM StudentTable where Username = '" + user + "' AND Password_Plain = '" + pass+"'");
if(rs.next()) {
if (rs.getString(16).equals(user) && rs.getString(17).equals(pass)) {
Stage stage;
Parent root;
stage = (Stage) ((Button) (event.getSource())).getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
Scene scene = new Scene(root);
String str = rs.getString(2);
stage.setScene(scene);
stage.show();
rs.close();
}
}
else{
userPassWrong.setText("CampusId or Password wrong.");
}
}
}
catch (Exception e ){
throw e;
}
}
}
| [
"[email protected]"
] | |
ec2b5b29f667783d8f776b7d94bbc8853d405d31 | 8f0ae91a5055ac51733b9c0c4694c89fa7466635 | /mycloud-providerdept8002/src/main/java/com/gpw/springcloud/DeptProvider8002_App.java | 78ddce232aff182e2208bacb1567984438b51309 | [
"MIT"
] | permissive | gpw1126/microservice | aa683250072a6301c7cc3fbf132effc234b0df7e | 4c487f594569873ebd24ce0d2a9b1992ce9676af | refs/heads/master | 2022-06-22T04:16:26.554728 | 2019-06-12T13:11:08 | 2019-06-12T13:11:08 | 191,164,639 | 0 | 0 | MIT | 2020-07-01T23:24:37 | 2019-06-10T12:33:35 | Java | UTF-8 | Java | false | false | 512 | java | package com.gpw.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @Author: Gpw
* @Date: 2019/6/7
* @Description: com.gpw.springcloud
* @Version: 1.0
*/
@SpringBootApplication
@EnableEurekaClient
public class DeptProvider8002_App {
public static void main(String[] args){
SpringApplication.run(DeptProvider8002_App.class, args);
}
}
| [
"[email protected]"
] | |
82b51fb899d3cadbe834735e35122d6e86ae3a61 | 2283f5fae1c4342e8ba1321aaa0d4764db19a3b3 | /jabac-client/src/main/java/com/essue/jabac/client/query/EqualsConditionCompiler.java | 33ddd8e40612b99217a76797fde760c35f8b9657 | [
"MIT"
] | permissive | chengked/jabac | 4da55f66c53d6db1ed5d0520303c568ac961779e | 4fa18de3d126624b302ffbc831197f9b46ebe1dc | refs/heads/master | 2023-03-23T18:32:48.724850 | 2021-03-12T11:18:17 | 2021-03-12T11:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 482 | java | package com.essue.jabac.client.query;
import com.essue.jabac.client.query.criteria.Criteria;
import com.essue.jabac.client.query.criteria.Eq;
import com.essue.jabac.core.policy.condition.ConditionEvaluator;
public class EqualsConditionCompiler implements ConditionCompiler {
@Override
public Criteria compile(final String key, final Object value) {
return new Eq(key, value);
}
@Override
public String getOp() {
return ConditionEvaluator.EQUALS.getOp();
}
}
| [
"[email protected]"
] | |
5313be39f27c35af9718f29f23e0c761103a9bd4 | d10e7f704ac04675787964b4a38be65ea15b4080 | /server/src/main/java/edp/davinci/model/DisplaySlide.java | e8db59435e751ccb2aa273c2c1b920de0f767188 | [
"EPL-1.0",
"BSD-3-Clause",
"Classpath-exception-2.0",
"W3C",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"CDDL-1.0",
"LGPL-2.1-only",
"MIT",
"GPL-2.0-only",
"SAX-PD",
"Apache-2.0",
"LGPL-2.0-or-later",
"JSON",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | a85255/davinci | 1f552d70a41efc8a0d405cdb9c3b9f1e683e9157 | eda2a424997115c7383df179be9fa9993d1b4c02 | refs/heads/master | 2022-12-24T04:59:59.153107 | 2019-10-30T07:55:21 | 2019-10-30T07:55:21 | 214,928,373 | 1 | 0 | Apache-2.0 | 2022-12-10T06:41:45 | 2019-10-14T02:13:26 | TypeScript | UTF-8 | Java | false | false | 1,427 | java | /*
* <<
* Davinci
* ==
* Copyright (C) 2016 - 2019 EDP
* ==
* 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 edp.davinci.model;
import edp.davinci.common.model.RecordInfo;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Data
@NotNull(message = "DisplaySlide info cannot be null")
public class DisplaySlide extends RecordInfo<DisplaySlide> {
@Min(value = 1L, message = "Invalid slide id")
private Long id;
@Min(value = 1L, message = "Invalid display id")
private Long displayId;
private Integer index;
private String config;
@Override
public String toString() {
return "DisplaySlide{" +
"id=" + id +
", displayId=" + displayId +
", index=" + index +
", config='" + config + '\'' +
'}';
}
} | [
"[email protected]"
] | |
8cfccb3ad91cfed8d5b585a701efe6a06be096a3 | 82380e31c433e6851dc1ff6f1bcccef30401c764 | /app/src/main/java/com/thoughworks/retail/binding/configuration/ProductConifguration.java | b73a2f088eb57bdbb48168199de442a86e3b079a | [] | no_license | Michelle0716/android-mvvp-master | 576201fa27f62ca4c8aa14afb381a0c72b029a79 | afe3794b5196d0c8c71bec0f2b336637296519ab | refs/heads/master | 2020-04-07T15:28:38.207361 | 2018-11-21T03:48:28 | 2018-11-21T03:48:28 | 158,487,216 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 993 | java | package com.thoughworks.retail.binding.configuration;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import com.thoughworks.retail.adapter.ProductAdapter;
import com.thoughworks.retail.database.RetailDataUtil;
/**
* Created by prateek.aggarwal on 8/18/16.
*/
public class ProductConifguration extends BaseRecyclerConfiguration {
private ProductAdapter mAdapter;
/**
* Initialize product recyclerview
* @param context Application context
* @param manager instance of fragment manager
* */
public void initialize(Context context,FragmentManager manager){
setLayoutManager(new LinearLayoutManager(context));
setItemAnimator(new DefaultItemAnimator());
mAdapter = new ProductAdapter(context,manager, RetailDataUtil.getInstance(context).getProduct());
setAdapter(mAdapter);
}
}
| [
"1031983332b"
] | 1031983332b |
bdd08b72c79cc81df5a1b61d473ca7f016314d4a | 914d043510ed3f71d967c5622b8c757fb033bfb3 | /spring-boot-autoconfigure-data-jdbc-plus/src/main/java/com/navercorp/spring/boot/autoconfigure/data/jdbc/plus/repository/JdbcPlusReactiveSupportRepositoriesRegistrar.java | 6fed94c02fbfbd2830a2028dcb018a51cffc95ee | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | naver/spring-jdbc-plus | ee53940b290d1d84b67446d4aa964e139622bdde | 7ad384bc3d50ac66e3d06405973044ec0267a174 | refs/heads/main | 2023-08-31T00:20:28.505637 | 2023-08-28T02:29:19 | 2023-08-28T02:29:19 | 233,731,825 | 245 | 40 | Apache-2.0 | 2023-08-23T09:40:51 | 2020-01-14T01:41:35 | Java | UTF-8 | Java | false | false | 1,896 | java | /*
* Spring JDBC Plus
*
* Copyright 2020-2021 NAVER Corp.
*
* 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.navercorp.spring.boot.autoconfigure.data.jdbc.plus.repository;
import java.lang.annotation.Annotation;
import org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import com.navercorp.spring.data.jdbc.plus.repository.config.EnableJdbcPlusReactiveSupportRepositories;
import com.navercorp.spring.data.jdbc.plus.repository.config.JdbcPlusRepositoryReactiveSupportConfigExtension;
/**
* The type Jdbc plus reactive support repositories registrar.
*
* @author Myeonghyeon Lee
*/
class JdbcPlusReactiveSupportRepositoriesRegistrar extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableJdbcPlusReactiveSupportRepositories.class;
}
@Override
protected Class<?> getConfiguration() {
return EnableJdbcPlusReactiveSupportRepositoriesConfiguration.class;
}
@Override
protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() {
return new JdbcPlusRepositoryReactiveSupportConfigExtension();
}
@EnableJdbcPlusReactiveSupportRepositories
private static class EnableJdbcPlusReactiveSupportRepositoriesConfiguration {
}
}
| [
"[email protected]"
] | |
62570c45ee44616df6fb6c17ec2329cae33b8bfe | ef1c8abca88b805d0b39c0cf449423983f88765b | /src/main/java/com/aspose/slides/model/ParagraphFormat.java | 8f751623b53ee01fa05a99c88cfe1270025427af | [
"MIT"
] | permissive | aspose-slides-cloud/aspose-slides-cloud-java | 86525cc27d92ece398f1d6977616470e41500d86 | 17d3006f15ea03562eebcd2fd42acc76bad4a514 | refs/heads/master | 2023-08-07T14:44:35.755022 | 2023-07-30T13:11:17 | 2023-07-30T13:11:17 | 149,193,516 | 0 | 4 | MIT | 2022-05-20T20:55:44 | 2018-09-17T22:01:33 | Java | UTF-8 | Java | false | false | 31,011 | java | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2018 Aspose.Slides for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
package com.aspose.slides.model;
import java.util.Objects;
import com.aspose.slides.model.FillFormat;
import com.aspose.slides.model.PortionFormat;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
/**
* Paragraph formatting properties.
*/
@ApiModel(description = "Paragraph formatting properties.")
public class ParagraphFormat {
@SerializedName(value = "depth", alternate = { "Depth" })
private Integer depth;
/**
* Text alignment.
*/
@JsonAdapter(AlignmentEnum.Adapter.class)
public enum AlignmentEnum {
LEFT("Left"),
CENTER("Center"),
RIGHT("Right"),
JUSTIFY("Justify"),
JUSTIFYLOW("JustifyLow"),
DISTRIBUTED("Distributed"),
NOTDEFINED("NotDefined");
private String value;
AlignmentEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static AlignmentEnum fromValue(String text) {
for (AlignmentEnum b : AlignmentEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<AlignmentEnum> {
@Override
public void write(final JsonWriter jsonWriter, final AlignmentEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public AlignmentEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return AlignmentEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "alignment", alternate = { "Alignment" })
private AlignmentEnum alignment;
@SerializedName(value = "marginLeft", alternate = { "MarginLeft" })
private Double marginLeft;
@SerializedName(value = "marginRight", alternate = { "MarginRight" })
private Double marginRight;
@SerializedName(value = "spaceBefore", alternate = { "SpaceBefore" })
private Double spaceBefore;
@SerializedName(value = "spaceAfter", alternate = { "SpaceAfter" })
private Double spaceAfter;
@SerializedName(value = "spaceWithin", alternate = { "SpaceWithin" })
private Double spaceWithin;
/**
* Font alignment.
*/
@JsonAdapter(FontAlignmentEnum.Adapter.class)
public enum FontAlignmentEnum {
AUTOMATIC("Automatic"),
TOP("Top"),
CENTER("Center"),
BOTTOM("Bottom"),
BASELINE("Baseline"),
DEFAULT("Default");
private String value;
FontAlignmentEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static FontAlignmentEnum fromValue(String text) {
for (FontAlignmentEnum b : FontAlignmentEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<FontAlignmentEnum> {
@Override
public void write(final JsonWriter jsonWriter, final FontAlignmentEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public FontAlignmentEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return FontAlignmentEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "fontAlignment", alternate = { "FontAlignment" })
private FontAlignmentEnum fontAlignment;
@SerializedName(value = "indent", alternate = { "Indent" })
private Double indent;
/**
* Determines whether the Right to Left writing is used in a paragraph. No inheritance applied.
*/
@JsonAdapter(RightToLeftEnum.Adapter.class)
public enum RightToLeftEnum {
FALSE("False"),
TRUE("True"),
NOTDEFINED("NotDefined");
private String value;
RightToLeftEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static RightToLeftEnum fromValue(String text) {
for (RightToLeftEnum b : RightToLeftEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<RightToLeftEnum> {
@Override
public void write(final JsonWriter jsonWriter, final RightToLeftEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public RightToLeftEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return RightToLeftEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "rightToLeft", alternate = { "RightToLeft" })
private RightToLeftEnum rightToLeft;
/**
* Determines whether the East Asian line break is used in a paragraph. No inheritance applied.
*/
@JsonAdapter(EastAsianLineBreakEnum.Adapter.class)
public enum EastAsianLineBreakEnum {
FALSE("False"),
TRUE("True"),
NOTDEFINED("NotDefined");
private String value;
EastAsianLineBreakEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static EastAsianLineBreakEnum fromValue(String text) {
for (EastAsianLineBreakEnum b : EastAsianLineBreakEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<EastAsianLineBreakEnum> {
@Override
public void write(final JsonWriter jsonWriter, final EastAsianLineBreakEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public EastAsianLineBreakEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return EastAsianLineBreakEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "eastAsianLineBreak", alternate = { "EastAsianLineBreak" })
private EastAsianLineBreakEnum eastAsianLineBreak;
/**
* Determines whether the Latin line break is used in a paragraph. No inheritance applied.
*/
@JsonAdapter(LatinLineBreakEnum.Adapter.class)
public enum LatinLineBreakEnum {
FALSE("False"),
TRUE("True"),
NOTDEFINED("NotDefined");
private String value;
LatinLineBreakEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static LatinLineBreakEnum fromValue(String text) {
for (LatinLineBreakEnum b : LatinLineBreakEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<LatinLineBreakEnum> {
@Override
public void write(final JsonWriter jsonWriter, final LatinLineBreakEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public LatinLineBreakEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return LatinLineBreakEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "latinLineBreak", alternate = { "LatinLineBreak" })
private LatinLineBreakEnum latinLineBreak;
/**
* Determines whether the hanging punctuation is used in a paragraph. No inheritance applied.
*/
@JsonAdapter(HangingPunctuationEnum.Adapter.class)
public enum HangingPunctuationEnum {
FALSE("False"),
TRUE("True"),
NOTDEFINED("NotDefined");
private String value;
HangingPunctuationEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static HangingPunctuationEnum fromValue(String text) {
for (HangingPunctuationEnum b : HangingPunctuationEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<HangingPunctuationEnum> {
@Override
public void write(final JsonWriter jsonWriter, final HangingPunctuationEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public HangingPunctuationEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return HangingPunctuationEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "hangingPunctuation", alternate = { "HangingPunctuation" })
private HangingPunctuationEnum hangingPunctuation;
@SerializedName(value = "defaultTabSize", alternate = { "DefaultTabSize" })
private Double defaultTabSize;
@SerializedName(value = "defaultPortionFormat", alternate = { "DefaultPortionFormat" })
private PortionFormat defaultPortionFormat;
@SerializedName(value = "bulletChar", alternate = { "BulletChar" })
private String bulletChar;
@SerializedName(value = "bulletHeight", alternate = { "BulletHeight" })
private Double bulletHeight;
/**
* Bullet type.
*/
@JsonAdapter(BulletTypeEnum.Adapter.class)
public enum BulletTypeEnum {
NONE("None"),
SYMBOL("Symbol"),
NUMBERED("Numbered"),
PICTURE("Picture"),
NOTDEFINED("NotDefined");
private String value;
BulletTypeEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static BulletTypeEnum fromValue(String text) {
for (BulletTypeEnum b : BulletTypeEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<BulletTypeEnum> {
@Override
public void write(final JsonWriter jsonWriter, final BulletTypeEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public BulletTypeEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return BulletTypeEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "bulletType", alternate = { "BulletType" })
private BulletTypeEnum bulletType;
@SerializedName(value = "numberedBulletStartWith", alternate = { "NumberedBulletStartWith" })
private Integer numberedBulletStartWith;
/**
* Numbered bullet style.
*/
@JsonAdapter(NumberedBulletStyleEnum.Adapter.class)
public enum NumberedBulletStyleEnum {
BULLETALPHALCPERIOD("BulletAlphaLCPeriod"),
BULLETALPHAUCPERIOD("BulletAlphaUCPeriod"),
BULLETARABICPARENRIGHT("BulletArabicParenRight"),
BULLETARABICPERIOD("BulletArabicPeriod"),
BULLETROMANLCPARENBOTH("BulletRomanLCParenBoth"),
BULLETROMANLCPARENRIGHT("BulletRomanLCParenRight"),
BULLETROMANLCPERIOD("BulletRomanLCPeriod"),
BULLETROMANUCPERIOD("BulletRomanUCPeriod"),
BULLETALPHALCPARENBOTH("BulletAlphaLCParenBoth"),
BULLETALPHALCPARENRIGHT("BulletAlphaLCParenRight"),
BULLETALPHAUCPARENBOTH("BulletAlphaUCParenBoth"),
BULLETALPHAUCPARENRIGHT("BulletAlphaUCParenRight"),
BULLETARABICPARENBOTH("BulletArabicParenBoth"),
BULLETARABICPLAIN("BulletArabicPlain"),
BULLETROMANUCPARENBOTH("BulletRomanUCParenBoth"),
BULLETROMANUCPARENRIGHT("BulletRomanUCParenRight"),
BULLETSIMPCHINPLAIN("BulletSimpChinPlain"),
BULLETSIMPCHINPERIOD("BulletSimpChinPeriod"),
BULLETCIRCLENUMDBPLAIN("BulletCircleNumDBPlain"),
BULLETCIRCLENUMWDWHITEPLAIN("BulletCircleNumWDWhitePlain"),
BULLETCIRCLENUMWDBLACKPLAIN("BulletCircleNumWDBlackPlain"),
BULLETTRADCHINPLAIN("BulletTradChinPlain"),
BULLETTRADCHINPERIOD("BulletTradChinPeriod"),
BULLETARABICALPHADASH("BulletArabicAlphaDash"),
BULLETARABICABJADDASH("BulletArabicAbjadDash"),
BULLETHEBREWALPHADASH("BulletHebrewAlphaDash"),
BULLETKANJIKOREANPLAIN("BulletKanjiKoreanPlain"),
BULLETKANJIKOREANPERIOD("BulletKanjiKoreanPeriod"),
BULLETARABICDBPLAIN("BulletArabicDBPlain"),
BULLETARABICDBPERIOD("BulletArabicDBPeriod"),
BULLETTHAIALPHAPERIOD("BulletThaiAlphaPeriod"),
BULLETTHAIALPHAPARENRIGHT("BulletThaiAlphaParenRight"),
BULLETTHAIALPHAPARENBOTH("BulletThaiAlphaParenBoth"),
BULLETTHAINUMPERIOD("BulletThaiNumPeriod"),
BULLETTHAINUMPARENRIGHT("BulletThaiNumParenRight"),
BULLETTHAINUMPARENBOTH("BulletThaiNumParenBoth"),
BULLETHINDIALPHAPERIOD("BulletHindiAlphaPeriod"),
BULLETHINDINUMPERIOD("BulletHindiNumPeriod"),
BULLETKANJISIMPCHINDBPERIOD("BulletKanjiSimpChinDBPeriod"),
BULLETHINDINUMPARENRIGHT("BulletHindiNumParenRight"),
BULLETHINDIALPHA1PERIOD("BulletHindiAlpha1Period"),
NOTDEFINED("NotDefined");
private String value;
NumberedBulletStyleEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static NumberedBulletStyleEnum fromValue(String text) {
for (NumberedBulletStyleEnum b : NumberedBulletStyleEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<NumberedBulletStyleEnum> {
@Override
public void write(final JsonWriter jsonWriter, final NumberedBulletStyleEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public NumberedBulletStyleEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return NumberedBulletStyleEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "numberedBulletStyle", alternate = { "NumberedBulletStyle" })
private NumberedBulletStyleEnum numberedBulletStyle;
@SerializedName(value = "bulletFillFormat", alternate = { "BulletFillFormat" })
private FillFormat bulletFillFormat;
public ParagraphFormat() {
super();
}
public ParagraphFormat depth(Integer depth) {
this.depth = depth;
return this;
}
/**
* Depth.
* @return depth
**/
@ApiModelProperty(value = "Depth.")
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
public ParagraphFormat alignment(AlignmentEnum alignment) {
this.alignment = alignment;
return this;
}
/**
* Text alignment.
* @return alignment
**/
@ApiModelProperty(value = "Text alignment.")
public AlignmentEnum getAlignment() {
return alignment;
}
public void setAlignment(AlignmentEnum alignment) {
this.alignment = alignment;
}
public ParagraphFormat marginLeft(Double marginLeft) {
this.marginLeft = marginLeft;
return this;
}
/**
* Left margin.
* @return marginLeft
**/
@ApiModelProperty(value = "Left margin.")
public Double getMarginLeft() {
return marginLeft;
}
public void setMarginLeft(Double marginLeft) {
this.marginLeft = marginLeft;
}
public ParagraphFormat marginRight(Double marginRight) {
this.marginRight = marginRight;
return this;
}
/**
* Right margin.
* @return marginRight
**/
@ApiModelProperty(value = "Right margin.")
public Double getMarginRight() {
return marginRight;
}
public void setMarginRight(Double marginRight) {
this.marginRight = marginRight;
}
public ParagraphFormat spaceBefore(Double spaceBefore) {
this.spaceBefore = spaceBefore;
return this;
}
/**
* Left spacing.
* @return spaceBefore
**/
@ApiModelProperty(value = "Left spacing.")
public Double getSpaceBefore() {
return spaceBefore;
}
public void setSpaceBefore(Double spaceBefore) {
this.spaceBefore = spaceBefore;
}
public ParagraphFormat spaceAfter(Double spaceAfter) {
this.spaceAfter = spaceAfter;
return this;
}
/**
* Right spacing.
* @return spaceAfter
**/
@ApiModelProperty(value = "Right spacing.")
public Double getSpaceAfter() {
return spaceAfter;
}
public void setSpaceAfter(Double spaceAfter) {
this.spaceAfter = spaceAfter;
}
public ParagraphFormat spaceWithin(Double spaceWithin) {
this.spaceWithin = spaceWithin;
return this;
}
/**
* Spacing between lines.
* @return spaceWithin
**/
@ApiModelProperty(value = "Spacing between lines.")
public Double getSpaceWithin() {
return spaceWithin;
}
public void setSpaceWithin(Double spaceWithin) {
this.spaceWithin = spaceWithin;
}
public ParagraphFormat fontAlignment(FontAlignmentEnum fontAlignment) {
this.fontAlignment = fontAlignment;
return this;
}
/**
* Font alignment.
* @return fontAlignment
**/
@ApiModelProperty(value = "Font alignment.")
public FontAlignmentEnum getFontAlignment() {
return fontAlignment;
}
public void setFontAlignment(FontAlignmentEnum fontAlignment) {
this.fontAlignment = fontAlignment;
}
public ParagraphFormat indent(Double indent) {
this.indent = indent;
return this;
}
/**
* First line indent.
* @return indent
**/
@ApiModelProperty(value = "First line indent.")
public Double getIndent() {
return indent;
}
public void setIndent(Double indent) {
this.indent = indent;
}
public ParagraphFormat rightToLeft(RightToLeftEnum rightToLeft) {
this.rightToLeft = rightToLeft;
return this;
}
/**
* Determines whether the Right to Left writing is used in a paragraph. No inheritance applied.
* @return rightToLeft
**/
@ApiModelProperty(value = "Determines whether the Right to Left writing is used in a paragraph. No inheritance applied.")
public RightToLeftEnum getRightToLeft() {
return rightToLeft;
}
public void setRightToLeft(RightToLeftEnum rightToLeft) {
this.rightToLeft = rightToLeft;
}
public ParagraphFormat eastAsianLineBreak(EastAsianLineBreakEnum eastAsianLineBreak) {
this.eastAsianLineBreak = eastAsianLineBreak;
return this;
}
/**
* Determines whether the East Asian line break is used in a paragraph. No inheritance applied.
* @return eastAsianLineBreak
**/
@ApiModelProperty(value = "Determines whether the East Asian line break is used in a paragraph. No inheritance applied.")
public EastAsianLineBreakEnum getEastAsianLineBreak() {
return eastAsianLineBreak;
}
public void setEastAsianLineBreak(EastAsianLineBreakEnum eastAsianLineBreak) {
this.eastAsianLineBreak = eastAsianLineBreak;
}
public ParagraphFormat latinLineBreak(LatinLineBreakEnum latinLineBreak) {
this.latinLineBreak = latinLineBreak;
return this;
}
/**
* Determines whether the Latin line break is used in a paragraph. No inheritance applied.
* @return latinLineBreak
**/
@ApiModelProperty(value = "Determines whether the Latin line break is used in a paragraph. No inheritance applied.")
public LatinLineBreakEnum getLatinLineBreak() {
return latinLineBreak;
}
public void setLatinLineBreak(LatinLineBreakEnum latinLineBreak) {
this.latinLineBreak = latinLineBreak;
}
public ParagraphFormat hangingPunctuation(HangingPunctuationEnum hangingPunctuation) {
this.hangingPunctuation = hangingPunctuation;
return this;
}
/**
* Determines whether the hanging punctuation is used in a paragraph. No inheritance applied.
* @return hangingPunctuation
**/
@ApiModelProperty(value = "Determines whether the hanging punctuation is used in a paragraph. No inheritance applied.")
public HangingPunctuationEnum getHangingPunctuation() {
return hangingPunctuation;
}
public void setHangingPunctuation(HangingPunctuationEnum hangingPunctuation) {
this.hangingPunctuation = hangingPunctuation;
}
public ParagraphFormat defaultTabSize(Double defaultTabSize) {
this.defaultTabSize = defaultTabSize;
return this;
}
/**
* Returns or sets default tabulation size with no inheritance.
* @return defaultTabSize
**/
@ApiModelProperty(value = "Returns or sets default tabulation size with no inheritance.")
public Double getDefaultTabSize() {
return defaultTabSize;
}
public void setDefaultTabSize(Double defaultTabSize) {
this.defaultTabSize = defaultTabSize;
}
public ParagraphFormat defaultPortionFormat(PortionFormat defaultPortionFormat) {
this.defaultPortionFormat = defaultPortionFormat;
return this;
}
/**
* Default portion format.
* @return defaultPortionFormat
**/
@ApiModelProperty(value = "Default portion format.")
public PortionFormat getDefaultPortionFormat() {
return defaultPortionFormat;
}
public void setDefaultPortionFormat(PortionFormat defaultPortionFormat) {
this.defaultPortionFormat = defaultPortionFormat;
}
public ParagraphFormat bulletChar(String bulletChar) {
this.bulletChar = bulletChar;
return this;
}
/**
* Bullet char.
* @return bulletChar
**/
@ApiModelProperty(value = "Bullet char.")
public String getBulletChar() {
return bulletChar;
}
public void setBulletChar(String bulletChar) {
this.bulletChar = bulletChar;
}
public ParagraphFormat bulletHeight(Double bulletHeight) {
this.bulletHeight = bulletHeight;
return this;
}
/**
* Bullet height.
* @return bulletHeight
**/
@ApiModelProperty(value = "Bullet height.")
public Double getBulletHeight() {
return bulletHeight;
}
public void setBulletHeight(Double bulletHeight) {
this.bulletHeight = bulletHeight;
}
public ParagraphFormat bulletType(BulletTypeEnum bulletType) {
this.bulletType = bulletType;
return this;
}
/**
* Bullet type.
* @return bulletType
**/
@ApiModelProperty(value = "Bullet type.")
public BulletTypeEnum getBulletType() {
return bulletType;
}
public void setBulletType(BulletTypeEnum bulletType) {
this.bulletType = bulletType;
}
public ParagraphFormat numberedBulletStartWith(Integer numberedBulletStartWith) {
this.numberedBulletStartWith = numberedBulletStartWith;
return this;
}
/**
* Starting number for a numbered bullet.
* @return numberedBulletStartWith
**/
@ApiModelProperty(value = "Starting number for a numbered bullet.")
public Integer getNumberedBulletStartWith() {
return numberedBulletStartWith;
}
public void setNumberedBulletStartWith(Integer numberedBulletStartWith) {
this.numberedBulletStartWith = numberedBulletStartWith;
}
public ParagraphFormat numberedBulletStyle(NumberedBulletStyleEnum numberedBulletStyle) {
this.numberedBulletStyle = numberedBulletStyle;
return this;
}
/**
* Numbered bullet style.
* @return numberedBulletStyle
**/
@ApiModelProperty(value = "Numbered bullet style.")
public NumberedBulletStyleEnum getNumberedBulletStyle() {
return numberedBulletStyle;
}
public void setNumberedBulletStyle(NumberedBulletStyleEnum numberedBulletStyle) {
this.numberedBulletStyle = numberedBulletStyle;
}
public ParagraphFormat bulletFillFormat(FillFormat bulletFillFormat) {
this.bulletFillFormat = bulletFillFormat;
return this;
}
/**
* Bullet fill format.
* @return bulletFillFormat
**/
@ApiModelProperty(value = "Bullet fill format.")
public FillFormat getBulletFillFormat() {
return bulletFillFormat;
}
public void setBulletFillFormat(FillFormat bulletFillFormat) {
this.bulletFillFormat = bulletFillFormat;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ParagraphFormat paragraphFormat = (ParagraphFormat) o;
return true && Objects.equals(this.depth, paragraphFormat.depth) && Objects.equals(this.alignment, paragraphFormat.alignment) && Objects.equals(this.marginLeft, paragraphFormat.marginLeft) && Objects.equals(this.marginRight, paragraphFormat.marginRight) && Objects.equals(this.spaceBefore, paragraphFormat.spaceBefore) && Objects.equals(this.spaceAfter, paragraphFormat.spaceAfter) && Objects.equals(this.spaceWithin, paragraphFormat.spaceWithin) && Objects.equals(this.fontAlignment, paragraphFormat.fontAlignment) && Objects.equals(this.indent, paragraphFormat.indent) && Objects.equals(this.rightToLeft, paragraphFormat.rightToLeft) && Objects.equals(this.eastAsianLineBreak, paragraphFormat.eastAsianLineBreak) && Objects.equals(this.latinLineBreak, paragraphFormat.latinLineBreak) && Objects.equals(this.hangingPunctuation, paragraphFormat.hangingPunctuation) && Objects.equals(this.defaultTabSize, paragraphFormat.defaultTabSize) && Objects.equals(this.defaultPortionFormat, paragraphFormat.defaultPortionFormat) && Objects.equals(this.bulletChar, paragraphFormat.bulletChar) && Objects.equals(this.bulletHeight, paragraphFormat.bulletHeight) && Objects.equals(this.bulletType, paragraphFormat.bulletType) && Objects.equals(this.numberedBulletStartWith, paragraphFormat.numberedBulletStartWith) && Objects.equals(this.numberedBulletStyle, paragraphFormat.numberedBulletStyle) && Objects.equals(this.bulletFillFormat, paragraphFormat.bulletFillFormat);
}
@Override
public int hashCode() {
return Objects.hash(depth, alignment, marginLeft, marginRight, spaceBefore, spaceAfter, spaceWithin, fontAlignment, indent, rightToLeft, eastAsianLineBreak, latinLineBreak, hangingPunctuation, defaultTabSize, defaultPortionFormat, bulletChar, bulletHeight, bulletType, numberedBulletStartWith, numberedBulletStyle, bulletFillFormat);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ParagraphFormat {\n");
sb.append(" depth: ").append(toIndentedString(depth)).append("\n");
sb.append(" alignment: ").append(toIndentedString(alignment)).append("\n");
sb.append(" marginLeft: ").append(toIndentedString(marginLeft)).append("\n");
sb.append(" marginRight: ").append(toIndentedString(marginRight)).append("\n");
sb.append(" spaceBefore: ").append(toIndentedString(spaceBefore)).append("\n");
sb.append(" spaceAfter: ").append(toIndentedString(spaceAfter)).append("\n");
sb.append(" spaceWithin: ").append(toIndentedString(spaceWithin)).append("\n");
sb.append(" fontAlignment: ").append(toIndentedString(fontAlignment)).append("\n");
sb.append(" indent: ").append(toIndentedString(indent)).append("\n");
sb.append(" rightToLeft: ").append(toIndentedString(rightToLeft)).append("\n");
sb.append(" eastAsianLineBreak: ").append(toIndentedString(eastAsianLineBreak)).append("\n");
sb.append(" latinLineBreak: ").append(toIndentedString(latinLineBreak)).append("\n");
sb.append(" hangingPunctuation: ").append(toIndentedString(hangingPunctuation)).append("\n");
sb.append(" defaultTabSize: ").append(toIndentedString(defaultTabSize)).append("\n");
sb.append(" defaultPortionFormat: ").append(toIndentedString(defaultPortionFormat)).append("\n");
sb.append(" bulletChar: ").append(toIndentedString(bulletChar)).append("\n");
sb.append(" bulletHeight: ").append(toIndentedString(bulletHeight)).append("\n");
sb.append(" bulletType: ").append(toIndentedString(bulletType)).append("\n");
sb.append(" numberedBulletStartWith: ").append(toIndentedString(numberedBulletStartWith)).append("\n");
sb.append(" numberedBulletStyle: ").append(toIndentedString(numberedBulletStyle)).append("\n");
sb.append(" bulletFillFormat: ").append(toIndentedString(bulletFillFormat)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
private static final Map<String, Object> typeDeterminers = new Hashtable<String, Object>();
}
| [
"[email protected]"
] | |
10f42831924cd8d379b3e5fc18456387f6a9ab7a | b0f1624d5a2b1dcc02fde18626b2e14d16d0872a | /Allocator.diagram/src/AllocatorMetamodel/diagram/edit/policies/SoftwareSoftwareCompartmentCanonicalEditPolicy.java | 6c7fe9d64f94271ae858cc9ba25fa93e6a6b4166 | [] | no_license | isvogor-foi/Scall | b6afb225e9d6eff395bdce489cac53814d6dcc00 | 53caceaa94fc3637a73179d7e7fb9e6f1afaeca6 | refs/heads/master | 2021-01-10T20:54:40.483471 | 2015-01-31T17:52:36 | 2015-01-31T17:52:36 | 30,115,433 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,161 | java | package AllocatorMetamodel.diagram.edit.policies;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.diagram.ui.commands.DeferredLayoutCommand;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.SetViewMutabilityCommand;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CanonicalEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
/**
* @generated
*/
public class SoftwareSoftwareCompartmentCanonicalEditPolicy extends
CanonicalEditPolicy {
/**
* @generated
*/
protected void refreshOnActivate() {
// Need to activate editpart children before invoking the canonical refresh for EditParts to add event listeners
List<?> c = getHost().getChildren();
for (int i = 0; i < c.size(); i++) {
((EditPart) c.get(i)).activate();
}
super.refreshOnActivate();
}
/**
* @generated
*/
protected EStructuralFeature getFeatureToSynchronize() {
return AllocatorMetamodel.AllocatorMetamodelPackage.eINSTANCE
.getSoftware_SWNodes();
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
protected List getSemanticChildrenList() {
View viewObject = (View) getHost().getModel();
LinkedList<EObject> result = new LinkedList<EObject>();
List<AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor> childDescriptors = AllocatorMetamodel.diagram.part.Allocator_metamodelDiagramUpdater
.getSoftwareSoftwareCompartment_7001SemanticChildren(viewObject);
for (AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor d : childDescriptors) {
result.add(d.getModelElement());
}
return result;
}
/**
* @generated
*/
protected boolean isOrphaned(Collection<EObject> semanticChildren,
final View view) {
return isMyDiagramElement(view)
&& !semanticChildren.contains(view.getElement());
}
/**
* @generated
*/
private boolean isMyDiagramElement(View view) {
return AllocatorMetamodel.diagram.edit.parts.SWNodeEditPart.VISUAL_ID == AllocatorMetamodel.diagram.part.Allocator_metamodelVisualIDRegistry
.getVisualID(view);
}
/**
* @generated
*/
protected void refreshSemantic() {
if (resolveSemanticElement() == null) {
return;
}
LinkedList<IAdaptable> createdViews = new LinkedList<IAdaptable>();
List<AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor> childDescriptors = AllocatorMetamodel.diagram.part.Allocator_metamodelDiagramUpdater
.getSoftwareSoftwareCompartment_7001SemanticChildren((View) getHost()
.getModel());
LinkedList<View> orphaned = new LinkedList<View>();
// we care to check only views we recognize as ours
LinkedList<View> knownViewChildren = new LinkedList<View>();
for (View v : getViewChildren()) {
if (isMyDiagramElement(v)) {
knownViewChildren.add(v);
}
}
// alternative to #cleanCanonicalSemanticChildren(getViewChildren(), semanticChildren)
//
// iteration happens over list of desired semantic elements, trying to find best matching View, while original CEP
// iterates views, potentially losing view (size/bounds) information - i.e. if there are few views to reference same EObject, only last one
// to answer isOrphaned == true will be used for the domain element representation, see #cleanCanonicalSemanticChildren()
for (Iterator<AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor> descriptorsIterator = childDescriptors
.iterator(); descriptorsIterator.hasNext();) {
AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor next = descriptorsIterator
.next();
String hint = AllocatorMetamodel.diagram.part.Allocator_metamodelVisualIDRegistry
.getType(next.getVisualID());
LinkedList<View> perfectMatch = new LinkedList<View>(); // both semanticElement and hint match that of NodeDescriptor
for (View childView : getViewChildren()) {
EObject semanticElement = childView.getElement();
if (next.getModelElement().equals(semanticElement)) {
if (hint.equals(childView.getType())) {
perfectMatch.add(childView);
// actually, can stop iteration over view children here, but
// may want to use not the first view but last one as a 'real' match (the way original CEP does
// with its trick with viewToSemanticMap inside #cleanCanonicalSemanticChildren
}
}
}
if (perfectMatch.size() > 0) {
descriptorsIterator.remove(); // precise match found no need to create anything for the NodeDescriptor
// use only one view (first or last?), keep rest as orphaned for further consideration
knownViewChildren.remove(perfectMatch.getFirst());
}
}
// those left in knownViewChildren are subject to removal - they are our diagram elements we didn't find match to,
// or those we have potential matches to, and thus need to be recreated, preserving size/location information.
orphaned.addAll(knownViewChildren);
//
ArrayList<CreateViewRequest.ViewDescriptor> viewDescriptors = new ArrayList<CreateViewRequest.ViewDescriptor>(
childDescriptors.size());
for (AllocatorMetamodel.diagram.part.Allocator_metamodelNodeDescriptor next : childDescriptors) {
String hint = AllocatorMetamodel.diagram.part.Allocator_metamodelVisualIDRegistry
.getType(next.getVisualID());
IAdaptable elementAdapter = new CanonicalElementAdapter(
next.getModelElement(), hint);
CreateViewRequest.ViewDescriptor descriptor = new CreateViewRequest.ViewDescriptor(
elementAdapter, Node.class, hint, ViewUtil.APPEND, false,
host().getDiagramPreferencesHint());
viewDescriptors.add(descriptor);
}
boolean changed = deleteViews(orphaned.iterator());
//
CreateViewRequest request = getCreateViewRequest(viewDescriptors);
Command cmd = getCreateViewCommand(request);
if (cmd != null && cmd.canExecute()) {
SetViewMutabilityCommand.makeMutable(
new EObjectAdapter(host().getNotationView())).execute();
executeCommand(cmd);
@SuppressWarnings("unchecked")
List<IAdaptable> nl = (List<IAdaptable>) request.getNewObject();
createdViews.addAll(nl);
}
if (changed || createdViews.size() > 0) {
postProcessRefreshSemantic(createdViews);
}
if (createdViews.size() > 1) {
// perform a layout of the container
DeferredLayoutCommand layoutCmd = new DeferredLayoutCommand(host()
.getEditingDomain(), createdViews, host());
executeCommand(new ICommandProxy(layoutCmd));
}
makeViewsImmutable(createdViews);
}
}
| [
"[email protected]"
] | |
ed9033737132db6d63030a2fa5d0a05cfb91abbf | fc160694094b89ab09e5c9a0f03db80437eabc93 | /java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/CompleteTrialRequestOrBuilder.java | aeb5f2f62f91efcc941bd4e4a1327c5f56d1bb9d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | googleapis/google-cloud-java | 4f4d97a145e0310db142ecbc3340ce3a2a444e5e | 6e23c3a406e19af410a1a1dd0d0487329875040e | refs/heads/main | 2023-09-04T09:09:02.481897 | 2023-08-31T20:45:11 | 2023-08-31T20:45:11 | 26,181,278 | 1,122 | 685 | Apache-2.0 | 2023-09-13T21:21:23 | 2014-11-04T17:57:16 | Java | UTF-8 | Java | false | false | 4,218 | java | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/vizier_service.proto
package com.google.cloud.aiplatform.v1;
public interface CompleteTrialRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.aiplatform.v1.CompleteTrialRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The Trial's name.
* Format:
* `projects/{project}/locations/{location}/studies/{study}/trials/{trial}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Required. The Trial's name.
* Format:
* `projects/{project}/locations/{location}/studies/{study}/trials/{trial}`
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the finalMeasurement field is set.
*/
boolean hasFinalMeasurement();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The finalMeasurement.
*/
com.google.cloud.aiplatform.v1.Measurement getFinalMeasurement();
/**
*
*
* <pre>
* Optional. If provided, it will be used as the completed Trial's
* final_measurement; Otherwise, the service will auto-select a
* previously reported measurement as the final-measurement
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1.Measurement final_measurement = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
com.google.cloud.aiplatform.v1.MeasurementOrBuilder getFinalMeasurementOrBuilder();
/**
*
*
* <pre>
* Optional. True if the Trial cannot be run with the given Parameter, and
* final_measurement will be ignored.
* </pre>
*
* <code>bool trial_infeasible = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The trialInfeasible.
*/
boolean getTrialInfeasible();
/**
*
*
* <pre>
* Optional. A human readable reason why the trial was infeasible. This should
* only be provided if `trial_infeasible` is true.
* </pre>
*
* <code>string infeasible_reason = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The infeasibleReason.
*/
java.lang.String getInfeasibleReason();
/**
*
*
* <pre>
* Optional. A human readable reason why the trial was infeasible. This should
* only be provided if `trial_infeasible` is true.
* </pre>
*
* <code>string infeasible_reason = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for infeasibleReason.
*/
com.google.protobuf.ByteString getInfeasibleReasonBytes();
}
| [
"[email protected]"
] | |
52987c7659565bbc414b69f10e997774f16241a5 | 6fc800f970b9ad25fa0c767a0117009688e28c8a | /app/src/main/java/com/lwf/retrofitdemo/thread/MyTask.java | 995aca33e9f02377ec766536e6d786d8854456f7 | [] | no_license | LiWenFei/retrofitdemo | e2c77a6de9936e7026a3b2611ed74f2d9df28aec | 0ac41b13332149a80e7f774b8fbffb3c67bf7197 | refs/heads/master | 2020-07-01T03:43:14.339098 | 2016-11-18T06:52:36 | 2016-11-18T06:52:36 | 74,099,906 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,807 | java | package com.lwf.retrofitdemo.thread;
import android.support.annotation.NonNull;
import java.util.concurrent.Executor;
/**
* 异步任务类
*/
public abstract class MyTask implements Runnable {
private static final MoreExecutor MORE_EXECUTOR = new MoreExecutor();
private static final int CORE_POOL_SIZE = 5;
/**
* 异步任务类
*/
public MyTask() {
}
/**
* 外部接口,处理请求
*
* @param run Runnable
* @param isLTimeOper 是否是耗时操作.
*/
public static void runInBackground(Runnable run, boolean isLTimeOper) {
if (isLTimeOper) {
MORE_EXECUTOR.execute(run);
} else {
AsyncTaskAssistant.executeOnThreadPool(run);
}
}
/**
* 并发执行多任务。
*/
private static class MoreExecutor implements Executor {
public int runCount = 0;
/**
* @param add 同步执行,维护runCount字段
*/
private synchronized void editRuncount(boolean add) {
if (add) {
runCount++;
} else {
runCount--;
}
}
/**
* 占用线程池CORE_POOL_SIZE-1个,如果满了立即创建thread执行;
*/
public synchronized void execute(@NonNull final Runnable r) {
if (runCount >= (CORE_POOL_SIZE - 1)) {
new Thread(r).start();
} else {
editRuncount(true);
executeTask(r);
editRuncount(false);
}
}
/**
* @param runtask Runnable
*/
protected synchronized void executeTask(Runnable runtask) {
AsyncTaskAssistant.executeOnThreadPool(runtask);
}
}
}
| [
"[email protected]"
] | |
c7976d094a217a05a7408f70acee41f8f3a23a1e | 1b72958ab7d8749594fd0dca20e3d9e793151b4e | /application-ocps/contentBridge-core/src/main/java/com/ctb/contentBridge/core/publish/tools/ImageValidation.java | 6a2e527973982514cbf5289536ffedf823507ceb | [] | no_license | sumit-sardar/GitMigrationRepo01 | d0a89e33d3c7d873fac2dd66a7a5e59fd2b1bc3a | a474889914ea0e9805547ac7f4659c49e1a6b712 | refs/heads/master | 2021-01-17T00:45:16.256869 | 2016-05-12T18:37:01 | 2016-05-12T18:37:01 | 61,346,131 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,807 | java | package com.ctb.contentBridge.core.publish.tools;
import java.util.*;
import org.jdom.*;
import org.xml.sax.*;
import com.ctb.contentBridge.core.exception.BusinessException;
import com.ctb.contentBridge.core.publish.iknowxml.R2XmlTools;
import com.ctb.contentBridge.core.publish.sax.replacement.AbsolutePathOperation;
/**
* Created by IntelliJ IDEA.
* User: mwshort
* Date: Aug 8, 2003
* Time: 11:36:22 AM
* To change this template use Options | File Templates.
*/
public class ImageValidation {
AbsolutePathOperation imagesHolder;
public ImageValidation(Element element) {
try {
AbsolutePathOperation absolutePathOperation = new AbsolutePathOperation();
this.imagesHolder = absolutePathOperation;
// R2XmlTools.replaceAttributes(element,"//BMPPrint/@FileName",absolutePathOperation);
R2XmlTools.replaceAttributes(element, "//EPSPrint/@FileName",
absolutePathOperation);
R2XmlTools.replaceAttributes(element, "//Flash/@FileName",
absolutePathOperation);
} catch (JDOMException e) {
throw new BusinessException("Could not read JDOM document: "
+ e.getMessage());
} catch (SAXException e) {
throw new BusinessException("Could not read inputsource: "
+ e.getMessage());
}
}
public Set getArtFileNames() {
return imagesHolder.getFilenames();
}
public boolean validateArt() {
return imagesHolder.allFilesExist();
}
public Set getInvalidArtFileNames() {
return imagesHolder.invalidFiles();
}
public String toString() {
return imagesHolder.toString();
}
}
| [
""
] | |
06a88e841d7825843c366c510dbaca1fab955062 | 6a520aab0e037b4d8e104b9df48982d661d9c471 | /pet-clinic-data/src/test/java/guru/springframework/dependencyInversionPrinciple/ElectricPowerSwitchTest.java | 4bb028bb87be62c87ece40c3a937c5c34976106f | [] | no_license | ashutoshcp/spring5webapp | 1ee8018810fac152598fd119deeb8c772d102e74 | fff2e84e161babe085a4b3c7de95cb99df05b8b0 | refs/heads/master | 2022-06-23T12:44:48.364371 | 2022-06-16T04:10:39 | 2022-06-16T04:10:39 | 187,286,073 | 0 | 0 | null | 2019-05-17T21:55:48 | 2019-05-17T21:55:48 | null | UTF-8 | Java | false | false | 537 | java | package guru.springframework.dependencyInversionPrinciple;
import org.junit.Test;
public class ElectricPowerSwitchTest {
@Test
public void testPress() {
SwitchAble switchAbleBulb = new LightBulb();
Switch bulbPowerSwitch = new ElectricPowerSwitch(switchAbleBulb);
for (int i = 0; i < 2; i++) {
bulbPowerSwitch.press();
}
SwitchAble switchAbleFan = new Fan();
Switch fanPowerSwitch = new ElectricPowerSwitch(switchAbleFan);
for (int i = 0; i < 3; i++) {
fanPowerSwitch.press();
}
}
}
| [
"[email protected]"
] | |
213805aea0e7344be13cd3fd2d495728c818a810 | 62b6160a0941c7175d970e1e478eb5be6716f1bb | /miao/src/main/java/com/lqh/miao/net/api/GroupAPI.java | 1719771a58a4e24d7139138838104b2eeeac4854 | [] | no_license | linqiaqia0622/Miaobo | 734e2ffdca3c02fb6fe87dc387a51cb1ce04d051 | 1350223422a56d514209e88bfc140bfb66430793 | refs/heads/master | 2020-07-05T17:03:49.195829 | 2016-08-20T09:21:16 | 2016-08-20T09:21:16 | 66,076,539 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,124 | java | /*
* Copyright (C) 2010-2013 The SINA WEIBO Open Source 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 com.lqh.miao.net.api;
import android.content.Context;
import android.text.TextUtils;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.sina.weibo.sdk.openapi.AbsOpenAPI;
/**
* 此类封装了分组的接口。
* 详情见<a href="http://t.cn/8F3geol">评论接口</a>
*
* @author SINA
* @date 2014-03-03
*/
public class GroupAPI extends AbsOpenAPI {
/**
* 过滤类型ID,0:全部、1:原创、2:图片、3:视频、4:音乐
*/
public static final int FEATURE_ALL = 0;
public static final int FEATURE_ORIGINAL = 1;
public static final int FEATURE_PICTURE = 2;
public static final int FEATURE_VIDEO = 3;
public static final int FEATURE_MUSICE = 4;
public GroupAPI(Context context, String appKey, Oauth2AccessToken accessToken) {
super(context, appKey, accessToken);
}
private static final String SERVER_URL_PRIX = API_SERVER + "/friendships/groups";
/**
* 获取当前登陆用户好友分组列表。
*
* @param listener 异步请求回调接口
*/
public void groups(RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
requestAsync(SERVER_URL_PRIX + ".json", params, HTTPMETHOD_GET, listener);
}
/**
* 获取当前登录用户某一好友分组的微博列表。
*
* @param list_id 需要查询的好友分组ID,建议使用返回值里的idstr,当查询的为私有分组时,则当前登录用户必须为其所有者
* @param since_id 若指定此参数,则返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0
* @param max_id 若指定此参数,则返回ID小于或等于max_id的微博,默认为0
* @param count 单页返回的记录条数,默认为50
* @param page 返回结果的页码,默认为1
* @param base_app 是否只获取当前应用的数据。false为否(所有数据),true为是(仅当前应用),默认为false
* @param featureType 过滤类型ID,0:全部,1:原创, 2:图片,3:视频,4:音乐
* {@link #FEATURE_ALL}
* {@link #FEATURE_ORIGINAL}
* {@link #FEATURE_PICTURE}
* {@link #FEATURE_VIDEO}
* {@link #FEATURE_MUSICE}
* @param listener 异步请求回调接口
*/
public void timeline(long list_id, long since_id, long max_id, int count, int page, boolean base_app,
int featureType, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
params.put("since_id", since_id);
params.put("max_id", max_id);
params.put("count", count);
params.put("page", page);
params.put("base_app", base_app ? 1 : 0);
params.put("feature", featureType);
requestAsync(SERVER_URL_PRIX + "/timeline.json", params, HTTPMETHOD_GET, listener);
}
// TODO 获取当前登陆用户某一好友分组的微博ID列表
public void timelineIds() {
}
/**
* 获取某一好友分组下的成员列表。
*
* @param list_id 获取某一好友分组下的成员列表
* @param count 单页返回的记录条数,默认为50,最大不超过200
* @param cursor 分页返回结果的游标,下一页用返回值里的next_cursor,上一页用previous_cursor,默认为0
* @param listener 异步请求回调接口
*/
public void members(long list_id, int count, int cursor, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
params.put("count", count);
params.put("cursor", cursor);
requestAsync(SERVER_URL_PRIX + "/members.json", params, HTTPMETHOD_GET, listener);
}
// TODO 获取某一好友分组下的成员列表的ID
public void membersIds() {
}
// TODO 批量取好友分组成员的分组说明
public void memberDescriptionPatch() {
}
/**
* 判断某个用户是否是当前登录用户指定好友分组内的成员。
*
* @param uid 需要判断的用户的UID
* @param list_id 指定的当前用户的好友分组ID,建议使用返回值里的idstr
* @param listener 异步请求回调接口
*/
public void isMember(long uid, long list_id, RequestListener listener) {
WeiboParameters params = buildeMembersParams(list_id, uid);
requestAsync(SERVER_URL_PRIX + "/is_member.json", params, HTTPMETHOD_GET, listener);
}
// TODO 批量获取某些用户在指定用户的好友分组中的收录信息
public void listed() {
}
;
/**
* 获取当前登陆用户某个分组的详细信息。
*
* @param list_id 需要查询的好友分组ID,建议使用返回值里的idstr
* @param listener 异步请求回调接口
*/
public void showGroup(long list_id, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
requestAsync(SERVER_URL_PRIX + "/show.json", params, HTTPMETHOD_GET, listener);
}
/**
* 批量获取好友分组的详细信息。
*
* @param list_ids 需要查询的好友分组ID,建议使用返回值里的idstr,多个之间用逗号分隔,每次不超过20个
* @param uids 参数list_ids所指的好友分组的所有者UID,多个之间用逗号分隔,每次不超过20个,需与list_ids一一对应
* @param listener 异步请求回调接口
*/
public void showGroupBatch(String list_ids, long uids, RequestListener listener) {
WeiboParameters params = buildeMembersParams(Long.valueOf(list_ids), uids);
requestAsync(SERVER_URL_PRIX + "/show_batch.json", params, HTTPMETHOD_GET, listener);
}
/**
* 创建好友分组。
*
* @param name 要创建的好友分组的名称,不超过10个汉字,20个半角字符
* @param description 要创建的好友分组的描述,不超过70个汉字,140个半角字符
* @param tags 要创建的好友分组的标签,多个之间用逗号分隔,最多不超过10个,每个不超过7个汉字,14个半角字符
* @param listener 异步请求回调接口
*/
public void create(String name, String description, String tags, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("name", name);
if (TextUtils.isEmpty(description) == false) {
params.put("description", description);
}
if (TextUtils.isEmpty(tags) == false) {
params.put("tags", tags);
}
requestAsync(SERVER_URL_PRIX + "/create.json", params, HTTPMETHOD_POST, listener);
}
/**
* 更新好友分组。
*
* @param list_id 需要更新的好友分组ID,建议使用返回值里的idstr,只能更新当前登录用户自己创建的分组
* @param name 要创建的好友分组的名称,不超过10个汉字,20个半角字符
* @param description 要创建的好友分组的描述,不超过70个汉字,140个半角字符
* @param tags 要创建的好友分组的标签,多个之间用逗号分隔,最多不超过10个,每个不超过7个汉字,14个半角字符
* @param listener 异步请求回调接口
*/
public void update(long list_id, String name, String description, String tags, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
if (TextUtils.isEmpty(name) == false) {
params.put("name", name);
}
if (TextUtils.isEmpty(description) == false) {
params.put("description", description);
}
if (TextUtils.isEmpty(tags) == false) {
params.put("tags", tags);
}
requestAsync(SERVER_URL_PRIX + "/update.json", params, HTTPMETHOD_POST, listener);
}
/**
* 删除好友分组。
*
* @param list_id 要删除的好友分组ID,建议使用返回值里的idstr
* @param listener 异步请求回调接口
*/
public void deleteGroup(long list_id, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
requestAsync(SERVER_URL_PRIX + "/destroy.json", params, HTTPMETHOD_POST, listener);
}
/**
* 添加关注用户到好友分组。
*
* @param list_id 好友分组ID,建议使用返回值里的idstr
* @param uid 好友分组ID,建议使用返回值里的idstr
* @param listener 异步请求回调接口
*/
public void addMember(long list_id, long uid, RequestListener listener) {
WeiboParameters params = buildeMembersParams(list_id, uid);
requestAsync(SERVER_URL_PRIX + "/members/add.json", params, HTTPMETHOD_POST, listener);
}
/**
* 批量添加用户到好友分组。
*
* @param list_id 好友分组ID,建议使用返回值里的idstr
* @param uids 需要添加的用户的UID,多个之间用逗号分隔,最多不超过30个
* @param group_descriptions 添加成员的分组说明,每个说明最多8个汉字,16个半角字符,多个需先URLencode,然后再用半角逗号分隔,最多不超过30个,且需与uids参数一一对应
* @param listener 异步请求回调接口
*/
public void addMemberBatch(long list_id, String uids, String group_descriptions, RequestListener listener) {
WeiboParameters params = buildeMembersParams(list_id, Long.valueOf(uids));
params.put("group_descriptions", group_descriptions);
requestAsync(SERVER_URL_PRIX + "/members/add_batch.json", params, HTTPMETHOD_POST, listener);
}
/**
* 更新好友分组中成员的分组说明。
*
* @param list_id 好友分组ID,建议使用返回值里的idstr
* @param uid 需要更新分组成员说明的用户的UID
* @param group_description 需要更新的分组成员说明,每个说明最多8个汉字,16个半角字符,需要URLencode
* @param listener 异步请求回调接口
*/
public void updateMembers(long list_id, long uid, String group_description, RequestListener listener) {
WeiboParameters params = buildeMembersParams(list_id, uid);
if (TextUtils.isDigitsOnly(group_description) == false) {
params.put("group_description", group_description);
}
requestAsync(SERVER_URL_PRIX + "/members/update.json", params, HTTPMETHOD_POST, listener);
}
/**
* 删除好友分组内的关注用户。
*
* @param list_id 好友分组ID,建议使用返回值里的idstr
* @param uid 需要删除的用户的UID
* @param listener 异步请求回调接口
*/
public void deleteMembers(long list_id, long uid, RequestListener listener) {
WeiboParameters params = buildeMembersParams(list_id, uid);
requestAsync(SERVER_URL_PRIX + "/members/destroy.json", params, HTTPMETHOD_POST, listener);
}
/**
* 调整当前登录用户的好友分组顺序。
*
* @param list_ids 调整好顺序后的分组ID列表,以逗号分隔,例:57,38,表示57排第一、38排第二,以此类推
* @param count 好友分组数量,必须与用户所有的分组数一致、与分组ID的list_id个数一致
* @param listener 异步请求回调接口
*/
public void order(String list_ids, int count, RequestListener listener) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_ids);
params.put("count", count);
requestAsync(SERVER_URL_PRIX + "/order.json", params, HTTPMETHOD_POST, listener);
}
private WeiboParameters buildeMembersParams(long list_id, long uid) {
WeiboParameters params = new WeiboParameters(mAppKey);
params.put("list_id", list_id);
params.put("uid", uid);
return params;
}
}
| [
"[email protected]"
] | |
fa770586d6bf3432cafabf0edfbda334619a48dd | 70aa8a1a5fc9ecc683b8526fedfcf20fcc2d77a5 | /src/main/java/pl/edu/agh/cs/kraksimcitydesigner/parser/ParsingException.java | 3749c41aab9797fb402172a355d972050cc2e70a | [] | no_license | Pysiokot/kraksim | cd837453b80bf1625da331e60385a6e3a7f1bcf3 | 398082b6ab6d43114bd331e73a6f0925c45202ea | refs/heads/master | 2022-12-20T04:21:19.862986 | 2020-09-29T16:32:30 | 2020-09-29T16:32:30 | 237,761,884 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 722 | java | package pl.edu.agh.cs.kraksimcitydesigner.parser;
// TODO: Auto-generated Javadoc
public class ParsingException extends Exception
{
private static final long serialVersionUID = 5515541347396062670L;
/**
* Instantiates a new parsing exception.
*/
public ParsingException() {
super();
}
/**
* Instantiates a new parsing exception.
*
* @param message the message
* @param cause the cause
*/
public ParsingException(String message, Throwable cause) {
super( message, cause );
}
/**
* Instantiates a new parsing exception.
*
* @param message the message
*/
public ParsingException(String message) {
super( message );
}
}
| [
"[email protected]"
] | |
46b84b9e994fb9ce41f4d47d29e68a0354afdba0 | e63363389e72c0822a171e450a41c094c0c1a49c | /Mate20_9_0_0/src/main/java/com/android/server/rms/iaware/appmng/AppStartPolicyCfg.java | 478e4a1af91d61e3804fdf121aa9b9357c573123 | [] | no_license | solartcc/HwFrameWorkSource | fc23ca63bcf17865e99b607cc85d89e16ec1b177 | 5b92ed0f1ccb4bafc0fdb08b6fc4d98447b754ad | refs/heads/master | 2022-12-04T21:14:37.581438 | 2020-08-25T04:30:43 | 2020-08-25T04:30:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,966 | java | package com.android.server.rms.iaware.appmng;
public final class AppStartPolicyCfg {
public static final int APPSTART_DEFAULT = -1;
public enum AppStartAppOversea {
CHINA(0),
OVERSEA(1),
UNKNONW(2);
int mPriority;
private AppStartAppOversea(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartAppSrcRange {
PRERECG(0),
NONPRERECG(1);
int mPriority;
private AppStartAppSrcRange(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartCallerAction {
PUSHSDK(0),
BTMEDIABROWSER(1),
NOTIFYLISTENER(2);
int mPriority;
private AppStartCallerAction(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartCallerStatus {
BACKGROUND(0),
FOREGROUND(1);
int mPriority;
private AppStartCallerStatus(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartOversea {
CHINA(0),
OVERSEA(1);
int mPriority;
private AppStartOversea(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartScreenStatus {
SCREENOFF(0),
SCREENON(1);
int mPriority;
private AppStartScreenStatus(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartTargetStat {
ALIVE(0),
WIDGET(1),
MUSIC(2),
RECORD(3),
GUIDE(4),
UPDOWNLOAD(5),
HEALTH(6),
FGACTIVITY(7),
WALLPAPER(8),
INPUTMETHOD(9),
WIDGETUPDATE(10);
int mPriority;
private AppStartTargetStat(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
public enum AppStartTargetType {
IM(0),
BLIND(1),
TTS(2),
CLOCK(3),
PAY(4),
SHARE(5),
BUSINESS(6),
EMAIL(7),
RCV_MONEY(8),
HABIT_IM(9);
int mPriority;
private AppStartTargetType(int priority) {
this.mPriority = priority;
}
public int getPriority() {
return this.mPriority;
}
}
private AppStartPolicyCfg() {
}
}
| [
"[email protected]"
] | |
cd39b9eb9208967cf3a8526785d8056be4b62a00 | 4c08b25f6b0260c16d2a06b0fc33fe5c2aa28cc6 | /src/main/java/com/spatil/common/model/Error.java | c33e86d4693bfa06d5fb6c89d3547426d94076f4 | [] | no_license | imsantosh6369/gameservice | 41a410353af344e0f01b4289f4bdbc5d3b64d80f | 12c7254b09a768395317597663d49bb789f8f409 | refs/heads/master | 2020-03-08T04:38:57.860699 | 2018-04-08T18:11:31 | 2018-04-08T18:11:31 | 127,928,101 | 0 | 0 | null | 2018-04-08T18:11:32 | 2018-04-03T15:19:22 | Java | UTF-8 | Java | false | false | 524 | java | package com.spatil.common.model;
public class Error {
public Error(String message,int errorCode) {
this.setMessage(message);
this.setErrorCode(errorCode);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
String message;
int errorCode;
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
| [
"[email protected]"
] | |
c2ef64000efb02c2454737d1e45b2bf3cb55782b | 5abfd4c4a469c133b66d03ea392122ac5a8bc1a2 | /src/main/java/com/pronix/sbc/service/impl/PuestoDeTrabajoServiceImpl.java | 972ec35060735f8bf7ae2f3712edf80a96cb0199 | [] | no_license | Garritosk8CR/sbc_server_client | 56ddabde9f5b1e4831b372f207a44a3e8cfa3e22 | 5d810ac15b0a4e09bf9bc7227e18362ceff80aee | refs/heads/master | 2022-03-23T01:33:31.003169 | 2019-12-15T21:06:33 | 2019-12-15T21:06:33 | 227,466,041 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,429 | java | package com.pronix.sbc.service.impl;
import com.pronix.sbc.service.PuestoDeTrabajoService;
import com.pronix.sbc.domain.PuestoDeTrabajo;
import com.pronix.sbc.repository.PuestoDeTrabajoRepository;
import com.pronix.sbc.service.dto.PuestoDeTrabajoDTO;
import com.pronix.sbc.service.mapper.PuestoDeTrabajoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Service Implementation for managing {@link PuestoDeTrabajo}.
*/
@Service
@Transactional
public class PuestoDeTrabajoServiceImpl implements PuestoDeTrabajoService {
private final Logger log = LoggerFactory.getLogger(PuestoDeTrabajoServiceImpl.class);
private final PuestoDeTrabajoRepository puestoDeTrabajoRepository;
private final PuestoDeTrabajoMapper puestoDeTrabajoMapper;
public PuestoDeTrabajoServiceImpl(PuestoDeTrabajoRepository puestoDeTrabajoRepository, PuestoDeTrabajoMapper puestoDeTrabajoMapper) {
this.puestoDeTrabajoRepository = puestoDeTrabajoRepository;
this.puestoDeTrabajoMapper = puestoDeTrabajoMapper;
}
/**
* Save a puestoDeTrabajo.
*
* @param puestoDeTrabajoDTO the entity to save.
* @return the persisted entity.
*/
@Override
public PuestoDeTrabajoDTO save(PuestoDeTrabajoDTO puestoDeTrabajoDTO) {
log.debug("Request to save PuestoDeTrabajo : {}", puestoDeTrabajoDTO);
PuestoDeTrabajo puestoDeTrabajo = puestoDeTrabajoMapper.toEntity(puestoDeTrabajoDTO);
puestoDeTrabajo = puestoDeTrabajoRepository.save(puestoDeTrabajo);
return puestoDeTrabajoMapper.toDto(puestoDeTrabajo);
}
/**
* Get all the puestoDeTrabajos.
*
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public List<PuestoDeTrabajoDTO> findAll() {
log.debug("Request to get all PuestoDeTrabajos");
return puestoDeTrabajoRepository.findAllWithEagerRelationships().stream()
.map(puestoDeTrabajoMapper::toDto)
.collect(Collectors.toCollection(LinkedList::new));
}
/**
* Get all the puestoDeTrabajos with eager load of many-to-many relationships.
*
* @return the list of entities.
*/
public Page<PuestoDeTrabajoDTO> findAllWithEagerRelationships(Pageable pageable) {
return puestoDeTrabajoRepository.findAllWithEagerRelationships(pageable).map(puestoDeTrabajoMapper::toDto);
}
/**
* Get one puestoDeTrabajo by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<PuestoDeTrabajoDTO> findOne(Long id) {
log.debug("Request to get PuestoDeTrabajo : {}", id);
return puestoDeTrabajoRepository.findOneWithEagerRelationships(id)
.map(puestoDeTrabajoMapper::toDto);
}
/**
* Delete the puestoDeTrabajo by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete PuestoDeTrabajo : {}", id);
puestoDeTrabajoRepository.deleteById(id);
}
}
| [
"[email protected]"
] | |
dde8b4e8d4033314f31024936bd0bc0724012544 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_a65603b657fa86387c6d36d143edb67b4e98f80b/ParameterisationSection/28_a65603b657fa86387c6d36d143edb67b4e98f80b_ParameterisationSection_t.java | b483e82a5c00db961785af7c3651205ab392e585 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 9,943 | java | /*
* Created on 17.may.2006
*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*
*/
package org.cubictest.ui.sections;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.apache.commons.lang.ObjectUtils;
import org.cubictest.model.Test;
import org.cubictest.model.parameterization.ParameterList;
import org.cubictest.persistence.ParameterPersistance;
import org.cubictest.ui.gef.command.ChangeParameterListCommand;
import org.cubictest.ui.gef.command.ChangeParameterListIndexCommand;
import org.cubictest.ui.gef.controller.TestEditPart;
import org.cubictest.ui.gef.editors.GraphicalTestEditor;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Path;
import org.eclipse.gef.commands.Command;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceComparator;
import org.eclipse.ui.views.navigator.ResourcePatternFilter;
import org.eclipse.ui.views.properties.tabbed.AbstractPropertySection;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
public class ParameterisationSection extends AbstractPropertySection implements PropertyChangeListener {
private Test test;
private Label fileLabel;
private Text fileName;
private Button chooseFileButton;
private Label paramIndexLabel;
private Spinner paramIndexSpinner;
private Button refreshParamButton;
private Button createParamsFileButton;
ResourcePatternFilter filter = new ResourcePatternFilter(){
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof IFolder)
return true;
if (element instanceof IProject)
return true;
return !super.select(viewer, parentElement, element);
}
};
SelectionListener selectionListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ElementTreeSelectionDialog dialog =
new ElementTreeSelectionDialog(new Shell(),
new WorkbenchLabelProvider(), new WorkbenchContentProvider());
dialog.setTitle("Select a Parameterisation file");
filter.setPatterns(new String[]{"*.params"});
dialog.addFilter(filter);
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
if(test.getParamList() != null){
dialog.setInitialSelection(test.getParamList().getFileName());
}
if (dialog.open() == Window.OK) {
IResource element = (IResource) dialog.getFirstResult();
if (element == null)
return;
String oldName = fileName.getText();
fileName.setText(element.getFullPath().toString());
if(!oldName.equals(fileName.getText()))
filePathChanged();
}
}
};
class FileNameListener implements ModifyListener{
public void modifyText(ModifyEvent e) {
String text = fileName.getText();
ParameterList list = test.getParamList();
if((list == null && !"".equals(text)) ||
(list != null && !list.getFileName().equals(text)))
filePathChanged();
}
}
@Override
public void createControls(Composite parent,
TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent, aTabbedPropertySheetPage);
//parent.setLayout( new GridLayout());
Composite composite = getWidgetFactory()
.createFlatFormComposite(parent);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.makeColumnsEqualWidth = false;
fileLabel = getWidgetFactory().createLabel(composite, "Choose parameter file:");
GridData data = new GridData();
data.widthHint = STANDARD_LABEL_WIDTH + 50;
fileLabel.setLayoutData(data);
data = new GridData();
//data.horizontalSpan = 2;
data.widthHint = 300;
fileName = getWidgetFactory().createText(composite, "");
fileName.setLayoutData(data);
FileNameListener fileNameListener = new FileNameListener();
fileName.addModifyListener(fileNameListener);
data = new GridData();
data.widthHint = 150;
chooseFileButton = new Button(composite, SWT.NONE);
chooseFileButton.setText("Browse...");
chooseFileButton.addSelectionListener(selectionListener);
chooseFileButton.setLayoutData(data);
createParamsFileButton = getWidgetFactory().createButton(composite, "Create parameter file", SWT.PUSH);
createParamsFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("WOO");
}
});
createParamsFileButton.setLayoutData(data);
paramIndexLabel = getWidgetFactory().createLabel(composite, "Parameter index:");
paramIndexSpinner = new Spinner(composite, SWT.BORDER);
paramIndexSpinner.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
ChangeParameterListIndexCommand command = new ChangeParameterListIndexCommand();
command.setParameterList(test.getParamList());
command.setNewIndex(paramIndexSpinner.getSelection());
command.setTest(test);
executeCommand(command);
}
});
refreshParamButton = getWidgetFactory().createButton(composite, "Refresh parameters", SWT.PUSH);
refreshParamButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
filePathChanged();
}
});
refreshParamButton.setLayoutData(data);
composite.setLayout(gridLayout);
}
private void updateIndexSpinner() {
if(test != null && null != test.getParamList()){
ParameterList list = test.getParamList();
int length = list.inputParameterSize();
paramIndexSpinner.setValues(list.getParameterIndex(), 0,
(length <= 0) ? 0 : length-1,0, 1, 5);
}
}
@Override
public void setInput(IWorkbenchPart part, ISelection selection) {
super.setInput(part, selection);
if(test != null){
test.removePropertyChangeListener(this);
if(test.getParamList() != null)
test.getParamList().removePropertyChangeListener(this);
}
Assert.isTrue(selection instanceof IStructuredSelection);
Object input = ((IStructuredSelection) selection).getFirstElement();
Assert.isTrue(input instanceof TestEditPart);
test = (Test) ((TestEditPart) input).getModel();
test.addPropertyChangeListener(this);
if(test.getParamList() != null)
test.getParamList().addPropertyChangeListener(this);
}
private void filePathChanged() {
String text = fileName.getText();
ParameterList list = null;
try{
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(text));
if(file.exists())
list = ParameterPersistance.loadFromFile(file);
}catch (Exception e) {
// list will be null
}
if(!ObjectUtils.equals(list, test.getParamList())){
ChangeParameterListCommand command = new ChangeParameterListCommand();
command.setTest(test);
command.setNewParamList(list);
command.setOldParamList(test.getParamList());
executeCommand(command);
}
}
private void executeCommand(Command command) {
IWorkbenchPart part = getPart();
if(part instanceof GraphicalTestEditor)
((GraphicalTestEditor)part).getCommandStack().execute(command);
}
@Override
public void refresh() {
super.refresh();
boolean visibile = (test.getParamList() != null);
refreshParamButton.setVisible(visibile);
paramIndexLabel.setVisible(visibile && test.getParamList().inputParameterSize()>1);
paramIndexSpinner.setVisible(visibile && test.getParamList().inputParameterSize()>1);
if(test.getParamList() != null){
fileName.setText(test.getParamList().getFileName());
updateIndexSpinner();
}
}
public void propertyChange(PropertyChangeEvent event) {
if(event.getOldValue() instanceof ParameterList){
((ParameterList)event.getOldValue()).removePropertyChangeListener(this);
}
if(event.getNewValue() instanceof ParameterList){
((ParameterList)event.getNewValue()).removePropertyChangeListener(this);
}
refresh();
}
@Override
public void aboutToBeHidden() {
super.aboutToBeHidden();
test.removePropertyChangeListener(this);
if(test.getParamList() != null)
test.getParamList().removePropertyChangeListener(this);
}
}
| [
"[email protected]"
] | |
321938eaa7c10dc11f8946529f239ba07a8205b9 | 00d2576408bacb56499ce3aa595be3b49f78b7ed | /softgroup/services/messenger/messenger-api/src/main/java/com/softgroup/messenger/api/message/GetMessagesRequestData.java | 01aeaa44500b7f2ecc4a378c43fb5df29ddb3367 | [] | no_license | VasjaVn/cources.server-parallel | 05e1324467ad11535561403bc8272ad3e4580922 | e71b4a8fad3c979f76d9d743c0d3234f832c7029 | refs/heads/master | 2021-01-17T08:25:05.485078 | 2017-05-18T05:28:09 | 2017-05-18T05:28:09 | 83,904,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 231 | java | package com.softgroup.messenger.api.message;
import com.softgroup.common.protocol.RequestData;
public class GetMessagesRequestData implements RequestData {
private static final long serialVersionUID = 8479408464515950926L;
}
| [
"[email protected]"
] | |
ed1ccb8a63585fdd13b0ab0ffa9f41b473815348 | b98c635746a6abbea60e78a18aa63ce8646e4bdd | /batching/src/test/java/de/hub/cs/dbis/aeolus/batching/api/BatchingFieldsGroupingMultipleITCase.java | 0dcb0b2de37cbca06cb96813e9df1d269544e73c | [
"Apache-2.0"
] | permissive | InsightsDev-dev/aeolus | 56e5b8693d85f45434c7b02f4404cded9f6d8a12 | 32f3a34f153a32ca87cdfa3fa063eb6bdb159c10 | refs/heads/master | 2020-12-24T09:07:48.734615 | 2016-07-23T20:55:47 | 2016-07-23T20:55:47 | 69,042,504 | 0 | 0 | null | 2016-09-23T16:33:21 | 2016-09-23T16:33:21 | null | UTF-8 | Java | false | false | 3,787 | java | /*
* #!
* %
* Copyright (C) 2014 - 2016 Humboldt-Universität zu Berlin
* %
* 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 de.hub.cs.dbis.aeolus.batching.api;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;
import de.hub.cs.dbis.aeolus.batching.BatchingOutputFieldsDeclarer;
import de.hub.cs.dbis.aeolus.testUtils.RandomSpout;
/**
* @author Matthias J. Sax
*/
public class BatchingFieldsGroupingMultipleITCase {
private long seed;
private Random r;
@Before
public void prepare() {
this.seed = System.currentTimeMillis();
this.r = new Random(this.seed);
System.out.println("Test seed: " + this.seed);
}
@SuppressWarnings("rawtypes")
@Test(timeout = 30000)
public void testFieldsGroupingMultiple() {
final String topologyName = "testTopology";
final int maxValue = 1000;
final int batchSize = 1 + this.r.nextInt(5);
final int numberOfAttributes = 1 + this.r.nextInt(10);
final int numberOfConsumers = 2 + this.r.nextInt(3);
final Integer spoutDop = new Integer(1);
final Integer[] boltDop = new Integer[numberOfConsumers];
final Fields[] groupingFiels = new Fields[numberOfConsumers];
final String[][] schema = new String[numberOfConsumers][];
for(int i = 0; i < numberOfConsumers; ++i) {
boltDop[i] = new Integer(1 + this.r.nextInt(5));
LinkedList<String> attributes = new LinkedList<String>();
for(int j = 0; j < numberOfAttributes; ++j) {
attributes.add("" + (char)('a' + j));
}
schema[i] = new String[1 + this.r.nextInt(numberOfAttributes)];
for(int j = 0; j < schema[i].length; ++j) {
schema[i][j] = new String(attributes.remove(this.r.nextInt(attributes.size())));
}
groupingFiels[i] = new Fields(schema[i]);
}
LocalCluster cluster = new LocalCluster();
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(VerifyBolt.SPOUT_ID, new RandomSpout(numberOfAttributes, maxValue, new String[] {"stream1"},
this.seed), spoutDop);
builder.setSpout(VerifyBolt.BATCHING_SPOUT_ID, new SpoutOutputBatcher(new RandomSpout(numberOfAttributes,
maxValue, new String[] {"stream2"}, this.seed), batchSize), spoutDop);
for(int i = 0; i < numberOfConsumers; ++i) {
builder
.setBolt("Bolt-" + i, new InputDebatcher(new VerifyBolt(new Fields(schema[i]), groupingFiels[i])),
boltDop[i]).fieldsGrouping(VerifyBolt.SPOUT_ID, "stream1", groupingFiels[i])
.fieldsGrouping(VerifyBolt.BATCHING_SPOUT_ID, "stream2", groupingFiels[i])
.directGrouping(VerifyBolt.BATCHING_SPOUT_ID, BatchingOutputFieldsDeclarer.STREAM_PREFIX + "stream2");
}
cluster.submitTopology(topologyName, new HashMap(), builder.createTopology());
Utils.sleep(10 * 1000);
cluster.killTopology(topologyName);
Utils.sleep(5 * 1000); // give "kill" some time to clean up; otherwise, test might hang and time out
cluster.shutdown();
Assert.assertEquals(new LinkedList<String>(), VerifyBolt.errorMessages);
Assert.assertTrue(VerifyBolt.matchedTuples > 0);
}
}
| [
"[email protected]"
] | |
dc6388d06fabbee08666761e22e79760b310933b | fb241f812f71f03a7cc32e736c5b9ab3b3cb5c3d | /book-spring-boot-actual-combat-jsp/src/main/java/com/learning/spring/boot/BookSpringBootActualCombatJspApplication.java | 093c9f22c9c49ae9658a5dd1fc00527fcb66a6fc | [] | no_license | BerryHang/book-spring-boot-actual-combat | 58af3734e255e91946b2d0cb3a217400f41d6f7f | 59c819dd568f5165e323e742e869bdb6463a51c9 | refs/heads/master | 2022-09-03T21:41:28.055643 | 2020-01-17T08:22:45 | 2020-01-17T08:22:45 | 155,185,154 | 3 | 0 | null | 2022-09-01T23:08:29 | 2018-10-29T09:28:07 | JavaScript | UTF-8 | Java | false | false | 576 | java | package com.learning.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author beibei.huang
* @Title: BookSpringBootActualCombatJspApplication
* @ProjectName book-spring-boot-actual-combat-parent
* @Description: JSP应用启动类
* @date 2018/11/2 15:19
*/
@SpringBootApplication
public class BookSpringBootActualCombatJspApplication {
public static void main(String[] args) {
SpringApplication.run(BookSpringBootActualCombatJspApplication.class, args);
}
}
| [
"[email protected]"
] | |
f161bd70ee4cfd66409e61f2168882fbcf5e0d06 | 29c0d84c069f63800f635f71b120dff151d353e5 | /src/com/nju/state/DispenseOutState.java | 1e9e32835730572f01a6a98e2897586b6c328149 | [] | no_license | littlefishvv/DesignPattern | b46785666cffd321b440c7b1720d7cdfc9dce9bf | 0e8ed7b730296855080269d7de0c5a7c9d797756 | refs/heads/master | 2022-12-20T16:29:05.136141 | 2020-10-13T06:57:24 | 2020-10-13T06:57:24 | 303,614,238 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 824 | java | package com.nju.state;
/**
* @author :Siyuan Gao
* @date :Created in 2020/10/3 10:49
* @description:奖品发放完的状态
* @modified By:
* @version: $
*/
public class DispenseOutState extends State {
// 初始化时传入活动引用
RaffleActivity activity;
public DispenseOutState(RaffleActivity activity) {
this.activity = activity;
}
//这个状态不会转变为其他状态
@Override
public void deductMoney() {
System.out.println("奖品发送完了,请下次再参加");
}
@Override
public boolean raffle() {
System.out.println("奖品发送完了,请下次再参加");
return false;
}
@Override
public void dispensePrize() {
System.out.println("奖品发送完了,请下次再参加");
}
}
| [
"[email protected]"
] | |
46fb0728ddf4e75652db6e26504e40ee85d4f47e | b85be04099edfef45f01669e44c5d584f7d3cb85 | /SocketClientApp/src/org/loup/activity/MainActivity.java | 277039a1c63d0eeb936252b6e4c6a7b8e96afc73 | [] | no_license | lu911/android_push_client | 5e3294894b62e70a2d70129eaf7e481187447936 | 401572e3267446291aa40fd6fb22df49e038bacf | refs/heads/master | 2023-02-18T22:34:35.568548 | 2013-09-21T10:54:50 | 2013-09-21T10:54:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,169 | java | /*
* Copyright © 2013 Yuk SeungChan, All rights reserved.
*/
package org.loup.activity;
import android.content.Intent;
import android.util.Log;
import com.cnp.activity.R;
import org.bson.*;
import org.bson.io.BSONByteBuffer;
import org.loup.net.NetworkCallback;
import org.loup.net.manager.SocketNetworkManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.loup.service.NetworkService;
import java.io.UnsupportedEncodingException;
public class MainActivity extends Activity implements OnClickListener, NetworkCallback
{
private Button btn_send = null;
private TextView tv_viewer = null;
private EditText et_data = null;
private SocketNetworkManager socketNetworkManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
socketNetworkManager = SocketNetworkManager.getInstance();
socketNetworkManager.setNetworkCallback(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_send = (Button)findViewById(R.id.btn_send);
btn_send.setOnClickListener(this);
tv_viewer = (TextView)findViewById(R.id.tv_viewer);
et_data = (EditText)findViewById(R.id.et_data);
Intent in = new Intent(this, NetworkService.class);
startService(in);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btn_send:
BasicBSONObject basicBSONObject = new BasicBSONObject();
basicBSONObject.put("url", "/chat/push/");
basicBSONObject.put("message", et_data.getText().toString());
SocketNetworkManager.getInstance().send(new BasicBSONEncoder().encode(basicBSONObject));
break;
}
}
private final Handler handler = new Handler()
{
public void handleMessage(Message msg) {
tv_viewer.setText("You Send : " + msg.obj.toString() + "");
}
};
@Override
public void connect()
{
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void disconnect()
{
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void success(byte[] data)
{
BSONByteBuffer buffer = BSONByteBuffer.wrap(data);
BSONObject bsonObject = new BasicBSONDecoder().readObject(buffer.array());
String message = bsonObject.get("message").toString();
Log.d("loup", "bson : " + bsonObject);
Log.d("loup", "message : " + message);
Message msg = handler.obtainMessage();
msg.obj = message;
handler.sendMessage(msg);
}
@Override
public void error(String data) {
Log.d("loup", data);
}
}
| [
"[email protected]"
] | |
5bd73109f962e81be60c01dbe112573331e47790 | d3885b29bb1cba965a92ca05927ada63cbcac504 | /app/src/androidTest/java/edu/tecii/android/practica6radiobutnoti/ExampleInstrumentedTest.java | f9d1b48e186f12a605eb9cf7b3b7bbf189184add | [] | no_license | JuanChacon/Practica6RadioButNoti | d88c87f13f8d7e97bc0713b78cf3f53af700f655 | 76c5900b59f0957bc5de382cf4a63cf6e3de9d6d | refs/heads/master | 2021-07-04T13:21:28.858993 | 2017-09-27T18:30:49 | 2017-09-27T18:30:49 | 105,054,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 782 | java | package edu.tecii.android.practica6radiobutnoti;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("edu.tecii.android.practica6radiobutnoti", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
382a489622f0e3304948f3b3aa020ef86fbc4165 | 5786b8c28f069ae9b9b7f850edf4d4c1b5cf976c | /languages/CSharp/source_gen/CSharp/behavior/Pointer_type_block_1_2_1_BehaviorDescriptor.java | e5828c67aae62bb201be5d21ba2587ce66a1d681 | [
"Apache-2.0"
] | permissive | vaclav/MPS_CSharp | 681ea277dae2e7503cd0f2d21cb3bb7084f6dffc | deea11bfe3711dd241d9ca3f007b810d574bae76 | refs/heads/master | 2021-01-13T14:36:41.949662 | 2019-12-03T15:26:21 | 2019-12-03T15:26:21 | 72,849,927 | 19 | 5 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package CSharp.behavior;
/*Generated by MPS */
/**
* Will be removed after 3.4
* Need to support compilation of the legacy behavior descriptors before the language is rebuilt
* This class is not involved in the actual method invocation
*/
@Deprecated
public class Pointer_type_block_1_2_1_BehaviorDescriptor {
public String getConceptFqName() {
return null;
}
}
| [
"[email protected]"
] | |
dba3a84464cba2162013f8860c8d93e237e19043 | a5b4bfe810d08e2a59a1f385a5a054da860a0623 | /android accessibility API test/OnInitializeAccessibilityEventTest/app/src/main/java/com/example/oninitializeaccessibilityeventtest/MainActivity.java | 3c31a874ec11cab1e75fdfb13e401815681f3cf7 | [] | no_license | khsbory/solutions-for-accessibility | e646bc8dafa3d60b475671bd9d0337cb1af339ef | 324e079e800f63a57e35aad12b3cb12dfcb6449c | refs/heads/master | 2023-07-11T21:42:25.110140 | 2021-08-03T02:47:28 | 2021-08-03T02:47:28 | 298,873,849 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,500 | java | package com.example.oninitializeaccessibilityeventtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initButton();
}
private void initButton() {
if (Build.VERSION.SDK_INT >= 14) {
// If the API version is equal of higher than the version in
// which onInitializeAccessibilityNodeInfo was introduced we
// register a delegate with a customized implementation.
Button button = findViewById(R.id.button);
button.setAccessibilityDelegate(new View.AccessibilityDelegate() {
public void onInitializeAccessibilityEvent(View host,
AccessibilityEvent event1) {
Log.d("plusapps", "onInitializeAccessibilityEvent");
// Let the default implementation populate the info.
super.onInitializeAccessibilityEvent(host, event1);
// Set some other information.
event1.setChecked(false);
}
});
}
}
} | [
"[email protected]"
] | |
2508fe090fac01bce2aee304cef368f9fc91dba3 | 10e665bcc8126ad87a8cbf99fffba983ed6994cc | /MySpringMVC/src/main/java/lee/sample/framework/util/pagination/ImagePaginationRenderer.java | 252ecedeec1e87aca5cf51d379907bddf7889d61 | [] | no_license | PlumpMath/MySpringMVC | 7abd5fba7220d9a4b11ac0ffeecad00aaab4ae3f | bc0b37e7cfcd4d87d44b211987d56e399de56841 | refs/heads/master | 2021-01-18T20:24:41.184686 | 2013-08-25T08:36:51 | 2013-08-25T08:36:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,343 | java | package lee.sample.framework.util.pagination;
import javax.servlet.ServletContext;
import org.springframework.web.context.ServletContextAware;
public class ImagePaginationRenderer extends AbstractPaginationRenderer implements ServletContextAware {
private ServletContext servletContext;
public ImagePaginationRenderer(){
}
public void initVariables(){
firstPageLabel = "<a href=\"#\" onclick=\"{0}({1}); return false;\"><image src=\"" + servletContext.getContextPath() + "/images/bt_first.gif\" border=0/></a> ";
previousPageLabel = "<a href=\"#\" onclick=\"{0}({1}); return false;\"><image src=\"" + servletContext.getContextPath() + "/images/bt_prev.gif\" border=0/></a> ";
currentPageLabel = "<strong>{0}</strong> ";
otherPageLabel = "<a href=\"#\" onclick=\"{0}({1}); return false;\">{2}</a> ";
nextPageLabel = "<a href=\"#\" onclick=\"{0}({1}); return false;\"><image src=\"" + servletContext.getContextPath() + "/images/bt_next.gif\" border=0/></a> ";
lastPageLabel = "<a href=\"#\" onclick=\"{0}({1}); return false;\"><image src=\"" + servletContext.getContextPath() + "/images/bt_last.gif\" border=0/></a> ";
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
initVariables();
}
}
| [
"[email protected]"
] | |
29893d9c9d76049636487e6c7237b23b5f515018 | bae05728457196af51c269cd6a0b1efc6d8495f7 | /MyGenerate/MyGenerate/src/main/java/cn/gameboys/frame/IGenerateHandler.java | f13bb385bb04a893dd278ec9d5c49bbdc6e64f80 | [] | no_license | Sniper2016/MyGenerate | 24e07ef132ad73fe54b12d06372ec58479018918 | 4238b3d7aec7576cb93834ec9465c87dec6278ee | refs/heads/master | 2022-07-02T23:28:37.270396 | 2019-09-23T14:28:41 | 2019-09-23T14:28:41 | 210,371,532 | 0 | 0 | null | 2022-06-21T01:55:53 | 2019-09-23T14:07:56 | Java | UTF-8 | Java | false | false | 105 | java | package cn.gameboys.frame;
public interface IGenerateHandler<T> {
void init();
String resolve();
}
| [
"[email protected]"
] | |
7631e20812b9d163b49d942a3fe456a4e862a6a4 | 498dd2daff74247c83a698135e4fe728de93585a | /clients/google-api-services-compute/alpha/1.31.0/com/google/api/services/compute/model/AllocationShareSettings.java | 7a144e6678d8bcda4ee75e1ed467812bb2c59ee9 | [
"Apache-2.0"
] | permissive | googleapis/google-api-java-client-services | 0e2d474988d9b692c2404d444c248ea57b1f453d | eb359dd2ad555431c5bc7deaeafca11af08eee43 | refs/heads/main | 2023-08-23T00:17:30.601626 | 2023-08-20T02:16:12 | 2023-08-20T02:16:12 | 147,399,159 | 545 | 390 | Apache-2.0 | 2023-09-14T02:14:14 | 2018-09-04T19:11:33 | null | UTF-8 | Java | false | false | 3,146 | java | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Model definition for AllocationShareSettings.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class AllocationShareSettings extends com.google.api.client.json.GenericJson {
/**
* A List of Project names to specify consumer projects for this shared-reservation. This is only
* valid when share_type's value is SPECIFIC_PROJECTS.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> projects;
/**
* Type of sharing for this shared-reservation
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String shareType;
/**
* A List of Project names to specify consumer projects for this shared-reservation. This is only
* valid when share_type's value is SPECIFIC_PROJECTS.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getProjects() {
return projects;
}
/**
* A List of Project names to specify consumer projects for this shared-reservation. This is only
* valid when share_type's value is SPECIFIC_PROJECTS.
* @param projects projects or {@code null} for none
*/
public AllocationShareSettings setProjects(java.util.List<java.lang.String> projects) {
this.projects = projects;
return this;
}
/**
* Type of sharing for this shared-reservation
* @return value or {@code null} for none
*/
public java.lang.String getShareType() {
return shareType;
}
/**
* Type of sharing for this shared-reservation
* @param shareType shareType or {@code null} for none
*/
public AllocationShareSettings setShareType(java.lang.String shareType) {
this.shareType = shareType;
return this;
}
@Override
public AllocationShareSettings set(String fieldName, Object value) {
return (AllocationShareSettings) super.set(fieldName, value);
}
@Override
public AllocationShareSettings clone() {
return (AllocationShareSettings) super.clone();
}
}
| [
"[email protected]"
] | |
796337204987b74214a53b3bf6b2d2f66d848630 | 432ff9313b7cd18250915d48ee0ffaa169239910 | /Java/src/com/leetcode/Medium/RemoveCoveredIntervals.java | 11fb327f6b38f64abc5ecac55acaee2720acc1b1 | [] | no_license | shankarmattigatti/LeetCode | 86752735ba28cf5be0c128085848950b4d0aefb5 | 93bc76fb118748195d3a5f7b03cc183129d7b4b7 | refs/heads/master | 2023-08-30T01:10:29.571034 | 2023-08-12T03:38:52 | 2023-08-12T03:38:52 | 174,800,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 594 | java | package com.leetcode.Medium;
import java.util.Arrays;
import java.util.Comparator;
// 1288. Remove Covered Intervals
public class RemoveCoveredIntervals {
public int removeCoveredIntervals(int[][] intervals) {
int res = 0, left = -1, right = -1;
Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
for (int[] interval : intervals) {
if (interval[0] > left && interval[1] > right) {
left = interval[0];
res++;
}
right = Math.max(right, interval[1]);
}
return res;
}
}
| [
"[email protected]"
] | |
bfcdcee371c28c66e2b7ec89c86b63f1c8e51be4 | 1f80547828944fb428530dc5e8710108d7d7194e | /src/test/java/ru/junit/utils/AllCategories.java | 4777d6fa056c5468fca5daa9a194286961f298cd | [] | no_license | OlgaLevitskaya/junittrenning | 615559e8c6fe8117d8c55846de38959ada0d391a | 8d030a705fe0084e0af79ce6265dcd4ab41436d7 | refs/heads/master | 2020-03-19T03:44:07.944359 | 2018-06-11T16:18:20 | 2018-06-11T16:18:20 | 135,756,681 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 150 | java | package ru.junit.utils;
public interface AllCategories {
public static interface PositiveTests {}
public static interface NegativeTests {}
}
| [
"[email protected]"
] | |
98a5eafef2975361e8a7eb0d23a7bff168b4b87d | fa866ad6134108f7444efa545633cd57fa552425 | /Project4/src/main/java/edu/berkeley/cs186/database/cli/ExampleLoader.java | d027f23f2d3a1327d5e2930b6fbee69bc74edcbc | [] | no_license | sunilpimenta/MOOCbase | b4fc0ff0c54593ba0e8ed9dc3a7cb4e857110632 | ca4a896928f443da9324566eda2d75eca4018b12 | refs/heads/main | 2023-02-11T01:49:53.339267 | 2020-12-29T18:30:01 | 2020-12-29T18:30:01 | 331,160,257 | 2 | 2 | null | 2021-01-20T01:42:03 | 2021-01-20T01:42:03 | null | UTF-8 | Java | false | false | 5,373 | java | package edu.berkeley.cs186.database.cli;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import edu.berkeley.cs186.database.Database;
import edu.berkeley.cs186.database.DatabaseException;
import edu.berkeley.cs186.database.Transaction;
import edu.berkeley.cs186.database.concurrency.LockManager;
import edu.berkeley.cs186.database.databox.DataBox;
import edu.berkeley.cs186.database.databox.FloatDataBox;
import edu.berkeley.cs186.database.databox.IntDataBox;
import edu.berkeley.cs186.database.databox.StringDataBox;
import edu.berkeley.cs186.database.databox.Type;
import edu.berkeley.cs186.database.memory.ClockEvictionPolicy;
import edu.berkeley.cs186.database.table.Schema;
public class ExampleLoader {
public static Database setupDatabase() throws IOException {
// Basic database for project 1 through 3
Database database = new Database("demo", 25);
// Use the following after completing project 4 (locking)
// Database database = new Database("demo", 25, new LockManager());
// Use the following after completing project 5 (recovery)
// Database database = new Database("demo", 25, new LockManager(), new ClockEvictionPolicy(), true);
database.setWorkMem(5); // B=5
//Create schemas
List<String> studentSchemaNames = new ArrayList<>();
studentSchemaNames.add("sid");
studentSchemaNames.add("name");
studentSchemaNames.add("major");
studentSchemaNames.add("gpa");
List<Type> studentSchemaTypes = new ArrayList<>();
studentSchemaTypes.add(Type.intType());
studentSchemaTypes.add(Type.stringType(20));
studentSchemaTypes.add(Type.stringType(20));
studentSchemaTypes.add(Type.floatType());
Schema studentSchema = new Schema(studentSchemaNames, studentSchemaTypes);
try(Transaction t = database.beginTransaction()) {
try {
t.createTable(studentSchema, "Students");
} catch (DatabaseException e) {
return database;
}
List<String> courseSchemaNames = new ArrayList<>();
courseSchemaNames.add("cid");
courseSchemaNames.add("name");
courseSchemaNames.add("department");
List<Type> courseSchemaTypes = new ArrayList<>();
courseSchemaTypes.add(Type.intType());
courseSchemaTypes.add(Type.stringType(20));
courseSchemaTypes.add(Type.stringType(20));
Schema courseSchema = new Schema(courseSchemaNames, courseSchemaTypes);
try {
t.createTable(courseSchema, "Courses");
} catch (DatabaseException e) {
// Do nothing
}
List<String> enrollmentSchemaNames = new ArrayList<>();
enrollmentSchemaNames.add("sid");
enrollmentSchemaNames.add("cid");
List<Type> enrollmentSchemaTypes = new ArrayList<>();
enrollmentSchemaTypes.add(Type.intType());
enrollmentSchemaTypes.add(Type.intType());
Schema enrollmentSchema = new Schema(enrollmentSchemaNames, enrollmentSchemaTypes);
try {
t.createTable(enrollmentSchema, "Enrollments");
} catch (DatabaseException e) {
// Do nothing
}
}
try(Transaction transaction = database.beginTransaction()) {
// read student tuples
List<String> studentLines = Files.readAllLines(Paths.get("data", "Students.csv"), Charset.defaultCharset());
for (String line : studentLines) {
String[] splits = line.split(",");
List<DataBox> values = new ArrayList<>();
values.add(new IntDataBox(Integer.parseInt(splits[0])));
values.add(new StringDataBox(splits[1].trim(), 20));
values.add(new StringDataBox(splits[2].trim(), 20));
values.add(new FloatDataBox(Float.parseFloat(splits[3])));
transaction.insert("Students", values);
}
List<String> courseLines = Files.readAllLines(Paths.get("data", "Courses.csv"), Charset.defaultCharset());
for (String line : courseLines) {
String[] splits = line.split(",");
List<DataBox> values = new ArrayList<>();
values.add(new IntDataBox(Integer.parseInt(splits[0])));
values.add(new StringDataBox(splits[1].trim(), 20));
values.add(new StringDataBox(splits[2].trim(), 20));
transaction.insert("Courses", values);
}
List<String> enrollmentLines = Files.readAllLines(Paths.get("data", "Enrollments.csv"),
Charset.defaultCharset());
for (String line : enrollmentLines) {
String[] splits = line.split(",");
List<DataBox> values = new ArrayList<>();
values.add(new IntDataBox(Integer.parseInt(splits[0])));
values.add(new IntDataBox(Integer.parseInt(splits[1])));
transaction.insert("Enrollments", values);
}
}
return database;
}
} | [
"[email protected]"
] | |
4af73f46d199adfe21dba55c243fe0e5ff9e02d6 | a9463fcc723cab6d527904b7ebb8d30d3c913159 | /tic-server/android/cardevice-gps/app/src/main/java/cn/bidostar/ticserver/model/RequestCommonParamsDto.java | 4d6cb40120ea41a5f510a0875c009de7c6f01a48 | [] | no_license | yangx2015/wdxc | 85cddf42da4a84c92714d882994bf2ad72824491 | ff7cee63edde5d5d82559dcceccf395ee68df548 | refs/heads/master | 2021-10-24T20:16:40.190679 | 2019-03-21T02:25:04 | 2019-03-21T02:25:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,424 | java | package cn.bidostar.ticserver.model;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
import java.io.Serializable;
/**
* 公共接收参数对象
* @author wanggang
*
*/
@Table(name="requestdtomodel")
public class RequestCommonParamsDto implements Serializable {
@Column(name="id",isId = true)
public int id;
@Column(name="deviceId")
private String deviceId;//设备id(每次都必须上传)
@Column(name="channelId")
private String channelId;//用于推送(每次都必须上传)
@Column(name="deviceTag")
private String deviceTag;//设备tag主要也是 用于推送(每次都必须上传)
@Column(name="startTime")
private String startTime;//开始时间
private String endTime;//结束时间
@Column(name="longitude")
private String longitude;//经度(参数几乎每个接口都会上传)
@Column(name="latitude")
private String latitude;//纬度(参数几乎每个接口都会上传)
@Column(name="speed")
private String speed;//速度
@Column(name="direction")
private String direction;//方向
@Column(name="eventType")
private String eventType;//事件 00点火,01熄火,02急加速 ,04 GPS,05 上传图片,06上传视频, 07上传图片(突发事件记录),08上传视频(突发事件记录)
private String filePath;//文件相对路径(上传视频或者图片才会使用的参数)
private String fileLocalPath;//文件本地绝对路径(上传视频或者图片才会使用的参数)
private String fileRealName;//上传的文件在设备中的名称(上传视频或者图片才会使用的参数)
private String fileSize;//文件大小(上传视频或者图片才会使用的参数)
private String filePostfix;//文件后缀(可以用于文件类型)
private String taskId;//任务id(用于上传服务器下载命令之后,终端上传之后回调给服务器之后的数据使用)
@Column(name="sczt")
private String sczt;//汽车是在运行中还是已经熄火的数据上传标识
private String cmdType;//命令类型(推送消息时使用) 01:超速设定 02:灵敏度设定 11:拍视频 12:拍图片
/**
cmdType 02:
设置加减速监测灵敏等级,level 1-6,默认为 2 :
1. 速度从零加到百公里约58秒内,能够被检测到急加速;
2. 速度从零加到百公里约29秒内,能够被检测到急加速;
3. 速度从零加到百公里约19秒内,能够被检测到急加速;
4. 速度从零加到百公里约14秒内,能够被检测到急加速;
5. 速度从零加到百公里约11秒内,能够被检测到急加速;
6. 速度从零加到百公里约9秒内,能够被检测到急加速
01: 值不能大于120且不能小于10
*/
private String cmd;//具体命令(推送消息时使用)
private String cmdParams;//其它参数(推送消息时使用)
@Column(name="dwjd")
private String dwjd;//GPS定位角度
@Column(name="gpsjd")
private String gpsjd;//GPS精度
@Column(name="fxj")
private String fxj;//方向角
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getDeviceTag() {
return deviceTag;
}
public void setDeviceTag(String deviceTag) {
this.deviceTag = deviceTag;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileLocalPath() {
return fileLocalPath;
}
public void setFileLocalPath(String fileLocalPath) {
this.fileLocalPath = fileLocalPath;
}
public String getFileRealName() {
return fileRealName;
}
public void setFileRealName(String fileRealName) {
this.fileRealName = fileRealName;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getFilePostfix() {
return filePostfix;
}
public void setFilePostfix(String filePostfix) {
this.filePostfix = filePostfix;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCmdType() {
return cmdType;
}
public void setCmdType(String cmdType) {
this.cmdType = cmdType;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public String getCmdParams() {
return cmdParams;
}
public void setCmdParams(String cmdParams) {
this.cmdParams = cmdParams;
}
public String getDwjd() {
return dwjd;
}
public void setDwjd(String dwjd) {
this.dwjd = dwjd;
}
public String getGpsjd() {
return gpsjd;
}
public void setGpsjd(String gpsjd) {
this.gpsjd = gpsjd;
}
public String getFxj() {
return fxj;
}
public void setFxj(String fxj) {
this.fxj = fxj;
}
public String getSczt() {
return sczt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "RequestCommonParamsDto{" +
"id=" + id +
", deviceId='" + deviceId + '\'' +
", channelId='" + channelId + '\'' +
", deviceTag='" + deviceTag + '\'' +
", startTime='" + startTime + '\'' +
", endTime='" + endTime + '\'' +
", longitude='" + longitude + '\'' +
", latitude='" + latitude + '\'' +
", speed='" + speed + '\'' +
", direction='" + direction + '\'' +
", eventType='" + eventType + '\'' +
", filePath='" + filePath + '\'' +
", fileLocalPath='" + fileLocalPath + '\'' +
", fileRealName='" + fileRealName + '\'' +
", fileSize='" + fileSize + '\'' +
", filePostfix='" + filePostfix + '\'' +
", taskId='" + taskId + '\'' +
", sczt='" + sczt + '\'' +
", cmdType='" + cmdType + '\'' +
", cmd='" + cmd + '\'' +
", cmdParams='" + cmdParams + '\'' +
", dwjd='" + dwjd + '\'' +
", gpsjd='" + gpsjd + '\'' +
", fxj='" + fxj + '\'' +
'}';
}
public void setSczt(String sczt) {
this.sczt = sczt;
}
}
| [
"[email protected]"
] | |
6aeb506d557a740a11b536fafa230b93ef5c90e4 | 96b47813670522cc131127aa2fc55a980fad9a12 | /src/main/java/com/icinfo/common/listener/JobForWXAccessTokenListener.java | e1e20d1510997aa6bc837d3520c9797d03132492 | [] | no_license | orzzzzz/wechattest | 0e15076e2af4dc00e3463bb992ebe476fca565f8 | 85dc611766262e999915f222b75c5df06e995078 | refs/heads/master | 2021-01-20T19:26:29.351778 | 2016-08-08T00:49:05 | 2016-08-08T00:49:05 | 65,006,827 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,098 | java | package com.icinfo.common.listener;
import com.icinfo.common.util.AccessTokenUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 描述:TODO
*
* @author zhangmengwen
* @date 2016/8/5
*/
public class JobForWXAccessTokenListener implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
Runnable runnable = new Runnable() {
public void run() {
/**
* 定时设置accessToken
*/
AccessTokenUtil.initAndSetAccessToken();
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnable, 1, 30, TimeUnit.SECONDS);
}
}
} | [
"[email protected]"
] | |
bac352cb8b1f0a0cbe5336a7d2b96598f9d9bb7e | c7531c2978103f7f6dc46d7ecceb9c56305f47fd | /src/main/java/cubes/main/dao/UserRepository.java | 4bf4e0045f33d91eaeb1b6004bf35bb765cf5778 | [] | no_license | milanzn/MyBlog | 97bd82eebb97e8c7981306cd5aa8a68e8be26301 | 4ea5b5560948a158510603a11534811e55652733 | refs/heads/main | 2023-08-17T23:46:24.063492 | 2021-09-15T19:37:14 | 2021-09-15T19:37:14 | 405,728,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 240 | java | package cubes.main.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import cubes.main.entity.User;
public interface UserRepository extends JpaRepository<User, String>{
public User findByUsername(String username);
}
| [
"[email protected]"
] | |
9d329b007ce092b57aaab3445a372151a8933b59 | 41e9d4aebb7a9fb6a317f3a0583ae099e791cd41 | /src/com/company/Place.java | b6bbcbc894653f38882d672e009e9562535996ce | [] | no_license | PetchMa/MazeSearchDFS | 25c4c180e5ef41eccac17150de71f984ce97ca98 | ef01615834b8b75d1503bbaa0e60782116f6defe | refs/heads/master | 2020-09-03T04:12:38.234957 | 2019-11-04T15:22:10 | 2019-11-04T15:22:10 | 219,383,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,421 | java | /*=================================================================
Place Class
Peter Ma
Oct 27 2019
Java JDK 11 LTS
=================================================================
Problem Definition – Hold the location of the mouse via coordinate pairs
Input – The row and the columns for the position/point
Output – The needed attributes of the point
Process – simply gets and sets the values of the x and y coordinate
=================================================================
List of Identifiers - will be listed in each file.
=================================================================
Let x be the row value for the position <type int>
let Y be the column value for the position <type int>
*/
package com.company;
public class Place {
private int x;
private int y;
/**Place method
* This is the constructor method that initializes the Place object
*
* List of local variables
* none
*
* @param - none
* @return none
*/
public Place(int x, int y) {
this.x = x; // initialize X variable
this.y = y; // initialize Y variable
}// end of constructor
/**setX method
* This procedural method helps set the variable X
*
* List of local variables
* none
*
* @param - X <type int>
* @return none
*/
public void setX(int x) {
this.x = x; // sets the private X var
}// end of setX method
/**setY method
* This procedural method helps set the variable Y
*
* List of local variables
* none
*
* @param - Y <type int>
* @return none
*/
public void setY(int y) {
this.y = y;
}// end of setY method
/**getX method
* This functional method helps access the private variable X
*
* List of local variables
* none
*
* @param - NONE
* @return X <type int>
*/
public int getX() {
return x; // returns the private variable X
}//end of getX method
/**getY method
* This functional method helps access the private variable Y
*
* List of local variables
* none
*
* @param - NONE
* @return Y <type int>
*/
public int getY() {
return y;// returns the Private variable Y
}// end of getY method
}// end of class
| [
"[email protected]"
] | |
b8403a8ec59f400c5832f467d43a32289bf52fe9 | 14746c4b8511abe301fd470a152de627327fe720 | /soroush-android-1.10.0_source_from_JADX/com/google/android/gms/common/api/C1720i.java | a6180154631693ac8a3db7314e4c39e2f751b5cb | [] | no_license | maasalan/soroush-messenger-apis | 3005c4a43123c6543dbcca3dd9084f95e934a6f4 | 29867bf53a113a30b1aa36719b1c7899b991d0a8 | refs/heads/master | 2020-03-21T21:23:20.693794 | 2018-06-28T19:57:01 | 2018-06-28T19:57:01 | 139,060,676 | 3 | 2 | null | null | null | null | UTF-8 | Java | false | false | 94 | java | package com.google.android.gms.common.api;
public interface C1720i {
Status mo3007a();
}
| [
"[email protected]"
] | |
93e1da8fdd79def9d31708ab8bb7c1bfa48059b9 | d0201573017e860718e9320fd6ea03f7d6bb2ef3 | /mybookstore/src/mybookstore/book/dao/BookDao.java | 924dd97bd018cd2fa17652754d5e241b6cc2c8b0 | [] | no_license | LongQiudao/mybookstore | c576c2c88553072dd3de8c5755eb83861d29524c | d87a00de9879edc03dc7e3f030759657759c9547 | refs/heads/master | 2020-04-01T10:37:24.059505 | 2018-10-15T14:13:02 | 2018-10-15T14:13:02 | 153,065,924 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,082 | java | package mybookstore.book.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import mybookstore.book.domain.Book;
import mybookstore.category.domain.Category;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.itcast.commons.CommonUtils;
import cn.itcast.jdbc.TxQueryRunner;
public class BookDao {
private QueryRunner qr = new TxQueryRunner();
/**
* 查询所有图书
* **/
public List<Book> findAll() {
try {
String sql = "select *from book where del=false";
return qr.query(sql, new BeanListHandler<Book>(Book.class));
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 按分类查询
*
*
* */
public List<Book> findByCategory(String cid) {
try {
String sql = "select *from book where cid = ? and del=false";
return qr.query(sql, new BeanListHandler<Book>(Book.class), cid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 加载图书
* */
public Book findByBid(String bid) {
try {
/*
* 我们需要在book对象中保存category的信息
*/
String sql = "select *from book where bid = ?";
Map<String, Object> map = qr.query(sql, new MapHandler(), bid);
// 使用map,映射出两个对象,再给这两个对象建立关系
Category category = CommonUtils.toBean(map, Category.class);
Book book = CommonUtils.toBean(map, Book.class);
book.setCategory(category);
return book;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 获取指定分类下的图书本数
* */
public int getCountByCid(String cid) {
try {
String sql = "select count(*) from book where cid = ? and del=false";
Number num = (Number) qr.query(sql, new ScalarHandler(), cid);
return num.intValue();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 删除图书
*
* */
public void delete(String bid) {
try {
String sql = "update book set del=true where bid=?";
qr.update(sql, bid);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 添加图书
* */
public void add(Book book) {
try {
String sql = "insert into book values(?,?,?,?,?,?,?)";
Object[] params = { book.getBid(), book.getBname(),
book.getPrice(), book.getAuthor(), book.getImage(),
book.getCategory().getCid(),book.isDel() };
qr.update(sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void edit(Book book) {
try {
String sql = "update book set bname=?,price=?,author=?,image=?,cid=?where bid =?";
Object[] params = { book.getBname(), book.getPrice(),
book.getAuthor(), book.getImage(),
book.getCategory().getCid(), book.getBid() };
qr.update(sql, params);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
| [
"[email protected]"
] | |
b5093a72016af186b73529bb1bdaffe63796fef2 | aaabffe8bf55973bfb1390cf7635fd00ca8ca945 | /src/main/java/com/microsoft/graph/models/generated/BaseOutlookItem.java | af71d6837983f357a13b157e74584a80f4f6a323 | [
"MIT"
] | permissive | rgrebski/msgraph-sdk-java | e595e17db01c44b9c39d74d26cd925b0b0dfe863 | 759d5a81eb5eeda12d3ed1223deeafd108d7b818 | refs/heads/master | 2020-03-20T19:41:06.630857 | 2018-03-16T17:31:43 | 2018-03-16T17:31:43 | 137,648,798 | 0 | 0 | null | 2018-06-17T11:07:06 | 2018-06-17T11:07:05 | null | UTF-8 | Java | false | false | 2,584 | java | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.generated;
import com.microsoft.graph.concurrency.*;
import com.microsoft.graph.core.*;
import com.microsoft.graph.models.extensions.*;
import com.microsoft.graph.models.generated.*;
import com.microsoft.graph.http.*;
import com.microsoft.graph.requests.extensions.*;
import com.microsoft.graph.requests.generated.*;
import com.microsoft.graph.options.*;
import com.microsoft.graph.serializer.*;
import java.util.Arrays;
import java.util.EnumSet;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.annotations.*;
import java.util.HashMap;
import java.util.Map;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Base Outlook Item.
*/
public class BaseOutlookItem extends Entity implements IJsonBackedObject {
/**
* The Created Date Time.
*
*/
@SerializedName("createdDateTime")
@Expose
public java.util.Calendar createdDateTime;
/**
* The Last Modified Date Time.
*
*/
@SerializedName("lastModifiedDateTime")
@Expose
public java.util.Calendar lastModifiedDateTime;
/**
* The Change Key.
*
*/
@SerializedName("changeKey")
@Expose
public String changeKey;
/**
* The Categories.
*
*/
@SerializedName("categories")
@Expose
public java.util.List<String> categories;
/**
* The raw representation of this class
*/
private JsonObject rawObject;
/**
* The serializer
*/
private ISerializer serializer;
/**
* Gets the raw representation of this class
*
* @return the raw representation of this class
*/
public JsonObject getRawObject() {
return rawObject;
}
/**
* Gets serializer
*
* @return the serializer
*/
protected ISerializer getSerializer() {
return serializer;
}
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(final ISerializer serializer, final JsonObject json) {
this.serializer = serializer;
rawObject = json;
}
}
| [
"[email protected]"
] | |
fee34cba73ed1af8ffe9461123ec9c971c1b2884 | 90e710e40de92f143d53955a17f96806c3b08ea6 | /app/src/main/java/com/olmatix/internal/Connections.java | 46a9629d6af1520671a48b562ace2e18ae68b900 | [] | no_license | MPTechnolabs/Controller | 60d679047d532fa36f62d1f614886bbab98ae86b | ab5921d0f27543f86f56d30ca0d66b79cf5b8744 | refs/heads/master | 2020-06-22T06:50:55.791075 | 2016-11-30T12:48:19 | 2016-11-30T12:48:19 | 74,751,924 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,141 | java | /*******************************************************************************
* Copyright (c) 1999, 2014 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* James Sutton - Updating in new Sample App
*/
package com.olmatix.internal;
import android.content.Context;
import com.olmatix.Connection;
import org.eclipse.paho.android.service.MqttAndroidClient;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <code>Connections</code> is a singleton class which stores all the connection objects
* in one central place so they can be passed between activities using a client handle.
*/
public class Connections {
/** Singleton instance of <code>Connections</code>**/
private static Connections instance = null;
/** List of {@link Connection} object **/
private HashMap<String, Connection> connections = null;
/** {@link Persistence} object used to save, delete and restore connections**/
private Persistence persistence = null;
/**
* Create a Connections object
* @param context Applications context
*/
private Connections(Context context){
connections = new HashMap<String, Connection>();
// If there is state, attempt to restore it
persistence = new Persistence(context);
try {
List<Connection> connectionList = persistence.restoreConnections(context);
for(Connection connection : connectionList) {
System.out.println("Connection was persisted.." + connection.handle());
connections.put(connection.handle(), connection);
}
} catch (PersistenceException e){
e.printStackTrace();
}
}
/**
* Returns an already initalised instance of <code>Connections</code>, if Connections has yet to be created, it will
* create and return that instance.
* @param context The applications context used to create the <code>Connections</code> object if it is not already initialised
* @return <code>Connections</code> instance
*/
public synchronized static Connections getInstance(Context context){
if(instance == null){
instance = new Connections(context);
}
return instance;
}
/**
* Finds and returns a {@link Connection} object that the given client handle points to
* @param handle The handle to the {@link Connection} to return
* @return a connection associated with the client handle, <code>null</code> if one is not found
*/
public Connection getConnection(String handle){
return connections.get(handle);
}
/**
* Adds a {@link Connection} object to the collection of connections associated with this object
* @param connection {@link Connection} to add
*/
public void addConnection(Connection connection){
connections.put(connection.handle(), connection);
try{
persistence.persistConnection(connection);
} catch (PersistenceException e){
// @todo Handle this error more appropriately
//error persisting well lets just swallow this
e.printStackTrace();
}
}
/**
* Create a fully initialised <code>MqttAndroidClient</code> for the parameters given
* @param context The Applications context
* @param serverURI The ServerURI to connect to
* @param clientId The clientId for this client
* @return new instance of MqttAndroidClient
*/
public MqttAndroidClient createClient(Context context, String serverURI, String clientId){
MqttAndroidClient client = new MqttAndroidClient(context, serverURI, clientId);
return client;
}
/**
* Get all the connections assiciated with this <code>Connections</code> object.
* @return <code>Map</code> of connections
*/
public Map<String, Connection> getConnections(){
return connections;
}
/**
* Removes a connection from the map of connections
* @param connection connection to be removed
*/
public void removeConnection(Connection connection){
connections.remove(connection.handle());
persistence.deleteConnection(connection);
}
/**
* Updates an existing connection within the map of
* connections as well as in the persisted model
* @param connection connection to be updated.
*/
public void updateConnection(Connection connection){
connections.put(connection.handle(), connection);
try{
persistence.updateConnection(connection);
} catch(PersistenceException e){
// TODO - Handle this update error
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
94354b3f59411882063eae03267f2cff6aa15fa5 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/28/28_b1e872236a38312c03dfb4ebeeaea6f2b1e88129/VideoCamera/28_b1e872236a38312c03dfb4ebeeaea6f2b1e88129_VideoCamera_t.java | 9b451ae8f7798c8e27cfa1d867961797a33f7d1a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 109,132 | java | /*
* Copyright (C) 2007 The Android Open Source 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 com.android.camera;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CamcorderProfile;
import android.media.CameraProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.camera.ui.CameraPicker;
import com.android.camera.ui.IndicatorControlContainer;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.PreviewSurfaceView;
import com.android.camera.ui.Rotatable;
import com.android.camera.ui.RotateImageView;
import com.android.camera.ui.RotateLayout;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.ui.TwoStateImageView;
import com.android.camera.ui.ZoomControl;
import com.android.gallery3d.common.ApiHelper;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/**
* The Camcorder activity.
*/
public class VideoCamera extends ActivityBase
implements CameraPreference.OnPreferenceChangedListener,
ShutterButton.OnShutterButtonListener, MediaRecorder.OnErrorListener,
MediaRecorder.OnInfoListener, ModePicker.OnModeChangeListener,
EffectsRecorder.EffectsListener {
private static final String TAG = "videocamera";
// We number the request code from 1000 to avoid collision with Gallery.
private static final int REQUEST_EFFECT_BACKDROPPER = 1000;
private static final int CHECK_DISPLAY_ROTATION = 3;
private static final int CLEAR_SCREEN_DELAY = 4;
private static final int UPDATE_RECORD_TIME = 5;
private static final int ENABLE_SHUTTER_BUTTON = 6;
private static final int SHOW_TAP_TO_SNAPSHOT_TOAST = 7;
private static final int SWITCH_CAMERA = 8;
private static final int SWITCH_CAMERA_START_ANIMATION = 9;
private static final int SHRINK_SURFACE_VIEW = 10;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private static final long SHUTTER_BUTTON_TIMEOUT = 500L; // 500ms
/**
* An unpublished intent flag requesting to start recording straight away
* and return as soon as recording is stopped.
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
private boolean mSnapshotInProgress = false;
private static final String EFFECT_BG_FROM_GALLERY = "gallery";
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private ComboPreferences mPreferences;
private PreferenceGroup mPreferenceGroup;
private PreviewFrameLayout mPreviewFrameLayout;
private boolean mSurfaceViewReady;
private SurfaceHolder.Callback mSurfaceViewCallback;
private PreviewSurfaceView mPreviewSurfaceView;
private CameraScreenNail.OnFrameDrawnListener mFrameDrawnListener;
private IndicatorControlContainer mIndicatorControlContainer;
private View mReviewControl;
private RotateDialogController mRotateDialog;
// An review image having same size as preview. It is displayed when
// recording is stopped in capture intent.
private ImageView mReviewImage;
private Rotatable mReviewCancelButton;
private Rotatable mReviewDoneButton;
private RotateImageView mReviewPlayButton;
private View mReviewRetakeButton;
private ModePicker mModePicker;
private ShutterButton mShutterButton;
private TextView mRecordingTimeView;
private RotateLayout mBgLearningMessageRotater;
private View mBgLearningMessageFrame;
private LinearLayout mLabelsLinearLayout;
private boolean mIsVideoCaptureIntent;
private boolean mQuickCapture;
private MediaRecorder mMediaRecorder;
private EffectsRecorder mEffectsRecorder;
private boolean mEffectsDisplayResult;
private int mEffectType = EffectsRecorder.EFFECT_NONE;
private Object mEffectParameter = null;
private String mEffectUriFromGallery = null;
private String mPrefVideoEffectDefault;
private boolean mResetEffect = true;
private boolean mSwitchingCamera;
private boolean mMediaRecorderRecording = false;
private long mRecordingStartTime;
private boolean mRecordingTimeCountsDown = false;
private RotateLayout mRecordingTimeRect;
private long mOnResumeTime;
// The video file that the hardware camera is about to record into
// (or is recording into.)
private String mVideoFilename;
private ParcelFileDescriptor mVideoFileDescriptor;
// The video file that has already been recorded, and that is being
// examined by the user.
private String mCurrentVideoFilename;
private Uri mCurrentVideoUri;
private ContentValues mCurrentVideoValues;
private CamcorderProfile mProfile;
// The video duration limit. 0 menas no limit.
private int mMaxVideoDurationInMs;
// Time Lapse parameters.
private boolean mCaptureTimeLapse = false;
// Default 0. If it is larger than 0, the camcorder is in time lapse mode.
private int mTimeBetweenTimeLapseFrameCaptureMs = 0;
private View mTimeLapseLabel;
private int mDesiredPreviewWidth;
private int mDesiredPreviewHeight;
boolean mPreviewing = false; // True if preview is started.
// The display rotation in degrees. This is only valid when mPreviewing is
// true.
private int mDisplayRotation;
private int mCameraDisplayOrientation;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private VideoNamer mVideoNamer;
private final Handler mHandler = new MainHandler();
private MyOrientationEventListener mOrientationListener;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// The orientation compensation for icons and thumbnails. Ex: if the value
// is 90, the UI components should be rotated 90 degrees counter-clockwise.
private int mOrientationCompensation = 0;
// The orientation compensation when we start recording.
private int mOrientationCompensationAtRecordStart;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private ZoomControl mZoomControl;
private boolean mRestoreFlash; // This is used to check if we need to restore the flash
// status when going back from gallery.
// This Handler is used to post message back onto the main thread of the
// application
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ENABLE_SHUTTER_BUTTON:
mShutterButton.setEnabled(true);
break;
case CLEAR_SCREEN_DELAY: {
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case UPDATE_RECORD_TIME: {
updateRecordingTime();
break;
}
case CHECK_DISPLAY_ROTATION: {
// Restart the preview if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if ((Util.getDisplayRotation(VideoCamera.this) != mDisplayRotation)
&& !mMediaRecorderRecording && !mSwitchingCamera) {
startPreview();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_SNAPSHOT_TOAST: {
showTapToSnapshotToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
((CameraScreenNail) mCameraScreenNail).animateSwitchCamera();
// Enable all camera controls.
mSwitchingCamera = false;
break;
}
case SHRINK_SURFACE_VIEW: {
mPreviewSurfaceView.shrink();
break;
}
default:
Log.v(TAG, "Unhandled message: " + msg.what);
break;
}
}
}
private BroadcastReceiver mReceiver = null;
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
stopVideoRecording();
} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
Toast.makeText(VideoCamera.this,
getResources().getString(R.string.wait), Toast.LENGTH_LONG).show();
}
}
}
private String createName(long dateTaken) {
Date date = new Date(dateTaken);
SimpleDateFormat dateFormat = new SimpleDateFormat(
getString(R.string.video_file_name_format));
return dateFormat.format(date);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = Util.getCameraFacingIntentExtras(this);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
private void initializeSurfaceView() {
mPreviewSurfaceView = (PreviewSurfaceView) findViewById(R.id.preview_surface_view);
if (!ApiHelper.HAS_SURFACE_TEXTURE) { // API level < 11
if (mSurfaceViewCallback == null) {
mSurfaceViewCallback = new SurfaceViewCallback();
}
mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback);
mPreviewSurfaceView.setVisibility(View.VISIBLE);
} else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) { // API level < 16
if (mSurfaceViewCallback == null) {
mSurfaceViewCallback = new SurfaceViewCallback();
mFrameDrawnListener = new CameraScreenNail.OnFrameDrawnListener() {
@Override
public void onFrameDrawn(CameraScreenNail c) {
mHandler.sendEmptyMessage(SHRINK_SURFACE_VIEW);
}
};
}
mPreviewSurfaceView.getHolder().addCallback(mSurfaceViewCallback);
mPreviewSurfaceView.setVisibility(View.VISIBLE);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreferences = new ComboPreferences(this);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mPreferences.setLocalId(this, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
mPrefVideoEffectDefault = getString(R.string.pref_video_effect_default);
resetEffect();
/*
* To reduce startup time, we start the preview in another thread.
* We make sure the preview is started at the end of onCreate.
*/
CameraOpenThread cameraOpenThread = new CameraOpenThread();
cameraOpenThread.start();
mContentResolver = getContentResolver();
setContentView(R.layout.video_camera);
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsVideoCaptureIntent = isVideoCaptureIntent();
createCameraScreenNail(!mIsVideoCaptureIntent);
initializeSurfaceView();
// Make sure camera device is opened.
try {
cameraOpenThread.join();
if (mOpenCameraFail) {
Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
return;
} else if (mCameraDisabled) {
Util.showErrorAndFinish(this, R.string.camera_disabled);
return;
}
} catch (InterruptedException ex) {
// ignore
}
Thread startPreviewThread = new Thread(new Runnable() {
@Override
public void run() {
readVideoPreferences();
startPreview();
}
});
startPreviewThread.start();
initializeControlByIntent();
initializeMiscControls();
mRotateDialog = new RotateDialogController(this, R.layout.rotate_dialog);
mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
mOrientationListener = new MyOrientationEventListener(this);
mLocationManager = new LocationManager(this, null);
// Make sure preview is started.
try {
startPreviewThread.join();
if (mOpenCameraFail) {
Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
return;
} else if (mCameraDisabled) {
Util.showErrorAndFinish(this, R.string.camera_disabled);
return;
}
} catch (InterruptedException ex) {
// ignore
}
showTimeLapseUI(mCaptureTimeLapse);
initializeVideoSnapshot();
resizeForPreviewAspectRatio();
initializeIndicatorControl();
}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(this, mParameters,
mCameraId, CameraHolder.instance().getCameraInfo());
// Remove the video quality preference setting when the quality is given in the intent.
mPreferenceGroup = filterPreferenceScreenByIntent(
settings.getPreferenceGroup(R.xml.video_preferences));
}
private boolean collapseCameraControls() {
if ((mIndicatorControlContainer != null)
&& mIndicatorControlContainer.dismissSettingPopup()) {
return true;
}
if (mModePicker != null && mModePicker.dismissModeSelection()) return true;
return false;
}
private void enableCameraControls(boolean enable) {
if (mIndicatorControlContainer != null) {
mIndicatorControlContainer.setEnabled(enable);
}
if (mModePicker != null) mModePicker.setEnabled(enable);
}
private void initializeIndicatorControl() {
mIndicatorControlContainer =
(IndicatorControlContainer) findViewById(R.id.indicator_control);
if (mIndicatorControlContainer == null) return;
loadCameraPreferences();
final String[] SETTING_KEYS = {
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
CameraSettings.KEY_WHITE_BALANCE,
CameraSettings.KEY_VIDEO_EFFECT,
CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL,
CameraSettings.KEY_VIDEO_QUALITY};
final String[] OTHER_SETTING_KEYS = {
CameraSettings.KEY_RECORD_LOCATION};
CameraPicker.setImageResourceId(R.drawable.ic_switch_video_facing_holo_light);
mIndicatorControlContainer.initialize(this, mPreferenceGroup,
mParameters.isZoomSupported(), SETTING_KEYS, OTHER_SETTING_KEYS);
mIndicatorControlContainer.setListener(this);
mCameraPicker = (CameraPicker) mIndicatorControlContainer.findViewById(
R.id.camera_picker);
if (effectsActive()) {
mIndicatorControlContainer.overrideSettings(
CameraSettings.KEY_VIDEO_QUALITY,
Integer.toString(getLowVideoQuality()));
}
}
@TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
private static int getLowVideoQuality() {
if (ApiHelper.HAS_FINE_RESOLUTION_QUALITY_LEVELS) {
return CamcorderProfile.QUALITY_480P;
} else {
return CamcorderProfile.QUALITY_LOW;
}
}
private class MyOrientationEventListener
extends OrientationEventListener {
public MyOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == ORIENTATION_UNKNOWN) return;
int newOrientation = Util.roundOrientation(orientation, mOrientation);
if (mOrientation != newOrientation) {
mOrientation = newOrientation;
// The input of effects recorder is affected by
// android.hardware.Camera.setDisplayOrientation. Its value only
// compensates the camera orientation (no Display.getRotation).
// So the orientation hint here should only consider sensor
// orientation.
if (effectsActive()) {
mEffectsRecorder.setOrientationHint(mOrientation);
}
}
// When the screen is unlocked, display rotation may change. Always
// calculate the up-to-date orientationCompensation.
int orientationCompensation =
(mOrientation + Util.getDisplayRotation(VideoCamera.this)) % 360;
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
// Do not rotate the icons during recording because the video
// orientation is fixed after recording.
if (!mMediaRecorderRecording) {
setOrientationIndicator(mOrientationCompensation, true);
}
}
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_SNAPSHOT_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_SNAPSHOT_TOAST);
showTapToSnapshotToast();
}
}
}
private void setOrientationIndicator(int orientation, boolean animation) {
Rotatable[] indicators = {mThumbnailView, mModePicker,
mBgLearningMessageRotater, mIndicatorControlContainer,
mReviewDoneButton, mReviewPlayButton, mRotateDialog};
for (Rotatable indicator : indicators) {
if (indicator != null) indicator.setOrientation(orientation, animation);
}
// We change the orientation of the review cancel button only for tablet
// UI because there's a label along with the X icon. For phone UI, we
// don't change the orientation because there's only a symmetrical X
// icon.
if (mReviewCancelButton instanceof RotateLayout) {
mReviewCancelButton.setOrientation(orientation, animation);
}
// We change the orientation of the linearlayout only for phone UI because when in portrait
// the width is not enough.
if (mLabelsLinearLayout != null) {
if (((orientation / 90) & 1) == 0) {
mLabelsLinearLayout.setOrientation(LinearLayout.VERTICAL);
} else {
mLabelsLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
}
}
mRecordingTimeRect.setOrientation(mOrientationCompensation, animation);
}
private void startPlayVideoActivity() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(mCurrentVideoUri, convertOutputFormatToMimeType(mProfile.fileFormat));
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "Couldn't view video " + mCurrentVideoUri, ex);
}
}
@OnClickAttr
public void onThumbnailClicked(View v) {
if (!mMediaRecorderRecording && mThumbnail != null
&& !mSwitchingCamera) {
gotoGallery();
}
}
@OnClickAttr
public void onReviewRetakeClicked(View v) {
deleteCurrentVideo();
hideAlert();
}
@OnClickAttr
public void onReviewPlayClicked(View v) {
startPlayVideoActivity();
}
@OnClickAttr
public void onReviewDoneClicked(View v) {
doReturnToCaller(true);
}
@OnClickAttr
public void onReviewCancelClicked(View v) {
stopVideoRecording();
doReturnToCaller(false);
}
private void onStopVideoRecording() {
mEffectsDisplayResult = true;
boolean recordFail = stopVideoRecording();
if (mIsVideoCaptureIntent) {
if (!effectsActive()) {
if (mQuickCapture) {
doReturnToCaller(!recordFail);
} else if (!recordFail) {
showAlert();
}
}
} else if (!recordFail){
// Start capture animation.
if (!mPaused && ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
// The capture animation is disabled on ICS because we use SurfaceView
// for preview during recording. When the recording is done, we switch
// back to use SurfaceTexture for preview and we need to stop then start
// the preview. This will cause the preview flicker since the preview
// will not be continuous for a short period of time.
((CameraScreenNail) mCameraScreenNail).animateCapture(getCameraRotation());
}
if (!effectsActive()) getThumbnail();
}
}
private int getCameraRotation() {
return (mOrientationCompensation - mDisplayRotation + 360) % 360;
}
public void onProtectiveCurtainClick(View v) {
// Consume clicks
}
@Override
public void onShutterButtonClick() {
if (collapseCameraControls() || mSwitchingCamera) return;
boolean stop = mMediaRecorderRecording;
if (stop) {
onStopVideoRecording();
} else {
startVideoRecording();
}
mShutterButton.setEnabled(false);
// Keep the shutter button disabled when in video capture intent
// mode and recording is stopped. It'll be re-enabled when
// re-take button is clicked.
if (!(mIsVideoCaptureIntent && stop)) {
mHandler.sendEmptyMessageDelayed(
ENABLE_SHUTTER_BUTTON, SHUTTER_BUTTON_TIMEOUT);
}
}
@Override
public void onShutterButtonFocus(boolean pressed) {
// Do nothing (everything happens in onShutterButtonClick).
}
private void readVideoPreferences() {
// The preference stores values from ListPreference and is thus string type for all values.
// We need to convert it to int manually.
String defaultQuality = CameraSettings.getDefaultVideoQuality(mCameraId,
getResources().getString(R.string.pref_video_quality_default));
String videoQuality =
mPreferences.getString(CameraSettings.KEY_VIDEO_QUALITY,
defaultQuality);
int quality = Integer.valueOf(videoQuality);
// Set video quality.
Intent intent = getIntent();
if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
int extraVideoQuality =
intent.getIntExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
if (extraVideoQuality > 0) {
quality = CamcorderProfile.QUALITY_HIGH;
} else { // 0 is mms.
quality = CamcorderProfile.QUALITY_LOW;
}
}
// Set video duration limit. The limit is read from the preference,
// unless it is specified in the intent.
if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
int seconds =
intent.getIntExtra(MediaStore.EXTRA_DURATION_LIMIT, 0);
mMaxVideoDurationInMs = 1000 * seconds;
} else {
mMaxVideoDurationInMs = CameraSettings.DEFAULT_VIDEO_DURATION;
}
// Set effect
mEffectType = CameraSettings.readEffectType(mPreferences);
if (mEffectType != EffectsRecorder.EFFECT_NONE) {
mEffectParameter = CameraSettings.readEffectParameter(mPreferences);
// Set quality to be no higher than 480p.
CamcorderProfile profile = CamcorderProfile.get(mCameraId, quality);
if (profile.videoFrameHeight > 480) {
quality = getLowVideoQuality();
}
// On initial startup, can get here before indicator control is
// enabled. In that case, UI quality override handled in
// initializeIndicatorControl.
if (mIndicatorControlContainer != null) {
mIndicatorControlContainer.overrideSettings(
CameraSettings.KEY_VIDEO_QUALITY,
Integer.toString(getLowVideoQuality()));
}
} else {
mEffectParameter = null;
if (mIndicatorControlContainer != null) {
mIndicatorControlContainer.overrideSettings(
CameraSettings.KEY_VIDEO_QUALITY,
null);
}
}
// Read time lapse recording interval.
if (ApiHelper.HAS_TIME_LAPSE_RECORDING) {
String frameIntervalStr = mPreferences.getString(
CameraSettings.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL,
getString(R.string.pref_video_time_lapse_frame_interval_default));
mTimeBetweenTimeLapseFrameCaptureMs = Integer.parseInt(frameIntervalStr);
mCaptureTimeLapse = (mTimeBetweenTimeLapseFrameCaptureMs != 0);
}
// TODO: This should be checked instead directly +1000.
if (mCaptureTimeLapse) quality += 1000;
mProfile = CamcorderProfile.get(mCameraId, quality);
getDesiredPreviewSize();
}
private void writeDefaultEffectToPrefs() {
ComboPreferences.Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_VIDEO_EFFECT,
getString(R.string.pref_video_effect_default));
editor.apply();
}
@TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
private void getDesiredPreviewSize() {
mParameters = mCameraDevice.getParameters();
if (ApiHelper.HAS_GET_SUPPORTED_VIDEO_SIZE) {
if (mParameters.getSupportedVideoSizes() == null || effectsActive()) {
mDesiredPreviewWidth = mProfile.videoFrameWidth;
mDesiredPreviewHeight = mProfile.videoFrameHeight;
} else { // Driver supports separates outputs for preview and video.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size preferred = mParameters.getPreferredPreviewSizeForVideo();
int product = preferred.width * preferred.height;
Iterator<Size> it = sizes.iterator();
// Remove the preview sizes that are not preferred.
while (it.hasNext()) {
Size size = it.next();
if (size.width * size.height > product) {
it.remove();
}
}
Size optimalSize = Util.getOptimalPreviewSize(this, sizes,
(double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
mDesiredPreviewWidth = optimalSize.width;
mDesiredPreviewHeight = optimalSize.height;
}
} else {
mDesiredPreviewWidth = mProfile.videoFrameWidth;
mDesiredPreviewHeight = mProfile.videoFrameHeight;
}
Log.v(TAG, "mDesiredPreviewWidth=" + mDesiredPreviewWidth +
". mDesiredPreviewHeight=" + mDesiredPreviewHeight);
}
private void resizeForPreviewAspectRatio() {
mPreviewFrameLayout.setAspectRatio(
(double) mProfile.videoFrameWidth / mProfile.videoFrameHeight);
}
@Override
protected void installIntentFilter() {
super.installIntentFilter();
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_EJECT);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter.addDataScheme("file");
mReceiver = new MyBroadcastReceiver();
registerReceiver(mReceiver, intentFilter);
}
@Override
protected void onResume() {
mPaused = false;
super.onResume();
if (mOpenCameraFail || mCameraDisabled) return;
mZoomValue = 0;
showVideoSnapshotUI(false);
// Start orientation listener as soon as possible because it takes
// some time to get first orientation.
mOrientationListener.enable();
if (!mPreviewing) {
if (resetEffect()) {
mBgLearningMessageFrame.setVisibility(View.GONE);
mIndicatorControlContainer.reloadPreferences();
}
CameraOpenThread cameraOpenThread = new CameraOpenThread();
cameraOpenThread.start();
try {
cameraOpenThread.join();
if (mOpenCameraFail) {
Util.showErrorAndFinish(this, R.string.cannot_connect_camera);
return;
} else if (mCameraDisabled) {
Util.showErrorAndFinish(this, R.string.camera_disabled);
return;
}
} catch (InterruptedException ex) {
// ignore
}
readVideoPreferences();
resizeForPreviewAspectRatio();
startPreview();
}
// Initializing it here after the preview is started.
initializeZoom();
keepScreenOnAwhile();
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
if (!mIsVideoCaptureIntent) {
getLastThumbnail();
mModePicker.setCurrentMode(ModePicker.MODE_VIDEO);
}
if (mPreviewing) {
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
// Dismiss open menu if exists.
PopupManager.getInstance(this).notifyShowPopup(null);
mVideoNamer = new VideoNamer();
}
private void setDisplayOrientation() {
mDisplayRotation = Util.getDisplayRotation(this);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// The display rotation is handled by gallery.
mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
} else {
// We need to consider display rotation ourselves.
mCameraDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
}
}
private void startPreview() {
Log.v(TAG, "startPreview");
mCameraDevice.setErrorCallback(mErrorCallback);
if (mPreviewing == true) {
stopPreview();
if (effectsActive() && mEffectsRecorder != null) {
mEffectsRecorder.release();
mEffectsRecorder = null;
}
}
setDisplayOrientation();
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
setCameraParameters();
try {
if (!effectsActive()) {
if (ApiHelper.HAS_SURFACE_TEXTURE) {
mCameraDevice.setPreviewTextureAsync(
((CameraScreenNail) mCameraScreenNail).getSurfaceTexture());
} else {
mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
}
mCameraDevice.startPreviewAsync();
} else {
initializeEffectsPreview();
mEffectsRecorder.startPreview();
}
} catch (Throwable ex) {
closeCamera();
throw new RuntimeException("startPreview failed", ex);
}
mPreviewing = true;
}
private void stopPreview() {
mCameraDevice.stopPreview();
mPreviewing = false;
}
// Closing the effects out. Will shut down the effects graph.
private void closeEffects() {
Log.v(TAG, "Closing effects");
mEffectType = EffectsRecorder.EFFECT_NONE;
if (mEffectsRecorder == null) {
Log.d(TAG, "Effects are already closed. Nothing to do");
return;
}
// This call can handle the case where the camera is already released
// after the recording has been stopped.
mEffectsRecorder.release();
mEffectsRecorder = null;
}
// By default, we want to close the effects as well with the camera.
private void closeCamera() {
closeCamera(true);
}
// In certain cases, when the effects are active, we may want to shutdown
// only the camera related parts, and handle closing the effects in the
// effectsUpdate callback.
// For example, in onPause, we want to make the camera available to
// outside world immediately, however, want to wait till the effects
// callback to shut down the effects. In such a case, we just disconnect
// the effects from the camera by calling disconnectCamera. That way
// the effects can handle that when shutting down.
//
// @param closeEffectsAlso - indicates whether we want to close the
// effects also along with the camera.
private void closeCamera(boolean closeEffectsAlso) {
Log.v(TAG, "closeCamera");
if (mCameraDevice == null) {
Log.d(TAG, "already stopped.");
return;
}
if (mEffectsRecorder != null) {
// Disconnect the camera from effects so that camera is ready to
// be released to the outside world.
mEffectsRecorder.disconnectCamera();
}
if (closeEffectsAlso) closeEffects();
mCameraDevice.setZoomChangeListener(null);
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mCameraDevice = null;
mPreviewing = false;
mSnapshotInProgress = false;
}
private void releasePreviewResources() {
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail;
if (screenNail.getSurfaceTexture() != null) {
screenNail.releaseSurfaceTexture();
}
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
mHandler.removeMessages(SHRINK_SURFACE_VIEW);
}
}
}
@Override
protected void onPause() {
mPaused = true;
if (mMediaRecorderRecording) {
// Camera will be released in onStopVideoRecording.
onStopVideoRecording();
} else {
closeCamera();
if (!effectsActive()) releaseMediaRecorder();
}
if (effectsActive()) {
// If the effects are active, make sure we tell the graph that the
// surfacetexture is not valid anymore. Disconnect the graph from
// the display. This should be done before releasing the surface
// texture.
mEffectsRecorder.disconnectDisplay();
} else {
// Close the file descriptor and clear the video namer only if the
// effects are not active. If effects are active, we need to wait
// till we get the callback from the Effects that the graph is done
// recording. That also needs a change in the stopVideoRecording()
// call to not call closeCamera if the effects are active, because
// that will close down the effects are well, thus making this if
// condition invalid.
closeVideoFileDescriptor();
clearVideoNamer();
}
releasePreviewResources();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
resetScreenOn();
if (mIndicatorControlContainer != null) {
mIndicatorControlContainer.dismissSettingPopup();
}
if (mOrientationListener != null) mOrientationListener.disable();
if (mLocationManager != null) mLocationManager.recordLocation(false);
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mPendingSwitchCameraId = -1;
mSwitchingCamera = false;
// Call onPause after stopping video recording. So the camera can be
// released as soon as possible.
super.onPause();
}
@Override
public void onUserInteraction() {
super.onUserInteraction();
if (!mMediaRecorderRecording && !isFinishing()) keepScreenOnAwhile();
}
@Override
public void onBackPressed() {
if (mPaused) return;
if (mMediaRecorderRecording) {
onStopVideoRecording();
} else if (!collapseCameraControls()) {
super.onBackPressed();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Do not handle any key if the activity is paused.
if (mPaused) {
return true;
}
switch (keyCode) {
case KeyEvent.KEYCODE_CAMERA:
if (event.getRepeatCount() == 0) {
mShutterButton.performClick();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (event.getRepeatCount() == 0) {
mShutterButton.performClick();
return true;
}
break;
case KeyEvent.KEYCODE_MENU:
if (mMediaRecorderRecording) return true;
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_CAMERA:
mShutterButton.setPressed(false);
return true;
}
return super.onKeyUp(keyCode, event);
}
private boolean isVideoCaptureIntent() {
String action = getIntent().getAction();
return (MediaStore.ACTION_VIDEO_CAPTURE.equals(action));
}
private void doReturnToCaller(boolean valid) {
Intent resultIntent = new Intent();
int resultCode;
if (valid) {
resultCode = RESULT_OK;
resultIntent.setData(mCurrentVideoUri);
} else {
resultCode = RESULT_CANCELED;
}
setResultEx(resultCode, resultIntent);
finish();
}
private void cleanupEmptyFile() {
if (mVideoFilename != null) {
File f = new File(mVideoFilename);
if (f.length() == 0 && f.delete()) {
Log.v(TAG, "Empty video file deleted: " + mVideoFilename);
mVideoFilename = null;
}
}
}
private void setupMediaRecorderPreviewDisplay() {
// Nothing to do here if using SurfaceTexture.
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface());
} else if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
// We stop the preview here before unlocking the device because we
// need to change the SurfaceTexture to SurfaceView for preview.
stopPreview();
mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
// The orientation for SurfaceTexture is different from that for
// SurfaceView. For SurfaceTexture we don't need to consider the
// display rotation. Just consider the sensor's orientation and we
// will set the orientation correctly when showing the texture.
// Gallery will handle the orientation for the preview. For
// SurfaceView we will have to take everything into account so the
// display rotation is considered.
mCameraDevice.setDisplayOrientation(
Util.getDisplayOrientation(mDisplayRotation, mCameraId));
mCameraDevice.startPreviewAsync();
mPreviewing = true;
mMediaRecorder.setPreviewDisplay(mPreviewSurfaceView.getHolder().getSurface());
}
}
// Prepares media recorder.
private void initializeRecorder() {
Log.v(TAG, "initializeRecorder");
// If the mCameraDevice is null, then this activity is going to finish
if (mCameraDevice == null) return;
if (!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING && ApiHelper.HAS_SURFACE_TEXTURE) {
mPreviewSurfaceView.expand();
if (!mSurfaceViewReady) {
Log.e(TAG, "Surface view is not ready");
return;
}
}
Intent intent = getIntent();
Bundle myExtras = intent.getExtras();
long requestedSizeLimit = 0;
closeVideoFileDescriptor();
if (mIsVideoCaptureIntent && myExtras != null) {
Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
if (saveUri != null) {
try {
mVideoFileDescriptor =
mContentResolver.openFileDescriptor(saveUri, "rw");
mCurrentVideoUri = saveUri;
} catch (java.io.FileNotFoundException ex) {
// invalid uri
Log.e(TAG, ex.toString());
}
}
requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
}
mMediaRecorder = new MediaRecorder();
setupMediaRecorderPreviewDisplay();
// Unlock the camera object before passing it to media recorder.
mCameraDevice.unlock();
mMediaRecorder.setCamera(mCameraDevice.getCamera());
if (!mCaptureTimeLapse) {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
}
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(mProfile);
mMediaRecorder.setMaxDuration(mMaxVideoDurationInMs);
if (mCaptureTimeLapse) {
double fps = 1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs;
setCaptureRate(mMediaRecorder, fps);
}
setRecordLocation();
// Set output file.
// Try Uri in the intent first. If it doesn't exist, use our own
// instead.
if (mVideoFileDescriptor != null) {
mMediaRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
} else {
generateVideoFilename(mProfile.fileFormat);
mMediaRecorder.setOutputFile(mVideoFilename);
}
// Set maximum file size.
long maxFileSize = getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD;
if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
maxFileSize = requestedSizeLimit;
}
try {
mMediaRecorder.setMaxFileSize(maxFileSize);
} catch (RuntimeException exception) {
// We are going to ignore failure of setMaxFileSize here, as
// a) The composer selected may simply not support it, or
// b) The underlying media framework may not handle 64-bit range
// on the size restriction.
}
// See android.hardware.Camera.Parameters.setRotation for
// documentation.
// Note that mOrientation here is the device orientation, which is the opposite of
// what activity.getWindowManager().getDefaultDisplay().getRotation() would return,
// which is the orientation the graphics need to rotate in order to render correctly.
int rotation = 0;
if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - mOrientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + mOrientation) % 360;
}
}
mMediaRecorder.setOrientationHint(rotation);
mOrientationCompensationAtRecordStart = mOrientationCompensation;
try {
mMediaRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "prepare failed for " + mVideoFilename, e);
releaseMediaRecorder();
throw new RuntimeException(e);
}
mMediaRecorder.setOnErrorListener(this);
mMediaRecorder.setOnInfoListener(this);
}
@TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB)
private static void setCaptureRate(MediaRecorder recorder, double fps) {
recorder.setCaptureRate(fps);
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setRecordLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Location loc = mLocationManager.getCurrentLocation();
if (loc != null) {
mMediaRecorder.setLocation((float) loc.getLatitude(),
(float) loc.getLongitude());
}
}
}
private void initializeEffectsPreview() {
Log.v(TAG, "initializeEffectsPreview");
// If the mCameraDevice is null, then this activity is going to finish
if (mCameraDevice == null) return;
boolean inLandscape = (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mEffectsDisplayResult = false;
mEffectsRecorder = new EffectsRecorder(this);
// TODO: Confirm none of the following need to go to initializeEffectsRecording()
// and none of these change even when the preview is not refreshed.
mEffectsRecorder.setCameraDisplayOrientation(mCameraDisplayOrientation);
mEffectsRecorder.setCamera(mCameraDevice);
mEffectsRecorder.setCameraFacing(info.facing);
mEffectsRecorder.setProfile(mProfile);
mEffectsRecorder.setEffectsListener(this);
mEffectsRecorder.setOnInfoListener(this);
mEffectsRecorder.setOnErrorListener(this);
// The input of effects recorder is affected by
// android.hardware.Camera.setDisplayOrientation. Its value only
// compensates the camera orientation (no Display.getRotation). So the
// orientation hint here should only consider sensor orientation.
int orientation = 0;
if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
orientation = mOrientation;
}
mEffectsRecorder.setOrientationHint(orientation);
mOrientationCompensationAtRecordStart = mOrientationCompensation;
CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail;
mEffectsRecorder.setPreviewSurfaceTexture(screenNail.getSurfaceTexture(),
screenNail.getWidth(), screenNail.getHeight());
if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER &&
((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) {
mEffectsRecorder.setEffect(mEffectType, mEffectUriFromGallery);
} else {
mEffectsRecorder.setEffect(mEffectType, mEffectParameter);
}
}
private void initializeEffectsRecording() {
Log.v(TAG, "initializeEffectsRecording");
Intent intent = getIntent();
Bundle myExtras = intent.getExtras();
long requestedSizeLimit = 0;
closeVideoFileDescriptor();
if (mIsVideoCaptureIntent && myExtras != null) {
Uri saveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
if (saveUri != null) {
try {
mVideoFileDescriptor =
mContentResolver.openFileDescriptor(saveUri, "rw");
mCurrentVideoUri = saveUri;
} catch (java.io.FileNotFoundException ex) {
// invalid uri
Log.e(TAG, ex.toString());
}
}
requestedSizeLimit = myExtras.getLong(MediaStore.EXTRA_SIZE_LIMIT);
}
mEffectsRecorder.setProfile(mProfile);
// important to set the capture rate to zero if not timelapsed, since the
// effectsrecorder object does not get created again for each recording
// session
if (mCaptureTimeLapse) {
mEffectsRecorder.setCaptureRate((1000 / (double) mTimeBetweenTimeLapseFrameCaptureMs));
} else {
mEffectsRecorder.setCaptureRate(0);
}
// Set output file
if (mVideoFileDescriptor != null) {
mEffectsRecorder.setOutputFile(mVideoFileDescriptor.getFileDescriptor());
} else {
generateVideoFilename(mProfile.fileFormat);
mEffectsRecorder.setOutputFile(mVideoFilename);
}
// Set maximum file size.
long maxFileSize = getStorageSpace() - Storage.LOW_STORAGE_THRESHOLD;
if (requestedSizeLimit > 0 && requestedSizeLimit < maxFileSize) {
maxFileSize = requestedSizeLimit;
}
mEffectsRecorder.setMaxFileSize(maxFileSize);
mEffectsRecorder.setMaxDuration(mMaxVideoDurationInMs);
}
private void releaseMediaRecorder() {
Log.v(TAG, "Releasing media recorder.");
if (mMediaRecorder != null) {
cleanupEmptyFile();
mMediaRecorder.reset();
mMediaRecorder.release();
mMediaRecorder = null;
}
mVideoFilename = null;
}
private void releaseEffectsRecorder() {
Log.v(TAG, "Releasing effects recorder.");
if (mEffectsRecorder != null) {
cleanupEmptyFile();
mEffectsRecorder.release();
mEffectsRecorder = null;
}
mEffectType = EffectsRecorder.EFFECT_NONE;
mVideoFilename = null;
}
private void generateVideoFilename(int outputFileFormat) {
long dateTaken = System.currentTimeMillis();
String title = createName(dateTaken);
// Used when emailing.
String filename = title + convertOutputFormatToFileExt(outputFileFormat);
String mime = convertOutputFormatToMimeType(outputFileFormat);
String path = Storage.DIRECTORY + '/' + filename;
String tmpPath = path + ".tmp";
mCurrentVideoValues = new ContentValues(7);
mCurrentVideoValues.put(Video.Media.TITLE, title);
mCurrentVideoValues.put(Video.Media.DISPLAY_NAME, filename);
mCurrentVideoValues.put(Video.Media.DATE_TAKEN, dateTaken);
mCurrentVideoValues.put(Video.Media.MIME_TYPE, mime);
mCurrentVideoValues.put(Video.Media.DATA, path);
mCurrentVideoValues.put(Video.Media.RESOLUTION,
Integer.toString(mProfile.videoFrameWidth) + "x" +
Integer.toString(mProfile.videoFrameHeight));
Location loc = mLocationManager.getCurrentLocation();
if (loc != null) {
mCurrentVideoValues.put(Video.Media.LATITUDE, loc.getLatitude());
mCurrentVideoValues.put(Video.Media.LONGITUDE, loc.getLongitude());
}
mVideoNamer.prepareUri(mContentResolver, mCurrentVideoValues);
mVideoFilename = tmpPath;
Log.v(TAG, "New video filename: " + mVideoFilename);
}
private boolean addVideoToMediaStore() {
boolean fail = false;
if (mVideoFileDescriptor == null) {
mCurrentVideoValues.put(Video.Media.SIZE,
new File(mCurrentVideoFilename).length());
long duration = SystemClock.uptimeMillis() - mRecordingStartTime;
if (duration > 0) {
if (mCaptureTimeLapse) {
duration = getTimeLapseVideoLength(duration);
}
mCurrentVideoValues.put(Video.Media.DURATION, duration);
} else {
Log.w(TAG, "Video duration <= 0 : " + duration);
}
try {
mCurrentVideoUri = mVideoNamer.getUri();
addSecureAlbumItemIfNeeded(true, mCurrentVideoUri);
// Rename the video file to the final name. This avoids other
// apps reading incomplete data. We need to do it after the
// above mVideoNamer.getUri() call, so we are certain that the
// previous insert to MediaProvider is completed.
String finalName = mCurrentVideoValues.getAsString(
Video.Media.DATA);
if (new File(mCurrentVideoFilename).renameTo(new File(finalName))) {
mCurrentVideoFilename = finalName;
}
mContentResolver.update(mCurrentVideoUri, mCurrentVideoValues
, null, null);
sendBroadcast(new Intent(Util.ACTION_NEW_VIDEO,
mCurrentVideoUri));
} catch (Exception e) {
// We failed to insert into the database. This can happen if
// the SD card is unmounted.
Log.e(TAG, "failed to add video to media store", e);
mCurrentVideoUri = null;
mCurrentVideoFilename = null;
fail = true;
} finally {
Log.v(TAG, "Current video URI: " + mCurrentVideoUri);
}
}
mCurrentVideoValues = null;
return fail;
}
private void deleteCurrentVideo() {
// Remove the video and the uri if the uri is not passed in by intent.
if (mCurrentVideoFilename != null) {
deleteVideoFile(mCurrentVideoFilename);
mCurrentVideoFilename = null;
if (mCurrentVideoUri != null) {
mContentResolver.delete(mCurrentVideoUri, null, null);
mCurrentVideoUri = null;
}
}
updateStorageSpaceAndHint();
}
private void deleteVideoFile(String fileName) {
Log.v(TAG, "Deleting video " + fileName);
File f = new File(fileName);
if (!f.delete()) {
Log.v(TAG, "Could not delete " + fileName);
}
}
private PreferenceGroup filterPreferenceScreenByIntent(
PreferenceGroup screen) {
Intent intent = getIntent();
if (intent.hasExtra(MediaStore.EXTRA_VIDEO_QUALITY)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
if (intent.hasExtra(MediaStore.EXTRA_DURATION_LIMIT)) {
CameraSettings.removePreferenceFromScreen(screen,
CameraSettings.KEY_VIDEO_QUALITY);
}
return screen;
}
// from MediaRecorder.OnErrorListener
@Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "MediaRecorder error. what=" + what + ". extra=" + extra);
if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN) {
// We may have run out of space on the sdcard.
stopVideoRecording();
updateStorageSpaceAndHint();
}
}
// from MediaRecorder.OnInfoListener
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
} else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
if (mMediaRecorderRecording) onStopVideoRecording();
// Show the toast.
Toast.makeText(this, R.string.video_reach_size_limit,
Toast.LENGTH_LONG).show();
}
}
/*
* Make sure we're not recording music playing in the background, ask the
* MediaPlaybackService to pause playback.
*/
private void pauseAudioPlayback() {
// Shamelessly copied from MediaPlaybackService.java, which
// should be public, but isn't.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
sendBroadcast(i);
}
// For testing.
public boolean isRecording() {
return mMediaRecorderRecording;
}
private void startVideoRecording() {
Log.v(TAG, "startVideoRecording");
setSwipingEnabled(false);
updateStorageSpaceAndHint();
if (getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
Log.v(TAG, "Storage issue, ignore the start request");
return;
}
mCurrentVideoUri = null;
if (effectsActive()) {
initializeEffectsRecording();
if (mEffectsRecorder == null) {
Log.e(TAG, "Fail to initialize effect recorder");
return;
}
} else {
initializeRecorder();
if (mMediaRecorder == null) {
Log.e(TAG, "Fail to initialize media recorder");
return;
}
}
pauseAudioPlayback();
if (effectsActive()) {
try {
mEffectsRecorder.startRecording();
} catch (RuntimeException e) {
Log.e(TAG, "Could not start effects recorder. ", e);
releaseEffectsRecorder();
return;
}
} else {
try {
mMediaRecorder.start(); // Recording is now started
} catch (RuntimeException e) {
Log.e(TAG, "Could not start media recorder. ", e);
releaseMediaRecorder();
// If start fails, frameworks will not lock the camera for us.
mCameraDevice.lock();
return;
}
}
// The parameters may have been changed by MediaRecorder upon starting
// recording. We need to alter the parameters if we support camcorder
// zoom. To reduce latency when setting the parameters during zoom, we
// update mParameters here once.
if (ApiHelper.HAS_ZOOM_WHEN_RECORDING) {
mParameters = mCameraDevice.getParameters();
}
enableCameraControls(false);
mMediaRecorderRecording = true;
mRecordingStartTime = SystemClock.uptimeMillis();
showRecordingUI(true);
updateRecordingTime();
keepScreenOn();
}
private void showRecordingUI(boolean recording) {
if (recording) {
mIndicatorControlContainer.dismissSecondLevelIndicator();
if (mThumbnailView != null) mThumbnailView.setEnabled(false);
mShutterButton.setImageResource(R.drawable.btn_shutter_video_recording);
mRecordingTimeView.setText("");
mRecordingTimeView.setVisibility(View.VISIBLE);
if (mReviewControl != null) mReviewControl.setVisibility(View.GONE);
if (mCaptureTimeLapse) {
mIndicatorControlContainer.startTimeLapseAnimation(
mTimeBetweenTimeLapseFrameCaptureMs,
mRecordingStartTime);
}
// The camera is not allowed to be accessed in older api levels during
// recording. It is therefore necessary to hide the zoom UI on older
// platforms.
// See the documentation of android.media.MediaRecorder.start() for
// further explanation.
if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING
&& mParameters.isZoomSupported()) {
mZoomControl.setVisibility(View.GONE);
}
} else {
if (mThumbnailView != null) mThumbnailView.setEnabled(true);
mShutterButton.setImageResource(R.drawable.btn_shutter_video);
mRecordingTimeView.setVisibility(View.GONE);
if (mReviewControl != null) mReviewControl.setVisibility(View.VISIBLE);
if (mCaptureTimeLapse) {
mIndicatorControlContainer.stopTimeLapseAnimation();
}
if (!ApiHelper.HAS_ZOOM_WHEN_RECORDING
&& mParameters.isZoomSupported()) {
mZoomControl.setVisibility(View.VISIBLE);
}
}
}
private void getThumbnail() {
if (mCurrentVideoUri != null) {
Bitmap videoFrame = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename,
mThumbnailViewWidth);
if (videoFrame != null) {
mThumbnail = Thumbnail.createThumbnail(mCurrentVideoUri, videoFrame, 0);
mThumbnailView.setBitmap(mThumbnail.getBitmap());
}
}
}
private void showAlert() {
Bitmap bitmap = null;
if (mVideoFileDescriptor != null) {
bitmap = Thumbnail.createVideoThumbnailBitmap(mVideoFileDescriptor.getFileDescriptor(),
mPreviewFrameLayout.getWidth());
} else if (mCurrentVideoFilename != null) {
bitmap = Thumbnail.createVideoThumbnailBitmap(mCurrentVideoFilename,
mPreviewFrameLayout.getWidth());
}
if (bitmap != null) {
// MetadataRetriever already rotates the thumbnail. We should rotate
// it to match the UI orientation (and mirror if it is front-facing camera).
CameraInfo[] info = CameraHolder.instance().getCameraInfo();
boolean mirror = (info[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT);
bitmap = Util.rotateAndMirror(bitmap, -mOrientationCompensationAtRecordStart,
mirror);
mReviewImage.setImageBitmap(bitmap);
mReviewImage.setVisibility(View.VISIBLE);
}
Util.fadeOut(mShutterButton);
Util.fadeOut(mIndicatorControlContainer);
Util.fadeIn(mReviewRetakeButton);
Util.fadeIn((View) mReviewDoneButton);
Util.fadeIn(mReviewPlayButton);
showTimeLapseUI(false);
}
private void hideAlert() {
mReviewImage.setVisibility(View.GONE);
mShutterButton.setEnabled(true);
enableCameraControls(true);
Util.fadeOut((View) mReviewDoneButton);
Util.fadeOut(mReviewRetakeButton);
Util.fadeOut(mReviewPlayButton);
Util.fadeIn(mShutterButton);
Util.fadeIn(mIndicatorControlContainer);
if (mCaptureTimeLapse) {
showTimeLapseUI(true);
}
}
private boolean stopVideoRecording() {
Log.v(TAG, "stopVideoRecording");
setSwipingEnabled(true);
boolean fail = false;
if (mMediaRecorderRecording) {
boolean shouldAddToMediaStoreNow = false;
try {
if (effectsActive()) {
// This is asynchronous, so we can't add to media store now because thumbnail
// may not be ready. In such case addVideoToMediaStore is called later
// through a callback from the MediaEncoderFilter to EffectsRecorder,
// and then to the VideoCamera.
mEffectsRecorder.stopRecording();
} else {
mMediaRecorder.setOnErrorListener(null);
mMediaRecorder.setOnInfoListener(null);
mMediaRecorder.stop();
shouldAddToMediaStoreNow = true;
}
mCurrentVideoFilename = mVideoFilename;
Log.v(TAG, "stopVideoRecording: Setting current video filename: "
+ mCurrentVideoFilename);
} catch (RuntimeException e) {
Log.e(TAG, "stop fail", e);
if (mVideoFilename != null) deleteVideoFile(mVideoFilename);
fail = true;
}
mMediaRecorderRecording = false;
// If the activity is paused, this means activity is interrupted
// during recording. Release the camera as soon as possible because
// face unlock or other applications may need to use the camera.
// However, if the effects are active, then we can only release the
// camera and cannot release the effects recorder since that will
// stop the graph. It is possible to separate out the Camera release
// part and the effects release part. However, the effects recorder
// does hold on to the camera, hence, it needs to be "disconnected"
// from the camera in the closeCamera call.
if (mPaused) {
// Closing only the camera part if effects active. Effects will
// be closed in the callback from effects.
boolean closeEffects = !effectsActive();
closeCamera(closeEffects);
}
showRecordingUI(false);
if (!mIsVideoCaptureIntent) {
enableCameraControls(true);
}
// The orientation was fixed during video recording. Now make it
// reflect the device orientation as video recording is stopped.
setOrientationIndicator(mOrientationCompensation, true);
keepScreenOnAwhile();
if (shouldAddToMediaStoreNow) {
if (addVideoToMediaStore()) fail = true;
}
}
// always release media recorder if no effects running
if (!effectsActive()) {
releaseMediaRecorder();
if (!mPaused) {
mCameraDevice.lock();
if (ApiHelper.HAS_SURFACE_TEXTURE &&
!ApiHelper.HAS_SURFACE_TEXTURE_RECORDING) {
stopPreview();
// Switch back to use SurfaceTexture for preview.
((CameraScreenNail) mCameraScreenNail).setOneTimeOnFrameDrawnListener(
mFrameDrawnListener);
startPreview();
}
}
}
// Update the parameters here because the parameters might have been altered
// by MediaRecorder.
if (!mPaused) mParameters = mCameraDevice.getParameters();
return fail;
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
private void keepScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private static String millisecondToTimeString(long milliSeconds, boolean displayCentiSeconds) {
long seconds = milliSeconds / 1000; // round down to compute seconds
long minutes = seconds / 60;
long hours = minutes / 60;
long remainderMinutes = minutes - (hours * 60);
long remainderSeconds = seconds - (minutes * 60);
StringBuilder timeStringBuilder = new StringBuilder();
// Hours
if (hours > 0) {
if (hours < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(hours);
timeStringBuilder.append(':');
}
// Minutes
if (remainderMinutes < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderMinutes);
timeStringBuilder.append(':');
// Seconds
if (remainderSeconds < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderSeconds);
// Centi seconds
if (displayCentiSeconds) {
timeStringBuilder.append('.');
long remainderCentiSeconds = (milliSeconds - seconds * 1000) / 10;
if (remainderCentiSeconds < 10) {
timeStringBuilder.append('0');
}
timeStringBuilder.append(remainderCentiSeconds);
}
return timeStringBuilder.toString();
}
private long getTimeLapseVideoLength(long deltaMs) {
// For better approximation calculate fractional number of frames captured.
// This will update the video time at a higher resolution.
double numberOfFrames = (double) deltaMs / mTimeBetweenTimeLapseFrameCaptureMs;
return (long) (numberOfFrames / mProfile.videoFrameRate * 1000);
}
private void updateRecordingTime() {
if (!mMediaRecorderRecording) {
return;
}
long now = SystemClock.uptimeMillis();
long delta = now - mRecordingStartTime;
// Starting a minute before reaching the max duration
// limit, we'll countdown the remaining time instead.
boolean countdownRemainingTime = (mMaxVideoDurationInMs != 0
&& delta >= mMaxVideoDurationInMs - 60000);
long deltaAdjusted = delta;
if (countdownRemainingTime) {
deltaAdjusted = Math.max(0, mMaxVideoDurationInMs - deltaAdjusted) + 999;
}
String text;
long targetNextUpdateDelay;
if (!mCaptureTimeLapse) {
text = millisecondToTimeString(deltaAdjusted, false);
targetNextUpdateDelay = 1000;
} else {
// The length of time lapse video is different from the length
// of the actual wall clock time elapsed. Display the video length
// only in format hh:mm:ss.dd, where dd are the centi seconds.
text = millisecondToTimeString(getTimeLapseVideoLength(delta), true);
targetNextUpdateDelay = mTimeBetweenTimeLapseFrameCaptureMs;
}
mRecordingTimeView.setText(text);
if (mRecordingTimeCountsDown != countdownRemainingTime) {
// Avoid setting the color on every update, do it only
// when it needs changing.
mRecordingTimeCountsDown = countdownRemainingTime;
int color = getResources().getColor(countdownRemainingTime
? R.color.recording_time_remaining_text
: R.color.recording_time_elapsed_text);
mRecordingTimeView.setTextColor(color);
}
long actualNextUpdateDelay = targetNextUpdateDelay - (delta % targetNextUpdateDelay);
mHandler.sendEmptyMessageDelayed(
UPDATE_RECORD_TIME, actualNextUpdateDelay);
}
private static boolean isSupported(String value, List<String> supported) {
return supported == null ? false : supported.indexOf(value) >= 0;
}
@SuppressWarnings("deprecation")
private void setCameraParameters() {
mParameters.setPreviewSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
mParameters.setPreviewFrameRate(mProfile.videoFrameRate);
// Set flash mode.
String flashMode;
if (mShowCameraAppView) {
flashMode = mPreferences.getString(
CameraSettings.KEY_VIDEOCAMERA_FLASH_MODE,
getString(R.string.pref_camera_video_flashmode_default));
} else {
flashMode = Parameters.FLASH_MODE_OFF;
}
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
getString(R.string.pref_camera_whitebalance_default));
if (isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
// Set continuous autofocus.
List<String> supportedFocus = mParameters.getSupportedFocusModes();
if (isSupported(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, supportedFocus)) {
mParameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mParameters.set(Util.RECORDING_HINT, Util.TRUE);
// Enable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "true");
}
// Set picture size.
// The logic here is different from the logic in still-mode camera.
// There we determine the preview size based on the picture size, but
// here we determine the picture size based on the preview size.
List<Size> supported = mParameters.getSupportedPictureSizes();
Size optimalSize = Util.getOptimalVideoSnapshotPictureSize(supported,
(double) mDesiredPreviewWidth / mDesiredPreviewHeight);
Size original = mParameters.getPictureSize();
if (!original.equals(optimalSize)) {
mParameters.setPictureSize(optimalSize.width, optimalSize.height);
}
Log.v(TAG, "Video snapshot size is " + optimalSize.width + "x" +
optimalSize.height);
// Set JPEG quality.
int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId,
CameraProfile.QUALITY_HIGH);
mParameters.setJpegQuality(jpegQuality);
mCameraDevice.setParameters(mParameters);
// Keep preview size up to date.
mParameters = mCameraDevice.getParameters();
updateCameraScreenNailSize(mDesiredPreviewWidth, mDesiredPreviewHeight);
}
private void updateCameraScreenNailSize(int width, int height) {
if (!ApiHelper.HAS_SURFACE_TEXTURE) return;
if (mCameraDisplayOrientation % 180 != 0) {
int tmp = width;
width = height;
height = tmp;
}
CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail;
int oldWidth = screenNail.getWidth();
int oldHeight = screenNail.getHeight();
if (oldWidth != width || oldHeight != height) {
screenNail.setSize(width, height);
notifyScreenNailChanged();
}
if (screenNail.getSurfaceTexture() == null) {
screenNail.acquireSurfaceTexture();
}
}
private void switchToOtherMode(int mode) {
if (isFinishing()) return;
if (mThumbnail != null) ThumbnailHolder.keep(mThumbnail);
MenuHelper.gotoMode(mode, this, mSecureCamera);
finish();
}
@Override
public void onModeChanged(int mode) {
if (mode != ModePicker.MODE_VIDEO) switchToOtherMode(mode);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_EFFECT_BACKDROPPER:
if (resultCode == RESULT_OK) {
// onActivityResult() runs before onResume(), so this parameter will be
// seen by startPreview from onResume()
mEffectUriFromGallery = data.getData().toString();
Log.v(TAG, "Received URI from gallery: " + mEffectUriFromGallery);
mResetEffect = false;
} else {
mEffectUriFromGallery = null;
Log.w(TAG, "No URI from gallery");
mResetEffect = true;
}
break;
}
}
@Override
public void onEffectsUpdate(int effectId, int effectMsg) {
Log.v(TAG, "onEffectsUpdate. Effect Message = " + effectMsg);
if (effectMsg == EffectsRecorder.EFFECT_MSG_EFFECTS_STOPPED) {
// Effects have shut down. Hide learning message if any,
// and restart regular preview.
mBgLearningMessageFrame.setVisibility(View.GONE);
checkQualityAndStartPreview();
} else if (effectMsg == EffectsRecorder.EFFECT_MSG_RECORDING_DONE) {
// This follows the codepath from onStopVideoRecording.
if (mEffectsDisplayResult && !addVideoToMediaStore()) {
if (mIsVideoCaptureIntent) {
if (mQuickCapture) {
doReturnToCaller(true);
} else {
showAlert();
}
} else {
getThumbnail();
}
}
mEffectsDisplayResult = false;
// In onPause, these were not called if the effects were active. We
// had to wait till the effects recording is complete to do this.
if (mPaused) {
closeVideoFileDescriptor();
clearVideoNamer();
}
} else if (effectMsg == EffectsRecorder.EFFECT_MSG_PREVIEW_RUNNING) {
// Enable the shutter button once the preview is complete.
mShutterButton.setEnabled(true);
} else if (effectId == EffectsRecorder.EFFECT_BACKDROPPER) {
switch (effectMsg) {
case EffectsRecorder.EFFECT_MSG_STARTED_LEARNING:
mBgLearningMessageFrame.setVisibility(View.VISIBLE);
break;
case EffectsRecorder.EFFECT_MSG_DONE_LEARNING:
case EffectsRecorder.EFFECT_MSG_SWITCHING_EFFECT:
mBgLearningMessageFrame.setVisibility(View.GONE);
break;
}
}
// In onPause, this was not called if the effects were active. We had to
// wait till the effects completed to do this.
if (mPaused) {
Log.v(TAG, "OnEffectsUpdate: closing effects if activity paused");
closeEffects();
}
}
public void onCancelBgTraining(View v) {
// Remove training message
mBgLearningMessageFrame.setVisibility(View.GONE);
// Write default effect out to shared prefs
writeDefaultEffectToPrefs();
// Tell the indicator controller to redraw based on new shared pref values
mIndicatorControlContainer.reloadPreferences();
// Tell VideoCamer to re-init based on new shared pref values.
onSharedPreferenceChanged();
}
@Override
public synchronized void onEffectsError(Exception exception, String fileName) {
// TODO: Eventually we may want to show the user an error dialog, and then restart the
// camera and encoder gracefully. For now, we just delete the file and bail out.
if (fileName != null && new File(fileName).exists()) {
deleteVideoFile(fileName);
}
try {
if (Class.forName("android.filterpacks.videosink.MediaRecorderStopException")
.isInstance(exception)) {
Log.w(TAG, "Problem recoding video file. Removing incomplete file.");
return;
}
} catch (ClassNotFoundException ex) {
Log.w(TAG, ex);
}
throw new RuntimeException("Error during recording!", exception);
}
private void initializeControlByIntent() {
if (mIsVideoCaptureIntent) {
// Cannot use RotateImageView for "done" and "cancel" button because
// the tablet layout uses RotateLayout, which cannot be cast to
// RotateImageView.
mReviewDoneButton = (Rotatable) findViewById(R.id.btn_done);
mReviewCancelButton = (Rotatable) findViewById(R.id.btn_cancel);
mReviewPlayButton = (RotateImageView) findViewById(R.id.btn_play);
mReviewRetakeButton = findViewById(R.id.btn_retake);
findViewById(R.id.btn_cancel).setVisibility(View.VISIBLE);
// Not grayed out upon disabled, to make the follow-up fade-out
// effect look smooth. Note that the review done button in tablet
// layout is not a TwoStateImageView.
if (mReviewDoneButton instanceof TwoStateImageView) {
((TwoStateImageView) mReviewDoneButton).enableFilter(false);
}
} else {
mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail);
mThumbnailView.enableFilter(false);
mThumbnailView.setVisibility(View.VISIBLE);
mThumbnailViewWidth = mThumbnailView.getLayoutParams().width;
mModePicker = (ModePicker) findViewById(R.id.mode_picker);
mModePicker.setVisibility(View.VISIBLE);
mModePicker.setOnModeChangeListener(this);
}
}
private void initializeMiscControls() {
mPreviewFrameLayout = (PreviewFrameLayout) findViewById(R.id.frame);
mPreviewFrameLayout.setOnLayoutChangeListener(this);
mReviewImage = (ImageView) findViewById(R.id.review_image);
mShutterButton = (ShutterButton) findViewById(R.id.shutter_button);
mShutterButton.setImageResource(R.drawable.btn_shutter_video);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.requestFocus();
// Disable the shutter button if effects are ON since it might take
// a little more time for the effects preview to be ready. We do not
// want to allow recording before that happens. The shutter button
// will be enabled when we get the message from effectsrecorder that
// the preview is running. This becomes critical when the camera is
// swapped.
if (effectsActive()) {
mShutterButton.setEnabled(false);
}
mRecordingTimeView = (TextView) findViewById(R.id.recording_time);
mRecordingTimeRect = (RotateLayout) findViewById(R.id.recording_time_rect);
mTimeLapseLabel = findViewById(R.id.time_lapse_label);
// The R.id.labels can only be found in phone layout.
// That is, mLabelsLinearLayout should be null in tablet layout.
mLabelsLinearLayout = (LinearLayout) findViewById(R.id.labels);
mBgLearningMessageRotater = (RotateLayout) findViewById(R.id.bg_replace_message);
mBgLearningMessageFrame = findViewById(R.id.bg_replace_message_frame);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setDisplayOrientation();
// Change layout in response to configuration change
LayoutInflater inflater = getLayoutInflater();
LinearLayout appRoot = (LinearLayout) findViewById(R.id.camera_app_root);
appRoot.setOrientation(
newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
appRoot.removeAllViews();
inflater.inflate(R.layout.preview_frame_video, appRoot);
inflater.inflate(R.layout.camera_control, appRoot);
// from onCreate()
initializeControlByIntent();
initializeSurfaceView();
initializeMiscControls();
showTimeLapseUI(mCaptureTimeLapse);
initializeVideoSnapshot();
resizeForPreviewAspectRatio();
initializeIndicatorControl();
// from onResume()
showVideoSnapshotUI(false);
initializeZoom();
if (!mIsVideoCaptureIntent) {
updateThumbnailView();
mModePicker.setCurrentMode(ModePicker.MODE_VIDEO);
}
}
@Override
public void onOverriddenPreferencesClicked() {
}
@Override
public void onRestorePreferencesClicked() {
Runnable runnable = new Runnable() {
@Override
public void run() {
restorePreferences();
}
};
mRotateDialog.showAlertDialog(
null,
getString(R.string.confirm_restore_message),
getString(android.R.string.ok), runnable,
getString(android.R.string.cancel), null);
}
private void restorePreferences() {
// Reset the zoom. Zoom value is not stored in preference.
if (mParameters.isZoomSupported()) {
mZoomValue = 0;
setCameraParameters();
mZoomControl.setZoomIndex(0);
}
if (mIndicatorControlContainer != null) {
mIndicatorControlContainer.dismissSettingPopup();
CameraSettings.restorePreferences(this, mPreferences,
mParameters);
mIndicatorControlContainer.reloadPreferences();
onSharedPreferenceChanged();
}
}
private boolean effectsActive() {
return (mEffectType != EffectsRecorder.EFFECT_NONE);
}
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()" or preview has not started yet
if (mPaused) return;
synchronized (mPreferences) {
// If mCameraDevice is not ready then we can set the parameter in
// startPreview().
if (mCameraDevice == null) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
// Check if the current effects selection has changed
if (updateEffectSelection()) return;
readVideoPreferences();
showTimeLapseUI(mCaptureTimeLapse);
// We need to restart the preview if preview size is changed.
Size size = mParameters.getPreviewSize();
if (size.width != mDesiredPreviewWidth
|| size.height != mDesiredPreviewHeight) {
if (!effectsActive()) {
stopPreview();
} else {
mEffectsRecorder.release();
mEffectsRecorder = null;
}
resizeForPreviewAspectRatio();
startPreview(); // Parameters will be set in startPreview().
} else {
setCameraParameters();
}
}
}
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mPendingSwitchCameraId = cameraId;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
Log.d(TAG, "Start to copy texture.");
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
((CameraScreenNail) mCameraScreenNail).copyTexture();
// Disable all camera controls.
mSwitchingCamera = true;
} else {
switchCamera();
}
}
private void switchCamera() {
if (mPaused) return;
Log.d(TAG, "Start to switch camera.");
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
mCameraPicker.setCameraId(mCameraId);
closeCamera();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(this, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
CameraOpenThread cameraOpenThread = new CameraOpenThread();
cameraOpenThread.start();
try {
cameraOpenThread.join();
} catch (InterruptedException ex) {
// ignore
}
readVideoPreferences();
startPreview();
initializeVideoSnapshot();
resizeForPreviewAspectRatio();
initializeIndicatorControl();
// From onResume
initializeZoom();
setOrientationIndicator(mOrientationCompensation, false);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
}
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
protected void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
private boolean updateEffectSelection() {
int previousEffectType = mEffectType;
Object previousEffectParameter = mEffectParameter;
mEffectType = CameraSettings.readEffectType(mPreferences);
mEffectParameter = CameraSettings.readEffectParameter(mPreferences);
if (mEffectType == previousEffectType) {
if (mEffectType == EffectsRecorder.EFFECT_NONE) return false;
if (mEffectParameter.equals(previousEffectParameter)) return false;
}
Log.v(TAG, "New effect selection: " + mPreferences.getString(
CameraSettings.KEY_VIDEO_EFFECT, "none"));
if (mEffectType == EffectsRecorder.EFFECT_NONE) {
// Stop effects and return to normal preview
mEffectsRecorder.stopPreview();
mPreviewing = false;
return true;
}
if (mEffectType == EffectsRecorder.EFFECT_BACKDROPPER &&
((String) mEffectParameter).equals(EFFECT_BG_FROM_GALLERY)) {
// Request video from gallery to use for background
Intent i = new Intent(Intent.ACTION_PICK);
i.setDataAndType(Video.Media.EXTERNAL_CONTENT_URI,
"video/*");
i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(i, REQUEST_EFFECT_BACKDROPPER);
return true;
}
if (previousEffectType == EffectsRecorder.EFFECT_NONE) {
// Stop regular preview and start effects.
stopPreview();
checkQualityAndStartPreview();
} else {
// Switch currently running effect
mEffectsRecorder.setEffect(mEffectType, mEffectParameter);
}
return true;
}
// Verifies that the current preview view size is correct before starting
// preview. If not, resets the surface texture and resizes the view.
private void checkQualityAndStartPreview() {
readVideoPreferences();
showTimeLapseUI(mCaptureTimeLapse);
Size size = mParameters.getPreviewSize();
if (size.width != mDesiredPreviewWidth
|| size.height != mDesiredPreviewHeight) {
resizeForPreviewAspectRatio();
}
// Start up preview again
startPreview();
}
private void showTimeLapseUI(boolean enable) {
if (mTimeLapseLabel != null) {
mTimeLapseLabel.setVisibility(enable ? View.VISIBLE : View.GONE);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (mSwitchingCamera) return true;
// Check if the popup window should be dismissed first.
if (m.getAction() == MotionEvent.ACTION_DOWN) {
float x = m.getX();
float y = m.getY();
// Dismiss the mode selection window if the ACTION_DOWN event is out
// of its view area.
if ((mModePicker != null) && !Util.pointInView(x, y, mModePicker)) {
mModePicker.dismissModeSelection();
}
// Check if the popup window is visible.
View popup = mIndicatorControlContainer.getActiveSettingPopup();
if (popup != null) {
// Let popup window, indicator control or preview frame handle the
// event by themselves. Dismiss the popup window if users touch on
// other areas.
if (!Util.pointInView(x, y, popup)
&& !Util.pointInView(x, y, mIndicatorControlContainer)) {
mIndicatorControlContainer.dismissSettingPopup();
}
}
}
return super.dispatchTouchEvent(m);
}
private class ZoomChangeListener implements ZoomControl.OnZoomChangedListener {
@Override
public void onZoomValueChanged(int index) {
// Not useful to change zoom value when the activity is paused.
if (mPaused) return;
mZoomValue = index;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParametersAsync(mParameters);
}
}
private void initializeZoom() {
mZoomControl = (ZoomControl) findViewById(R.id.zoom_control);
if (!mParameters.isZoomSupported()) return;
mZoomMax = mParameters.getMaxZoom();
// Currently we use immediate zoom for fast zooming to get better UX and
// there is no plan to take advantage of the smooth zoom.
mZoomControl.setZoomMax(mZoomMax);
mZoomControl.setZoomIndex(mParameters.getZoom());
mZoomControl.setOnZoomChangeListener(new ZoomChangeListener());
}
private void initializeVideoSnapshot() {
if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
setSingleTapUpListener(mPreviewFrameLayout);
// Show the tap to focus toast if this is the first start.
if (mPreferences.getBoolean(
CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_SNAPSHOT_TOAST, 1000);
}
} else {
setSingleTapUpListener(null);
}
}
void showVideoSnapshotUI(boolean enabled) {
if (Util.isVideoSnapshotSupported(mParameters) && !mIsVideoCaptureIntent) {
mPreviewFrameLayout.showBorder(enabled);
mIndicatorControlContainer.enableZoom(!enabled);
mShutterButton.setEnabled(!enabled);
}
}
// Preview area is touched. Take a picture.
@Override
protected void onSingleTapUp(View view, int x, int y) {
if (mMediaRecorderRecording && effectsActive()) {
new RotateTextToast(this, R.string.disable_video_snapshot_hint,
mOrientation).show();
return;
}
if (mPaused || mSnapshotInProgress
|| !mMediaRecorderRecording || effectsActive()) {
return;
}
// Set rotation and gps data.
int rotation = Util.getJpegRotation(mCameraId, mOrientation);
mParameters.setRotation(rotation);
Location loc = mLocationManager.getCurrentLocation();
Util.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
Log.v(TAG, "Video snapshot start");
mCameraDevice.takePicture(null, null, null, new JpegPictureCallback(loc));
showVideoSnapshotUI(true);
mSnapshotInProgress = true;
}
@Override
protected void updateCameraAppView() {
super.updateCameraAppView();
if (!mPreviewing || mParameters.getFlashMode() == null) return;
// When going to and back from gallery, we need to turn off/on the flash.
if (!mShowCameraAppView) {
if (mParameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) {
mRestoreFlash = false;
return;
}
mRestoreFlash = true;
setCameraParameters();
} else if (mRestoreFlash) {
mRestoreFlash = false;
setCameraParameters();
}
}
@Override
protected void onFullScreenChanged(boolean full) {
super.onFullScreenChanged(full);
if (ApiHelper.HAS_SURFACE_TEXTURE) return;
if (full) {
mPreviewSurfaceView.expand();
} else {
mPreviewSurfaceView.shrink();
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(byte [] jpegData, android.hardware.Camera camera) {
Log.v(TAG, "onPictureTaken");
mSnapshotInProgress = false;
showVideoSnapshotUI(false);
storeImage(jpegData, mLocation);
}
}
private void storeImage(final byte[] data, Location loc) {
long dateTaken = System.currentTimeMillis();
String title = Util.createJpegName(dateTaken);
int orientation = Exif.getOrientation(data);
Size s = mParameters.getPictureSize();
Uri uri = Storage.addImage(mContentResolver, title, dateTaken, loc, orientation, data,
s.width, s.height);
if (uri != null) {
// Create a thumbnail whose width is equal or bigger than that of the preview.
int ratio = (int) Math.ceil((double) mParameters.getPictureSize().width
/ mPreviewFrameLayout.getWidth());
int inSampleSize = Integer.highestOneBit(ratio);
mThumbnail = Thumbnail.createThumbnail(data, orientation, inSampleSize, uri);
if (mThumbnail != null) {
mThumbnailView.setBitmap(mThumbnail.getBitmap());
}
Util.broadcastNewPicture(this, uri);
}
}
private boolean resetEffect() {
if (mResetEffect) {
String value = mPreferences.getString(CameraSettings.KEY_VIDEO_EFFECT,
mPrefVideoEffectDefault);
if (!mPrefVideoEffectDefault.equals(value)) {
writeDefaultEffectToPrefs();
return true;
}
}
mResetEffect = true;
return false;
}
private String convertOutputFormatToMimeType(int outputFileFormat) {
if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
return "video/mp4";
}
return "video/3gpp";
}
private String convertOutputFormatToFileExt(int outputFileFormat) {
if (outputFileFormat == MediaRecorder.OutputFormat.MPEG_4) {
return ".mp4";
}
return ".3gp";
}
private void closeVideoFileDescriptor() {
if (mVideoFileDescriptor != null) {
try {
mVideoFileDescriptor.close();
} catch (IOException e) {
Log.e(TAG, "Fail to close fd", e);
}
mVideoFileDescriptor = null;
}
}
private void showTapToSnapshotToast() {
new RotateTextToast(this, R.string.video_snapshot_hint, mOrientationCompensation)
.show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_VIDEO_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
private void clearVideoNamer() {
if (mVideoNamer != null) {
mVideoNamer.finish();
mVideoNamer = null;
}
}
private static class VideoNamer extends Thread {
private boolean mRequestPending;
private ContentResolver mResolver;
private ContentValues mValues;
private boolean mStop;
private Uri mUri;
// Runs in main thread
public VideoNamer() {
start();
}
// Runs in main thread
public synchronized void prepareUri(
ContentResolver resolver, ContentValues values) {
mRequestPending = true;
mResolver = resolver;
mValues = new ContentValues(values);
notifyAll();
}
// Runs in main thread
public synchronized Uri getUri() {
// wait until the request is done.
while (mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
Uri uri = mUri;
mUri = null;
return uri;
}
// Runs in namer thread
@Override
public synchronized void run() {
while (true) {
if (mStop) break;
if (!mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
cleanOldUri();
generateUri();
mRequestPending = false;
notifyAll();
}
cleanOldUri();
}
// Runs in main thread
public synchronized void finish() {
mStop = true;
notifyAll();
}
// Runs in namer thread
private void generateUri() {
Uri videoTable = Uri.parse("content://media/external/video/media");
mUri = mResolver.insert(videoTable, mValues);
}
// Runs in namer thread
private void cleanOldUri() {
if (mUri == null) return;
mResolver.delete(mUri, null, null);
mUri = null;
}
}
private class SurfaceViewCallback implements SurfaceHolder.Callback {
public SurfaceViewCallback() {}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "Surface changed. width=" + width + ". height=" + height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "Surface created");
mSurfaceViewReady = true;
if (mPaused) return;
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
mCameraDevice.setPreviewDisplayAsync(mPreviewSurfaceView.getHolder());
if (!mPreviewing) {
startPreview();
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "Surface destroyed");
mSurfaceViewReady = false;
if (mPaused) return;
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
stopVideoRecording();
stopPreview();
}
}
}
}
| [
"[email protected]"
] | |
8dfc5b495c2ba493da887bec5bb76f89678a4faa | 5c1e4e6fef09d28bdad22c8216fcc196da5d9756 | /src/main/java/votacao/Votacao.java | 1b8497193cca6fe86b31c2570fa233df391a9bf5 | [] | no_license | felipecechin/junit-tests | a8d97245937dd835ccd18015426a23edd9d658ad | d9ebc4f04b0224ad30662bec33aed7ca0c5b97fc | refs/heads/master | 2023-01-31T14:26:07.640926 | 2020-12-18T15:16:02 | 2020-12-18T15:16:02 | 322,358,940 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 825 | java | package votacao;
import java.util.Calendar;
public class Votacao {
/*
* Retorna um texto informando se a pessoa pode ou não votar
* dado um nome e a data de nascimento
*/
public static String podeVotar(String nome, int anoDeNascimento) {
String retorno = null;
int idade = retornaAnoAtual() - anoDeNascimento;
if (idade < 16) {
retorno = nome + " voce nao pode votar";
} else if (idade <= 17 || idade > 70) {
retorno = nome + " seu voto e facultativo";
} else {
retorno = nome + " seu voto e obrigatorio";
}
return retorno;
}
/*
* Retorna o ano atual (do seu computador)
*/
private static int retornaAnoAtual() {
return Calendar.getInstance().get(Calendar.YEAR);
}
} | [
"[email protected]"
] | |
8749ba57e07bf3916df9bfe24fe86731b49c0334 | 8c04a17311926770816416dda7aa267c575219b3 | /src/main/java/com/epam/tutorial/lockerapp/control/LockerControl.java | 8a67292bc3648c99f1b6780ea88ab0ae5b70a2c2 | [] | no_license | briansolo1985/locker-jsp-webapp | f60805035eba1bd9a5c789c5c86d8d59de751a34 | edeeb9f2a70ad2f58f82bf8d657539dd4014eeb9 | refs/heads/master | 2021-01-19T22:47:18.032747 | 2017-04-20T11:39:28 | 2017-04-20T11:39:28 | 88,858,795 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,394 | java | package com.epam.tutorial.lockerapp.control;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.epam.tutorial.lockerapp.entities.Employee;
import com.epam.tutorial.lockerapp.entities.EmployeeManager;
import com.epam.tutorial.lockerapp.entities.Locker;
import com.epam.tutorial.lockerapp.entities.LockerManager;
import com.epam.tutorial.lockerapp.exception.AppException;
/**
* This is an interface class for communicating with client side through servlet
* and jsp in a thread safe way.
*
* @author Ferenc Kis
* @version 1.1
*/
public class LockerControl {
@SuppressWarnings("unused")
private static final Logger logger = LoggerFactory
.getLogger(LockerControl.class);
private LockerManager lockerManager;
private EmployeeManager employeeManager;
public LockerControl() throws AppException {
lockerManager = LockerManager.getInstance();
employeeManager = EmployeeManager.getInstance();
init();
}
/**
* Getting method for list of lockers.
*
* @return List<Locker> or null.
* @exception AppException
* on error.
* @see AppException
*/
public List<Locker> getLockers() {
return lockerManager.getLockerList();
}
/**
* Getting method for list of employees.
*
* @return List<Employee> or null.
* @exception AppException
* on error.
* @see AppException
*/
public List<Employee> getUsers() {
return employeeManager.getEmployeeList();
}
/**
* Initializing application environment for testing.
*
* @exception AppException
* on error.
* @see AppException
*/
public synchronized void init() throws AppException {
employeeManager.load();
lockerManager.load();
}
/**
* Interface method for reserving a locker for someone.
*
* @param Employee
* e, who wants to reserve.
* @param String
* lockerID, target locker.
* @exception AppException
* on error.
* @see AppException
*/
public synchronized void reserve(Employee employee, String lockerID)
throws AppException {
lockerManager.reserve(employee, lockerID);
}
/**
* Interface method for releasing a locker.
*
* @param Employee
* e, who wants to release.
* @param String
* lockerID, target locker.
* @exception AppException
* on error.
* @see AppException
*/
public synchronized void release(Employee employee, String lockerID)
throws AppException {
lockerManager.release(employee, lockerID);
}
/**
* Interface method for logging users in.
*
* @param String
* userID, string of three letters.
* @exception AppException
* on error.
* @see AppException
*/
public synchronized Employee login(String userID) throws AppException {
return employeeManager.login(userID);
}
/**
* Interface method for logging users out.
*
* @param Employee
* e, who wants to log out.
* @exception AppException
* on error.
* @see AppException
*/
public synchronized void logout(Employee employee) throws AppException {
employeeManager.logout(employee);
}
public void setLockerManager(LockerManager lockerManager) {
this.lockerManager = lockerManager;
}
public void setEmployeeManager(EmployeeManager employeeManager) {
this.employeeManager = employeeManager;
}
}
| [
"[email protected]"
] | |
b3c41e0008a4f51f8d7822e91029002ef2e2a442 | e66170bbe0e10fa88274a2fa8ea62e212c6d17b2 | /app/src/main/java/edu/utep/cs5381/platformer/levels/LevelForest.java | ba692270c985bfff7b5a57b52fba8aa20ba654a6 | [] | no_license | mahdafr/19u_cs5381-platformer | 172d2431919e3af50a099c678a039997878f1166 | a5614203267e2d218a76045b68b4f06485b04ce5 | refs/heads/master | 2020-07-14T08:13:14.016365 | 2019-12-11T06:05:46 | 2019-12-11T06:05:46 | 205,280,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,851 | java | package edu.utep.cs5381.platformer.levels;
import java.util.ArrayList;
import edu.utep.cs5381.platformer.visuals.BackgroundData;
public class LevelForest extends LevelData {
public LevelForest() {
tiles = new ArrayList<String>();
this.tiles.add("p.......t..................g.........................................................................................uuu");
this.tiles.add(".............ddddddddddddddddddddddddddd...................1111111....111............................................555");
this.tiles.add("11111111111111111111111111111111111111111111111111111.........................11....................................1...");
this.tiles.add(".......w.w.....w.w..w..........w.............................................1111111111.................................");
this.tiles.add("...................................................................11.11111.......................................1.....");
this.tiles.add("................................................................11......................................................");
this.tiles.add("............................................1111111....11111111.....................w..w..w.....................1.......");
this.tiles.add("....11111111111111111111......11111111111...............................................................................");
this.tiles.add("5.............................................................................................................1.........");
this.tiles.add("55............................................................................c.c.c.....................................");
this.tiles.add("..55..........................................................................11111111111111111111..........1...........");
this.tiles.add(".....55..............................................55...55.....55555..................................................");
this.tiles.add("........55..55....55...55....55.....55...55....55..................................................1.......1............");
this.tiles.add("7.............................d........................................................................................7");
this.tiles.add("7...............................................................................z....................1...1............7");
this.tiles.add("7....................................................................d.........z.z.....................................7");
this.tiles.add("7w..........................................1...............z.................z.z.z....................1..............w7");
this.tiles.add("7........1111111111.......111111111111.....111111111111111111111111..111111111111111111111111111111111111111111111111117");
this.tiles.add("7............................................d.........g.......................d............d.......d......c.c.c.c.e...7");
this.tiles.add("7....1....z........1..........zzz....z........................................z...z....................................7");
this.tiles.add("111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
// Declare the values for the teleports in order of appearance
locations = new ArrayList<Location>();
this.locations.add(new Location("LevelMountain", 118f, 17f));
backgroundDataList = new ArrayList<BackgroundData>();
// note that speeds less than 2 cause problems
this.backgroundDataList.add(new BackgroundData("forest", true, -1, -2, 19, 4, 20 ));
this.backgroundDataList.add(new BackgroundData("grass", true, 1, 18, 22, 24, 4 ));
}
}
| [
"[email protected]"
] | |
a62294a6b8a98f52166ed544671b2a8aa9a60865 | e0fda336ec1028bb1b6e5fe6c865da0f36c29c95 | /common-parent/src/main/java/com/yuyang/common/cache/SerializationUtils.java | 2e40f3a80f7c87880884193c8550dd832e083815 | [] | no_license | yuyang0403/syscentrol | 6d63653bde723292a08f37dacc445d3f8a3cc056 | 7d0188b3bcb535d43d8eeefcaf19d0a51ded36c5 | refs/heads/master | 2021-07-04T14:25:20.863025 | 2019-03-22T06:05:39 | 2019-03-22T06:05:39 | 137,903,159 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,215 | java | package com.yuyang.common.cache;
import java.io.*;
/**
* 用于调用session、cache等缓存服务时序列化对象, 改写自org.springframework.util.SerializationUtils,
* 主要替换了deserialize方法,使用自定义的ObjectInputStream,解决反序列化时找不到类的问题
*
*/
public class SerializationUtils {
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
} catch (IOException ex) {
throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
}
return baos.toByteArray();
}
public static Object deserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return ois.readObject();
} catch (IOException ex) {
throw new IllegalArgumentException("Failed to deserialize object", ex);
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("Failed to deserialize object type", ex);
}
}
}
| [
"[email protected]"
] | |
05794cf8281ef9e85a065ee70bbee2864f009cdf | c88a4eb70adf8b1466711fa4c0d327a1f6c6e6bc | /icoin/src/main/java/com/mx/bitso/challenge/icoin/controller/OrderBookController.java | cb396f0946d3e4eeb68b3526d8663bf81a374f90 | [] | no_license | israel-arteaga/sonar-trading-challenge | f1fffdf137ff1de6257ff38c5b8e821ddea89e6c | 0e0e6a4db73b62881e5ad6696430c5b0c9e4f804 | refs/heads/master | 2020-03-25T19:21:42.721795 | 2018-09-25T05:40:51 | 2018-09-25T05:40:51 | 144,078,897 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 781 | java | package com.mx.bitso.challenge.icoin.controller;
import com.mx.bitso.challenge.icoin.model.OrderBookWrapper;
import com.mx.bitso.challenge.icoin.service.OrderBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@CrossOrigin
@RestController
@RequestMapping(value = "/icoin")
public class OrderBookController {
@Autowired
OrderBookService orderBookService;
@RequestMapping(value = "/orderbook/{n}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public OrderBookWrapper getNBestAsksAndBids(@PathVariable("n") String n) throws Exception {
return orderBookService.getBestAsksAndBids(Integer.valueOf(n));
}
}
| [
"[email protected]"
] | |
235c4c0947925875780b9cb5e1a00d6d910ccb5b | e9d4316f8b10e5e110825d49f4c0a09c431e5862 | /app/src/main/java/com/svalero/apimoviesprueba/movies/adapter/ListAdapter.java | b4351558e0f0fada83e9a020666c46feeec9254c | [] | no_license | PideroAntonio80/AppiMovies | b26bb77efb0a83e1465ae89d62ec608d280b6678 | 54b19ab4862115913186fd1b26344ba8858f2f9e | refs/heads/master | 2023-03-29T16:07:33.935585 | 2020-12-21T17:38:32 | 2020-12-21T17:38:32 | 322,866,713 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,082 | java | package com.svalero.apimoviesprueba.movies.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import com.svalero.apimoviesprueba.R;
import com.svalero.apimoviesprueba.beans.Movie;
import com.svalero.apimoviesprueba.onemovie.view.OneMovieActivity;
import java.util.ArrayList;
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.MovieViewHolder> {
private ArrayList<Movie> lstMovies;
/*Tantos elementos como objetos quiera mostrar en la fila*/
public static class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView img;
public TextView titulo;
public TextView fecha;
public Context context;
public LinearLayout rowList;
public MovieViewHolder(View v){
super(v);
context = v.getContext();
rowList = v.findViewById(R.id.rowList);
img = (ImageView) v.findViewById(R.id.imgMovie);
titulo = (TextView) v.findViewById(R.id.txtTitulo);
fecha = (TextView) v.findViewById(R.id.txtFecha);
v.setOnClickListener(this);
}
/*void setOnClickListeners() {
rowList.setOnClickListener(this);
}*/
@Override
public void onClick(View v) {
Intent intent = new Intent(context, OneMovieActivity.class);
intent.putExtra("titulo", titulo.getText());
intent.putExtra("fecha", fecha.getText());
context.startActivity(intent);
}
}
public ListAdapter(ArrayList<Movie> lstMovies) {
this.lstMovies = lstMovies;
}
@NonNull
@Override
public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_list, parent,false);
return new MovieViewHolder(v);
}
//ListAdapter. <-- Estaba antes de MovieViewHolder (linea 47)
@Override
public void onBindViewHolder(@NonNull MovieViewHolder holder, int position) {
// Enlace=pintado
// holder.img
// Vídeo de Picasso o Glide
Movie movie = lstMovies.get(position);
Picasso.get().load(movie.getImage()).into(holder.img);
holder.titulo.setText(movie.getTitulo());
holder.fecha.setText(movie.getFecha());
//-->holder.setOnClickListeners();
//----------------------------------------------------------
//holder.vote.setText(movie.getVote());
// Picasso.with(context).load(movie.getImage()).into(holder.img);
//----------------------------------------------------------
}
@Override
public int getItemCount() {
return lstMovies.size();
}
}
| [
"[email protected]"
] | |
0e8ace31b9f711a861c7e0145366b09b4218ac47 | b2b70d2962759c08e4ff317ea34c625ff26487e5 | /src/main/java/levy/daniel/application/model/services/metier/personne/package-info.java | 5b8b9c6509e8632bbf79b6b4e4e4973bcc2f31ed | [] | no_license | DanielLEVY25021961/regex_javafx | fbca6f2c54ad2de0ba6054b2b50e430ec96332b2 | 74bc1e919543170422376eb3f626b72244f7067e | refs/heads/master | 2021-07-08T04:26:00.346463 | 2019-02-26T08:30:54 | 2019-02-26T08:30:54 | 143,826,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 325 | java | /**
* class package-info :<br/>
* .<br/>
* <br/>
*
* - Exemple d'utilisation :<br/>
*<br/>
*
* - Mots-clé :<br/>
* <br/>
*
* - Dépendances :<br/>
* <br/>
*
*
* @author dan Lévy
* @version 1.0
* @since 9 mai 2018
*
*/
package levy.daniel.application.model.services.metier.personne;
| [
"[email protected]"
] | |
fbaf6ba5bb229834123495d632278a21e3e32cac | 218c04852127ccef77ea94650ac55384438ac678 | /Pract_12/SaveStudent.java | 83dd4eeccc9cda1c5c69c166b46ebbeb64da3612 | [
"MIT"
] | permissive | Realocity/JAVA_Practical | 24506b7eb6dbe165cf5311ace608f54a391a22ab | f9cd905892cabdb060cbcce66daf665acc0659c9 | refs/heads/main | 2023-05-05T23:19:00.307155 | 2021-05-20T04:42:53 | 2021-05-20T04:42:53 | 364,268,142 | 0 | 1 | null | 2021-05-20T04:42:53 | 2021-05-04T13:37:56 | Java | UTF-8 | Java | false | false | 796 | java | import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SaveStudent {
JdbcConnection jdbcObj = new JdbcConnection();
public void storeStudentDetail(String Name,int RollNo,String Course,String DOB,String email) throws SQLException {
Connection con = jdbcObj.getConnection();
PreparedStatement stmtt = null;
try {
stmtt = con.prepareStatement("insert into student_details values(?,?,?,?,?)");
stmtt.setString(1, Name);
stmtt.setInt(2, RollNo);
stmtt.setString(3, Course);
stmtt.setString(4, DOB);
stmtt.setString(5, email);
int i = stmtt.executeUpdate();
System.out.println(i + " records inserted");
}
catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
stmtt.close();
}
}
}
| [
"[email protected]"
] | |
89ad9747b1c71dc3338eeb807e4f4438980654b3 | 8c7f7c467cc103417c6c3f4eddcc46e701797363 | /src/main/java/com/crud/tasks/service/MailCreatorService.java | 99194758f505256414a44d63e5e29e6061b9529b | [] | no_license | RobertWojtaszczyk/robert-wojtaszczyk-kodilla-tasks | 2e06eec74356aa1646645b35341b2f3032fad400 | c18ad86e2668f254348758360b145737e3705243 | refs/heads/master | 2020-03-08T14:44:19.204817 | 2018-06-18T19:06:31 | 2018-06-18T19:06:31 | 128,193,784 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 686 | java | package com.crud.tasks.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.util.Map;
@Service
public class MailCreatorService {
@Autowired
@Qualifier("templateEngine")
private TemplateEngine templateEngine;
public String buildEmail(String templateName, Map<String, Object> contextData) {
Context context = new Context();
contextData.forEach(context::setVariable);
return templateEngine.process(templateName, context);
}
} | [
"[email protected]"
] | |
abfbaac7f9fa2dc7d08b255e63ce48d89663faf2 | fcb7a2a7cefe35405b739dccabf18b5424de22e7 | /app/src/main/java/com/ryanzhou/company/inventoryapp/model/Product.java | f9e61f18aa9c3008b0b33f6e446b83aca357046c | [] | no_license | ryanzhou7/InventoryApp | cd94f882da0cdfcc0eda2e86cb9a55d3509cd5ad | b8c3668d8f141c3832b10b97a83af9b87d31d5c5 | refs/heads/master | 2021-01-20T19:05:30.465688 | 2016-08-01T20:26:08 | 2016-08-01T20:26:08 | 62,030,385 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,470 | java | package com.ryanzhou.company.inventoryapp.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by ryanzhou on 6/27/16.
*/
public class Product implements Parcelable {
public static final String PRODUCT_BUNDLE_KEY = "productBundleKey";
public static final String PRODUCT_NAME_KEY = "productNameKey";
private String name;
private String supplierPhoneNumber;
private int imageResourceId;
private int numDollars;
private int numCents;
private int quantity;
public Product(int numDollars, int numCents, int quantity, String name, String supplierPhoneNumber,
int imageResourceId) {
this.setName(name);
this.setNumCents(numCents);
this.setNumDollars(numDollars);
this.setQuantity(quantity);
this.setSupplierPhoneNumber(supplierPhoneNumber);
this.setImageResourceId(imageResourceId);
}
protected Product(Parcel in) {
name = in.readString();
supplierPhoneNumber = in.readString();
imageResourceId = in.readInt();
numDollars = in.readInt();
numCents = in.readInt();
quantity = in.readInt();
}
public static final Creator<Product> CREATOR = new Creator<Product>() {
@Override
public Product createFromParcel(Parcel in) {
return new Product(in);
}
@Override
public Product[] newArray(int size) {
return new Product[size];
}
};
public int getNumDollars() {
return numDollars;
}
public void setNumDollars(int numDollars) {
this.numDollars = numDollars;
}
public int getNumCents() {
return numCents;
}
public void setNumCents(int numCents) {
this.numCents = numCents;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageResourceId() {
return imageResourceId;
}
public void setImageResourceId(int imageResourceId) {
this.imageResourceId = imageResourceId;
}
public String getSupplierPhoneNumberForIntentCall() {
StringBuilder stringBuilder = new StringBuilder("tel:");
stringBuilder.append(supplierPhoneNumber);
return stringBuilder.toString();
}
public void setSupplierPhoneNumber(String supplierPhoneNumber) {
this.supplierPhoneNumber = supplierPhoneNumber;
}
public String getSupplierPhoneNumber() {
return this.supplierPhoneNumber;
}
public String getPriceForDisplay() {
StringBuilder stringBuilder = new StringBuilder("$");
stringBuilder.append(String.valueOf(getNumDollars()));
stringBuilder.append(".");
stringBuilder.append(String.valueOf(getNumCents()));
if( getNumCents() == 0 )
stringBuilder.append("0");
return stringBuilder.toString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(supplierPhoneNumber);
dest.writeInt(imageResourceId);
dest.writeInt(numDollars);
dest.writeInt(numCents);
dest.writeInt(quantity);
}
}
| [
"[email protected]"
] | |
4a535c7a188ae56f1091680e50358e57f9360882 | 25b43412199889f29e1305a4120d05a766b13539 | /app/src/main/java/com/specialty/administrator/home/Home_F.java | b0b84157182129be271b687f50bc1debd4f5e8e0 | [] | no_license | Cchenbin/Graduation-Project | c1c7673dfa642c46ec17ac07ac4953dae6aea0fc | 19a00ce59e3cbb1eff833245019146d2ecbe53cd | refs/heads/master | 2021-09-05T07:24:49.523301 | 2018-01-25T06:39:51 | 2018-01-25T06:39:51 | 114,838,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,417 | java | package com.specialty.administrator.home;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.specialty.administrator.abView.AbSlidingPlayView;
import com.specialty.administrator.classify.Classification;
import com.specialty.administrator.specialty.R;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import static com.specialty.administrator.specialty.R.id.tv_home_customerService;
/**
* A simple {@link Fragment} subclass.
*/
public class Home_F extends Fragment implements View.OnClickListener {
/*首页轮播 */
private AbSlidingPlayView viewPager;
/*首页轮播的界面的资源*/
private int[] resid = {R.drawable.carousel, R.drawable.carousel1, R.drawable.carousel2};
/*存储首页轮播的界面*/
private ArrayList<View> allListView;
private ViewFlipper mVf_notice;
private int mCurrPos = 0;
private ArrayList<String> hAnnounList = new ArrayList<>();
private TextView[] tv_menu = new TextView[4];
private int[] tv_menu_id = {R.id.tv_home_charge, R.id.tv_home_trade, R.id.tv_home_help, tv_home_customerService};
private ImageView[] im_view = new ImageView[8];
private int[] im_view_id = {R.id.Recommend_1, R.id.Recommend_2, R.id.Recommend_3, R.id.Recommend_4, R.id.Recommend_5, R.id.Recommend_6, R.id.Recommend_7, R.id.Recommend_8};
public Home_F() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.home_f, container, false);
initView(rootView);
initData();
return rootView;
}
private void initView(View view) {
viewPager = view.findViewById(R.id.viewPager_menu);
//设置播放方式为顺序播放
viewPager.setPlayType(1);
//设置播放间隔时间
viewPager.setSleepTime(3000);
initViewPager();
initViewFlipper();
mVf_notice = view.findViewById(R.id.home_notice_vf);
for (int i = 0; i < tv_menu.length; i++) {
tv_menu[i] = view.findViewById(tv_menu_id[i]);
tv_menu[i].setOnClickListener(this);
}
for (int j = 0; j < im_view.length; j++) {
im_view[j] = view.findViewById(im_view_id[j]);
im_view[j].setOnClickListener(this);
}
}
private void initViewPager() {
if (allListView != null) {
allListView.clear();
allListView = null;
}
allListView = new ArrayList<>();
for (int i = 0; i < resid.length; i++) {
//导入ViewPager的布局
View view = LayoutInflater.from(getActivity()).inflate(R.layout.home_sildepic_item, null);
ImageView imageView = (view.findViewById(R.id.pic_item));
imageView.setImageResource(resid[i]);
allListView.add(view);
}
viewPager.addViews(allListView);
//开始轮播
viewPager.startPlay();
}
private void initData() {
hAnnounList.add("首页测试公告1");
hAnnounList.add("首页测试公告2");
hAnnounList.add("首页测试公告3");
}
/**
* 初始化滚动公告
*/
private void initViewFlipper() {
TimerTask task = new TimerTask() {
@Override
public void run() {
Home_F.this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
moveNext();
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 4000);
}
/**
* 滚动公告的下一条功能
*/
private void moveNext() {
setView(this.mCurrPos, this.mCurrPos + 1);
this.mVf_notice.setInAnimation(this.getActivity(), R.anim.in_bottomtop);
this.mVf_notice.setOutAnimation(this.getActivity(), R.anim.out_topbottom);
this.mVf_notice.showNext();
}
private void setView(int curr, int next) {
View noticeView = getActivity().getLayoutInflater().inflate(R.layout.home_sildenotice_item, null);
TextView tv_notice = (TextView) noticeView.findViewById(R.id.tv_announce);
if ((curr < next) && (next > (hAnnounList.size() - 1))) {
next = 0;
} else if ((curr > next) && (next < 0)) {
next = hAnnounList.size() - 1;
}
String title = "";
try {
title = hAnnounList.get(next).toString();
} catch (Exception e) {
}
tv_notice.setText(title);
// tv_notice.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View arg0) {
// // tiao_ 跳转到公告详情页面
//
// Intent intent = new Intent(getActivity(), ShowMessage.class);
// Bundle bundle = new Bundle();
// String href = "";
// try {
// href = hAnnounList.get(mCurrPos).get(params_annou[1]).toString();
// } catch (Exception e) {
// }
// bundle.putString("href", href);
// intent.putExtras(bundle);
// startActivity(intent);
// }
// });
if (mVf_notice.getChildCount() > 1) {
mVf_notice.removeViewAt(0);
}
mVf_notice.addView(noticeView, mVf_notice.getChildCount());
mCurrPos = next;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_home_charge:
if (getActivity() instanceof HeadPageCallback) {
((HeadPageCallback) getActivity()).HeadPageBtnCall(tv_menu[0]);
}
break;
case R.id.tv_home_trade:
if (getActivity() instanceof HeadPageCallback) {
((HeadPageCallback) getActivity()).HeadPageBtnCall(tv_menu[1]);
}
break;
case R.id.tv_home_help:
if (getActivity() instanceof HeadPageCallback) {
((HeadPageCallback) getActivity()).HeadPageBtnCall(tv_menu[2]);
}
break;
case R.id.tv_home_customerService:
if (getActivity() instanceof HeadPageCallback) {
((HeadPageCallback) getActivity()).HeadPageBtnCall(tv_menu[3]);
}
break;
case R.id.Recommend_1:
Intent intent = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent);
break;
case R.id.Recommend_2:
Intent intent2 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent2);
break;
case R.id.Recommend_3:
Intent intent3 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent3);
break;
case R.id.Recommend_4:
Intent intent4 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent4);
break;
case R.id.Recommend_5:
Intent intent5 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent5);
break;
case R.id.Recommend_6:
Intent intent6 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent6);
break;
case R.id.Recommend_7:
Intent intent7 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent7);
break;
case R.id.Recommend_8:
Intent intent8 = new Intent(Home_F.this.getActivity(), Classification.class);
startActivity(intent8);
break;
default:
break;
}
}
}
| [
"[email protected]"
] | |
023869b1d5826380baa6f5000b58a6a30da2e75d | 96670d2b28a3fb75d2f8258f31fc23d370af8a03 | /reverse_engineered/sources/ch/qos/logback/classic/joran/action/LevelAction.java | 1821ca9cf850613332c07a14297d34275f36cca7 | [] | no_license | P79N6A/speedx | 81a25b63e4f98948e7de2e4254390cab5612dcbd | 800b6158c7494b03f5c477a8cf2234139889578b | refs/heads/master | 2020-05-30T18:43:52.613448 | 2019-06-02T07:57:10 | 2019-06-02T08:15:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,433 | java | package ch.qos.logback.classic.joran.action;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.action.ActionConst;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.xml.sax.Attributes;
@Deprecated
public class LevelAction extends Action {
boolean inError = false;
public void begin(InterpretationContext interpretationContext, String str, Attributes attributes) {
Object peekObject = interpretationContext.peekObject();
if (peekObject instanceof Logger) {
Logger logger = (Logger) peekObject;
String name = logger.getName();
String subst = interpretationContext.subst(attributes.getValue("value"));
if (ActionConst.INHERITED.equalsIgnoreCase(subst) || ActionConst.NULL.equalsIgnoreCase(subst)) {
logger.setLevel(null);
} else {
logger.setLevel(Level.toLevel(subst, Level.DEBUG));
}
addInfo(name + " level set to " + logger.getLevel());
return;
}
this.inError = true;
addError("For element <level>, could not find a logger at the top of execution stack.");
}
public void end(InterpretationContext interpretationContext, String str) {
}
public void finish(InterpretationContext interpretationContext) {
}
}
| [
"Gith1974"
] | Gith1974 |
ca671b69dea314adfd9cf410c162757e759402c2 | 58a0438fc9e8371289f9c8f72024f157212705b8 | /src/com/user/controller/Logout.java | 2eb1c65f89e30126166626e3e5ac401904f1521e | [] | no_license | Ashish-rajpoot/SchoolManagmentSystem | acb1c6f6bca174d2e1385cdd3c6c99b2047f1ad8 | a45c29259013748f3890825215d112d4826dad2c | refs/heads/master | 2023-03-12T11:20:17.514407 | 2021-03-06T05:02:42 | 2021-03-06T05:02:42 | 344,323,524 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,098 | java | package com.user.controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(name = "logout", urlPatterns = {"/map/Logout"})
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Logout() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpSession session = request.getSession(false);
session.setAttribute("user", "");
session.removeAttribute("user");
session.invalidate();
response.sendRedirect("/SchoolManagmentSystem/login.jsp");
}
}
| [
"[email protected]"
] | |
0565f48f0b932ed9072a5eb0943ed25d222652a2 | 8e6e9df4005eb8fcde1e567269b9d3da08a12032 | /src/main/java/com/example/shoponline1/controller/MainController.java | f29a94772c80b1690911a59f8e1a7d94dec5de7b | [] | no_license | thanhnhat26061998/shoponline | 5c01b553e9ba005dc65cd38cbdf4a1fcd3361c66 | 0b5a771b9375a5a600fcaccb9fde0bbe9c449982 | refs/heads/master | 2022-12-22T23:27:19.588872 | 2020-10-01T12:52:15 | 2020-10-01T12:52:15 | 270,947,045 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,974 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.shoponline1.controller;
import com.example.shoponline1.dao.IProductDetailDao;
import com.example.shoponline1.dto.CartInfo;
import com.example.shoponline1.dto.CartLineInfo;
import com.example.shoponline1.dto.ProductCartDto;
import com.example.shoponline1.dto.ProductDto;
import com.example.shoponline1.entity.Product;
import com.example.shoponline1.entity.ProductDetail;
import com.example.shoponline1.entity.User;
import com.example.shoponline1.service.OrderServiceImpl;
import com.example.shoponline1.service.ProductDetailServiceImpl;
import com.example.shoponline1.service.ProductServiceImpl;
import com.example.shoponline1.utils.Utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
*
* @author thanh
*/
@Controller
@Transactional
public class MainController {
@Autowired
private OrderServiceImpl orderDAO;
@Autowired
private ProductServiceImpl productDAO;
@Autowired
private ProductDetailServiceImpl detailServiceImpl;
@Autowired
private IProductDetailDao productDetailDao;
//@Autowired
//private CustomerFormValidator customerFormValidator;
@InitBinder
public void myInitBinder(WebDataBinder dataBinder) {
Object target = dataBinder.getTarget();
if (target == null) {
return;
}
// Trường hợp update SL trên giỏ hàng.
// (@ModelAttribute("cartForm") @Validated CartInfo cartForm)
if (target.getClass() == CartInfo.class) {
} // Trường hợp save thông tin khách hàng.
// (@ModelAttribute @Validated CustomerInfo customerForm)
// else if (target.getClass() == CustomerForm.class) {
// dataBinder.setValidator(customerFormValidator);
// }
}
/*@RequestMapping("/")
public String listProductHandler(Model model, //
@RequestParam(value = "name", defaultValue = "") String likeName,
@RequestParam(value = "page", defaultValue = "1") int page) {
final int maxResult = 5;
final int maxNavigationPage = 10;
PaginationResult<ProductInfo> result = productDAO.queryProducts(page, //
maxResult, maxNavigationPage, likeName);
model.addAttribute("paginationProducts", result);
return "index";
}**/
@RequestMapping({"/buyProduct"})
public String listProductHandler(HttpServletRequest request, Model model, //
@RequestParam(value = "code", defaultValue = "") Integer code,
@RequestParam(value = "quantity", defaultValue = "") Integer quantity) {
ProductDetail productDetail = null;
if (code != null) {
//product = productDAO.findById(code);
productDetail = detailServiceImpl.findById(code);
}
if (productDetail != null) {
//
CartInfo cartInfo = Utils.getCartInSession(request);
ProductCartDto productInfo = new ProductCartDto(productDetail);
cartInfo.addProduct(productInfo, quantity);
}
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "redirect:/cart";
}
@RequestMapping({"/buyProducts"})
public String listProductHandlers(HttpServletRequest request, Model model, //
@RequestParam(value = "code", defaultValue = "") Integer code,
@RequestParam(value = "quantity", defaultValue = "") Integer quantity) {
ProductDetail productDetail = null;
if (code != null) {
//product = productDAO.findById(code);
productDetail = detailServiceImpl.findById(code);
}
if (productDetail != null) {
//
CartInfo cartInfo = Utils.getCartInSession(request);
ProductCartDto productInfo = new ProductCartDto(productDetail);
cartInfo.addProduct(productInfo, 1);
}
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "redirect:/home";
}
@RequestMapping({"/cartRemoveProduct"})
public String removeProductHandler(HttpServletRequest request, Model model, //
@RequestParam(value = "code", defaultValue = "") Integer code) {
ProductDetail productDetail = null;
if (code != null) {
//product = productDAO.findById(code);
productDetail = detailServiceImpl.findById(code);
}
if (productDetail != null) {
CartInfo cartInfo = Utils.getCartInSession(request);
ProductCartDto productInfo = new ProductCartDto(productDetail);
cartInfo.removeProduct(productInfo);
}
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "redirect:/cart";
}
// POST: Giảm số lượng cho các sản phẩm đã mua.
@RequestMapping(value = {"/decreaseProduct"}, method = RequestMethod.GET)
public String shoppingCartDecreaseQty(HttpServletRequest request, //
Model model, //
@ModelAttribute("cartForm") CartInfo cartForm,
@RequestParam(value = "code", defaultValue = "") Integer code) {
ProductDetail product = null;
if (code != null) {
product = productDetailDao.findById(code).get();
}
if (product != null) {
CartInfo cartInfo = Utils.getCartInSession(request);
List<CartLineInfo> lines = cartInfo.getCartLines();
for (CartLineInfo line : lines) {
if ((line.getProductInfo().getProductId() == (code)) && (line.getQuantity() > 1)) {
int newQuantity = line.getQuantity() - 1;
if (line != null) {
line.setQuantity(newQuantity);
}
}
}
}
return "redirect:/cart";
}
// POST: Tăng số lượng cho các sản phẩm đã mua.
@RequestMapping(value = {"/increaseProduct"}, method = RequestMethod.GET)
public String shoppingCartIncreaseQty(HttpServletRequest request, //
Model model, //
@ModelAttribute("cartForm") CartInfo cartForm,
@RequestParam(value = "code", defaultValue = "") Integer code) {
ProductDetail product = null;
if (code != null) {
product = productDetailDao.findById(code).get();
}
if (product != null) {
CartInfo cartInfo = Utils.getCartInSession(request);
List<CartLineInfo> lines = cartInfo.getCartLines();
for (CartLineInfo line : lines) {
if ((line.getProductInfo().getProductId() == (code)) && (line.getQuantity() <= 10)) {
int newQuantity = line.getQuantity() + 1;
if (line != null) {
line.setQuantity(newQuantity);
}
}
}
}
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "redirect:/cart";
}
// GET: Hiển thị giỏ hàng.
@RequestMapping(value = {"/cart"}, method = RequestMethod.GET)
public String shoppingCart(HttpServletRequest request, Model model, HttpSession session) {
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
if (session.getAttribute("user") != null) {
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
}
return "business/cart/cart";
}
// GET: Nhập thông tin khách hàng.
/* @RequestMapping(value = {"/shoppingCartCustomer"}, method = RequestMethod.GET)
public String shoppingCartCustomerForm(HttpServletRequest request, Model model,
@ModelAttribute("cartForm") CartInfo cartForm,
HttpSession session) {
CartInfo cartInfo = Utils.getCartInSession(request);
if (cartInfo.isEmpty()) {
return "redirect:/cart";
}
if (session.getAttribute("user") != null) {
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
}
//CustomerForm customerForm = new CustomerForm(customerInfo);
//model.addAttribute("customerForm", user);
model.addAttribute("cartForm", cartInfo);
return "business/cart/customerInfo";
}
// POST: Save thông tin khách hàng.
@RequestMapping(value = {"/shoppingCartCustomer"}, method = RequestMethod.POST)
public String shoppingCartCustomerSave(HttpServletRequest request, //
Model model, //
@ModelAttribute("customerForm") @Validated CustomerForm customerForm, //
BindingResult result, //
final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
customerForm.setValid(false);
// Forward tới trang nhập lại.
return "customerInfo";
}
customerForm.setValid(true);
CartInfo cartInfo = Utils.getCartInSession(request);
CustomerInfo customerInfo = new CustomerInfo(customerForm);
cartInfo.setCustomerInfo(customerInfo);
return "redirect:/shoppingCartConfirmation";
}*/
// GET: Xem lại thông tin để xác nhận.
@RequestMapping(value = {"/shoppingCartConfirmation"}, method = RequestMethod.GET)
public String shoppingCartConfirmationReview(HttpServletRequest request,
Model model, HttpSession session) {
CartInfo cartInfo = Utils.getCartInSession(request);
if (cartInfo == null || cartInfo.isEmpty()) {
return "redirect:/cart";
}
if (session.getAttribute("user") != null) {
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
} else {
return "business/user/login";
}
model.addAttribute("myCart", cartInfo);
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "business/cart/infoConfirm";
}
// POST: Gửi đơn hàng (Save).
@RequestMapping(value = {"/confirmed"}, method = RequestMethod.GET)
public String shoppingCartConfirmationSave(HttpServletRequest request,
Model model, HttpSession session) {
CartInfo cartInfo = Utils.getCartInSession(request);
if (cartInfo.isEmpty()) {
return "redirect:/cart";
} else if (session.getAttribute("user") == null) {
return "business/user/login";
}
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
try {
orderDAO.saveOrder(cartInfo, user);
} catch (Exception e) {
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "business/cart/infoConfirm";
}
// Xóa giỏ hàng khỏi session.
Utils.removeCartInSession(request);
// Lưu thông tin đơn hàng cuối đã xác nhận mua.
Utils.storeLastOrderedCartInSession(request, cartInfo);
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "redirect:/shoppingCartFinalize";
}
@RequestMapping(value = {"/shoppingCartFinalize"}, method = RequestMethod.GET)
public String shoppingCartFinalize(HttpServletRequest request, Model model,
HttpSession session) {
CartInfo lastOrderedCart = Utils.getLastOrderedCartInSession(request);
if (lastOrderedCart == null) {
return "redirect:/cart";
}
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
model.addAttribute("lastOrderedCart", lastOrderedCart);
CartInfo myCart = Utils.getCartInSession(request);
model.addAttribute("cartForm", myCart);
return "business/cart/finish";
}
/* @RequestMapping(value = {"/productImage"}, method = RequestMethod.GET)
public void productImage(HttpServletRequest request, HttpServletResponse response, Model model,
@RequestParam("code") Integer code) throws IOException {
Product product = null;
if (code != null) {
product = this.productDAO.findProduct(code);
}
if (product != null && product.getImage() != null) {
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
response.getOutputStream().write(product.getImage());
}
response.getOutputStream().close();
}*/
}
| [
"[email protected]"
] | |
e48b13a8be2fce014a6b8d0a639117ba0aa232c2 | 2291e54fd076ba1b09310b59e74b9e6cf962bcf8 | /src/test/java/com/richo/test/findbugs/AppTest.java | 0c996d2454261c29289270da7f800de07ab07144 | [] | no_license | RichoDemus/findbugs-test | a84a19abfe0a105dbe7a88c87403de6567510d72 | 66e64206009372ce64e6520d1863432de7036009 | refs/heads/master | 2021-01-23T15:42:39.653412 | 2015-02-09T13:53:13 | 2015-02-09T13:53:13 | 30,418,883 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 651 | java | package com.richo.test.findbugs;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"[email protected]"
] | |
8d2a35d031869cd32d2e44d3ad354819ca581367 | b5f5d0b4f322d6ff6408b2de18d294ee4b82fb6c | /org.insightech.er/src/org/insightech/er/editor/model/dbexport/java/ExportToJavaManager.java | f68d72ebd76e28c3e234fd5fd86fe20f29f485e2 | [] | no_license | ljincheng/ermaster | cebd3abbfad62a33381e219d884d3577a3bfe13b | 2d618e1666585d0ef69170d9685c0307cff2beaa | refs/heads/master | 2022-11-21T10:06:38.066623 | 2020-07-27T04:20:38 | 2020-07-27T04:20:38 | 282,792,445 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,901 | java | package org.insightech.er.editor.model.dbexport.java;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import org.insightech.er.ResourceString;
import org.insightech.er.db.sqltype.SqlType;
import org.insightech.er.editor.model.ERDiagram;
import org.insightech.er.editor.model.dbexport.java.exportcode.ExportToJavaComponent;
import org.insightech.er.editor.model.dbexport.java.exportcode.ExportToJavaProjectCode;
import org.insightech.er.editor.model.dbexport.java.exportcode.ExportToJavaTemplate;
import org.insightech.er.editor.model.diagram_contents.element.node.NodeElement;
import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable;
import org.insightech.er.editor.model.diagram_contents.element.node.table.TableView;
import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn;
import org.insightech.er.editor.model.settings.export.ExportJavaSetting;
import org.insightech.er.util.Check;
import org.insightech.er.util.Format;
import org.insightech.er.util.io.FileUtils;
import org.insightech.er.util.io.IOUtils;
public class ExportToJavaManager {
private static final String TEMPLATE_DIR = "javasource/";
private static final String[] KEYWORDS = { "java.template.constructor",
"java.template.getter.description",
"java.template.set.adder.description",
"java.template.set.getter.description",
"java.template.set.property.description",
"java.template.set.setter.description",
"java.template.setter.description", };
private static final String TEMPLATE;
private static final String IMPLEMENTS;
private static final String PROPERTIES;
private static final String SET_PROPERTIES;
private static final String SETTER_GETTER;
private static final String SETTER_GETTER_ADDER;
private static final String HASHCODE_EQUALS;
private static final String HASHCODE_LOGIC;
private static final String EQUALS_LOGIC;
private static final String EXTENDS;
private static final String HIBERNATE_TEMPLATE;
private static final String HIBERNATE_PROPERTY;
private static final String HIBERNATE_ID;
private static final String HIBERNATE_COMPOSITE_ID;
private static final String HIBERNATE_COMPOSITE_ID_KEY;
private static final String BEBEENTITY_SETTER_GETTER;
static {
try {
TEMPLATE = loadResource("template");
IMPLEMENTS = loadResource("@implements");
PROPERTIES = loadResource("@properties");
SET_PROPERTIES = loadResource("@set_properties");
SETTER_GETTER = loadResource("@setter_getter");
SETTER_GETTER_ADDER = loadResource("@setter_getter_adder");
HASHCODE_EQUALS = loadResource("@hashCode_equals");
HASHCODE_LOGIC = loadResource("@hashCode logic");
EQUALS_LOGIC = loadResource("@equals logic");
EXTENDS = loadResource("@extends");
HIBERNATE_TEMPLATE = loadResource("hibernate/hbm");
HIBERNATE_PROPERTY = loadResource("hibernate/@property");
HIBERNATE_ID = loadResource("hibernate/@id");
HIBERNATE_COMPOSITE_ID = loadResource("hibernate/@composite_id");
HIBERNATE_COMPOSITE_ID_KEY = loadResource("hibernate/@composite_id_key");
BEBEENTITY_SETTER_GETTER = loadResource("entity/@setter_getter");
} catch (IOException e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
private ExportJavaSetting exportJavaSetting;
protected ERDiagram diagram;
private String packageDir;
private Set<String> importClasseNames;
private Set<String> sets;
public ExportToJavaManager(ExportJavaSetting exportJavaSetting,
ERDiagram diagram) {
this.packageDir = exportJavaSetting.getPackageName().replaceAll("\\.",
"\\/");
this.exportJavaSetting = exportJavaSetting;
this.diagram = diagram;
this.importClasseNames = new TreeSet<String>();
this.sets = new TreeSet<String>();
}
protected void doPreTask(ERTable table) {
}
protected void doPostTask() throws InterruptedException {
}
public void doProcess() throws IOException, InterruptedException {
for (ERTable table : diagram.getDiagramContents().getContents()
.getTableSet().getList()) {
this.doPreTask(table);
String className = this.getClassName(table);
String compositeIdClassName = null;
String content =null;
if(this.exportJavaSetting.isWithBebeEntity())
{
// content=this.generateEntityContent(diagram, table, compositeIdClassName);
// ExportToJavaTemplate componentExp=new ExportToJavaComponent(this.exportJavaSetting);
// StringBuilder contents= componentExp.generateContent(diagram, table, compositeIdClassName);
// componentExp.writeOut(contents.toString());
ExportToJavaProjectCode.generateContent(diagram, table, compositeIdClassName, exportJavaSetting);
}
// }else{
if (this.exportJavaSetting.isWithHibernate()) {
if (table.getPrimaryKeySize() > 1) {
compositeIdClassName = this.getCamelCaseName(table) + "Id";
String compositeIdContent = this
.generateCompositeIdContent(diagram, table,
compositeIdClassName);
this.writeOut(File.separator + this.packageDir
+ File.separator + compositeIdClassName + ".java",
compositeIdContent);
}
String hbmContent = this.generateHbmContent(diagram, table,
compositeIdClassName);
this.writeOut(File.separator + this.packageDir + File.separator
+ className + ".hbm.xml", hbmContent);
}
content = this.generateContent(diagram, table,
compositeIdClassName);
// }
this.writeOut(File.separator + this.packageDir + File.separator
+ className + ".java", content);
}
}
protected String getClassName(ERTable table) {
return this.getCamelCaseName(table)
+ this.getCamelCaseName(
this.exportJavaSetting.getClassNameSuffix(), true);
}
protected String getCamelCaseName(ERTable table) {
return this.getCamelCaseName(table.getLogicalName(), true);
// return this.getCamelCaseName(table.getPhysicalName(), true);
}
protected String getCamelCaseName(String name,boolean capital,boolean toUpperCase)
{
String className = name.toLowerCase();
if(!toUpperCase)
{
className=name;
}
if (capital && className.length() > 0) {
String first = className.substring(0, 1);
String other = className.substring(1);
className = first.toUpperCase() + other;
}
while (className.indexOf("_") == 0) {
className = className.substring(1);
}
int index = className.indexOf("_");
while (index != -1) {
String before = className.substring(0, index);
if (className.length() == index + 1) {
className = before;
break;
}
String target = className.substring(index + 1, index + 2);
String after = null;
if (className.length() == index + 1) {
after = "";
} else {
after = className.substring(index + 2);
}
className = before + target.toUpperCase() + after;
index = className.indexOf("_");
}
return className;
}
protected String getCamelCaseName(String name, boolean capital) {
String className = name.toLowerCase();
if (capital && className.length() > 0) {
String first = className.substring(0, 1);
String other = className.substring(1);
className = first.toUpperCase() + other;
}
while (className.indexOf("_") == 0) {
className = className.substring(1);
}
int index = className.indexOf("_");
while (index != -1) {
String before = className.substring(0, index);
if (className.length() == index + 1) {
className = before;
break;
}
String target = className.substring(index + 1, index + 2);
String after = null;
if (className.length() == index + 1) {
after = "";
} else {
after = className.substring(index + 2);
}
className = before + target.toUpperCase() + after;
index = className.indexOf("_");
}
return className;
}
private static String loadResource(String templateName) throws IOException {
String resourceName = TEMPLATE_DIR + templateName + ".txt";
InputStream in = ExportToJavaManager.class.getClassLoader()
.getResourceAsStream(resourceName);
if (in == null) {
throw new FileNotFoundException(resourceName);
}
try {
String content = IOUtils.toString(in);
for (String keyword : KEYWORDS) {
content = content.replaceAll(keyword, Matcher
.quoteReplacement(ResourceString
.getResourceString(keyword)));
}
return content;
} finally {
in.close();
}
}
private String generateEntityContent(ERDiagram diagram,ERTable table,String compositeIdClassName)throws IOException
{
this.importClasseNames.clear();
this.importClasseNames.add("com.bebe.common.Entity");
this.sets.clear();
this.exportJavaSetting.setExtendsClass("com.bebe.common.Entity");
String content=TEMPLATE;
content = content.replace("@implements", IMPLEMENTS);
content=this.replaceEntityPropertiesInfo(content, table,table.getExpandedColumns(), table.getReferringElementList(), compositeIdClassName);
content = this.replaceHashCodeEqualsInfo(content, table,
compositeIdClassName);
// String classDescription = ResourceString.getResourceString(
// "java.template.class.description").replaceAll(
// "@LogicalTableName",
// Matcher.quoteReplacement(table.getLogicalName()));
String classDescription = ResourceString.getResourceString(
"java.template.class.description").replaceAll(
"@LogicalTableName",
Matcher.quoteReplacement(table.getPhysicalName()));
content = this.replaceClassInfo(content, classDescription,
this.getCamelCaseName(table),
this.exportJavaSetting.getClassNameSuffix());
content = this.replaceExtendInfo(content);
content = this.replaceImportInfo(content);
content = this.replaceConstructorInfo(content);
return content;
}
private String generateContent(ERDiagram diagram, ERTable table,
String compositeIdClassName) throws IOException {
this.importClasseNames.clear();
this.importClasseNames.add("java.io.Serializable");
this.sets.clear();
String content = TEMPLATE;
content = content.replace("@implements", IMPLEMENTS);
content = this.replacePropertiesInfo(content, table,
compositeIdClassName);
content = this.replaceHashCodeEqualsInfo(content, table,
compositeIdClassName);
String classDescription = ResourceString.getResourceString(
"java.template.class.description").replaceAll(
"@LogicalTableName",
Matcher.quoteReplacement(table.getLogicalName()));
content = this.replaceClassInfo(content, classDescription,
this.getCamelCaseName(table),
this.exportJavaSetting.getClassNameSuffix());
content = this.replaceExtendInfo(content);
content = this.replaceImportInfo(content);
content = this.replaceConstructorInfo(content);
return content;
}
private String generateCompositeIdContent(ERDiagram diagram, ERTable table,
String compositeIdClassName) throws IOException {
this.importClasseNames.clear();
this.importClasseNames.add("java.io.Serializable");
this.sets.clear();
String content = TEMPLATE;
content = content.replace("@implements", IMPLEMENTS);
content = this.replacePropertiesInfo(content, null,
table.getPrimaryKeys(), null, null);
content = this.replaceHashCodeEqualsInfo(content, table, null);
String classDescription = ResourceString.getResourceString(
"java.template.composite.id.class.description").replaceAll(
"@LogicalTableName",
Matcher.quoteReplacement(table.getLogicalName()));
content = this.replaceClassInfo(content, classDescription,
compositeIdClassName, "");
content = this.replaceExtendInfo(content);
content = this.replaceImportInfo(content);
content = this.replaceConstructorInfo(content);
return content;
}
private String replacePropertiesInfo(String content, ERTable table,
String compositeIdClassName) throws IOException {
return replacePropertiesInfo(content, table,
table.getExpandedColumns(), table.getReferringElementList(),
compositeIdClassName);
}
private String replacePropertiesInfo(String content, ERTable table,
List<NormalColumn> columns, List<NodeElement> referringElementList,
String compositeIdClassName) throws IOException {
StringBuilder properties = new StringBuilder();
StringBuilder setterGetters = new StringBuilder();
if (compositeIdClassName != null) {
this.addCompositeIdContent(properties, PROPERTIES,
compositeIdClassName, table);
this.addCompositeIdContent(setterGetters, SETTER_GETTER,
compositeIdClassName, table);
}
for (NormalColumn normalColumn : columns) {
if (compositeIdClassName == null || !normalColumn.isPrimaryKey()
|| normalColumn.isForeignKey()) {
this.addContent(properties, PROPERTIES, normalColumn);
this.addContent(setterGetters, SETTER_GETTER, normalColumn);
}
}
if (referringElementList != null) {
for (NodeElement referringElement : referringElementList) {
if (referringElement instanceof TableView) {
TableView tableView = (TableView) referringElement;
this.addContent(properties, SET_PROPERTIES, tableView);
this.addContent(setterGetters, SETTER_GETTER_ADDER,
tableView);
this.sets.add(tableView.getPhysicalName());
}
}
}
content = content.replaceAll("@properties\r\n",
Matcher.quoteReplacement(properties.toString()));
content = content.replaceAll("@setter_getter\r\n",
Matcher.quoteReplacement(setterGetters.toString()));
return content;
}
private String replaceEntityPropertiesInfo(String content, ERTable table,
List<NormalColumn> columns, List<NodeElement> referringElementList,
String compositeIdClassName) throws IOException {
StringBuilder properties = new StringBuilder();
StringBuilder setterGetters = new StringBuilder();
for (NormalColumn normalColumn : columns) {
if (compositeIdClassName == null || !normalColumn.isPrimaryKey()
|| normalColumn.isForeignKey()) {
//this.addContent(properties, PROPERTIES, normalColumn);
this.addContent(setterGetters, BEBEENTITY_SETTER_GETTER, normalColumn);
}
}
content = content.replaceAll("@properties\r\n",
Matcher.quoteReplacement(properties.toString()));
content = content.replaceAll("@setter_getter\r\n",
Matcher.quoteReplacement(setterGetters.toString()));
return content;
}
private String replaceHashCodeEqualsInfo(String content, ERTable table,
String compositeIdClassName) throws IOException {
if (compositeIdClassName != null) {
StringBuilder hashCodes = new StringBuilder();
StringBuilder equals = new StringBuilder();
this.addCompositeIdContent(hashCodes, HASHCODE_LOGIC,
compositeIdClassName, table);
this.addCompositeIdContent(equals, EQUALS_LOGIC,
compositeIdClassName, table);
String hashCodeEquals = HASHCODE_EQUALS;
hashCodeEquals = hashCodeEquals.replaceAll("@hashCode logic\r\n",
Matcher.quoteReplacement(hashCodes.toString()));
hashCodeEquals = hashCodeEquals.replaceAll("@equals logic\r\n",
equals.toString());
content = content.replaceAll("@hashCode_equals\r\n",
hashCodeEquals.toString());
} else if (table.getPrimaryKeySize() > 0) {
StringBuilder hashCodes = new StringBuilder();
StringBuilder equals = new StringBuilder();
for (NormalColumn primaryKey : table.getPrimaryKeys()) {
this.addContent(hashCodes, HASHCODE_LOGIC, primaryKey);
this.addContent(equals, EQUALS_LOGIC, primaryKey);
}
String hashCodeEquals = HASHCODE_EQUALS;
hashCodeEquals = hashCodeEquals.replaceAll("@hashCode logic\r\n",
hashCodes.toString());
hashCodeEquals = hashCodeEquals.replaceAll("@equals logic\r\n",
equals.toString());
content = content.replaceAll("@hashCode_equals\r\n",
hashCodeEquals.toString());
} else {
content = content.replaceAll("@hashCode_equals\r\n", "");
}
return content;
}
private String replaceClassInfo(String content, String classDescription,
String className, String classNameSufix) {
if (Check.isEmptyTrim(this.exportJavaSetting.getPackageName())) {
content = content.replaceAll("package @package;\r\n\r\n", "");
} else {
content = content.replaceAll("@package",
this.exportJavaSetting.getPackageName());
}
content = content.replaceAll("@classDescription", classDescription);
content = content.replaceAll("@PhysicalTableName", className);
content = content.replaceAll("@suffix",
this.getCamelCaseName(classNameSufix, true));
// content = content.replaceAll("@version", "@version \\$Id\\$");
content = content.replaceAll("@version", "@version ");
return content;
}
private String replaceExtendInfo(String content) throws IOException {
if (Check.isEmpty(this.exportJavaSetting.getExtendsClass())) {
content = content.replaceAll("@import extends\r\n", "");
content = content.replaceAll("@extends ", "");
} else {
this.importClasseNames
.add(this.exportJavaSetting.getExtendsClass());
content = content.replaceAll("@extends",
Matcher.quoteReplacement(EXTENDS));
int index = this.exportJavaSetting.getExtendsClass().lastIndexOf(
".");
String extendsClassWithoutPackage = null;
if (index == -1) {
extendsClassWithoutPackage = this.exportJavaSetting
.getExtendsClass();
} else {
extendsClassWithoutPackage = this.exportJavaSetting
.getExtendsClass().substring(index + 1);
}
content = content.replaceAll("@extendsClassWithoutPackage",
extendsClassWithoutPackage);
content = content.replaceAll("@extendsClass",
this.exportJavaSetting.getExtendsClass());
}
return content;
}
private String replaceImportInfo(String content) {
StringBuilder imports = new StringBuilder();
for (String importClasseName : this.importClasseNames) {
imports.append("import ");
imports.append(importClasseName);
imports.append(";\r\n");
}
content = content.replaceAll("@import\r\n",
Matcher.quoteReplacement(imports.toString()));
return content;
}
private String replaceConstructorInfo(String content) {
StringBuilder constructor = new StringBuilder();
for (String tableName : this.sets) {
constructor.append("\t\tthis.");
constructor.append(this.getCamelCaseName(tableName, false));
constructor.append("Set = new HashSet<");
constructor.append(this.getCamelCaseName(tableName, true)
+ this.getCamelCaseName(
this.exportJavaSetting.getClassNameSuffix(), true));
constructor.append(">();\r\n");
}
content = content.replaceAll("@constructor\r\n",
Matcher.quoteReplacement(constructor.toString()));
return content;
}
private void addContent(StringBuilder contents, String template,
NormalColumn normalColumn) {
String value = null;
if (normalColumn.isForeignKey()) {
NormalColumn referencedColumn = normalColumn
.getRootReferencedColumn();
ERTable referencedTable = (ERTable) referencedColumn
.getColumnHolder();
String className = this.getClassName(referencedTable);
value = template.replaceAll("@type",
Matcher.quoteReplacement(className));
value = value.replaceAll("@logicalColumnName",
referencedTable.getName());
String physicalName = normalColumn.getPhysicalName().toLowerCase();
physicalName = physicalName.replaceAll(referencedColumn
.getPhysicalName().toLowerCase(), "");
if (physicalName.indexOf(referencedTable.getPhysicalName()
.toLowerCase()) == -1) {
physicalName = physicalName + referencedTable.getPhysicalName();
}
value = value.replaceAll("@physicalColumnName",
this.getCamelCaseName(physicalName, false));
value = value.replaceAll("@PhysicalColumnName",
this.getCamelCaseName(physicalName, true,false));
} else {
value = template.replaceAll("@type",
this.getClassName(normalColumn.getType()));
value = value.replaceAll("@logicalColumnName",
normalColumn.getLogicalName());
value = value.replaceAll("@physicalColumnName", this
.getCamelCaseName(normalColumn.getPhysicalName(), false));
value = value
.replaceAll(
"@PhysicalColumnName",
this.getCamelCaseName(
normalColumn.getPhysicalName(), true,false));
}
contents.append(value);
contents.append("\r\n");
}
private void addContent(StringBuilder contents, String template,
TableView tableView) {
String value = template;
this.importClasseNames.add("java.util.Set");
this.importClasseNames.add("java.util.HashSet");
value = value.replaceAll("@setType", Matcher.quoteReplacement("Set<"
+ this.getCamelCaseName(tableView.getPhysicalName(), true)
+ this.getCamelCaseName(
this.exportJavaSetting.getClassNameSuffix(), true)
+ ">"));
value = value.replaceAll(
"@type",
Matcher.quoteReplacement(this.getCamelCaseName(
tableView.getPhysicalName(), true)
+ this.getCamelCaseName(
this.exportJavaSetting.getClassNameSuffix(),
true)));
value = value.replaceAll("@logicalColumnName",
Matcher.quoteReplacement(tableView.getName()));
value = value.replaceAll(
"@physicalColumnName",
Matcher.quoteReplacement(this.getCamelCaseName(
tableView.getPhysicalName(), false)));
value = value.replaceAll(
"@PhysicalColumnName",
Matcher.quoteReplacement(this.getCamelCaseName(
tableView.getPhysicalName(), true)));
contents.append(value);
contents.append("\r\n");
}
private void addCompositeIdContent(StringBuilder contents, String template,
String compositeIdClassName, ERTable table) {
String compositeIdPropertyName = compositeIdClassName.substring(0, 1)
.toLowerCase() + compositeIdClassName.substring(1);
String propertyDescription = ResourceString.getResourceString(
"java.template.composite.id.property.description").replaceAll(
"@LogicalTableName",
Matcher.quoteReplacement(table.getLogicalName()));
String value = template;
value = value.replaceAll("@type", compositeIdClassName);
value = value.replaceAll("@logicalColumnName", propertyDescription);
value = value
.replaceAll("@physicalColumnName", compositeIdPropertyName);
value = value.replaceAll("@PhysicalColumnName", compositeIdClassName);
contents.append(value);
contents.append("\r\n");
}
private String getClassName(SqlType type) {
if (type == null) {
return "";
}
Class clazz = type.getJavaClass();
String name = clazz.getCanonicalName();
if (!name.startsWith("java.lang")) {
this.importClasseNames.add(name);
}
return clazz.getSimpleName();
}
private String getFullClassName(SqlType type) {
if (type == null) {
return "";
}
Class clazz = type.getJavaClass();
String name = clazz.getCanonicalName();
return name;
}
private void writeOut(String dstPath, String content) throws IOException {
dstPath = this.exportJavaSetting.getJavaOutput() + File.separator
+ "src" + dstPath;
File file = new File(dstPath);
file.getParentFile().mkdirs();
FileUtils.writeStringToFile(file, content,
this.exportJavaSetting.getSrcFileEncoding());
}
private String generateHbmContent(ERDiagram diagram, ERTable table,
String compositeIdClassName) throws IOException {
String content = HIBERNATE_TEMPLATE;
content = content.replaceAll("@package", Matcher
.quoteReplacement(this.exportJavaSetting.getPackageName()));
content = content.replaceAll("@PhysicalTableName",
Matcher.quoteReplacement(this.getCamelCaseName(table)));
content = content.replaceAll("@suffix", Matcher.quoteReplacement(Format
.null2blank(this.exportJavaSetting.getClassNameSuffix())));
content = content.replaceAll("@realTableName",
Matcher.quoteReplacement(table.getPhysicalName()));
StringBuilder properties = new StringBuilder();
if (table.getPrimaryKeySize() == 1) {
for (NormalColumn column : table.getPrimaryKeys()) {
String property = HIBERNATE_ID;
property = property.replaceAll("@physicalColumnName",
this.getCamelCaseName(column.getPhysicalName(), false));
property = property.replaceAll("@realColumnName",
column.getPhysicalName());
property = property.replaceAll("@type",
this.getFullClassName(column.getType()));
property = property.replaceAll("@generator", "assigned");
properties.append(property);
}
} else if (table.getPrimaryKeySize() > 1) {
String property = HIBERNATE_COMPOSITE_ID;
StringBuilder keys = new StringBuilder();
for (NormalColumn column : table.getPrimaryKeys()) {
String key = HIBERNATE_COMPOSITE_ID_KEY;
key = key.replaceAll("@physicalColumnName",
this.getCamelCaseName(column.getPhysicalName(), false));
key = key.replaceAll("@realColumnName",
column.getPhysicalName());
key = key.replaceAll("@type",
this.getFullClassName(column.getType()));
keys.append(key);
}
String compositeIdPropertyName = compositeIdClassName.substring(0,
1).toLowerCase()
+ compositeIdClassName.substring(1);
property = property.replaceAll("@compositeIdPropertyName",
compositeIdPropertyName);
property = property.replaceAll("@compositeIdClassName",
compositeIdClassName);
property = property.replaceAll("@key_properties", keys.toString());
properties.append(property);
}
for (NormalColumn column : table.getExpandedColumns()) {
if (!column.isPrimaryKey()) {
String property = HIBERNATE_PROPERTY;
property = property.replaceAll("@physicalColumnName",
this.getCamelCaseName(column.getPhysicalName(), false));
property = property.replaceAll("@realColumnName",
column.getPhysicalName());
property = property.replaceAll("@type",
this.getFullClassName(column.getType()));
property = property.replaceAll("@not-null",
String.valueOf(column.isNotNull()));
properties.append(property);
}
}
content = content.replaceAll("@properties\r\n", properties.toString());
return content;
}
}
| [
"[email protected]"
] | |
95c3c384dd37d7dae5d70c777fc5159c4994865a | 75a3ba29e9afbc3d8f5ef22fbbb22767ecbea0c3 | /Robot.java | d1e309fe101e0538b8b716d733b6a7b79333ff60 | [] | no_license | Apostol6666/Robot | c29e131194bdb84d638ba97d04451a57efc3cc32 | 18582d84ddf7f34d366c27350a820cef8df8215d | refs/heads/master | 2022-12-16T13:18:16.701777 | 2020-09-29T15:43:37 | 2020-09-29T15:43:37 | 299,647,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,571 | java | package com.company;
public class Robot {
int x;
int y;
Direction direct;
public Robot(int x, int y, Direction dir) {
this.x = x;
this.y = y;
this.direct = dir;
}
public Direction getDirection() {
return this.direct;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void turnLeft() {
if (this.direct == Direction.UP) {
this.direct = Direction.LEFT;
} else if (this.direct == Direction.DOWN) {
this.direct = Direction.RIGHT;
} else if (this.direct == Direction.LEFT) {
this.direct = Direction.DOWN;
} else if (this.direct == Direction.RIGHT) {
this.direct = Direction.UP;
}
}
public void turnRight() {
if (this.direct == Direction.UP) {
this.direct = Direction.RIGHT;
} else if (this.direct == Direction.DOWN) {
this.direct = Direction.LEFT;
} else if (this.direct == Direction.LEFT) {
this.direct = Direction.UP;
} else if (this.direct == Direction.RIGHT) {
this.direct = Direction.DOWN;
}
}
public void stepForward() {
if (this.direct == Direction.UP) {
++this.y;
}
if (this.direct == Direction.DOWN) {
--this.y;
}
if (this.direct == Direction.LEFT) {
--this.x;
}
if (this.direct == Direction.RIGHT) {
++this.x;
}
}
}
| [
"[email protected]"
] | |
fca0988a8dbf52a6c81c5d1d4b260da70b21fa9c | 5456502f97627278cbd6e16d002d50f1de3da7bb | /content/public/android/java/src/org/chromium/content/browser/ContentViewCore.java | b3093cf5c4c0635466a792fd521e19ece0d8753e | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 125,925 | java | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.assist.AssistStructure.ViewNode;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.util.Pair;
import android.view.ActionMode;
import android.view.DragEvent;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStructure;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener;
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import org.chromium.base.CommandLine;
import org.chromium.base.ObserverList;
import org.chromium.base.ObserverList.RewindableIterator;
import org.chromium.base.TraceEvent;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content.browser.accessibility.BrowserAccessibilityManager;
import org.chromium.content.browser.accessibility.captioning.CaptioningBridgeFactory;
import org.chromium.content.browser.accessibility.captioning.SystemCaptioningBridge;
import org.chromium.content.browser.accessibility.captioning.TextTrackSettings;
import org.chromium.content.browser.input.AnimationIntervalProvider;
import org.chromium.content.browser.input.ImeAdapter;
import org.chromium.content.browser.input.InputMethodManagerWrapper;
import org.chromium.content.browser.input.JoystickScrollProvider;
import org.chromium.content.browser.input.JoystickZoomProvider;
import org.chromium.content.browser.input.SelectPopup;
import org.chromium.content.browser.input.SelectPopupDialog;
import org.chromium.content.browser.input.SelectPopupDropdown;
import org.chromium.content.browser.input.SelectPopupItem;
import org.chromium.content.common.ContentSwitches;
import org.chromium.content_public.browser.AccessibilitySnapshotCallback;
import org.chromium.content_public.browser.AccessibilitySnapshotNode;
import org.chromium.content_public.browser.ActionModeCallbackHelper;
import org.chromium.content_public.browser.GestureStateListener;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.device.gamepad.GamepadList;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.ViewAndroidDelegate;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.base.ime.TextInputType;
import org.chromium.ui.display.DisplayAndroid;
import org.chromium.ui.display.DisplayAndroid.DisplayAndroidObserver;
import java.lang.annotation.Annotation;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
/**
* Provides a Java-side 'wrapper' around a WebContent (native) instance.
* Contains all the major functionality necessary to manage the lifecycle of a ContentView without
* being tied to the view system.
*/
@JNINamespace("content")
public class ContentViewCore implements AccessibilityStateChangeListener, DisplayAndroidObserver,
SystemCaptioningBridge.SystemCaptioningBridgeListener,
WindowAndroidProvider {
private static final String TAG = "cr_ContentViewCore";
// Used to avoid enabling zooming in / out if resulting zooming will
// produce little visible difference.
private static final float ZOOM_CONTROLS_EPSILON = 0.007f;
private static final ZoomControlsDelegate NO_OP_ZOOM_CONTROLS_DELEGATE =
new ZoomControlsDelegate() {
@Override
public void invokeZoomPicker() {}
@Override
public void dismissZoomPicker() {}
@Override
public void updateZoomControls() {}
};
// If the embedder adds a JavaScript interface object that contains an indirect reference to
// the ContentViewCore, then storing a strong ref to the interface object on the native
// side would prevent garbage collection of the ContentViewCore (as that strong ref would
// create a new GC root).
// For that reason, we store only a weak reference to the interface object on the
// native side. However we still need a strong reference on the Java side to
// prevent garbage collection if the embedder doesn't maintain their own ref to the
// interface object - the Java side ref won't create a new GC root.
// This map stores those references. We put into the map on addJavaScriptInterface()
// and remove from it in removeJavaScriptInterface(). The annotation class is stored for
// the purpose of migrating injected objects from one instance of CVC to another, which
// is used by Android WebView to support WebChromeClient.onCreateWindow scenario.
private final Map<String, Pair<Object, Class>> mJavaScriptInterfaces =
new HashMap<String, Pair<Object, Class>>();
// Additionally, we keep track of all Java bound JS objects that are in use on the
// current page to ensure that they are not garbage collected until the page is
// navigated. This includes interface objects that have been removed
// via the removeJavaScriptInterface API and transient objects returned from methods
// on the interface object. Note we use HashSet rather than Set as the native side
// expects HashSet (no bindings for interfaces).
private final HashSet<Object> mRetainedJavaScriptObjects = new HashSet<Object>();
/**
* A {@link WebContentsObserver} that listens to frame navigation events.
*/
private static class ContentViewWebContentsObserver extends WebContentsObserver {
// Using a weak reference avoids cycles that might prevent GC of WebView's WebContents.
private final WeakReference<ContentViewCore> mWeakContentViewCore;
ContentViewWebContentsObserver(ContentViewCore contentViewCore) {
super(contentViewCore.getWebContents());
mWeakContentViewCore = new WeakReference<ContentViewCore>(contentViewCore);
}
@Override
public void didFailLoad(boolean isProvisionalLoad, boolean isMainFrame, int errorCode,
String description, String failingUrl, boolean wasIgnoredByHandler) {
// Navigation that fails the provisional load will have the strong binding removed
// here. One for which the provisional load is commited will have the strong binding
// removed in navigationEntryCommitted() below.
if (isProvisionalLoad) determinedProcessVisibility();
}
@Override
public void didNavigateMainFrame(String url, String baseUrl,
boolean isNavigationToDifferentPage, boolean isFragmentNavigation, int statusCode) {
if (!isNavigationToDifferentPage) return;
resetPopupsAndInput();
}
@Override
public void renderProcessGone(boolean wasOomProtected) {
resetPopupsAndInput();
ContentViewCore contentViewCore = mWeakContentViewCore.get();
if (contentViewCore == null) return;
contentViewCore.mImeAdapter.resetAndHideKeyboard();
}
@Override
public void navigationEntryCommitted() {
determinedProcessVisibility();
}
private void resetPopupsAndInput() {
ContentViewCore contentViewCore = mWeakContentViewCore.get();
if (contentViewCore == null) return;
contentViewCore.mIsMobileOptimizedHint = false;
contentViewCore.hidePopupsAndClearSelection();
contentViewCore.resetScrollInProgress();
}
private void determinedProcessVisibility() {
ContentViewCore contentViewCore = mWeakContentViewCore.get();
if (contentViewCore == null) return;
// Signal to the process management logic that we can now rely on the process
// visibility signal for binding management. Before the navigation commits, its
// renderer is considered background even if the pending navigation happens in the
// foreground renderer. See crbug.com/421041 for more details.
ChildProcessLauncher.determinedVisibility(contentViewCore.getCurrentRenderProcessId());
}
}
/**
* Returns interval between consecutive animation frames.
*/
// TODO(crbug.com/635567): Fix this properly.
@SuppressLint("ParcelCreator")
private static class SystemAnimationIntervalProvider implements AnimationIntervalProvider {
@Override
public long getLastAnimationFrameInterval() {
return AnimationUtils.currentAnimationTimeMillis();
}
}
/**
* {@ResultReceiver} passed in InputMethodManager#showSoftInput}. We need this to scroll to the
* editable node at the right timing, which is after input method window shows up.
*/
// TODO(crbug.com/635567): Fix this properly.
@SuppressLint("ParcelCreator")
private static class ShowKeyboardResultReceiver extends ResultReceiver {
// Unfortunately, the memory life cycle of ResultReceiver object, once passed in
// showSoftInput(), is in the control of Android's input method framework and IME app,
// so we use a weakref to avoid tying CVC's lifetime to that of ResultReceiver object.
private final WeakReference<ContentViewCore> mContentViewCore;
public ShowKeyboardResultReceiver(ContentViewCore contentViewCore, Handler handler) {
super(handler);
mContentViewCore = new WeakReference<>(contentViewCore);
}
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
ContentViewCore contentViewCore = mContentViewCore.get();
if (contentViewCore == null) return;
contentViewCore.onShowKeyboardReceiveResult(resultCode);
}
}
/**
* Interface that consumers of {@link ContentViewCore} must implement to allow the proper
* dispatching of view methods through the containing view.
*
* <p>
* All methods with the "super_" prefix should be routed to the parent of the
* implementing container view.
*/
@SuppressWarnings("javadoc")
public interface InternalAccessDelegate {
/**
* @see View#onKeyUp(keyCode, KeyEvent)
*/
boolean super_onKeyUp(int keyCode, KeyEvent event);
/**
* @see View#dispatchKeyEvent(KeyEvent)
*/
boolean super_dispatchKeyEvent(KeyEvent event);
/**
* @see View#onGenericMotionEvent(MotionEvent)
*/
boolean super_onGenericMotionEvent(MotionEvent event);
/**
* @see View#onConfigurationChanged(Configuration)
*/
void super_onConfigurationChanged(Configuration newConfig);
/**
* @see View#onScrollChanged(int, int, int, int)
*/
void onScrollChanged(int lPix, int tPix, int oldlPix, int oldtPix);
/**
* @see View#awakenScrollBars()
*/
boolean awakenScrollBars();
/**
* @see View#awakenScrollBars(int, boolean)
*/
boolean super_awakenScrollBars(int startDelay, boolean invalidate);
}
/**
* An interface for controlling visibility and state of embedder-provided zoom controls.
*/
public interface ZoomControlsDelegate {
/**
* Called when it's reasonable to show zoom controls.
*/
void invokeZoomPicker();
/**
* Called when zoom controls need to be hidden (e.g. when the view hides).
*/
void dismissZoomPicker();
/**
* Called when page scale has been changed, so the controls can update their state.
*/
void updateZoomControls();
}
/**
* An interface that allows the embedder to be notified when the results of
* extractSmartClipData are available.
*/
public interface SmartClipDataListener {
public void onSmartClipDataExtracted(String text, String html, Rect clipRect);
}
private final Context mContext;
private final String mProductVersion;
private ViewGroup mContainerView;
private InternalAccessDelegate mContainerViewInternals;
private WebContents mWebContents;
private WebContentsObserver mWebContentsObserver;
private ContentViewClient mContentViewClient;
// Native pointer to C++ ContentViewCoreImpl object which will be set by nativeInit().
private long mNativeContentViewCore = 0;
private boolean mAttachedToWindow;
private final ObserverList<GestureStateListener> mGestureStateListeners;
private final RewindableIterator<GestureStateListener> mGestureStateListenersIterator;
private ZoomControlsDelegate mZoomControlsDelegate;
private PopupZoomer mPopupZoomer;
private SelectPopup mSelectPopup;
private long mNativeSelectPopupSourceFrame = 0;
private OverscrollRefreshHandler mOverscrollRefreshHandler;
private Runnable mFakeMouseMoveRunnable = null;
// Only valid when focused on a text / password field.
private ImeAdapter mImeAdapter;
// Size of the viewport in physical pixels as set from onSizeChanged.
private int mViewportWidthPix;
private int mViewportHeightPix;
private int mPhysicalBackingWidthPix;
private int mPhysicalBackingHeightPix;
private int mTopControlsHeightPix;
private int mBottomControlsHeightPix;
private boolean mTopControlsShrinkBlinkSize;
// Cached copy of all positions and scales as reported by the renderer.
private final RenderCoordinates mRenderCoordinates;
// Provides smooth gamepad joystick-driven scrolling.
private final JoystickScrollProvider mJoystickScrollProvider;
// Provides smooth gamepad joystick-driven zooming.
private JoystickZoomProvider mJoystickZoomProvider;
private boolean mIsMobileOptimizedHint;
private SelectionPopupController mSelectionPopupController;
private boolean mPreserveSelectionOnNextLossOfFocus;
// Whether native accessibility, i.e. without any script injection, is allowed.
private boolean mNativeAccessibilityAllowed;
// Whether native accessibility, i.e. without any script injection, has been enabled.
private boolean mNativeAccessibilityEnabled;
// Handles native accessibility, i.e. without any script injection.
private BrowserAccessibilityManager mBrowserAccessibilityManager;
// System accessibility service.
private final AccessibilityManager mAccessibilityManager;
// If true, the web contents are obscured by another view and we shouldn't
// return an AccessibilityNodeProvider or process touch exploration events.
private boolean mIsObscuredByAnotherView;
// Notifies the ContentViewCore when platform closed caption settings have changed
// if they are supported. Otherwise does nothing.
private final SystemCaptioningBridge mSystemCaptioningBridge;
// Accessibility touch exploration state.
private boolean mTouchExplorationEnabled;
// Whether accessibility focus should be set to the page when it finishes loading.
// This only applies if an accessibility service like TalkBack is running.
// This is desirable behavior for a browser window, but not for an embedded
// WebView.
private boolean mShouldSetAccessibilityFocusOnPageLoad;
// Temporary notification to tell onSizeChanged to focus a form element,
// because the OSK was just brought up.
private final Rect mFocusPreOSKViewportRect = new Rect();
// Store the x, y coordinates of the last touch or mouse event.
private float mLastFocalEventX;
private float mLastFocalEventY;
// Whether a touch scroll sequence is active, used to hide text selection
// handles. Note that a scroll sequence will *always* bound a pinch
// sequence, so this will also be true for the duration of a pinch gesture.
private boolean mTouchScrollInProgress;
// The outstanding fling start events that hasn't got fling end yet. It may be > 1 because
// onNativeFlingStopped() is called asynchronously.
private int mPotentiallyActiveFlingCount;
private SmartClipDataListener mSmartClipDataListener = null;
/**
* PID used to indicate an invalid render process.
*/
// Keep in sync with the value returned from ContentViewCoreImpl::GetCurrentRendererProcessId()
// if there is no render process.
public static final int INVALID_RENDER_PROCESS_PID = 0;
// Offsets for the events that passes through this ContentViewCore.
private float mCurrentTouchOffsetX;
private float mCurrentTouchOffsetY;
// Offsets for smart clip
private int mSmartClipOffsetX;
private int mSmartClipOffsetY;
// Whether the ContentViewCore requires the WebContents to be fullscreen in order to lock the
// screen orientation.
private boolean mFullscreenRequiredForOrientationLock = true;
// A ViewAndroidDelegate that delegates to the current container view.
private ViewAndroidDelegate mViewAndroidDelegate;
// A flag to determine if we enable hover feature or not.
private Boolean mEnableTouchHover;
// NOTE: This object will not be released by Android framework until the matching
// ResultReceiver in the InputMethodService (IME app) gets gc'ed.
private ShowKeyboardResultReceiver mShowKeyboardResultReceiver;
// The list of observers that are notified when ContentViewCore changes its WindowAndroid.
private final ObserverList<WindowAndroidChangedObserver> mWindowAndroidChangedObservers;
/**
* @param webContents The {@link WebContents} to find a {@link ContentViewCore} of.
* @return A {@link ContentViewCore} that is connected to {@code webContents} or
* {@code null} if none exists.
*/
public static ContentViewCore fromWebContents(WebContents webContents) {
return nativeFromWebContentsAndroid(webContents);
}
/**
* Constructs a new ContentViewCore. Embedders must call initialize() after constructing
* a ContentViewCore and before using it.
*
* @param context The context used to create this.
*/
public ContentViewCore(Context context, String productVersion) {
mContext = context;
mProductVersion = productVersion;
mRenderCoordinates = new RenderCoordinates();
mJoystickScrollProvider = new JoystickScrollProvider(this);
mAccessibilityManager = (AccessibilityManager)
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
mSystemCaptioningBridge = CaptioningBridgeFactory.getSystemCaptioningBridge(mContext);
mGestureStateListeners = new ObserverList<GestureStateListener>();
mGestureStateListenersIterator = mGestureStateListeners.rewindableIterator();
mWindowAndroidChangedObservers = new ObserverList<WindowAndroidChangedObserver>();
}
/**
* @return The context used for creating this ContentViewCore.
*/
@CalledByNative
public Context getContext() {
return mContext;
}
/**
* @return The ViewGroup that all view actions of this ContentViewCore should interact with.
*/
public ViewGroup getContainerView() {
return mContainerView;
}
/**
* @return The WebContents currently being rendered.
*/
public WebContents getWebContents() {
return mWebContents;
}
/**
* @return The WindowAndroid associated with this ContentViewCore.
*/
@Override
public WindowAndroid getWindowAndroid() {
if (mNativeContentViewCore == 0) return null;
return nativeGetJavaWindowAndroid(mNativeContentViewCore);
}
/**
* @return The SelectionPopupController that handles select action mode on web contents.
*/
@VisibleForTesting
public SelectionPopupController getSelectionPopupControllerForTesting() {
return mSelectionPopupController;
}
@VisibleForTesting
public void setSelectionPopupControllerForTesting(SelectionPopupController actionMode) {
mSelectionPopupController = actionMode;
}
@Override
public void addWindowAndroidChangedObserver(WindowAndroidChangedObserver observer) {
mWindowAndroidChangedObservers.addObserver(observer);
}
@Override
public void removeWindowAndroidChangedObserver(WindowAndroidChangedObserver observer) {
mWindowAndroidChangedObservers.removeObserver(observer);
}
/**
*
* @param browserControlsHeightPix The height of the browser controls in pixels.
* @param browserControlsShrinkBlinkSize The Y amount in pixels to shrink the viewport by. This
* specifies how much smaller the Blink layout size should be
* relative to the size of this View.
*/
public void setTopControlsHeight(int topControlsHeightPix, boolean topControlsShrinkBlinkSize) {
if (topControlsHeightPix == mTopControlsHeightPix
&& topControlsShrinkBlinkSize == mTopControlsShrinkBlinkSize) {
return;
}
mTopControlsHeightPix = topControlsHeightPix;
mTopControlsShrinkBlinkSize = topControlsShrinkBlinkSize;
if (mNativeContentViewCore != 0) nativeWasResized(mNativeContentViewCore);
}
/**
* Sets the height of the bottom controls. If necessary, triggers a renderer resize.
*/
public void setBottomControlsHeight(int bottomControlHeightPix) {
if (mBottomControlsHeightPix == bottomControlHeightPix) return;
mBottomControlsHeightPix = bottomControlHeightPix;
if (mNativeContentViewCore != 0) nativeWasResized(mNativeContentViewCore);
}
@VisibleForTesting
public void setImeAdapterForTest(ImeAdapter imeAdapter) {
mImeAdapter = imeAdapter;
}
@VisibleForTesting
public ImeAdapter getImeAdapterForTest() {
return mImeAdapter;
}
private ImeAdapter createImeAdapter() {
return new ImeAdapter(
new InputMethodManagerWrapper(mContext), new ImeAdapter.ImeAdapterDelegate() {
@Override
public void onImeEvent() {
mPopupZoomer.hide(true);
getContentViewClient().onImeEvent();
if (isFocusedNodeEditable()) mWebContents.dismissTextHandles();
}
@Override
public void onKeyboardBoundsUnchanged() {
assert mWebContents != null;
mWebContents.scrollFocusedEditableNodeIntoView();
}
@Override
public boolean performContextMenuAction(int id) {
assert mWebContents != null;
switch (id) {
case android.R.id.selectAll:
mWebContents.selectAll();
return true;
case android.R.id.cut:
mWebContents.cut();
return true;
case android.R.id.copy:
mWebContents.copy();
return true;
case android.R.id.paste:
mWebContents.paste();
return true;
default:
return false;
}
}
@Override
public View getAttachedView() {
return mContainerView;
}
@Override
public ResultReceiver getNewShowKeyboardReceiver() {
return ContentViewCore.this.getNewShowKeyboardReceiver();
}
});
}
/**
*
* @param viewDelegate Delegate to add/remove anchor views.
* @param internalDispatcher Handles dispatching all hidden or super methods to the
* containerView.
* @param webContents A WebContents instance to connect to.
* @param windowAndroid An instance of the WindowAndroid.
*/
// Perform important post-construction set up of the ContentViewCore.
// We do not require the containing view in the constructor to allow embedders to create a
// ContentViewCore without having fully created its containing view. The containing view
// is a vital component of the ContentViewCore, so embedders must exercise caution in what
// they do with the ContentViewCore before calling initialize().
// We supply the nativeWebContents pointer here rather than in the constructor to allow us
// to set the private browsing mode at a later point for the WebView implementation.
// Note that the caller remains the owner of the nativeWebContents and is responsible for
// deleting it after destroying the ContentViewCore.
public void initialize(ViewAndroidDelegate viewDelegate,
InternalAccessDelegate internalDispatcher, WebContents webContents,
WindowAndroid windowAndroid) {
mViewAndroidDelegate = viewDelegate;
setContainerView(viewDelegate.getContainerView());
long windowNativePointer = windowAndroid.getNativePointer();
assert windowNativePointer != 0;
mZoomControlsDelegate = NO_OP_ZOOM_CONTROLS_DELEGATE;
final float dipScale = windowAndroid.getDisplay().getDipScale();
mRenderCoordinates.reset();
mRenderCoordinates.setDeviceScaleFactor(dipScale, windowAndroid.getContext());
mNativeContentViewCore = nativeInit(webContents, mViewAndroidDelegate, windowNativePointer,
dipScale, mRetainedJavaScriptObjects);
mWebContents = nativeGetWebContentsAndroid(mNativeContentViewCore);
setContainerViewInternals(internalDispatcher);
initPopupZoomer(mContext);
mImeAdapter = createImeAdapter();
attachImeAdapter();
mSelectionPopupController = new SelectionPopupController(mContext, windowAndroid,
webContents, viewDelegate.getContainerView(), mRenderCoordinates, mImeAdapter);
mSelectionPopupController.setCallback(ActionModeCallbackHelper.EMPTY_CALLBACK);
mSelectionPopupController.setContainerView(getContainerView());
mWebContentsObserver = new ContentViewWebContentsObserver(this);
}
/**
* Updates the native {@link ContentViewCore} with a new window. This moves the NativeView and
* attached it to the new NativeWindow linked with the given {@link WindowAndroid}.
* @param windowAndroid The new {@link WindowAndroid} for this {@link ContentViewCore}.
*/
public void updateWindowAndroid(WindowAndroid windowAndroid) {
removeDisplayAndroidObserver();
long windowNativePointer = windowAndroid == null ? 0 : windowAndroid.getNativePointer();
nativeUpdateWindowAndroid(mNativeContentViewCore, windowNativePointer);
// TODO(yusufo): Rename this call to be general for tab reparenting.
// Clean up cached popups that may have been created with an old activity.
mSelectPopup = null;
destroyPastePopup();
addDisplayAndroidObserverIfNeeded();
for (WindowAndroidChangedObserver observer : mWindowAndroidChangedObservers) {
observer.onWindowAndroidChanged(windowAndroid);
}
}
/**
* Set {@link ActionMode.Callback} used by {@link SelectionPopupController}.
* @param callback ActionMode.Callback instance.
*/
public void setActionModeCallback(ActionMode.Callback callback) {
mSelectionPopupController.setCallback(callback);
}
private void addDisplayAndroidObserverIfNeeded() {
if (!mAttachedToWindow) return;
WindowAndroid windowAndroid = getWindowAndroid();
if (windowAndroid != null) {
DisplayAndroid display = windowAndroid.getDisplay();
display.addObserver(this);
onRotationChanged(display.getRotation());
onDIPScaleChanged(display.getDipScale());
}
}
private void removeDisplayAndroidObserver() {
WindowAndroid windowAndroid = getWindowAndroid();
if (windowAndroid != null) {
windowAndroid.getDisplay().removeObserver(this);
}
}
/**
* Sets a new container view for this {@link ContentViewCore}.
*
* <p>WARNING: This method can also be used to replace the existing container view,
* but you should only do it if you have a very good reason to. Replacing the
* container view has been designed to support fullscreen in the Webview so it
* might not be appropriate for other use cases.
*
* <p>This method only performs a small part of replacing the container view and
* embedders are responsible for:
* <ul>
* <li>Disconnecting the old container view from this ContentViewCore</li>
* <li>Updating the InternalAccessDelegate</li>
* <li>Reconciling the state of this ContentViewCore with the new container view</li>
* <li>Tearing down and recreating the native GL rendering where appropriate</li>
* <li>etc.</li>
* </ul>
*/
public void setContainerView(ViewGroup containerView) {
try {
TraceEvent.begin("ContentViewCore.setContainerView");
if (mContainerView != null) {
assert mOverscrollRefreshHandler == null;
hideSelectPopupWithCancelMessage();
mPopupZoomer.hide(false);
}
mContainerView = containerView;
mContainerView.setClickable(true);
if (mSelectionPopupController != null) {
mSelectionPopupController.setContainerView(containerView);
}
} finally {
TraceEvent.end("ContentViewCore.setContainerView");
}
}
@CalledByNative
private void onNativeContentViewCoreDestroyed(long nativeContentViewCore) {
assert nativeContentViewCore == mNativeContentViewCore;
mNativeContentViewCore = 0;
}
/**
* Set the Container view Internals.
* @param internalDispatcher Handles dispatching all hidden or super methods to the
* containerView.
*/
public void setContainerViewInternals(InternalAccessDelegate internalDispatcher) {
mContainerViewInternals = internalDispatcher;
}
@VisibleForTesting
void initPopupZoomer(Context context) {
mPopupZoomer = new PopupZoomer(context);
mPopupZoomer.setOnVisibilityChangedListener(new PopupZoomer.OnVisibilityChangedListener() {
// mContainerView can change, but this OnVisibilityChangedListener can only be used
// to add and remove views from the mContainerViewAtCreation.
private final ViewGroup mContainerViewAtCreation = mContainerView;
@Override
public void onPopupZoomerShown(final PopupZoomer zoomer) {
mContainerViewAtCreation.post(new Runnable() {
@Override
public void run() {
if (mContainerViewAtCreation.indexOfChild(zoomer) == -1) {
mContainerViewAtCreation.addView(zoomer);
}
}
});
}
@Override
public void onPopupZoomerHidden(final PopupZoomer zoomer) {
mContainerViewAtCreation.post(new Runnable() {
@Override
public void run() {
if (mContainerViewAtCreation.indexOfChild(zoomer) != -1) {
mContainerViewAtCreation.removeView(zoomer);
mContainerViewAtCreation.invalidate();
}
}
});
}
});
// TODO(yongsheng): LONG_TAP is not enabled in PopupZoomer. So need to dispatch a LONG_TAP
// gesture if a user completes a tap on PopupZoomer UI after a LONG_PRESS gesture.
PopupZoomer.OnTapListener listener = new PopupZoomer.OnTapListener() {
// mContainerView can change, but this OnTapListener can only be used
// with the mContainerViewAtCreation.
private final ViewGroup mContainerViewAtCreation = mContainerView;
@Override
public boolean onSingleTap(View v, MotionEvent e) {
mContainerViewAtCreation.requestFocus();
if (mNativeContentViewCore != 0) {
nativeSingleTap(mNativeContentViewCore, e.getEventTime(), e.getX(), e.getY());
}
return true;
}
@Override
public boolean onLongPress(View v, MotionEvent e) {
if (mNativeContentViewCore != 0) {
nativeLongPress(mNativeContentViewCore, e.getEventTime(), e.getX(), e.getY());
}
return true;
}
};
mPopupZoomer.setOnTapListener(listener);
}
@VisibleForTesting
public void setPopupZoomerForTest(PopupZoomer popupZoomer) {
mPopupZoomer = popupZoomer;
}
/**
* Destroy the internal state of the ContentView. This method may only be
* called after the ContentView has been removed from the view system. No
* other methods may be called on this ContentView after this method has
* been called.
* Warning: destroy() is not guranteed to be called in Android WebView.
* Any object that relies solely on destroy() being called to be cleaned up
* will leak in Android WebView. If appropriate, consider clean up in
* onDetachedFromWindow() which is guaranteed to be called in Android WebView.
*/
public void destroy() {
removeDisplayAndroidObserver();
if (mNativeContentViewCore != 0) {
nativeOnJavaContentViewCoreDestroyed(mNativeContentViewCore);
}
mWebContentsObserver.destroy();
mWebContentsObserver = null;
setSmartClipDataListener(null);
setZoomControlsDelegate(null);
mImeAdapter.resetAndHideKeyboard();
// TODO(igsolla): address TODO in ContentViewClient because ContentViewClient is not
// currently a real Null Object.
//
// Instead of deleting the client we use the Null Object pattern to avoid null checks
// in this class.
mContentViewClient = new ContentViewClient();
mWebContents = null;
mOverscrollRefreshHandler = null;
mNativeContentViewCore = 0;
mJavaScriptInterfaces.clear();
mRetainedJavaScriptObjects.clear();
for (mGestureStateListenersIterator.rewind(); mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onDestroyed();
}
mGestureStateListeners.clear();
hidePopupsAndPreserveSelection();
destroyPastePopup();
// See warning in javadoc before adding more clean up code here.
}
/**
* Returns true initially, false after destroy() has been called.
* It is illegal to call any other public method after destroy().
*/
public boolean isAlive() {
return mNativeContentViewCore != 0;
}
public void setContentViewClient(ContentViewClient client) {
if (client == null) {
throw new IllegalArgumentException("The client can't be null.");
}
mContentViewClient = client;
}
@VisibleForTesting
public ContentViewClient getContentViewClient() {
if (mContentViewClient == null) {
// We use the Null Object pattern to avoid having to perform a null check in this class.
// We create it lazily because most of the time a client will be set almost immediately
// after ContentView is created.
mContentViewClient = new ContentViewClient();
// We don't set the native ContentViewClient pointer here on purpose. The native
// implementation doesn't mind a null delegate and using one is better than passing a
// Null Object, since we cut down on the number of JNI calls.
}
return mContentViewClient;
}
@CalledByNative
private void onBackgroundColorChanged(int color) {
getContentViewClient().onBackgroundColorChanged(color);
}
/**
* @return Viewport width in physical pixels as set from onSizeChanged.
*/
@CalledByNative
public int getViewportWidthPix() {
return mViewportWidthPix;
}
/**
* @return Viewport height in physical pixels as set from onSizeChanged.
*/
@CalledByNative
public int getViewportHeightPix() {
return mViewportHeightPix;
}
/**
* @return Viewport height when the OSK is hidden in physical pixels as set from onSizeChanged.
*/
@CalledByNative
public int getViewportHeightWithOSKHiddenPix() {
return mViewportHeightPix + getContentViewClient().getSystemWindowInsetBottom();
}
/**
* @return Width of underlying physical surface.
*/
@CalledByNative
private int getPhysicalBackingWidthPix() {
return mPhysicalBackingWidthPix;
}
/**
* @return Height of underlying physical surface.
*/
@CalledByNative
private int getPhysicalBackingHeightPix() {
return mPhysicalBackingHeightPix;
}
/**
* @return The amount that the viewport size given to Blink is shrunk by the URL-bar..
*/
@CalledByNative
public boolean doBrowserControlsShrinkBlinkSize() {
return mTopControlsShrinkBlinkSize;
}
@CalledByNative
public int getTopControlsHeightPix() {
return mTopControlsHeightPix;
}
@CalledByNative
public int getBottomControlsHeightPix() {
return mBottomControlsHeightPix;
}
/**
* @return Current device scale factor (maps DIP pixels to physical pixels).
*/
@VisibleForTesting
public float getDeviceScaleFactor() {
return mRenderCoordinates.getDeviceScaleFactor();
}
/**
* @return Current page scale factor (maps CSS pixels to DIP pixels).
*/
@VisibleForTesting
public float getPageScaleFactor() {
return mRenderCoordinates.getPageScaleFactor();
}
/**
* @see android.webkit.WebView#getContentHeight()
*/
public float getContentHeightCss() {
return mRenderCoordinates.getContentHeightCss();
}
/**
* @see android.webkit.WebView#getContentWidth()
*/
public float getContentWidthCss() {
return mRenderCoordinates.getContentWidthCss();
}
/**
* @return The selected text (empty if no text selected).
*/
@VisibleForTesting
public String getSelectedText() {
return mSelectionPopupController.getSelectedText();
}
/**
* @return Whether the current focused node is editable.
*/
public boolean isFocusedNodeEditable() {
return mSelectionPopupController.isSelectionEditable();
}
/**
* @return Whether the HTML5 gamepad API is active.
*/
public boolean isGamepadAPIActive() {
return GamepadList.isGamepadAPIActive();
}
/**
* @see View#onTouchEvent(MotionEvent)
*/
public boolean onTouchEvent(MotionEvent event) {
// TODO(mustaq): Should we include MotionEvent.TOOL_TYPE_STYLUS here?
// crbug.com/592082
final boolean isTouchHandleEvent = false;
return sendTouchEvent(event, isTouchHandleEvent);
}
@TargetApi(Build.VERSION_CODES.M)
private boolean sendMouseEvent(MotionEvent event) {
TraceEvent.begin("sendMouseEvent");
MotionEvent offsetEvent = createOffsetMotionEvent(event);
try {
mContainerView.removeCallbacks(mFakeMouseMoveRunnable);
if (mNativeContentViewCore == 0) return false;
int eventAction = event.getActionMasked();
// For mousedown and mouseup events, we use ACTION_BUTTON_PRESS
// and ACTION_BUTTON_RELEASE respectively because they provide
// info about the changed-button.
if (eventAction == MotionEvent.ACTION_DOWN || eventAction == MotionEvent.ACTION_UP) {
return false;
}
nativeSendMouseEvent(mNativeContentViewCore, event.getEventTime(), eventAction,
offsetEvent.getX(), offsetEvent.getY(), event.getPointerId(0),
event.getPressure(0), event.getOrientation(0),
event.getAxisValue(MotionEvent.AXIS_TILT, 0), event.getActionButton(),
event.getButtonState(), event.getMetaState(), event.getToolType(0));
return true;
} finally {
offsetEvent.recycle();
TraceEvent.end("sendMouseEvent");
}
}
/**
* Called by PopupWindow-based touch handles.
* @param event the MotionEvent targeting the handle.
*/
public boolean onTouchHandleEvent(MotionEvent event) {
final boolean isTouchHandleEvent = true;
return sendTouchEvent(event, isTouchHandleEvent);
}
private boolean sendTouchEvent(MotionEvent event, boolean isTouchHandleEvent) {
TraceEvent.begin("sendTouchEvent");
try {
int eventAction = event.getActionMasked();
if (eventAction == MotionEvent.ACTION_DOWN) {
cancelRequestToScrollFocusedEditableNodeIntoView();
}
if (SPenSupport.isSPenSupported(mContext)) {
eventAction = SPenSupport.convertSPenEventAction(eventAction);
}
if (!isValidTouchEventActionForNative(eventAction)) return false;
if (mNativeContentViewCore == 0) return false;
// A zero offset is quite common, in which case the unnecessary copy should be avoided.
MotionEvent offset = null;
if (mCurrentTouchOffsetX != 0 || mCurrentTouchOffsetY != 0) {
offset = createOffsetMotionEvent(event);
event = offset;
}
final int pointerCount = event.getPointerCount();
float[] touchMajor = {event.getTouchMajor(),
pointerCount > 1 ? event.getTouchMajor(1) : 0};
float[] touchMinor = {event.getTouchMinor(),
pointerCount > 1 ? event.getTouchMinor(1) : 0};
for (int i = 0; i < 2; i++) {
if (touchMajor[i] < touchMinor[i]) {
float tmp = touchMajor[i];
touchMajor[i] = touchMinor[i];
touchMinor[i] = tmp;
}
}
final boolean consumed = nativeOnTouchEvent(mNativeContentViewCore, event,
event.getEventTime(), eventAction,
pointerCount, event.getHistorySize(), event.getActionIndex(),
event.getX(), event.getY(),
pointerCount > 1 ? event.getX(1) : 0,
pointerCount > 1 ? event.getY(1) : 0,
event.getPointerId(0), pointerCount > 1 ? event.getPointerId(1) : -1,
touchMajor[0], touchMajor[1],
touchMinor[0], touchMinor[1],
event.getOrientation(), pointerCount > 1 ? event.getOrientation(1) : 0,
event.getAxisValue(MotionEvent.AXIS_TILT),
pointerCount > 1 ? event.getAxisValue(MotionEvent.AXIS_TILT, 1) : 0,
event.getRawX(), event.getRawY(),
event.getToolType(0),
pointerCount > 1 ? event.getToolType(1) : MotionEvent.TOOL_TYPE_UNKNOWN,
event.getButtonState(),
event.getMetaState(),
isTouchHandleEvent);
if (offset != null) offset.recycle();
return consumed;
} finally {
TraceEvent.end("sendTouchEvent");
}
}
@CalledByNative
private void requestDisallowInterceptTouchEvent() {
mContainerView.requestDisallowInterceptTouchEvent(true);
}
private static boolean isValidTouchEventActionForNative(int eventAction) {
// Only these actions have any effect on gesture detection. Other
// actions have no corresponding WebTouchEvent type and may confuse the
// touch pipline, so we ignore them entirely.
return eventAction == MotionEvent.ACTION_DOWN
|| eventAction == MotionEvent.ACTION_UP
|| eventAction == MotionEvent.ACTION_CANCEL
|| eventAction == MotionEvent.ACTION_MOVE
|| eventAction == MotionEvent.ACTION_POINTER_DOWN
|| eventAction == MotionEvent.ACTION_POINTER_UP;
}
/**
* @return Whether a scroll targeting web content is in progress.
*/
public boolean isScrollInProgress() {
return mTouchScrollInProgress || mPotentiallyActiveFlingCount > 0;
}
private void setTouchScrollInProgress(boolean inProgress) {
if (mTouchScrollInProgress == inProgress) return;
mTouchScrollInProgress = inProgress;
mSelectionPopupController.updateActionModeVisibility(inProgress);
}
@SuppressWarnings("unused")
@CalledByNative
private void onFlingStartEventConsumed() {
mPotentiallyActiveFlingCount++;
setTouchScrollInProgress(false);
for (mGestureStateListenersIterator.rewind();
mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onFlingStartGesture(
computeVerticalScrollOffset(), computeVerticalScrollExtent());
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onFlingCancelEventAck() {
updateGestureStateListener(GestureEventType.FLING_CANCEL);
}
@SuppressWarnings("unused")
@CalledByNative
private void onScrollBeginEventAck() {
setTouchScrollInProgress(true);
hidePastePopup();
mZoomControlsDelegate.invokeZoomPicker();
updateGestureStateListener(GestureEventType.SCROLL_START);
}
@SuppressWarnings("unused")
@CalledByNative
private void onScrollUpdateGestureConsumed() {
mZoomControlsDelegate.invokeZoomPicker();
for (mGestureStateListenersIterator.rewind();
mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onScrollUpdateGestureConsumed();
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onScrollEndEventAck() {
setTouchScrollInProgress(false);
updateGestureStateListener(GestureEventType.SCROLL_END);
}
@SuppressWarnings("unused")
@CalledByNative
private void onPinchBeginEventAck() {
updateGestureStateListener(GestureEventType.PINCH_BEGIN);
}
@SuppressWarnings("unused")
@CalledByNative
private void onPinchEndEventAck() {
updateGestureStateListener(GestureEventType.PINCH_END);
}
@SuppressWarnings("unused")
@CalledByNative
private void onSingleTapEventAck(boolean consumed) {
for (mGestureStateListenersIterator.rewind();
mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onSingleTap(consumed);
}
hidePastePopup();
}
@SuppressWarnings("unused")
@CalledByNative
private void onShowUnhandledTapUIIfNeeded(int x, int y) {
mSelectionPopupController.onShowUnhandledTapUIIfNeeded(x, y);
}
/**
* Called just prior to a tap or press gesture being forwarded to the renderer.
*/
@SuppressWarnings("unused")
@CalledByNative
private boolean filterTapOrPressEvent(int type, int x, int y) {
if (type == GestureEventType.LONG_PRESS && offerLongPressToEmbedder()) {
return true;
}
updateForTapOrPress(type, x, y);
return false;
}
@VisibleForTesting
public void sendDoubleTapForTest(long timeMs, int x, int y) {
if (mNativeContentViewCore == 0) return;
nativeDoubleTap(mNativeContentViewCore, timeMs, x, y);
}
/**
* Flings the viewport with velocity vector (velocityX, velocityY).
* @param timeMs the current time.
* @param velocityX fling speed in x-axis.
* @param velocityY fling speed in y-axis.
*/
public void flingViewport(long timeMs, int velocityX, int velocityY) {
if (mNativeContentViewCore == 0) return;
nativeFlingCancel(mNativeContentViewCore, timeMs);
nativeScrollBegin(mNativeContentViewCore, timeMs, 0, 0, velocityX, velocityY, true);
nativeFlingStart(mNativeContentViewCore, timeMs, 0, 0, velocityX, velocityY, true);
}
/**
* Cancel any fling gestures active.
* @param timeMs Current time (in milliseconds).
*/
public void cancelFling(long timeMs) {
if (mNativeContentViewCore == 0) return;
nativeFlingCancel(mNativeContentViewCore, timeMs);
}
/**
* Add a listener that gets alerted on gesture state changes.
* @param listener Listener to add.
*/
public void addGestureStateListener(GestureStateListener listener) {
mGestureStateListeners.addObserver(listener);
}
/**
* Removes a listener that was added to watch for gesture state changes.
* @param listener Listener to remove.
*/
public void removeGestureStateListener(GestureStateListener listener) {
mGestureStateListeners.removeObserver(listener);
}
void updateGestureStateListener(int gestureType) {
for (mGestureStateListenersIterator.rewind();
mGestureStateListenersIterator.hasNext();) {
GestureStateListener listener = mGestureStateListenersIterator.next();
switch (gestureType) {
case GestureEventType.PINCH_BEGIN:
listener.onPinchStarted();
break;
case GestureEventType.PINCH_END:
listener.onPinchEnded();
break;
case GestureEventType.FLING_END:
listener.onFlingEndGesture(
computeVerticalScrollOffset(),
computeVerticalScrollExtent());
break;
case GestureEventType.SCROLL_START:
listener.onScrollStarted(
computeVerticalScrollOffset(),
computeVerticalScrollExtent());
break;
case GestureEventType.SCROLL_END:
listener.onScrollEnded(
computeVerticalScrollOffset(),
computeVerticalScrollExtent());
break;
default:
break;
}
}
}
/**
* To be called when the ContentView is shown.
*/
public void onShow() {
assert mWebContents != null;
mWebContents.onShow();
setAccessibilityState(mAccessibilityManager.isEnabled());
restoreSelectionPopupsIfNecessary();
}
/**
* @return The ID of the renderer process that backs this tab or
* {@link #INVALID_RENDER_PROCESS_PID} if there is none.
*/
public int getCurrentRenderProcessId() {
return nativeGetCurrentRenderProcessId(mNativeContentViewCore);
}
/**
* To be called when the ContentView is hidden.
*/
public void onHide() {
assert mWebContents != null;
hidePopupsAndPreserveSelection();
mWebContents.onHide();
}
private void hidePopupsAndClearSelection() {
mSelectionPopupController.destroyActionModeAndUnselect();
hidePastePopup();
hideSelectPopupWithCancelMessage();
mPopupZoomer.hide(false);
if (mWebContents != null) mWebContents.dismissTextHandles();
}
@CalledByNative
private void hidePopupsAndPreserveSelection() {
mSelectionPopupController.destroyActionModeAndKeepSelection();
hidePastePopup();
hideSelectPopupWithCancelMessage();
mPopupZoomer.hide(false);
}
private void restoreSelectionPopupsIfNecessary() {
mSelectionPopupController.restoreSelectionPopupsIfNecessary();
}
/**
* Hide action mode and put into destroyed state.
*/
public void destroySelectActionMode() {
mSelectionPopupController.finishActionMode();
}
public boolean isSelectActionBarShowing() {
return mSelectionPopupController.isActionModeValid();
}
private void resetGestureDetection() {
if (mNativeContentViewCore == 0) return;
nativeResetGestureDetection(mNativeContentViewCore);
}
/**
* @see View#onAttachedToWindow()
*/
@SuppressWarnings("javadoc")
public void onAttachedToWindow() {
mAttachedToWindow = true;
addDisplayAndroidObserverIfNeeded();
setAccessibilityState(mAccessibilityManager.isEnabled());
updateTextSelectionUI(true);
GamepadList.onAttachedToWindow(mContext);
mAccessibilityManager.addAccessibilityStateChangeListener(this);
mSystemCaptioningBridge.addListener(this);
mImeAdapter.onViewAttachedToWindow();
}
/**
* Update the text selection UI depending on the focus of the page. This will hide the selection
* handles and selection popups if focus is lost.
* TODO(mdjones): This was added as a temporary measure to hide text UI while Reader Mode or
* Contextual Search are showing. This should be removed in favor of proper focusing of the
* panel's ContentViewCore (which is currently not being added to the view hierarchy).
* @param focused If the ContentViewCore currently has focus.
*/
public void updateTextSelectionUI(boolean focused) {
setTextHandlesTemporarilyHidden(!focused);
if (focused) {
restoreSelectionPopupsIfNecessary();
} else {
hidePopupsAndPreserveSelection();
}
}
/**
* @see View#onDetachedFromWindow()
*/
@SuppressWarnings("javadoc")
@SuppressLint("MissingSuperCall")
public void onDetachedFromWindow() {
mAttachedToWindow = false;
mImeAdapter.onViewDetachedFromWindow();
mZoomControlsDelegate.dismissZoomPicker();
removeDisplayAndroidObserver();
GamepadList.onDetachedFromWindow();
mAccessibilityManager.removeAccessibilityStateChangeListener(this);
// WebView uses PopupWindows for handle rendering, which may remain
// unintentionally visible even after the WebView has been detached.
// Override the handle visibility explicitly to address this, but
// preserve the underlying selection for detachment cases like screen
// locking and app switching.
updateTextSelectionUI(false);
mSystemCaptioningBridge.removeListener(this);
}
/**
* @see View#onVisibilityChanged(android.view.View, int)
*/
public void onVisibilityChanged(View changedView, int visibility) {
if (visibility != View.VISIBLE) {
mZoomControlsDelegate.dismissZoomPicker();
}
}
/**
* @see View#onCreateInputConnection(EditorInfo)
*/
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return mImeAdapter.onCreateInputConnection(outAttrs);
}
/**
* @see View#onCheckIsTextEditor()
*/
public boolean onCheckIsTextEditor() {
return mImeAdapter.hasTextInputType();
}
/**
* @see View#onConfigurationChanged(Configuration)
*/
@SuppressWarnings("javadoc")
public void onConfigurationChanged(Configuration newConfig) {
try {
TraceEvent.begin("ContentViewCore.onConfigurationChanged");
mImeAdapter.onKeyboardConfigurationChanged(newConfig);
mContainerViewInternals.super_onConfigurationChanged(newConfig);
// To request layout has side effect, but it seems OK as it only happen in
// onConfigurationChange and layout has to be changed in most case.
mContainerView.requestLayout();
} finally {
TraceEvent.end("ContentViewCore.onConfigurationChanged");
}
}
/**
* @see View#onSizeChanged(int, int, int, int)
*/
@SuppressWarnings("javadoc")
public void onSizeChanged(int wPix, int hPix, int owPix, int ohPix) {
if (getViewportWidthPix() == wPix && getViewportHeightPix() == hPix) return;
mViewportWidthPix = wPix;
mViewportHeightPix = hPix;
if (mNativeContentViewCore != 0) {
nativeWasResized(mNativeContentViewCore);
}
updateAfterSizeChanged();
}
/**
* Called when the underlying surface the compositor draws to changes size.
* This may be larger than the viewport size.
*/
public void onPhysicalBackingSizeChanged(int wPix, int hPix) {
if (mPhysicalBackingWidthPix == wPix && mPhysicalBackingHeightPix == hPix) return;
mPhysicalBackingWidthPix = wPix;
mPhysicalBackingHeightPix = hPix;
if (mNativeContentViewCore != 0) {
nativeWasResized(mNativeContentViewCore);
}
}
private void updateAfterSizeChanged() {
mPopupZoomer.hide(false);
// Execute a delayed form focus operation because the OSK was brought
// up earlier.
if (!mFocusPreOSKViewportRect.isEmpty()) {
Rect rect = new Rect();
getContainerView().getWindowVisibleDisplayFrame(rect);
if (!rect.equals(mFocusPreOSKViewportRect)) {
// Only assume the OSK triggered the onSizeChanged if width was preserved.
if (rect.width() == mFocusPreOSKViewportRect.width()) {
assert mWebContents != null;
mWebContents.scrollFocusedEditableNodeIntoView();
}
cancelRequestToScrollFocusedEditableNodeIntoView();
}
}
}
private void cancelRequestToScrollFocusedEditableNodeIntoView() {
// Zero-ing the rect will prevent |updateAfterSizeChanged()| from
// issuing the delayed form focus event.
mFocusPreOSKViewportRect.setEmpty();
}
/**
* @see View#onWindowFocusChanged(boolean)
*/
public void onWindowFocusChanged(boolean hasWindowFocus) {
mImeAdapter.onWindowFocusChanged(hasWindowFocus);
if (!hasWindowFocus) resetGestureDetection();
mSelectionPopupController.onWindowFocusChanged(hasWindowFocus);
for (mGestureStateListenersIterator.rewind(); mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onWindowFocusChanged(hasWindowFocus);
}
}
public void onFocusChanged(boolean gainFocus) {
mImeAdapter.onViewFocusChanged(gainFocus);
mJoystickScrollProvider.setEnabled(gainFocus && !isFocusedNodeEditable());
if (gainFocus) {
restoreSelectionPopupsIfNecessary();
} else {
cancelRequestToScrollFocusedEditableNodeIntoView();
if (mPreserveSelectionOnNextLossOfFocus) {
mPreserveSelectionOnNextLossOfFocus = false;
hidePopupsAndPreserveSelection();
} else {
hidePopupsAndClearSelection();
// Clear the selection. The selection is cleared on destroying IME
// and also here since we may receive destroy first, for example
// when focus is lost in webview.
clearSelection();
}
}
if (mNativeContentViewCore != 0) nativeSetFocus(mNativeContentViewCore, gainFocus);
}
/**
* @see View#onKeyUp(int, KeyEvent)
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mPopupZoomer.isShowing() && keyCode == KeyEvent.KEYCODE_BACK) {
mPopupZoomer.hide(true);
return true;
}
return mContainerViewInternals.super_onKeyUp(keyCode, event);
}
/**
* @see View#dispatchKeyEvent(KeyEvent)
*/
public boolean dispatchKeyEvent(KeyEvent event) {
if (GamepadList.dispatchKeyEvent(event)) return true;
if (getContentViewClient().shouldOverrideKeyEvent(event)) {
return mContainerViewInternals.super_dispatchKeyEvent(event);
}
if (mImeAdapter.dispatchKeyEvent(event)) return true;
return mContainerViewInternals.super_dispatchKeyEvent(event);
}
/**
* @see View#onHoverEvent(MotionEvent)
* Mouse move events are sent on hover enter, hover move and hover exit.
* They are sent on hover exit because sometimes it acts as both a hover
* move and hover exit.
*/
public boolean onHoverEvent(MotionEvent event) {
TraceEvent.begin("onHoverEvent");
int eventAction = event.getActionMasked();
// Ignore ACTION_HOVER_ENTER & ACTION_HOVER_EXIT: every mouse-down on
// Android follows a hover-exit and is followed by a hover-enter. The
// MotionEvent spec seems to support this behavior indirectly.
if (eventAction == MotionEvent.ACTION_HOVER_ENTER
|| eventAction == MotionEvent.ACTION_HOVER_EXIT) {
return false;
}
MotionEvent offset = createOffsetMotionEvent(event);
try {
if (mBrowserAccessibilityManager != null && !mIsObscuredByAnotherView) {
return mBrowserAccessibilityManager.onHoverEvent(offset);
}
// TODO(lanwei): Remove this switch once experimentation is complete -
// crbug.com/418188
if (event.getToolType(0) == MotionEvent.TOOL_TYPE_FINGER) {
if (mEnableTouchHover == null) {
mEnableTouchHover =
CommandLine.getInstance().hasSwitch(ContentSwitches.ENABLE_TOUCH_HOVER);
}
if (!mEnableTouchHover.booleanValue()) return false;
}
mContainerView.removeCallbacks(mFakeMouseMoveRunnable);
if (mNativeContentViewCore != 0) {
nativeSendMouseEvent(mNativeContentViewCore, event.getEventTime(), eventAction,
offset.getX(), offset.getY(), event.getPointerId(0), event.getPressure(0),
event.getOrientation(0), event.getAxisValue(MotionEvent.AXIS_TILT, 0),
0 /* changedButton */, event.getButtonState(), event.getMetaState(),
event.getToolType(0));
}
return true;
} finally {
offset.recycle();
TraceEvent.end("onHoverEvent");
}
}
/**
* @see View#onGenericMotionEvent(MotionEvent)
*/
public boolean onGenericMotionEvent(MotionEvent event) {
if (GamepadList.onGenericMotionEvent(event)) return true;
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
mLastFocalEventX = event.getX();
mLastFocalEventY = event.getY();
switch (event.getActionMasked()) {
case MotionEvent.ACTION_SCROLL:
if (mNativeContentViewCore == 0) return false;
nativeSendMouseWheelEvent(mNativeContentViewCore, event.getEventTime(),
event.getX(), event.getY(),
event.getAxisValue(MotionEvent.AXIS_HSCROLL),
event.getAxisValue(MotionEvent.AXIS_VSCROLL),
mRenderCoordinates.getWheelScrollFactor());
// TODO(mustaq): Delete mFakeMouseMoveRunnable, see crbug.com/492738
mContainerView.removeCallbacks(mFakeMouseMoveRunnable);
// Send a delayed onMouseMove event so that we end
// up hovering over the right position after the scroll.
final MotionEvent eventFakeMouseMove = MotionEvent.obtain(event);
mFakeMouseMoveRunnable = new Runnable() {
@Override
public void run() {
onHoverEvent(eventFakeMouseMove);
eventFakeMouseMove.recycle();
}
};
mContainerView.postDelayed(mFakeMouseMoveRunnable, 250);
return true;
}
} else if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
if (mJoystickScrollProvider.onMotion(event)) return true;
if (mJoystickZoomProvider == null) {
mJoystickZoomProvider =
new JoystickZoomProvider(this, new SystemAnimationIntervalProvider());
}
if (mJoystickZoomProvider.onMotion(event)) return true;
}
return mContainerViewInternals.super_onGenericMotionEvent(event);
}
/**
* Sets the current amount to offset incoming touch events by (including MotionEvent and
* DragEvent). This is used to handle content moving and not lining up properly with the
* android input system.
* @param dx The X offset in pixels to shift touch events.
* @param dy The Y offset in pixels to shift touch events.
*/
public void setCurrentTouchEventOffsets(float dx, float dy) {
mCurrentTouchOffsetX = dx;
mCurrentTouchOffsetY = dy;
}
private MotionEvent createOffsetMotionEvent(MotionEvent src) {
MotionEvent dst = MotionEvent.obtain(src);
dst.offsetLocation(mCurrentTouchOffsetX, mCurrentTouchOffsetY);
return dst;
}
/**
* @see View#scrollBy(int, int)
* Currently the ContentView scrolling happens in the native side. In
* the Java view system, it is always pinned at (0, 0). scrollBy() and scrollTo()
* are overridden, so that View's mScrollX and mScrollY will be unchanged at
* (0, 0). This is critical for drawing ContentView correctly.
*/
public void scrollBy(float dxPix, float dyPix, boolean useLastFocalEventLocation) {
if (mNativeContentViewCore == 0) return;
if (dxPix == 0 && dyPix == 0) return;
long time = SystemClock.uptimeMillis();
// It's a very real (and valid) possibility that a fling may still
// be active when programatically scrolling. Cancelling the fling in
// such cases ensures a consistent gesture event stream.
if (mPotentiallyActiveFlingCount > 0) nativeFlingCancel(mNativeContentViewCore, time);
// x/y represents starting location of scroll.
final float x = useLastFocalEventLocation ? mLastFocalEventX : 0f;
final float y = useLastFocalEventLocation ? mLastFocalEventY : 0f;
nativeScrollBegin(
mNativeContentViewCore, time, x, y, -dxPix, -dyPix, !useLastFocalEventLocation);
nativeScrollBy(mNativeContentViewCore, time, x, y, dxPix, dyPix);
nativeScrollEnd(mNativeContentViewCore, time);
}
/**
* @see View#scrollTo(int, int)
*/
public void scrollTo(float xPix, float yPix) {
if (mNativeContentViewCore == 0) return;
final float xCurrentPix = mRenderCoordinates.getScrollXPix();
final float yCurrentPix = mRenderCoordinates.getScrollYPix();
final float dxPix = xPix - xCurrentPix;
final float dyPix = yPix - yCurrentPix;
scrollBy(dxPix, dyPix, false);
}
// NOTE: this can go away once ContentView.getScrollX() reports correct values.
// see: b/6029133
public int getNativeScrollXForTest() {
return mRenderCoordinates.getScrollXPixInt();
}
// NOTE: this can go away once ContentView.getScrollY() reports correct values.
// see: b/6029133
public int getNativeScrollYForTest() {
return mRenderCoordinates.getScrollYPixInt();
}
/**
* @see View#computeHorizontalScrollExtent()
*/
@SuppressWarnings("javadoc")
public int computeHorizontalScrollExtent() {
return mRenderCoordinates.getLastFrameViewportWidthPixInt();
}
/**
* @see View#computeHorizontalScrollOffset()
*/
@SuppressWarnings("javadoc")
public int computeHorizontalScrollOffset() {
return mRenderCoordinates.getScrollXPixInt();
}
/**
* @see View#computeHorizontalScrollRange()
*/
@SuppressWarnings("javadoc")
public int computeHorizontalScrollRange() {
return mRenderCoordinates.getContentWidthPixInt();
}
/**
* @see View#computeVerticalScrollExtent()
*/
@SuppressWarnings("javadoc")
public int computeVerticalScrollExtent() {
return mRenderCoordinates.getLastFrameViewportHeightPixInt();
}
/**
* @see View#computeVerticalScrollOffset()
*/
@SuppressWarnings("javadoc")
public int computeVerticalScrollOffset() {
return mRenderCoordinates.getScrollYPixInt();
}
/**
* @see View#computeVerticalScrollRange()
*/
@SuppressWarnings("javadoc")
public int computeVerticalScrollRange() {
return mRenderCoordinates.getContentHeightPixInt();
}
// End FrameLayout overrides.
/**
* @see View#awakenScrollBars(int, boolean)
*/
@SuppressWarnings("javadoc")
public boolean awakenScrollBars(int startDelay, boolean invalidate) {
// For the default implementation of ContentView which draws the scrollBars on the native
// side, calling this function may get us into a bad state where we keep drawing the
// scrollBars, so disable it by always returning false.
if (mContainerView.getScrollBarStyle() == View.SCROLLBARS_INSIDE_OVERLAY) {
return false;
} else {
return mContainerViewInternals.super_awakenScrollBars(startDelay, invalidate);
}
}
private void updateForTapOrPress(int type, float xPix, float yPix) {
if (type != GestureEventType.SINGLE_TAP_CONFIRMED
&& type != GestureEventType.SINGLE_TAP_UP
&& type != GestureEventType.LONG_PRESS
&& type != GestureEventType.LONG_TAP) {
return;
}
if (mContainerView.isFocusable() && mContainerView.isFocusableInTouchMode()
&& !mContainerView.isFocused()) {
mContainerView.requestFocus();
}
if (!mPopupZoomer.isShowing()) mPopupZoomer.setLastTouch(xPix, yPix);
mLastFocalEventX = xPix;
mLastFocalEventY = yPix;
}
public void setZoomControlsDelegate(ZoomControlsDelegate zoomControlsDelegate) {
if (zoomControlsDelegate == null) {
mZoomControlsDelegate = NO_OP_ZOOM_CONTROLS_DELEGATE;
return;
}
mZoomControlsDelegate = zoomControlsDelegate;
}
public void updateMultiTouchZoomSupport(boolean supportsMultiTouchZoom) {
if (mNativeContentViewCore == 0) return;
nativeSetMultiTouchZoomSupportEnabled(mNativeContentViewCore, supportsMultiTouchZoom);
}
public void updateDoubleTapSupport(boolean supportsDoubleTap) {
if (mNativeContentViewCore == 0) return;
nativeSetDoubleTapSupportEnabled(mNativeContentViewCore, supportsDoubleTap);
}
public void selectPopupMenuItems(int[] indices) {
if (mNativeContentViewCore != 0) {
nativeSelectPopupMenuItems(mNativeContentViewCore, mNativeSelectPopupSourceFrame,
indices);
}
mNativeSelectPopupSourceFrame = 0;
mSelectPopup = null;
}
/**
* Send the screen orientation value to the renderer.
*/
@VisibleForTesting
void sendOrientationChangeEvent(int orientation) {
if (mNativeContentViewCore == 0) return;
nativeSendOrientationChangeEvent(mNativeContentViewCore, orientation);
}
public ActionModeCallbackHelper getActionModeCallbackHelper() {
return mSelectionPopupController;
}
private void showSelectActionMode(boolean allowFallback) {
if (!mSelectionPopupController.showActionMode(allowFallback)) clearSelection();
}
public void clearSelection() {
mSelectionPopupController.clearSelection();
}
/**
* Ensure the selection is preserved the next time the view loses focus.
*/
public void preserveSelectionOnNextLossOfFocus() {
mPreserveSelectionOnNextLossOfFocus = true;
}
@CalledByNative
private void onSelectionEvent(
int eventType, int xAnchor, int yAnchor, int left, int top, int right, int bottom) {
mSelectionPopupController.onSelectionEvent(eventType, xAnchor, yAnchor,
left, top, right, bottom, isScrollInProgress(), mTouchScrollInProgress);
}
private void setTextHandlesTemporarilyHidden(boolean hide) {
if (mNativeContentViewCore == 0) return;
nativeSetTextHandlesTemporarilyHidden(mNativeContentViewCore, hide);
}
@SuppressWarnings("unused")
@CalledByNative
private void updateFrameInfo(float scrollOffsetX, float scrollOffsetY, float pageScaleFactor,
float minPageScaleFactor, float maxPageScaleFactor, float contentWidth,
float contentHeight, float viewportWidth, float viewportHeight,
float browserControlsHeightDp, float browserControlsShownRatio,
float bottomControlsHeightDp, float bottomControlsShownRatio,
boolean isMobileOptimizedHint, boolean hasInsertionMarker,
boolean isInsertionMarkerVisible, float insertionMarkerHorizontal,
float insertionMarkerTop, float insertionMarkerBottom) {
TraceEvent.begin("ContentViewCore:updateFrameInfo");
mIsMobileOptimizedHint = isMobileOptimizedHint;
// Adjust contentWidth/Height to be always at least as big as
// the actual viewport (as set by onSizeChanged).
final float deviceScale = mRenderCoordinates.getDeviceScaleFactor();
contentWidth = Math.max(contentWidth,
mViewportWidthPix / (deviceScale * pageScaleFactor));
contentHeight = Math.max(contentHeight,
mViewportHeightPix / (deviceScale * pageScaleFactor));
final float topBarShownPix =
browserControlsHeightDp * deviceScale * browserControlsShownRatio;
final float bottomBarShownPix = bottomControlsHeightDp * deviceScale
* bottomControlsShownRatio;
final boolean contentSizeChanged =
contentWidth != mRenderCoordinates.getContentWidthCss()
|| contentHeight != mRenderCoordinates.getContentHeightCss();
final boolean scaleLimitsChanged =
minPageScaleFactor != mRenderCoordinates.getMinPageScaleFactor()
|| maxPageScaleFactor != mRenderCoordinates.getMaxPageScaleFactor();
final boolean pageScaleChanged =
pageScaleFactor != mRenderCoordinates.getPageScaleFactor();
final boolean scrollChanged =
pageScaleChanged
|| scrollOffsetX != mRenderCoordinates.getScrollX()
|| scrollOffsetY != mRenderCoordinates.getScrollY();
final boolean topBarChanged = Float.compare(topBarShownPix,
mRenderCoordinates.getContentOffsetYPix()) != 0;
final boolean bottomBarChanged = Float.compare(bottomBarShownPix, mRenderCoordinates
.getContentOffsetYPixBottom()) != 0;
final boolean needHidePopupZoomer = contentSizeChanged || scrollChanged;
final boolean needUpdateZoomControls = scaleLimitsChanged || scrollChanged;
if (needHidePopupZoomer) mPopupZoomer.hide(true);
if (scrollChanged) {
mContainerViewInternals.onScrollChanged(
(int) mRenderCoordinates.fromLocalCssToPix(scrollOffsetX),
(int) mRenderCoordinates.fromLocalCssToPix(scrollOffsetY),
(int) mRenderCoordinates.getScrollXPix(),
(int) mRenderCoordinates.getScrollYPix());
}
mRenderCoordinates.updateFrameInfo(
scrollOffsetX, scrollOffsetY,
contentWidth, contentHeight,
viewportWidth, viewportHeight,
pageScaleFactor, minPageScaleFactor, maxPageScaleFactor,
topBarShownPix, bottomBarShownPix);
if (scrollChanged || topBarChanged) {
for (mGestureStateListenersIterator.rewind();
mGestureStateListenersIterator.hasNext();) {
mGestureStateListenersIterator.next().onScrollOffsetOrExtentChanged(
computeVerticalScrollOffset(),
computeVerticalScrollExtent());
}
}
if (needUpdateZoomControls) mZoomControlsDelegate.updateZoomControls();
if (topBarChanged) {
float topBarTranslate = topBarShownPix - browserControlsHeightDp * deviceScale;
getContentViewClient().onTopControlsChanged(topBarTranslate, topBarShownPix);
}
if (bottomBarChanged) {
float bottomBarTranslate = bottomControlsHeightDp * deviceScale - bottomBarShownPix;
getContentViewClient().onBottomControlsChanged(bottomBarTranslate, bottomBarShownPix);
}
if (mBrowserAccessibilityManager != null) {
mBrowserAccessibilityManager.notifyFrameInfoInitialized();
}
mImeAdapter.onUpdateFrameInfo(mRenderCoordinates, hasInsertionMarker,
isInsertionMarkerVisible, insertionMarkerHorizontal, insertionMarkerTop,
insertionMarkerBottom);
TraceEvent.end("ContentViewCore:updateFrameInfo");
}
@CalledByNative
private void updateImeAdapter(long nativeImeAdapterAndroid, int textInputType,
int textInputFlags, String text, int selectionStart, int selectionEnd,
int compositionStart, int compositionEnd, boolean showImeIfNeeded,
boolean isNonImeChange) {
try {
TraceEvent.begin("ContentViewCore.updateImeAdapter");
boolean focusedNodeEditable = (textInputType != TextInputType.NONE);
boolean focusedNodeIsPassword = (textInputType == TextInputType.PASSWORD);
mImeAdapter.attach(nativeImeAdapterAndroid);
mImeAdapter.updateKeyboardVisibility(
textInputType, textInputFlags, showImeIfNeeded);
mImeAdapter.updateState(text, selectionStart, selectionEnd, compositionStart,
compositionEnd, isNonImeChange);
boolean editableToggled = (focusedNodeEditable != isFocusedNodeEditable());
mSelectionPopupController.updateSelectionState(focusedNodeEditable,
focusedNodeIsPassword);
if (editableToggled) {
mJoystickScrollProvider.setEnabled(!focusedNodeEditable);
getContentViewClient().onFocusedNodeEditabilityChanged(focusedNodeEditable);
}
} finally {
TraceEvent.end("ContentViewCore.updateImeAdapter");
}
}
@CalledByNative
private void forceUpdateImeAdapter(long nativeImeAdapterAndroid) {
mImeAdapter.attach(nativeImeAdapterAndroid);
}
@SuppressWarnings("unused")
@CalledByNative
private void setTitle(String title) {
getContentViewClient().onUpdateTitle(title);
}
/**
* Called (from native) when the <select> popup needs to be shown.
* @param anchorView View anchored for popup.
* @param nativeSelectPopupSourceFrame The native RenderFrameHost that owns the popup.
* @param items Items to show.
* @param enabled POPUP_ITEM_TYPEs for items.
* @param multiple Whether the popup menu should support multi-select.
* @param selectedIndices Indices of selected items.
*/
@SuppressWarnings("unused")
@CalledByNative
private void showSelectPopup(View anchorView, long nativeSelectPopupSourceFrame, String[] items,
int[] enabled, boolean multiple, int[] selectedIndices, boolean rightAligned) {
if (mContainerView.getParent() == null || mContainerView.getVisibility() != View.VISIBLE) {
mNativeSelectPopupSourceFrame = nativeSelectPopupSourceFrame;
selectPopupMenuItems(null);
return;
}
hidePopupsAndClearSelection();
assert mNativeSelectPopupSourceFrame == 0 : "Zombie popup did not clear the frame source";
assert items.length == enabled.length;
List<SelectPopupItem> popupItems = new ArrayList<SelectPopupItem>();
for (int i = 0; i < items.length; i++) {
popupItems.add(new SelectPopupItem(items[i], enabled[i]));
}
if (DeviceFormFactor.isTablet(mContext) && !multiple && !isTouchExplorationEnabled()) {
mSelectPopup = new SelectPopupDropdown(
this, anchorView, popupItems, selectedIndices, rightAligned);
} else {
if (getWindowAndroid() == null) return;
Context windowContext = getWindowAndroid().getContext().get();
if (windowContext == null) return;
mSelectPopup = new SelectPopupDialog(
this, windowContext, popupItems, multiple, selectedIndices);
}
mNativeSelectPopupSourceFrame = nativeSelectPopupSourceFrame;
mSelectPopup.show();
}
/**
* Called when the <select> popup needs to be hidden.
*/
@CalledByNative
private void hideSelectPopup() {
if (mSelectPopup == null) return;
mSelectPopup.hide(false);
mSelectPopup = null;
mNativeSelectPopupSourceFrame = 0;
}
/**
* Called when the <select> popup needs to be hidden. This calls
* nativeSelectPopupMenuItems() with null indices.
*/
private void hideSelectPopupWithCancelMessage() {
if (mSelectPopup != null) mSelectPopup.hide(true);
}
/**
* @return The visible select popup being shown.
*/
@VisibleForTesting
public SelectPopup getSelectPopupForTest() {
return mSelectPopup;
}
@SuppressWarnings("unused")
@CalledByNative
private void showDisambiguationPopup(Rect targetRect, Bitmap zoomedBitmap) {
mPopupZoomer.setBitmap(zoomedBitmap);
mPopupZoomer.show(targetRect);
}
@SuppressWarnings("unused")
@CalledByNative
private MotionEventSynthesizer createMotionEventSynthesizer() {
return new MotionEventSynthesizer(this);
}
/**
* Initialize the view with an overscroll refresh handler.
* @param handler The refresh handler.
*/
public void setOverscrollRefreshHandler(OverscrollRefreshHandler handler) {
assert mOverscrollRefreshHandler == null || handler == null;
mOverscrollRefreshHandler = handler;
}
@SuppressWarnings("unused")
@CalledByNative
private boolean onOverscrollRefreshStart() {
if (mOverscrollRefreshHandler == null) return false;
return mOverscrollRefreshHandler.start();
}
@SuppressWarnings("unused")
@CalledByNative
private void onOverscrollRefreshUpdate(float delta) {
if (mOverscrollRefreshHandler != null) mOverscrollRefreshHandler.pull(delta);
}
@SuppressWarnings("unused")
@CalledByNative
private void onOverscrollRefreshRelease(boolean allowRefresh) {
if (mOverscrollRefreshHandler != null) mOverscrollRefreshHandler.release(allowRefresh);
}
@SuppressWarnings("unused")
@CalledByNative
private void onOverscrollRefreshReset() {
if (mOverscrollRefreshHandler != null) mOverscrollRefreshHandler.reset();
}
@SuppressWarnings("unused")
@CalledByNative
private void onSelectionChanged(String text) {
mSelectionPopupController.onSelectionChanged(text);
}
@SuppressWarnings("unused")
@CalledByNative
private void performLongPressHapticFeedback() {
mContainerView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
@CalledByNative
private void showPastePopup(int x, int y) {
mSelectionPopupController.showPastePopup(x, y);
}
private void hidePastePopup() {
mSelectionPopupController.hidePastePopup();
}
private void destroyPastePopup() {
mSelectionPopupController.destroyPastePopup();
}
private boolean canPaste() {
return ((ClipboardManager) mContext.getSystemService(
Context.CLIPBOARD_SERVICE)).hasPrimaryClip();
}
@SuppressWarnings("unused")
@CalledByNative
private void onRenderProcessChange() {
attachImeAdapter();
// Immediately sync closed caption settings to the new render process.
mSystemCaptioningBridge.syncToListener(this);
}
/**
* Attaches the native ImeAdapter object to the java ImeAdapter to allow communication via JNI.
*/
public void attachImeAdapter() {
if (mImeAdapter != null && mNativeContentViewCore != 0) {
mImeAdapter.attach(nativeGetNativeImeAdapter(mNativeContentViewCore));
}
}
/**
* @see View#hasFocus()
*/
@CalledByNative
private boolean hasFocus() {
// If the container view is not focusable, we consider it always focused from
// Chromium's point of view.
if (!mContainerView.isFocusable()) return true;
return mContainerView.hasFocus();
}
/**
* Checks whether the ContentViewCore can be zoomed in.
*
* @return True if the ContentViewCore can be zoomed in.
*/
// This method uses the term 'zoom' for legacy reasons, but relates
// to what chrome calls the 'page scale factor'.
public boolean canZoomIn() {
final float zoomInExtent = mRenderCoordinates.getMaxPageScaleFactor()
- mRenderCoordinates.getPageScaleFactor();
return zoomInExtent > ZOOM_CONTROLS_EPSILON;
}
/**
* Checks whether the ContentViewCore can be zoomed out.
*
* @return True if the ContentViewCore can be zoomed out.
*/
// This method uses the term 'zoom' for legacy reasons, but relates
// to what chrome calls the 'page scale factor'.
public boolean canZoomOut() {
final float zoomOutExtent = mRenderCoordinates.getPageScaleFactor()
- mRenderCoordinates.getMinPageScaleFactor();
return zoomOutExtent > ZOOM_CONTROLS_EPSILON;
}
/**
* Zooms in the ContentViewCore by 25% (or less if that would result in
* zooming in more than possible).
*
* @return True if there was a zoom change, false otherwise.
*/
// This method uses the term 'zoom' for legacy reasons, but relates
// to what chrome calls the 'page scale factor'.
public boolean zoomIn() {
if (!canZoomIn()) {
return false;
}
return pinchByDelta(1.25f);
}
/**
* Zooms out the ContentViewCore by 20% (or less if that would result in
* zooming out more than possible).
*
* @return True if there was a zoom change, false otherwise.
*/
// This method uses the term 'zoom' for legacy reasons, but relates
// to what chrome calls the 'page scale factor'.
public boolean zoomOut() {
if (!canZoomOut()) {
return false;
}
return pinchByDelta(0.8f);
}
/**
* Resets the zoom factor of the ContentViewCore.
*
* @return True if there was a zoom change, false otherwise.
*/
// This method uses the term 'zoom' for legacy reasons, but relates
// to what chrome calls the 'page scale factor'.
public boolean zoomReset() {
// The page scale factor is initialized to mNativeMinimumScale when
// the page finishes loading. Thus sets it back to mNativeMinimumScale.
if (!canZoomOut()) return false;
return pinchByDelta(
mRenderCoordinates.getMinPageScaleFactor()
/ mRenderCoordinates.getPageScaleFactor());
}
/**
* Simulate a pinch zoom gesture.
*
* @param delta the factor by which the current page scale should be multiplied by.
* @return whether the gesture was sent.
*/
public boolean pinchByDelta(float delta) {
if (mNativeContentViewCore == 0) return false;
long timeMs = SystemClock.uptimeMillis();
int xPix = getViewportWidthPix() / 2;
int yPix = getViewportHeightPix() / 2;
nativePinchBegin(mNativeContentViewCore, timeMs, xPix, yPix);
nativePinchBy(mNativeContentViewCore, timeMs, xPix, yPix, delta);
nativePinchEnd(mNativeContentViewCore, timeMs);
return true;
}
/**
* Send start of pinch zoom gesture.
*
* @param xPix X-coordinate of location from which pinch zoom would start.
* @param yPix Y-coordinate of location from which pinch zoom would start.
* @return whether the pinch zoom start gesture was sent.
*/
public boolean pinchBegin(int xPix, int yPix) {
if (mNativeContentViewCore == 0) return false;
nativePinchBegin(mNativeContentViewCore, SystemClock.uptimeMillis(), xPix, yPix);
return true;
}
/**
* Send pinch zoom gesture.
*
* @param xPix X-coordinate of pinch zoom location.
* @param yPix Y-coordinate of pinch zoom location.
* @param delta the factor by which the current page scale should be multiplied by.
* @return whether the pinchby gesture was sent.
*/
public boolean pinchBy(int xPix, int yPix, float delta) {
if (mNativeContentViewCore == 0) return false;
nativePinchBy(mNativeContentViewCore, SystemClock.uptimeMillis(), xPix, yPix, delta);
return true;
}
/**
* Stop pinch zoom gesture.
*
* @return whether the pinch stop gesture was sent.
*/
public boolean pinchEnd() {
if (mNativeContentViewCore == 0) return false;
nativePinchEnd(mNativeContentViewCore, SystemClock.uptimeMillis());
return true;
}
/**
* Invokes the graphical zoom picker widget for this ContentView.
*/
public void invokeZoomPicker() {
mZoomControlsDelegate.invokeZoomPicker();
}
/**
* Enables or disables inspection of JavaScript objects added via
* {@link #addJavascriptInterface(Object, String)} by means of Object.keys() method and
* "for .. in" loop. Being able to inspect JavaScript objects is useful
* when debugging hybrid Android apps, but can't be enabled for legacy applications due
* to compatibility risks.
*
* @param allow Whether to allow JavaScript objects inspection.
*/
public void setAllowJavascriptInterfacesInspection(boolean allow) {
nativeSetAllowJavascriptInterfacesInspection(mNativeContentViewCore, allow);
}
/**
* Returns JavaScript interface objects previously injected via
* {@link #addJavascriptInterface(Object, String)}.
*
* @return the mapping of names to interface objects and corresponding annotation classes
*/
public Map<String, Pair<Object, Class>> getJavascriptInterfaces() {
return mJavaScriptInterfaces;
}
/**
* This will mimic {@link #addPossiblyUnsafeJavascriptInterface(Object, String, Class)}
* and automatically pass in {@link JavascriptInterface} as the required annotation.
*
* @param object The Java object to inject into the ContentViewCore's JavaScript context. Null
* values are ignored.
* @param name The name used to expose the instance in JavaScript.
*/
public void addJavascriptInterface(Object object, String name) {
addPossiblyUnsafeJavascriptInterface(object, name, JavascriptInterface.class);
}
/**
* This method injects the supplied Java object into the ContentViewCore.
* The object is injected into the JavaScript context of the main frame,
* using the supplied name. This allows the Java object to be accessed from
* JavaScript. Note that that injected objects will not appear in
* JavaScript until the page is next (re)loaded. For example:
* <pre> view.addJavascriptInterface(new Object(), "injectedObject");
* view.loadData("<!DOCTYPE html><title></title>", "text/html", null);
* view.loadUrl("javascript:alert(injectedObject.toString())");</pre>
* <p><strong>IMPORTANT:</strong>
* <ul>
* <li> addJavascriptInterface() can be used to allow JavaScript to control
* the host application. This is a powerful feature, but also presents a
* security risk. Use of this method in a ContentViewCore containing
* untrusted content could allow an attacker to manipulate the host
* application in unintended ways, executing Java code with the permissions
* of the host application. Use extreme care when using this method in a
* ContentViewCore which could contain untrusted content. Particular care
* should be taken to avoid unintentional access to inherited methods, such
* as {@link Object#getClass()}. To prevent access to inherited methods,
* pass an annotation for {@code requiredAnnotation}. This will ensure
* that only methods with {@code requiredAnnotation} are exposed to the
* Javascript layer. {@code requiredAnnotation} will be passed to all
* subsequently injected Java objects if any methods return an object. This
* means the same restrictions (or lack thereof) will apply. Alternatively,
* {@link #addJavascriptInterface(Object, String)} can be called, which
* automatically uses the {@link JavascriptInterface} annotation.
* <li> JavaScript interacts with Java objects on a private, background
* thread of the ContentViewCore. Care is therefore required to maintain
* thread safety.</li>
* </ul></p>
*
* @param object The Java object to inject into the
* ContentViewCore's JavaScript context. Null
* values are ignored.
* @param name The name used to expose the instance in
* JavaScript.
* @param requiredAnnotation Restrict exposed methods to ones with this
* annotation. If {@code null} all methods are
* exposed.
*
*/
public void addPossiblyUnsafeJavascriptInterface(Object object, String name,
Class<? extends Annotation> requiredAnnotation) {
if (mNativeContentViewCore != 0 && object != null) {
mJavaScriptInterfaces.put(name, new Pair<Object, Class>(object, requiredAnnotation));
nativeAddJavascriptInterface(mNativeContentViewCore, object, name, requiredAnnotation);
}
}
/**
* Removes a previously added JavaScript interface with the given name.
*
* @param name The name of the interface to remove.
*/
public void removeJavascriptInterface(String name) {
mJavaScriptInterfaces.remove(name);
if (mNativeContentViewCore != 0) {
nativeRemoveJavascriptInterface(mNativeContentViewCore, name);
}
}
/**
* Return the current scale of the ContentView.
* @return The current page scale factor.
*/
@VisibleForTesting
public float getScale() {
return mRenderCoordinates.getPageScaleFactor();
}
@CalledByNative
private void startContentIntent(String contentUrl, boolean isMainFrame) {
getContentViewClient().onStartContentIntent(getContext(), contentUrl, isMainFrame);
}
@Override
public void onAccessibilityStateChanged(boolean enabled) {
setAccessibilityState(enabled);
}
/**
* Determines whether or not this ContentViewCore can handle this accessibility action.
* @param action The action to perform.
* @return Whether or not this action is supported.
*/
public boolean supportsAccessibilityAction(int action) {
// TODO(dmazzoni): implement this in BrowserAccessibilityManager.
return false;
}
/**
* Attempts to perform an accessibility action on the web content. If the accessibility action
* cannot be processed, it returns {@code null}, allowing the caller to know to call the
* super {@link View#performAccessibilityAction(int, Bundle)} method and use that return value.
* Otherwise the return value from this method should be used.
* @param action The action to perform.
* @param arguments Optional action arguments.
* @return Whether the action was performed or {@code null} if the call should be delegated to
* the super {@link View} class.
*/
public boolean performAccessibilityAction(int action, Bundle arguments) {
// TODO(dmazzoni): implement this in BrowserAccessibilityManager.
return false;
}
/**
* Set the BrowserAccessibilityManager, used for native accessibility
* (not script injection). This is only set when system accessibility
* has been enabled.
* @param manager The new BrowserAccessibilityManager.
*/
public void setBrowserAccessibilityManager(BrowserAccessibilityManager manager) {
mBrowserAccessibilityManager = manager;
if (mBrowserAccessibilityManager != null && mRenderCoordinates.hasFrameInfo()) {
mBrowserAccessibilityManager.notifyFrameInfoInitialized();
}
if (mBrowserAccessibilityManager == null) mNativeAccessibilityEnabled = false;
}
/**
* Get the BrowserAccessibilityManager, used for native accessibility
* (not script injection). This will return null when system accessibility
* is not enabled.
* @return This view's BrowserAccessibilityManager.
*/
public BrowserAccessibilityManager getBrowserAccessibilityManager() {
return mBrowserAccessibilityManager;
}
/**
* If native accessibility is enabled and no other views are temporarily
* obscuring this one, returns an AccessibilityNodeProvider that
* implements native accessibility for this view. Returns null otherwise.
* Lazily initializes native accessibility here if it's allowed.
* @return The AccessibilityNodeProvider, if available, or null otherwise.
*/
public AccessibilityNodeProvider getAccessibilityNodeProvider() {
if (mIsObscuredByAnotherView) return null;
if (mBrowserAccessibilityManager != null) {
return mBrowserAccessibilityManager.getAccessibilityNodeProvider();
}
if (mNativeAccessibilityAllowed && !mNativeAccessibilityEnabled
&& mNativeContentViewCore != 0) {
mNativeAccessibilityEnabled = true;
nativeSetAccessibilityEnabled(mNativeContentViewCore, true);
}
return null;
}
/**
* Set whether or not the web contents are obscured by another view.
* If true, we won't return an accessibility node provider or respond
* to touch exploration events.
*/
public void setObscuredByAnotherView(boolean isObscured) {
if (isObscured != mIsObscuredByAnotherView) {
mIsObscuredByAnotherView = isObscured;
getContainerView().sendAccessibilityEvent(
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
}
@TargetApi(Build.VERSION_CODES.M)
public void onProvideVirtualStructure(
final ViewStructure structure, final boolean ignoreScrollOffset) {
// Do not collect accessibility tree in incognito mode
if (getWebContents().isIncognito()) {
structure.setChildCount(0);
return;
}
structure.setChildCount(1);
final ViewStructure viewRoot = structure.asyncNewChild(0);
getWebContents().requestAccessibilitySnapshot(new AccessibilitySnapshotCallback() {
@Override
public void onAccessibilitySnapshot(AccessibilitySnapshotNode root) {
viewRoot.setClassName("");
viewRoot.setHint(mProductVersion);
if (root == null) {
viewRoot.asyncCommit();
return;
}
createVirtualStructure(viewRoot, root, ignoreScrollOffset);
}
});
}
// When creating the View structure, the left and top are relative to the parent node.
@TargetApi(Build.VERSION_CODES.M)
private void createVirtualStructure(ViewStructure viewNode, AccessibilitySnapshotNode node,
final boolean ignoreScrollOffset) {
viewNode.setClassName(node.className);
if (node.hasSelection) {
viewNode.setText(node.text, node.startSelection, node.endSelection);
} else {
viewNode.setText(node.text);
}
int left = (int) mRenderCoordinates.fromLocalCssToPix(node.x);
int top = (int) mRenderCoordinates.fromLocalCssToPix(node.y);
int width = (int) mRenderCoordinates.fromLocalCssToPix(node.width);
int height = (int) mRenderCoordinates.fromLocalCssToPix(node.height);
Rect boundsInParent = new Rect(left, top, left + width, top + height);
if (node.isRootNode) {
// Offset of the web content relative to the View.
boundsInParent.offset(0, (int) mRenderCoordinates.getContentOffsetYPix());
if (!ignoreScrollOffset) {
boundsInParent.offset(-(int) mRenderCoordinates.getScrollXPix(),
-(int) mRenderCoordinates.getScrollYPix());
}
}
viewNode.setDimens(boundsInParent.left, boundsInParent.top, 0, 0, width, height);
viewNode.setChildCount(node.children.size());
if (node.hasStyle) {
// The text size should be in physical pixels, not CSS pixels.
float textSize = mRenderCoordinates.fromLocalCssToPix(node.textSize);
int style = (node.bold ? ViewNode.TEXT_STYLE_BOLD : 0)
| (node.italic ? ViewNode.TEXT_STYLE_ITALIC : 0)
| (node.underline ? ViewNode.TEXT_STYLE_UNDERLINE : 0)
| (node.lineThrough ? ViewNode.TEXT_STYLE_STRIKE_THRU : 0);
viewNode.setTextStyle(textSize, node.color, node.bgcolor, style);
}
for (int i = 0; i < node.children.size(); i++) {
createVirtualStructure(viewNode.asyncNewChild(i), node.children.get(i), true);
}
viewNode.asyncCommit();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onSystemCaptioningChanged(TextTrackSettings settings) {
if (mNativeContentViewCore == 0) return;
nativeSetTextTrackSettings(mNativeContentViewCore,
settings.getTextTracksEnabled(), settings.getTextTrackBackgroundColor(),
settings.getTextTrackFontFamily(), settings.getTextTrackFontStyle(),
settings.getTextTrackFontVariant(), settings.getTextTrackTextColor(),
settings.getTextTrackTextShadow(), settings.getTextTrackTextSize());
}
/**
* Called when the processed text is replied from an activity that supports
* Intent.ACTION_PROCESS_TEXT.
* @param resultCode the code that indicates if the activity successfully processed the text
* @param data the reply that contains the processed text.
*/
public void onReceivedProcessTextResult(int resultCode, Intent data) {
mSelectionPopupController.onReceivedProcessTextResult(resultCode, data);
}
/**
* Returns true if accessibility is on and touch exploration is enabled.
*/
public boolean isTouchExplorationEnabled() {
return mTouchExplorationEnabled;
}
/**
* Turns browser accessibility on or off.
* If |state| is |false|, this turns off both native and injected accessibility.
* Otherwise, if accessibility script injection is enabled, this will enable the injected
* accessibility scripts. Native accessibility is enabled on demand.
*/
public void setAccessibilityState(boolean state) {
if (!state) {
mNativeAccessibilityAllowed = false;
mTouchExplorationEnabled = false;
} else {
mNativeAccessibilityAllowed = true;
mTouchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled();
}
}
/**
* Return whether or not we should set accessibility focus on page load.
*/
public boolean shouldSetAccessibilityFocusOnPageLoad() {
return mShouldSetAccessibilityFocusOnPageLoad;
}
/**
* Sets whether or not we should set accessibility focus on page load.
* This only applies if an accessibility service like TalkBack is running.
* This is desirable behavior for a browser window, but not for an embedded
* WebView.
*/
public void setShouldSetAccessibilityFocusOnPageLoad(boolean on) {
mShouldSetAccessibilityFocusOnPageLoad = on;
}
/**
*
* @return The cached copy of render positions and scales.
*/
public RenderCoordinates getRenderCoordinates() {
return mRenderCoordinates;
}
/**
* @return Whether the current page seems to be mobile-optimized. This hint is based upon
* rendered frames and may return different values when called multiple times for the
* same page (particularly during page load).
*/
public boolean getIsMobileOptimizedHint() {
return mIsMobileOptimizedHint;
}
@CalledByNative
private static Rect createRect(int x, int y, int right, int bottom) {
return new Rect(x, y, right, bottom);
}
public void extractSmartClipData(int x, int y, int width, int height) {
if (mNativeContentViewCore != 0) {
x += mSmartClipOffsetX;
y += mSmartClipOffsetY;
nativeExtractSmartClipData(mNativeContentViewCore, x, y, width, height);
}
}
/**
* Set offsets for smart clip.
*
* <p>This should be called if there is a viewport change introduced by,
* e.g., show and hide of a location bar.
*
* @param offsetX Offset for X position.
* @param offsetY Offset for Y position.
*/
public void setSmartClipOffsets(int offsetX, int offsetY) {
mSmartClipOffsetX = offsetX;
mSmartClipOffsetY = offsetY;
}
@CalledByNative
private void onSmartClipDataExtracted(String text, String html, Rect clipRect) {
// Translate the positions by the offsets introduced by location bar. Note that the
// coordinates are in dp scale, and that this definitely has the potential to be
// different from the offsets when extractSmartClipData() was called. However,
// as long as OEM has a UI that consumes all the inputs and waits until the
// callback is called, then there shouldn't be any difference.
// TODO(changwan): once crbug.com/416432 is resolved, try to pass offsets as
// separate params for extractSmartClipData(), and apply them not the new offset
// values in the callback.
final float deviceScale = mRenderCoordinates.getDeviceScaleFactor();
final int offsetXInDp = (int) (mSmartClipOffsetX / deviceScale);
final int offsetYInDp = (int) (mSmartClipOffsetY / deviceScale);
clipRect.offset(-offsetXInDp, -offsetYInDp);
if (mSmartClipDataListener != null) {
mSmartClipDataListener.onSmartClipDataExtracted(text, html, clipRect);
}
}
public void setSmartClipDataListener(SmartClipDataListener listener) {
mSmartClipDataListener = listener;
}
public void setBackgroundOpaque(boolean opaque) {
if (mNativeContentViewCore != 0) {
nativeSetBackgroundOpaque(mNativeContentViewCore, opaque);
}
}
/**
* @see View#onDragEvent(DragEvent)
*/
// TODO(hush): uncomment below when we build with API 24.
// @TargetApi(Build.VERSION_CODES.N)
public boolean onDragEvent(DragEvent event) {
if (mNativeContentViewCore == 0 || Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
return false;
}
ClipDescription clipDescription = event.getClipDescription();
// text/* will match text/uri-list, text/html, text/plain.
String[] mimeTypes =
clipDescription == null ? new String[0] : clipDescription.filterMimeTypes("text/*");
if (event.getAction() == DragEvent.ACTION_DRAG_STARTED) {
// TODO(hush): support dragging more than just text.
return mimeTypes != null && mimeTypes.length > 0
&& nativeIsTouchDragDropEnabled(mNativeContentViewCore);
}
StringBuilder content = new StringBuilder("");
if (event.getAction() == DragEvent.ACTION_DROP) {
// TODO(hush): obtain dragdrop permissions (via reflection?), when dragging files into
// Chrome/WebView is supported. Not necessary to do so for now, because only text
// dragging is supported.
ClipData clipData = event.getClipData();
final int itemCount = clipData.getItemCount();
for (int i = 0; i < itemCount; i++) {
ClipData.Item item = clipData.getItemAt(i);
content.append(item.coerceToStyledText(mContainerView.getContext()));
}
}
int[] locationOnScreen = new int[2];
mContainerView.getLocationOnScreen(locationOnScreen);
float xPix = event.getX() + mCurrentTouchOffsetX;
float yPix = event.getY() + mCurrentTouchOffsetY;
int xCss = (int) mRenderCoordinates.fromPixToDip(xPix);
int yCss = (int) mRenderCoordinates.fromPixToDip(yPix);
int screenXCss = (int) mRenderCoordinates.fromPixToDip(xPix + locationOnScreen[0]);
int screenYCss = (int) mRenderCoordinates.fromPixToDip(yPix + locationOnScreen[1]);
nativeOnDragEvent(mNativeContentViewCore, event.getAction(), xCss, yCss, screenXCss,
screenYCss, mimeTypes, content.toString());
return true;
}
/**
* Offer a long press gesture to the embedding View, primarily for WebView compatibility.
*
* @return true if the embedder handled the event.
*/
private boolean offerLongPressToEmbedder() {
return mContainerView.performLongClick();
}
/**
* Reset scroll and fling accounting, notifying listeners as appropriate.
* This is useful as a failsafe when the input stream may have been interruped.
*/
private void resetScrollInProgress() {
if (!isScrollInProgress()) return;
final boolean touchScrollInProgress = mTouchScrollInProgress;
final int potentiallyActiveFlingCount = mPotentiallyActiveFlingCount;
setTouchScrollInProgress(false);
mPotentiallyActiveFlingCount = 0;
if (touchScrollInProgress) updateGestureStateListener(GestureEventType.SCROLL_END);
if (potentiallyActiveFlingCount > 0) updateGestureStateListener(GestureEventType.FLING_END);
}
@CalledByNative
private void onNativeFlingStopped() {
// Note that mTouchScrollInProgress should normally be false at this
// point, but we reset it anyway as another failsafe.
setTouchScrollInProgress(false);
if (mPotentiallyActiveFlingCount <= 0) return;
mPotentiallyActiveFlingCount--;
updateGestureStateListener(GestureEventType.FLING_END);
}
// DisplayAndroidObserver method.
@Override
public void onRotationChanged(int rotation) {
// ActionMode#invalidate() won't be able to re-layout the floating
// action mode menu items according to the new rotation. So Chrome
// has to re-create the action mode.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& mSelectionPopupController.isActionModeValid()) {
hidePopupsAndPreserveSelection();
showSelectActionMode(true);
}
int rotationDegrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
rotationDegrees = 0;
break;
case Surface.ROTATION_90:
rotationDegrees = 90;
break;
case Surface.ROTATION_180:
rotationDegrees = 180;
break;
case Surface.ROTATION_270:
rotationDegrees = -90;
break;
default:
throw new IllegalStateException(
"Display.getRotation() shouldn't return that value");
}
sendOrientationChangeEvent(rotationDegrees);
}
// DisplayAndroidObserver method.
@Override
public void onDIPScaleChanged(float dipScale) {
WindowAndroid windowAndroid = getWindowAndroid();
if (windowAndroid == null || mNativeContentViewCore == 0) return;
mRenderCoordinates.setDeviceScaleFactor(dipScale, getWindowAndroid().getContext());
nativeSetDIPScale(mNativeContentViewCore, dipScale);
}
/**
* Set whether the ContentViewCore requires the WebContents to be fullscreen in order to lock
* the screen orientation.
*/
public void setFullscreenRequiredForOrientationLock(boolean value) {
mFullscreenRequiredForOrientationLock = value;
}
@CalledByNative
private boolean isFullscreenRequiredForOrientationLock() {
return mFullscreenRequiredForOrientationLock;
}
/**
* Sets the client to use for Contextual Search functionality.
* @param contextualSearchClient The client to notify for Contextual Search operations.
*/
public void setContextualSearchClient(ContextualSearchClient contextualSearchClient) {
mSelectionPopupController.setContextualSearchClient(contextualSearchClient);
}
/**
* Call this when we get result from ResultReceiver passed in calling showSoftInput().
* @param resultCode The result of showSoftInput() as defined in InputMethodManager.
*/
public void onShowKeyboardReceiveResult(int resultCode) {
if (resultCode == InputMethodManager.RESULT_SHOWN) {
// If OSK is newly shown, delay the form focus until
// the onSizeChanged (in order to adjust relative to the
// new size).
// TODO(jdduke): We should not assume that onSizeChanged will
// always be called, crbug.com/294908.
getContainerView().getWindowVisibleDisplayFrame(
mFocusPreOSKViewportRect);
} else if (hasFocus() && resultCode == InputMethodManager.RESULT_UNCHANGED_SHOWN) {
// If the OSK was already there, focus the form immediately.
if (mWebContents != null) {
mWebContents.scrollFocusedEditableNodeIntoView();
}
}
}
@VisibleForTesting
public ResultReceiver getNewShowKeyboardReceiver() {
if (mShowKeyboardResultReceiver == null) {
// Note: the returned object will get leaked by Android framework.
mShowKeyboardResultReceiver = new ShowKeyboardResultReceiver(this, new Handler());
}
return mShowKeyboardResultReceiver;
}
private native long nativeInit(WebContents webContents, ViewAndroidDelegate viewAndroidDelegate,
long windowAndroidPtr, float dipScale, HashSet<Object> retainedObjectSet);
private static native ContentViewCore nativeFromWebContentsAndroid(WebContents webContents);
private native void nativeUpdateWindowAndroid(
long nativeContentViewCoreImpl, long windowAndroidPtr);
private native WebContents nativeGetWebContentsAndroid(long nativeContentViewCoreImpl);
private native WindowAndroid nativeGetJavaWindowAndroid(long nativeContentViewCoreImpl);
private native void nativeOnJavaContentViewCoreDestroyed(long nativeContentViewCoreImpl);
private native void nativeSetFocus(long nativeContentViewCoreImpl, boolean focused);
private native void nativeSetDIPScale(long nativeContentViewCoreImpl, float dipScale);
private native void nativeSendOrientationChangeEvent(
long nativeContentViewCoreImpl, int orientation);
// All touch events (including flings, scrolls etc) accept coordinates in physical pixels.
private native boolean nativeOnTouchEvent(
long nativeContentViewCoreImpl, MotionEvent event,
long timeMs, int action, int pointerCount, int historySize, int actionIndex,
float x0, float y0, float x1, float y1,
int pointerId0, int pointerId1,
float touchMajor0, float touchMajor1,
float touchMinor0, float touchMinor1,
float orientation0, float orientation1,
float tilt0, float tilt1,
float rawX, float rawY,
int androidToolType0, int androidToolType1,
int androidButtonState, int androidMetaState,
boolean isTouchHandleEvent);
private native int nativeSendMouseEvent(long nativeContentViewCoreImpl, long timeMs, int action,
float x, float y, int pointerId, float pressure, float orientaton, float tilt,
int changedButton, int buttonState, int metaState, int toolType);
private native int nativeSendMouseWheelEvent(long nativeContentViewCoreImpl, long timeMs,
float x, float y, float ticksX, float ticksY, float pixelsPerTick);
private native void nativeScrollBegin(long nativeContentViewCoreImpl, long timeMs, float x,
float y, float hintX, float hintY, boolean targetViewport);
private native void nativeScrollEnd(long nativeContentViewCoreImpl, long timeMs);
private native void nativeScrollBy(
long nativeContentViewCoreImpl, long timeMs, float x, float y,
float deltaX, float deltaY);
private native void nativeFlingStart(long nativeContentViewCoreImpl, long timeMs, float x,
float y, float vx, float vy, boolean targetViewport);
private native void nativeFlingCancel(long nativeContentViewCoreImpl, long timeMs);
private native void nativeSingleTap(
long nativeContentViewCoreImpl, long timeMs, float x, float y);
private native void nativeDoubleTap(
long nativeContentViewCoreImpl, long timeMs, float x, float y);
private native void nativeLongPress(
long nativeContentViewCoreImpl, long timeMs, float x, float y);
private native void nativePinchBegin(
long nativeContentViewCoreImpl, long timeMs, float x, float y);
private native void nativePinchEnd(long nativeContentViewCoreImpl, long timeMs);
private native void nativePinchBy(long nativeContentViewCoreImpl, long timeMs,
float anchorX, float anchorY, float deltaScale);
private native void nativeSetTextHandlesTemporarilyHidden(
long nativeContentViewCoreImpl, boolean hidden);
private native void nativeResetGestureDetection(long nativeContentViewCoreImpl);
private native void nativeSetDoubleTapSupportEnabled(
long nativeContentViewCoreImpl, boolean enabled);
private native void nativeSetMultiTouchZoomSupportEnabled(
long nativeContentViewCoreImpl, boolean enabled);
private native void nativeSelectPopupMenuItems(long nativeContentViewCoreImpl,
long nativeSelectPopupSourceFrame, int[] indices);
private native long nativeGetNativeImeAdapter(long nativeContentViewCoreImpl);
private native int nativeGetCurrentRenderProcessId(long nativeContentViewCoreImpl);
private native void nativeSetAllowJavascriptInterfacesInspection(
long nativeContentViewCoreImpl, boolean allow);
private native void nativeAddJavascriptInterface(long nativeContentViewCoreImpl, Object object,
String name, Class requiredAnnotation);
private native void nativeRemoveJavascriptInterface(long nativeContentViewCoreImpl,
String name);
private native void nativeWasResized(long nativeContentViewCoreImpl);
private native void nativeSetAccessibilityEnabled(
long nativeContentViewCoreImpl, boolean enabled);
private native void nativeSetTextTrackSettings(long nativeContentViewCoreImpl,
boolean textTracksEnabled, String textTrackBackgroundColor, String textTrackFontFamily,
String textTrackFontStyle, String textTrackFontVariant, String textTrackTextColor,
String textTrackTextShadow, String textTrackTextSize);
private native void nativeExtractSmartClipData(long nativeContentViewCoreImpl,
int x, int y, int w, int h);
private native void nativeSetBackgroundOpaque(long nativeContentViewCoreImpl, boolean opaque);
private native boolean nativeIsTouchDragDropEnabled(long nativeContentViewCoreImpl);
private native void nativeOnDragEvent(long nativeContentViewCoreImpl, int action, int x, int y,
int screenX, int screenY, String[] mimeTypes, String content);
}
| [
"[email protected]"
] | |
aa0b080748eee975b185ab955ae8db5a4c511dcc | e3ebc3afe84bc979a0eeaaf28a5371ba061e28ec | /src/org/xez/jip/gwt/orders/server/OrdersServiceImpl.java | 0f6369ea6fe2684aaa90ab37be1d63d4ceca8ccc | [] | no_license | Xez99/GWT_lab_7 | 93928cb38611b2f3d906f5cdf48de9b82e7b933f | 440fc4d8a1e06c307205d244ef7161cc0d1bb060 | refs/heads/master | 2022-04-21T18:27:28.790348 | 2020-04-22T02:25:12 | 2020-04-22T02:25:12 | 257,768,711 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,624 | java | package org.xez.jip.gwt.orders.server;
import org.xez.jip.gwt.orders.client.OrdersService;
import org.xez.jip.gwt.orders.server.data.DataConfig;
import org.xez.jip.gwt.orders.server.data.DataProvider;
import org.xez.jip.gwt.orders.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.xez.jip.gwt.orders.shared.Order;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* The server-side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class OrdersServiceImpl extends RemoteServiceServlet implements OrdersService {
public List<Order> greetServer(String input) throws IllegalArgumentException {
// Verify that the input is valid.
if (!FieldVerifier.isValidName(input)) {
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException("ID must be 8 characters long");
}
input = escapeHtml(input);
DataProvider data = DataConfig.getDataProvider();
return data.getOrdersByUserId(input);
}
/**
* Escape an html string. Escaping data received from the client helps to
* prevent cross-site script vulnerabilities.
*
* @param html the html string to escape
* @return the escaped string
*/
private String escapeHtml(String html) {
if (html == null) {
return null;
}
return html.replaceAll("&", "&").replaceAll("<", "<").replaceAll(
">", ">");
}
}
| [
"[email protected]"
] | |
22d35816402e4e0f1f690b1ec951695c93ee2be4 | 84d8b226033bc9eafe6168bfd5542fb4b4206e4d | /src/main/java/com/course/springbootstarter/surattugasdtl/SuratTugasDtlService.java | 91f7ec8110d005564900fd00d9a1bf8fafe16834 | [] | no_license | tutnatha/kangen-water-restfull-svr-mgnt | e7e7773517672e734c7fd467ebaf60955690fa8b | 4c3f4745118e42ff7c73e9213e159edcf1e8b82f | refs/heads/master | 2022-06-18T10:12:00.726609 | 2019-08-13T14:07:08 | 2019-08-13T14:07:08 | 179,807,952 | 0 | 0 | null | 2022-05-25T23:17:28 | 2019-04-06T08:31:00 | Java | UTF-8 | Java | false | false | 1,306 | java | package com.course.springbootstarter.surattugasdtl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SuratTugasDtlService {
@Autowired
private SuratTugasDtlRepository suratTugasDtlRepository;
public List<SuratTugasDtl> getAllSuratTugasDtls() {
List<SuratTugasDtl> suratTugasDtls = new ArrayList<>();
suratTugasDtlRepository.findAll().forEach(suratTugasDtls::add);
return suratTugasDtls;
}
public SuratTugasDtl getSuratTugasDtl(String no) {
//return kamars.stream().filter(t -> t.getId().equals(id)).findFirst().get();
// return suratTugasDtlRepository.findOne(no); //error
return null; //sementara
}
public void addSuratTugasDtl(SuratTugasDtl suratTugasDtl) {
suratTugasDtlRepository.save(suratTugasDtl);
}
void updateSuratTugasDtl(String no, SuratTugasDtl suratTugasDtl) {
suratTugasDtlRepository.save(suratTugasDtl);
}
void updateSuratTugasDtl(SuratTugasDtl suratTugasDtl) {
suratTugasDtlRepository.save(suratTugasDtl);
}
void deleteSuratTugasDtl(String no) {
// suratTugasDtlRepository.delete(no); //sementara
}
}
| [
"[email protected]"
] | |
a1dfab5d9fbbb98193cefa4662d1ed2fba0479b1 | ec4eaa69d7c9546f2440b998060bd39e49193441 | /app/src/main/java/com/gengli/technician/adapter/MoreFittingAdapter.java | d09ed57b173a6784ee02e8ce37c701b3a374b816 | [] | no_license | zhanghui2017/TechnicianApp | c0f915c2b05f34c1f70178fbf67c5e98e0146b99 | d3110d662644b9bb5a31591a876828ab1df9ea71 | refs/heads/master | 2020-03-06T15:53:19.567689 | 2018-03-27T09:40:51 | 2018-03-27T09:40:51 | 126,963,587 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,751 | java | package com.gengli.technician.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.gengli.technician.R;
import com.gengli.technician.bean.Fitting;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
public class MoreFittingAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private List<Fitting> fittingList;
private LayoutInflater inflater;
private MoreFittingCountListener listener;
public MoreFittingAdapter(Context context, List<Fitting> fittingList) {
this.context = context;
this.fittingList = fittingList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setFittingCountListener(MoreFittingCountListener listener) {
this.listener = listener;
}
@Override
public int getCount() {
return fittingList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_more_fitting, null);
holder.text_more_fitting_name = (TextView) convertView.findViewById(R.id.text_more_fitting_name);
holder.text_more_fitting_last_count = (TextView) convertView.findViewById(R.id.text_more_fitting_last_count);
holder.text_more_fitting_cho_count = (TextView) convertView.findViewById(R.id.text_more_fitting_cho_count);
holder.img_more_fitting = (ImageView) convertView.findViewById(R.id.img_more_fitting);
holder.img_more_minus_bt = (ImageView) convertView.findViewById(R.id.img_more_minus_bt);
holder.img_more_add_bt = (ImageView) convertView.findViewById(R.id.img_more_add_bt);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Fitting fitting = fittingList.get(position);
holder.text_more_fitting_name.setText(fitting.getName());
holder.text_more_fitting_last_count.setText("" + fitting.getLastCount());
ImageLoader.getInstance().displayImage(fitting.getImgUrl(), holder.img_more_fitting);
holder.text_more_fitting_cho_count.setText(fitting.getCount() + "件");
holder.img_more_minus_bt.setOnClickListener(this);
holder.img_more_add_bt.setOnClickListener(this);
holder.img_more_minus_bt.setTag(position);
holder.img_more_add_bt.setTag(position);
return convertView;
}
@Override
public void onClick(View v) {
if (null == listener) return;
switch (v.getId()) {
case R.id.img_more_add_bt:
listener.addCount(v);
break;
case R.id.img_more_minus_bt:
listener.minusCount(v);
break;
}
}
private class ViewHolder {
private ImageView img_more_fitting;
private TextView text_more_fitting_name;
private TextView text_more_fitting_last_count;
private ImageView img_more_minus_bt;
private ImageView img_more_add_bt;
private TextView text_more_fitting_cho_count;
}
public interface MoreFittingCountListener {
void addCount(View v);
void minusCount(View v);
}
} | [
"[email protected]"
] | |
444a328e37e7cafb93152feb19e3b4dbb2db0d8d | 2a3adbd1a8cba3434263381997206fa86593cca4 | /toceansoft-excel-service/src/main/java/com/toceansoft/common/excel/service/ExcelConfigExcludeService.java | 961c6d2ac1b2ce3ec15dbc3c2ccbcfc056180a38 | [] | no_license | narci2010/toceansoft-base | e4590bd190e281d785bc01f5c40840f40f58fdc0 | 1b5e439e788a13d7a097a0aae92f78c194d9fc46 | refs/heads/master | 2022-09-11T15:03:29.800126 | 2019-06-04T09:54:40 | 2019-06-04T09:54:40 | 183,211,461 | 0 | 0 | null | 2022-09-01T23:05:50 | 2019-04-24T11:04:36 | JavaScript | UTF-8 | Java | false | false | 1,863 | java | /*
* Copyright 2010-2019 Tocean Group.
* 版权:商业代码,未经许可,禁止任何形式拷贝、传播及使用
* 文件名:ExcelConfigExcludeService.java
* 描述:
* 修改人: Tocean INC.
* 修改时间:2019-02-14 16:55:43
* 跟踪单号:
* 修改单号:
* 修改内容:
*/
package com.toceansoft.common.excel.service;
import com.toceansoft.common.excel.entity.ExcelConfigExcludeEntity;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Tocean INC.
*/
public interface ExcelConfigExcludeService {
/**
* 查询(指定对象)
* @param excelConfigExcludeId Long
* @return ExcelConfigExcludeEntity
*/
ExcelConfigExcludeEntity queryObject(Long excelConfigExcludeId);
/**
* 列表
*
* @param map
* Map<String, Object>
* @return List<ExcelConfigExcludeEntity>
*/
List<ExcelConfigExcludeEntity> queryList(Map<String, Object> map);
/**
* 总记录数量
*
* @param map
* Map<String, Object>
* @return int
*/
int queryTotal(Map<String, Object> map);
/**
* 保存
* @param excelConfigExclude ExcelConfigExcludeEntity
*
*/
void save(ExcelConfigExcludeEntity excelConfigExclude);
/**
* 修改
* @param excelConfigExclude ExcelConfigExcludeEntity
*
*/
void update(ExcelConfigExcludeEntity excelConfigExclude);
/**
* 删除
* @param excelConfigExcludeId Long
*
*/
void delete(Long excelConfigExcludeId);
/**
* 批量删除
* @param excelConfigExcludeIds Long[]
*
*/
void deleteBatch(Long[] excelConfigExcludeIds);
// /**
// * 通过excelConfigId 来删除ExcelConfigExcludeEntity
// * @param excelConfigId
// * excelConfigId
// */
// void deleteByExcelConfigId(Long excelConfigId);
}
| [
"[email protected]"
] | |
53c03183d06a048a2d9e65c6dfa42e23ae9ea727 | 21db81c7b34f59c96c18fc2f3d1ab40f2068f1b3 | /mse10ccenter/src/callcenter/web/action/forum/ThreadAction.java | 259e4f32e49c4f011c8754e5db8ff6d8806b29b1 | [] | no_license | GeorgePhys/mse10callcenter | b5252adc4f17942f767db271e6e9d9528ca0a498 | f835769398db9e82a27049c335758e4c2e0dc035 | refs/heads/master | 2021-01-10T17:31:51.930448 | 2011-09-29T23:34:14 | 2011-09-29T23:34:14 | 36,535,031 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,976 | java | package callcenter.web.action.forum;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import callcenter.entity.forum.ForumThread;
import callcenter.entity.forum.Post;
import callcenter.service.forum.ForumServiceBean;
import callcenter.web.action.BaseAction;
@ManagedBean(name = "threadAction")
@SessionScoped
public class ThreadAction extends BaseAction<ForumThread> {
private static final long serialVersionUID = 8981722129655621928L;
@EJB
private ForumServiceBean forumServiceBean;
private boolean isCreate;
private Post post;
public String init() {
setTargetEntity(new ForumThread());
isCreate = true;
setReadonly(false);
setPost(null);
return "forumThreadPreview";
}
public String preview(ForumThread forumThread) {
setTargetEntity(forumThread);
isCreate = false;
setReadonly(false);
setPost(null);
return "forumThreadPreview";
}
public void saveThread() {
if (isCreate) {
getTargetEntity().setCreatedBy(getUser());
isCreate = false;
}
ForumThread thread = forumServiceBean.save(getTargetEntity());
setTargetEntity(thread);
setReadonly(true);
}
public void savePost() {
getTargetEntity().getPosts().add(getPost());
getPost().setThread(getTargetEntity());
setPost(null);
saveThread();
}
public void addNewPost() {
Post post = new Post();
post.setFromUser(getUser());
setPost(post);
}
public void cancelAddPost() {
setPost(null);
}
/**
* @return the post
*/
public Post getPost() {
return post;
}
/**
* @param post
* the post to set
*/
public void setPost(Post post) {
this.post = post;
}
/**
* @return the isCreate
*/
public boolean isCreate() {
return isCreate;
}
/**
* @param isCreate
* the isCreate to set
*/
public void setCreate(boolean isCreate) {
this.isCreate = isCreate;
}
}
| [
"[email protected]"
] | |
e34681c83c10f247e20413ca417190f2757d71c9 | e49a7dd3cbb76aeb029f209218d747a0acdc1fe4 | /tetrecs/src/main/java/uk/ac/soton/comp1206/game/Game.java | 0a23e3c123fcc192564babcab5f16e2c5bb7747e | [] | no_license | cwsbowe/tetrECS | 32c60959e00db7968e16aa672e6b459f8bb6e257 | 6d5f7938dfcbb797b3f031569f2ff57899e57d08 | refs/heads/master | 2023-08-17T00:39:20.910707 | 2021-09-30T19:38:15 | 2021-09-30T19:38:15 | 412,200,769 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,691 | java | package uk.ac.soton.comp1206.game;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.scene.media.Media;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.ac.soton.comp1206.component.GameBlock;
import uk.ac.soton.comp1206.component.PieceBoard;
import uk.ac.soton.comp1206.ui.Multimedia;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* The Game class handles the main logic, state and properties of the TetrECS game. Methods to manipulate the game state
* and to handle actions made by the player should take place inside this class.
*/
public class Game {
private static final Logger logger = LogManager.getLogger(Game.class);
/**
* Number of rows
*/
protected final int rows;
/**
* Number of columns
*/
protected final int cols;
/**
* The grid model linked to the game
*/
protected final Grid grid;
protected final Grid pieceGrid;
protected final Grid followingPieceGrid;
//two upcoming pieces
private GamePiece currentPiece;
private GamePiece followingPiece;
//game variables
private SimpleIntegerProperty score = new SimpleIntegerProperty(0);
private SimpleIntegerProperty level = new SimpleIntegerProperty(0);
private SimpleIntegerProperty lives = new SimpleIntegerProperty(3);
private SimpleIntegerProperty multiplier = new SimpleIntegerProperty(1);
//score holder
private SimpleListProperty localScores = new SimpleListProperty();
//media variables
public Multimedia multimedia;
private Media placeSound;
private Media rotateSound;
private Media swapSound;
//boards holding upcoming pieces
public PieceBoard pieceBoard;
public PieceBoard followingPieceBoard;
//time controls
public Timer timer;
public Timer shownTimer;
public TimerTask timerTask;
public SimpleDoubleProperty timeLeft = new SimpleDoubleProperty(12);
public TimerTask reduceTimeLeft;
/**
* Create a new game with the specified rows and columns. Creates a corresponding grid model.
* @param cols number of columns
* @param rows number of rows
*/
public Game(int cols, int rows) {
this.cols = cols;
this.rows = rows;
//Create a new grid model to represent the game state
this.grid = new Grid(cols,rows);
this.pieceGrid = new Grid(3, 3);
this.followingPieceGrid = new Grid(3, 3);
}
/**
* Start the game
*/
public void start() {
logger.info("Starting game");
initialiseGame();
}
/**
* Initialise a new game and set up anything that needs to be done at the start
*/
public void initialiseGame() {
logger.info("Initialising game");
Media music = new Media(getClass().getResource("/music/game.wav").toExternalForm());
placeSound = new Media(getClass().getResource("/sounds/place.wav").toExternalForm());
rotateSound = new Media(getClass().getResource("/sounds/rotate.wav").toExternalForm());
swapSound = new Media(getClass().getResource("/sounds/transition.wav").toExternalForm());
logger.info("Game media established");
multimedia = new Multimedia();
multimedia.playMusic(music);
currentPiece = spawnPiece();
followingPiece = spawnPiece();
pieceBoard.displayPiece(currentPiece);
followingPieceBoard.displayPiece(followingPiece);
logger.info("Timers created");
timer = new Timer();
shownTimer = new Timer();
//recreating timers and timer tasks
timerTask = new TimerTask() {
@Override
public void run() {
gameLoop();
}
};
reduceTimeLeft = new TimerTask() {
@Override
public void run() {
setTimeLeft(getTimeLeft().get() - 0.5);
}
};
shownTimer.scheduleAtFixedRate(reduceTimeLeft, 500, 500);
timer.schedule(timerTask, getTimerDelay());
}
/**
* Handle what should happen when a particular block is clicked
* @param gameBlock the block that was clicked
*/
public void blockClicked(GameBlock gameBlock) {
//Get the position of this block
int x = gameBlock.getX();
int y = gameBlock.getY();
if (grid.canPlayPiece(currentPiece, x, y)) {
timer.cancel();
shownTimer.cancel();
grid.playPiece(currentPiece, x, y);
multimedia.playAudio(placeSound);
afterPiece();
nextPiece();
//recreating timers and timer tasks
timer = new Timer();
shownTimer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
gameLoop();
}
};
reduceTimeLeft = new TimerTask() {
@Override
public void run() {
setTimeLeft(getTimeLeft().get() - 0.5);
}
};
setTimeLeft(getTimerDelay() / 1000.0);
shownTimer.scheduleAtFixedRate(reduceTimeLeft, 500, 500);
timer.schedule(timerTask, getTimerDelay());
}
}
/**
* Get the grid model inside this game representing the game state of the board
* @return game grid model
*/
public Grid getGrid() {
return grid;
}
public Grid getPieceGrid() { return pieceGrid; }
public Grid getFollowingPieceGrid() { return followingPieceGrid; }
/**
* Get the number of columns in this game
* @return number of columns
*/
public int getCols() {
return cols;
}
/**
* Get the number of rows in this game
* @return number of rows
*/
public int getRows() {
return rows;
}
//Getting game variables
public SimpleIntegerProperty getScore() {
return score;
}
public SimpleIntegerProperty getLevel() {
return level;
}
public SimpleIntegerProperty getLives() {
return lives;
}
public SimpleIntegerProperty getMultiplier() {
return multiplier;
}
//Getting remaining time on timer
public SimpleDoubleProperty getTimeLeft() { return timeLeft; }
//Setting game variables
public void setScore(int value) {
score.set(value);
}
public void setLevel(int value) {
level.set(value);
}
public void setLives(int value) {
lives.set(value);
}
public void setMultiplier(int value) {
multiplier.set(value);
}
//Setting remaining time on timer
public void setTimeLeft(double value) {timeLeft.set(value);}
public void cancelTimer() {
timer.cancel();
}
public GamePiece spawnPiece() {
logger.info("Spawning piece");
Random rand = new Random();
int piece = rand.nextInt(15);
return GamePiece.createPiece(piece);
}
public void nextPiece() {
logger.info("Next piece");
currentPiece = followingPiece;
followingPiece = spawnPiece();
pieceBoard.displayPiece(currentPiece);
followingPieceBoard.displayPiece(followingPiece);
}
public void afterPiece() {
logger.info("After piece");
boolean current = true;
var rowsToClear = new ArrayList<Integer>();
var colsToClear = new ArrayList<Integer>();
int numOfRows = this.getRows();
int numOfCols = this.getCols();
//checks if any rows need to be cleared
for (int rowNum = 0; rowNum < numOfRows; rowNum++) {
for (int colNum = 0; colNum < numOfCols; colNum++) {
if (grid.get(colNum, rowNum) == 0) {
current = false;
}
}
if (current) {
rowsToClear.add(rowNum);
}
current = true;
}
//checks if any columns need to be cleared
for (int colNum = 0; colNum < numOfCols; colNum++) {
for (int rowNum = 0; rowNum < numOfRows; rowNum++) {
if (grid.get(colNum, rowNum) == 0) {
current = false;
}
}
if (current) {
colsToClear.add(colNum);
}
current = true;
}
//clearing rows
for (int rowNum : rowsToClear) {
for (int colNum = 0; colNum < numOfCols; colNum++) {
grid.set(colNum, rowNum, 0);
}
}
//clearing columns
for (int colNum : colsToClear) {
for (int rowNum = 0; rowNum < numOfCols; rowNum++) {
grid.set(colNum, rowNum, 0);
}
}
var numOfClearedRows = rowsToClear.size();
var numOfClearedCols = colsToClear.size();
var numOfClearedLines = numOfClearedRows + numOfClearedCols;
if (numOfClearedLines > 0) {
//works out the number of cleared blocks, accounting for duplicates
int blocks = numOfRows * numOfClearedCols + numOfCols * numOfClearedRows - numOfClearedRows * numOfClearedCols;
afterPiece(numOfClearedLines, blocks);
setMultiplier(getMultiplier().get() + 1);
} else {
setMultiplier(1);
}
}
//updates score and level
public void afterPiece(int lines, int blocks){
var previousScore = getScore();
var multiplier = getMultiplier();
var newScore = previousScore.get() + (lines * blocks * 10 * multiplier.get());
setLevel(Math.floorDiv(newScore, 1000));
setScore(newScore);
}
//rotates the current piece
public void rotateCurrentPiece() {
currentPiece.rotate();
pieceBoard.displayPiece(currentPiece);
multimedia.playAudio(rotateSound);
}
//swaps the current piece with the following piece
public void swapCurrentPieces() {
GamePiece temp = currentPiece;
currentPiece = followingPiece;
followingPiece = temp;
pieceBoard.displayPiece(currentPiece);
followingPieceBoard.displayPiece(followingPiece);
multimedia.playAudio(swapSound);
}
public int getTimerDelay() {
int level = getLevel().get();
if (level < 19) {
return 12000 - 500 * level;
} else {
return 2500;
}
}
public void gameLoop() {
//time runs out
setLives(getLives().get() - 1);
setMultiplier(1);
//reset timer
timer.cancel();
shownTimer.cancel();
setTimeLeft(getTimeLeft().get() / 1000.0);
//change piece
currentPiece = followingPiece;
followingPiece = spawnPiece();
pieceBoard.displayPiece(currentPiece);
followingPieceBoard.displayPiece(followingPiece);
//set new timer
timer = new Timer();
shownTimer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
gameLoop();
}
};
reduceTimeLeft = new TimerTask() {
@Override
public void run() {
setTimeLeft(getTimeLeft().get() - 0.5);
}
};
setTimeLeft(getTimerDelay() / 1000.0);
timer.schedule(timerTask, getTimerDelay());
shownTimer.scheduleAtFixedRate(reduceTimeLeft, 500, 500);
}
}
| [
"[email protected]"
] | |
1856e32756daa034a8bede04f49f8602da7d335b | e55fce53868a20d4111ba7b79f7f290e23e62921 | /jsp_ws/herbmall/src/com/herbmall/comments/model/commentDAO.java | 71c42a6f45393fde3a1c94eb58853bda76316321 | [] | no_license | immsee098/javaP2 | f34a48450fa10bb63315a2a79b121a497584b2e6 | dd607ba05e616470fdfcb2b37c7e44052952a950 | refs/heads/master | 2022-12-24T03:31:22.514335 | 2020-02-14T01:13:33 | 2020-02-14T01:13:33 | 203,916,710 | 0 | 0 | null | 2022-12-16T10:37:20 | 2019-08-23T03:25:52 | HTML | UTF-8 | Java | false | false | 1,280 | java | //윤해서
package com.herbmall.comments.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import com.herbmall.db.ConnectionPoolMgr;
public class commentDAO {
private ConnectionPoolMgr pool;
public commentDAO() {
pool = new ConnectionPoolMgr();
}
public List<commentVO> selectComment(int num) throws SQLException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<commentVO> list = new ArrayList<commentVO>();
try {
con = pool.getConnection();
String sql = "select * from comments\r\n" +
"where bdno=?";
ps=con.prepareStatement(sql);
ps.setInt(1, num);
rs = ps.executeQuery();
while(rs.next()) {
int no = rs.getInt("no");
String name = rs.getString("name");
String pwd = rs.getString("pwd");
Timestamp regdate = rs.getTimestamp("regdate");
String content = rs.getString("content");
int bdno = rs.getInt("bdno");
commentVO vo = new commentVO(no, name, pwd, regdate, content, bdno);
list.add(vo);
}
return list;
} finally {
pool.dbClose(rs, ps, con);
}
}
}
| [
"[email protected]"
] | |
e36c0acd5f15e2ea1ed3089d1aead1ddbba2301e | 2d189720c340fa9a43d62fd61e1c2b1451ac008f | /app/src/main/java/com/example/subm1moviecatalogue/models/Dates.java | 7d0549432aba9bd11dda5505346e9a48e933f592 | [] | no_license | pradprat/dicoding-MovieCatalogue | ff7f56e7af38d6edfc03ec71becaf1fc52053ec2 | 291bb348416f30eab574f080c91e98bcbd07deab | refs/heads/master | 2020-06-16T13:30:44.919050 | 2019-07-24T06:10:02 | 2019-07-24T06:10:02 | 195,593,154 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 632 | java |
package com.example.subm1moviecatalogue.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
public class Dates {
@SerializedName("maximum")
@Expose
private String mMaximum;
@SerializedName("minimum")
@Expose
private String mMinimum;
public String getMaximum() {
return mMaximum;
}
public void setMaximum(String maximum) {
mMaximum = maximum;
}
public String getMinimum() {
return mMinimum;
}
public void setMinimum(String minimum) {
mMinimum = minimum;
}
}
| [
"[email protected]"
] | |
e4d87563bacac366d8e44f4629c9ec48fc9df76a | 4d6328fbffe0c75ee4ec00fc658406226ce88603 | /src/inaer/client/CalculatorModel.java | e12f53a0eafdeca08162fb8b1953916dfbe10b8c | [] | no_license | AntonioTB1971/calculator | 12b7e09c30dfe60c14cd8608cc95f4d03c997ddf | 3aad8407595c40ba9dff37ec6acdb7ce3808f7da | refs/heads/master | 2021-01-11T01:18:19.449479 | 2016-10-17T21:17:19 | 2016-10-17T21:17:19 | 71,060,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,642 | java | package inaer.client;
import java.util.ArrayList;
import java.util.List;
import inaer.client.CalculatorController.ECommands;
interface CalculatorModelObserver {
public void onModelChange();
}
public class CalculatorModel {
private String textValue;
private double accumulator;
private boolean partialInvalid;
private CalculatorController.ECommands currentCommand;
private List<CalculatorModelObserver> observers = new ArrayList<CalculatorModelObserver>();
protected void notifyObservers() {
for (CalculatorModelObserver o : observers)
o.onModelChange();
}
public void addObserver(CalculatorModelObserver anObserver) {
observers.add(anObserver);
}
public CalculatorModel() {
textValue = "0";
accumulator = 0;
partialInvalid = true;
setCurrentCommand(ECommands.none);
}
public double getAccumulator() {
return accumulator;
}
public void setAccumulator(double accumulator) {
this.accumulator = accumulator;
notifyObservers();
}
public String getTextValue() {
return textValue;
}
public void setTextValue(String textValue) {
this.textValue = textValue;
notifyObservers();
}
public CalculatorController.ECommands getCurrentCommand() {
return currentCommand;
}
public void setCurrentCommand(CalculatorController.ECommands currentCommand) {
this.currentCommand = currentCommand;
notifyObservers();
}
public boolean isPartialInvalid() {
return partialInvalid;
}
public void setPartialInvalid(boolean partialInvalid) {
this.partialInvalid = partialInvalid;
notifyObservers();
}
}
| [
"[email protected]"
] | |
bc388a7bc74bb5dcca02f1c9834f0366d38908f8 | d00fb68fc270a60f8916d0852f95ddcc79939b34 | /xacj-interface/src/main/java/com/jfsoft/interfaces/webservice/client/Hello.java | e64386866fdb387d849366e03a81d6c39ba0d044 | [] | no_license | cMqQAQ/test | 12c284d86e47c646cab792486ebce024a3309710 | e5c883ffc9c5a464b64eed374b2868e8d573d683 | refs/heads/main | 2022-12-29T20:34:58.996880 | 2020-10-09T00:56:13 | 2020-10-09T00:56:13 | 302,497,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,268 | java |
package com.jfsoft.interfaces.webservice.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>hello complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="hello">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="arg0" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "hello", propOrder = {
"arg0"
})
public class Hello {
protected String arg0;
/**
* 获取arg0属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getArg0() {
return arg0;
}
/**
* 设置arg0属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArg0(String value) {
this.arg0 = value;
}
}
| [
"[email protected]"
] | |
9f9b98e14e94038fc3ee6cec94b886cedf91851a | 8a0afb86f64cdceef0e427079b8715dd484bf11c | /app/src/main/java/com/xi/liuliu/topnews/impl/ZoomInTransform.java | 0f57e9162b550952579320a2fbbad68d3ad3b721 | [] | no_license | xiyy/TopNews | 3c20f7458b63487383b274f18e88dd1f60b44ace | 51e5c228acd36a28ccd4fdb6026a800666498102 | refs/heads/master | 2020-06-18T06:39:52.570646 | 2019-07-11T05:52:32 | 2019-07-11T05:52:32 | 94,161,853 | 54 | 15 | null | null | null | null | UTF-8 | Java | false | false | 1,004 | java | package com.xi.liuliu.topnews.impl;
import android.support.v4.view.ViewPager;
import android.view.View;
/**
* Created by zhangxb171 on 2017/7/19.
*/
public class ZoomInTransform implements ViewPager.PageTransformer {
@Override
public void transformPage(View page, float position) {
int width = page.getWidth();
int height = page.getHeight();
//这里只对右边的View做了操作
if (position > 0 && position <= 1) {
//position是1.0->0,但是沒有等于0
//设置该View的X轴不动
page.setTranslationX(-width * position);
//设置缩放中心在View的正中心
page.setPivotX(width / 2);
page.setPivotY(height / 2);
//设置放缩比例(0.0,1.0]
page.setScaleX(1 - position);
page.setScaleY(1 - position);
} else if (position >= -1 && position < 0) {//对左侧View操作
} else {//对中间View操作
}
}
}
| [
"[email protected]"
] | |
704f357fcc507d55090675de72074fe59d7f4b72 | 79b8754148bb4f0b108cf3ffcf95583c77b5df0e | /src/main/java/com/book/mongo/UserService.java | 5689bc49b61406ce72c57d913a41175e55ec7229 | [] | no_license | zhangzheng181812/springtest1 | ffe8faef081a8a9539b9b7619e7031cf3af5911e | 3a2e77be890ea4abb8bbd9772a559d494d961134 | refs/heads/master | 2023-04-05T11:13:43.619720 | 2022-05-27T13:04:49 | 2022-05-27T13:04:49 | 141,992,281 | 0 | 0 | null | 2023-03-27T22:18:04 | 2018-07-23T09:29:02 | Java | UTF-8 | Java | false | false | 1,078 | java | package com.book.mongo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by admin on 2018/12/25.
*/
@Service
public class UserService {
@Autowired
private MongoTemplate mongoTemplate;
public void saveUser(User user) {
mongoTemplate.save(user, "test_user");
}
public User findUser(Long id) {
return mongoTemplate.findById(id, User.class);
}
public List<User> findUsers(String name, int page, int pageSize) {
//创建查询对象
Criteria regex = Criteria.where("name").regex(name);
// .and("id").regex("1");
Query query = Query.query(regex);
query.skip((page - 1) * pageSize);
query.limit(pageSize);
List<User> list = mongoTemplate.find(query, User.class);
return list;
}
}
| [
"[email protected]"
] | |
bebc553df8186e609cdc884053075b1cf18202ef | 55717aedd54faea5157a37c8537c470a62dd8988 | /latte-core/src/main/java/com/example/latte/delegates/web/WebViewInitializer.java | af980982d365b59408047ced1af632c6349a95a5 | [] | no_license | xiangruiwan/JopEC | d43e708fc1c7cc5201507b3f71dc42e00c8e9c7c | 71a208675b276cabc05598948af5cc60669dbcf9 | refs/heads/master | 2021-09-03T21:20:49.171062 | 2018-01-12T03:26:33 | 2018-01-12T03:26:41 | 110,545,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,771 | java | package com.example.latte.delegates.web;
import android.annotation.SuppressLint;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* Created by Administrator on 2018/1/8.
*/
public class WebViewInitializer {
@SuppressLint("SetJavaScriptEnabled")
public WebView createWebView(WebView webView) {
WebView.setWebContentsDebuggingEnabled(true);
//不能横向滚动
webView.setHorizontalScrollBarEnabled(false);
//不能纵向滚动
webView.setVerticalScrollBarEnabled(false);
//允许截图
webView.setDrawingCacheEnabled(true);
//屏蔽长按事件
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
//初始化WebSettings
final WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
final String ua = settings.getUserAgentString();
settings.setUserAgentString(ua + "Latte");
//隐藏缩放控件
settings.setBuiltInZoomControls(false);
settings.setDisplayZoomControls(false);
//禁止缩放
settings.setSupportZoom(false);
//文件权限
settings.setAllowFileAccess(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
//缓存相关
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
return webView;
}
}
| [
"[email protected]"
] | |
9af56fd8e305b00251faae749ea997bbd2dd9953 | 4e0f0650b3c453c3580c64db30baea91dd84addd | /src/AtomicReference/AtomicDemo.java | e96c5fe203afed8ab479d72ffb4cea34e16a9149 | [] | no_license | wangqiangacer/volatile | 6330f5e0e7f357ddc4529ac41a64d9e26686fc82 | 133382dce7e8519f7bcd8a618f5e15f8ff4b287f | refs/heads/master | 2020-06-25T02:34:57.885801 | 2019-08-31T14:09:19 | 2019-08-31T14:09:19 | 199,172,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 503 | java | package AtomicReference;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicDemo {
public static void main(String[] args) {
User zhangsan = new User("zhangsan", 22);
User lisi = new User("lisi", 23);
AtomicReference<User> atomicReference=new AtomicReference<User>();
atomicReference.set(zhangsan);
System.out.println(atomicReference.compareAndSet(zhangsan, lisi));
System.out.println(atomicReference.get().toString());
}
}
| [
"[email protected]"
] | |
327868d4d952c282823f308880abf00dd7afb59d | 34681071ddc6d8fd0bc1070dfae0f16682c7fc84 | /BIT504_as1/src/bit504_as1/Student.java | b97115790193f31ef9adc490cab1c5471b97f5d4 | [] | no_license | Anton-Stechman/assignment1-bit504 | 2a46caf89ebbcc129fcb9c69e120c5b948f46c15 | 35d7ffb5beb7a5b48c1e14044bc0b233ab254c95 | refs/heads/master | 2022-03-28T20:05:40.693688 | 2020-01-09T22:58:06 | 2020-01-09T22:58:06 | 232,922,368 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 493 | java | package bit504_as1;
public class Student
{
/*
* Course: BIT504
* Assignment: Assignment 1
* Student ID: 5000406
* Program By: Anton Stechman
*/
int id;
String firstName;
String lastName;
public AssignmentMarks math_marks;
public AssignmentMarks engl_marks;
public Student(int ID, String fName, String lName)
{
this.id = ID;
this.firstName = fName;
this.lastName = lName;
}
public String getFullName()
{
return firstName + " " + lastName;
}
}
| [
"[email protected]"
] | |
96851ae08c6a9de4d85341e8dae89c649b52c0b7 | 8055b532077b515c13920180e901b7c4e51eefab | /HelloJava/src/cn/ucai/day05/TestArray2.java | 877a82f5977aed650272071b0ba71782d63549e1 | [] | no_license | MyCloudream/java1017 | 1950629c3ea0079b126272d9b25d54870b79cafd | b111df2547e76d7aff8f91ec8ee74de0dc208d76 | refs/heads/master | 2021-01-12T06:31:47.897270 | 2016-12-26T09:52:48 | 2016-12-26T09:52:48 | 77,374,635 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 972 | java | package cn.ucai.day05;
/**
* 数组定义好之后,数组元素有默认初始化
* 各种数据类型的默认值:
* 1、byte、short、int、long数组:不同位数的0
* 2、float、double:不同位数的0.0
* 3、boolean:false
* 4、char:'\u0000'
*
* 对于引用数据类型来说,为null
*
*/
public class TestArray2 {
public static void main(String[] args) {
String[] strArrNames = {"张三","李四","王五"};
for(int i=0;i<strArrNames.length;i++){
System.out.println(strArrNames[i]);
}
System.out.println(strArrNames[1]);
/*int scoreArr2[] = new int[7];
// 数组的定义
int[] scoreArr = new int[7];
System.out.println(scoreArr[0]);
System.out.println(scoreArr[1]);
System.out.println(scoreArr[5]);
boolean[] boolArr = new boolean[10];
System.out.println(boolArr[3]);
char ch = '\u4E2D';
System.out.println(ch);
String[] strArr = new String[10];
System.out.println(strArr[4]);*/
}
}
| [
"[email protected]"
] | |
c6d4ab3d9a05083dcc574705daabe300826a40d5 | 4dbcde8a665efd59ce810bf59f7726f8feddd15d | /week-03/day04/Recursion/src/Refactorio.java | ad2ef11436e12931ee136020642ac39081bd0eed | [] | no_license | green-fox-academy/balesz9 | c9ac4905b83b64658605a4b6c0abca0e591adfed | 65fb2d88f1d749616aa3cf544aadf2cfad448a35 | refs/heads/master | 2020-04-15T13:55:38.780691 | 2019-03-21T01:40:56 | 2019-03-21T01:40:56 | 164,736,990 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | public class Refactorio {
public static void main(String[] args) {
int number = 10;
System.out.println(Refactorio(number));
}
public static int Refactorio(int n){
if (n <=1){
return 1;
}
else
return n*Refactorio(n-1);
}
}
// Create a recursive function called `refactorio`
// that returns it's input's factorial
| [
"[email protected]"
] | |
fa2f2cada182efa6d3a38f2f162b85413a99bb12 | bcc7b278fbe2645d526524e19c6835c98decca24 | /src/main/java/hello/servlet/web/frontcontroller/v2/controller/MemberSaveControllerV2.java | 3722d93e0955202aa58a251f63a44c97e2c15394 | [] | no_license | pok3mon025/spring-mvc-1 | fb04f9d7ba7498f600059bb6da65d7679e48c642 | 34ad80e70edb450ece63ec0bf6b9968f4adacf28 | refs/heads/master | 2023-07-16T20:02:19.055173 | 2021-08-24T07:28:02 | 2021-08-24T07:28:02 | 385,155,091 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,142 | java | package hello.servlet.web.frontcontroller.v2.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import hello.servlet.domain.member.Member;
import hello.servlet.domain.member.MemberRepository;
import hello.servlet.web.frontcontroller.MyView;
import hello.servlet.web.frontcontroller.v2.ControllerV2;
public class MemberSaveControllerV2 implements ControllerV2 {
private MemberRepository memberRepository = MemberRepository.getInstance();
@Override
public MyView process(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
String username = request.getParameter("username");
int age = Integer.parseInt(request.getParameter("age"));
Member member = new Member(username, age);
memberRepository.save(member);
//Model에 데이터를 보관한다.
request.setAttribute("member", member);
return new MyView("/WEB-INF/views/save-result.jsp");
}
}
| [
"[email protected]"
] | |
cb421d274915f1ab36f601cc3c30a0dc876d5583 | a82d14d7ea81c06b7ed3ff36435e84e0ab11df40 | /src/test/java/hermanos/bistro/pizza/PizzaApplicationTests.java | 12f28e53230aecb55f0b18513dcb9656cc9ea868 | [] | no_license | longht95/hermanos_bistro | b0f6f3a77b507f30175392c35fd10a4468816547 | 793ae888e9ff614b4fbff19b82863b29aa6684ba | refs/heads/main | 2023-06-12T10:10:49.324108 | 2021-07-01T12:47:21 | 2021-07-01T12:47:21 | 376,249,823 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 212 | java | package hermanos.bistro.pizza;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PizzaApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
f2ae6524468483162e8c98397f98577e0b3a02ee | 66fb902eb15f595586594b58d853debf3035d1e7 | /musicplayer/src/main/java/ru/job4j/aop/logger/Logger.java | adcb476b66e4c9af39d83952a78ba53c9a884b29 | [] | no_license | Zhekbland/job4j_spring | 669a36c5c2554e80b89b51247c3a73f27bbe8d4b | fdf4b84632ca20c179fc798986148ac177f95e35 | refs/heads/master | 2022-12-22T14:05:00.720310 | 2019-11-17T20:50:13 | 2019-11-17T20:50:13 | 221,518,284 | 1 | 0 | null | 2022-12-16T05:08:56 | 2019-11-13T17:46:15 | Java | UTF-8 | Java | false | false | 466 | java | package ru.job4j.aop.logger;
import org.springframework.stereotype.Component;
/**
* Class Logger is an Aspect.
*
* @author Evgeny Shpytev (mailto:[email protected]).
* @version 1.
* @since 13.11.2019.
*/
@Component()
public class Logger {
public void printValue(Object obj) {
System.out.println(obj);
}
public void init() {
System.out.println("init");
}
public void close() {
System.out.println("close");
}
}
| [
"[email protected]"
] | |
1d4d87291473a1416fb929243d12b7d5406ed894 | 1c09cc4939b199ea204303daa502e34c8e70d0c0 | /Flipkart_Automation/src/main/java/com/support/ServiceType.java | 371836b813b6f3dc95276ec48e3e6e15a4fc89d5 | [] | no_license | nareshbabumandula/Flipkart | 213da33ee6e45288cbc4861d03d80f62265730e5 | 2b203d97365e96d3108a15395e6e971096988d34 | refs/heads/main | 2023-05-13T22:03:59.013215 | 2021-05-30T13:35:33 | 2021-05-30T13:35:33 | 344,669,583 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 83 | java | package com.support;
public enum ServiceType {
HIGH,
MEDIUM,
LOW
}
| [
"[email protected]"
] | |
6159936e11a31cffd7f16ce4c5cd9c85f7b2c9cf | 75950d61f2e7517f3fe4c32f0109b203d41466bf | /samples/tags/fabric3-samples-parent-pom-1.6/trunk/apps/bigbank/bigbank-loan/src/main/java/org/fabric3/samples/bigbank/credit/CreditBureau.java | c8e039fb1b344e3eaa8a0a8d45f3359c9d33041d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | codehaus/fabric3 | 3677d558dca066fb58845db5b0ad73d951acf880 | 491ff9ddaff6cb47cbb4452e4ddbf715314cd340 | refs/heads/master | 2023-07-20T00:34:33.992727 | 2012-10-31T16:32:19 | 2012-10-31T16:32:19 | 36,338,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,023 | java | /*
* Copyright (c) 2010 Metaform Systems
*
* See the NOTICE file distributed with this work for information
* regarding copyright ownership. This file is licensed
* 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.fabric3.samples.bigbank.credit;
/**
* @version $Rev$ $Date$
*/
public interface CreditBureau {
/**
* Performs the credit score.
*
* @param ein the applicant's employer identification number
* @return the credit score
*/
int score(String ein);
}
| [
"jmarino@83866bfc-822f-0410-aa35-bd5043b85eaf"
] | jmarino@83866bfc-822f-0410-aa35-bd5043b85eaf |
ac300f0fc07479bf6eb37af5f2aaf3619241bfee | 8e2f6073fc76c70d3f1fd0c3ea11c0cab21533f7 | /omniazero-integration/src/main/java/it/studiofontanelli/omniazero/integration/dao/AbiIstatRegioneDao.java | 93278c7bc24a1d01e24a6bd7d855522cade61bbf | [] | no_license | studiofontanelli/omniazero | bfa90d42c50749a070b70e5585c9615dfbcf3187 | 4293c210eccfe45581bfb37cc8f9d91175caaca8 | refs/heads/master | 2021-01-22T06:14:22.423735 | 2017-03-05T17:52:28 | 2017-03-05T17:52:28 | 81,748,927 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package it.studiofontanelli.omniazero.integration.dao;
import it.studiofontanelli.omniazero.integration.dto.AbiIstatRegione;
import it.studiofontanelli.omniazero.integration.input.DecodificaInput;
public interface AbiIstatRegioneDao extends CommonDao<AbiIstatRegione, DecodificaInput> {
}
| [
"[email protected]"
] | |
eeb0581a7d684ae6ec09325acbb855face7bd960 | 4fd38f6e4e6e6ee4aa59f03289104d7c619081ec | /BowlingGame/src/kata/game/test/GameTest.java | 782e25a8fcf7b17d5a7893009e075288ac16059b | [] | no_license | RayHo8224/TDD_Test | 462dc3e2e56df2b83420e037e03a2fac026f5917 | 5fa276288761881a7cf49714c753204450879681 | refs/heads/master | 2021-05-12T09:14:44.923355 | 2018-01-13T08:54:22 | 2018-01-13T08:54:22 | 117,311,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,929 | java | package kata.game.test;
import static org.junit.Assert.*;
import kata.game.*;
import org.junit.Before;
import org.junit.Test;
public class GameTest {
private Game game;
@Before
public void setUp() throws Exception {
game = new Game();
}
// 測試玩家投球共20次全洗溝 (gutter)時的總得分數
// 期望結果值:0
@Test
public void testGutterGame() {
int expected = 0;
int actual;
rollMany(20, 0);
actual = game.scores();
assertEquals(expected, actual);
}
// 測試玩家投球共20次,每次都只得一分時的總得分數
// 期望結果值:20
@Test
public void testAllOne() {
int expected = 20;
int actual;
rollMany(20, 1);
actual = game.scores();
assertEquals(expected, actual);
}
// 測試玩家整局只有一次補中+次一計分格投球的分數
// 共 20 次投球機會,其餘 17 次皆0分
@Test
public void testOneSpare() {
int expected = 26;
int actual;
rollSpare();
game.roll(8);
game.roll(0);
rollMany(16, 0);
actual = game.scores();
assertEquals(expected, actual);
}
// 測試玩家整局只有一次全中+次一計分格兩次投球的分數
// 共 19 次投球機會,其餘 16 次皆0分
@Test
public void testOneStrike() throws Exception {
int expected = 24;
int actual;
rollStrike();
game.roll(3);
game.roll(4);
rollMany(16,0);
actual=game.scores();
assertEquals(expected, actual);
}
// 測試玩家在所有全倒的12次投球的總得分數 (滿分300分)
@Test
public void testPerfectGame() throws Exception {
int expected = 300;
int actual;
rollMany(12,10);
actual = game.scores();
assertEquals(expected, actual);
}
private void rollMany(int roll, int bottle) {
for (int i = 0; i < roll; i++) {
game.roll(bottle);
}
}
private void rollSpare() {
game.roll(5);
game.roll(5);
}
private void rollStrike(){
game.roll(10);
}
}
| [
"ray@ray"
] | ray@ray |
e38f3f2180ef7307e5720531adb5b7dff1508a0c | d092457677dfefdb5d4bad0691475ef92fa109e7 | /桌面汇总/新建文件夹/src/org/omg/IOP/ServiceContextListHolder.java | aff2eb7f16780bbad2542079189cb61ad4ad24d5 | [] | no_license | 9127menglei/config-repo | 19b0c8472902e8d1abc5a024ff7b2282d0d9fe02 | 632173c84a868853a77fc346c54cf28b8bd1c576 | refs/heads/master | 2020-03-28T00:48:29.214252 | 2019-01-03T02:29:40 | 2019-01-03T02:29:40 | 147,451,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,053 | java | package org.omg.IOP;
/**
* org/omg/IOP/ServiceContextListHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-i586-cygwin/jdk8u161/10277/corba/src/share/classes/org/omg/PortableInterceptor/IOP.idl
* Tuesday, December 19, 2017 5:10:18 PM PST
*/
/** An array of service contexts, forming a service context list. */
public final class ServiceContextListHolder implements org.omg.CORBA.portable.Streamable
{
public org.omg.IOP.ServiceContext value[] = null;
public ServiceContextListHolder ()
{
}
public ServiceContextListHolder (org.omg.IOP.ServiceContext[] initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = org.omg.IOP.ServiceContextListHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
org.omg.IOP.ServiceContextListHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return org.omg.IOP.ServiceContextListHelper.type ();
}
}
| [
"[email protected]"
] | |
6b53182f8992c740dc7387d41ce4168f5cad53b5 | 87f05413601c67f3ec7a086c2d04f22abd257c6f | /java/commercials.java | 400353e60b9aec817dff1970748c2ebedda7ccf3 | [] | no_license | Sakshamgoel/Kattis-solutions | ed2c1c8fd53124bb6760cb1471b59ca95649c7e7 | 5f2163625737c3fce7c36a7519c132fde31289ad | refs/heads/master | 2023-06-25T14:47:03.298250 | 2021-07-06T17:54:02 | 2021-07-06T17:54:02 | 284,612,845 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 720 | java | import java.util.Scanner;
import java.util.Arrays;
public class commercials {
static int[] items;
static int students;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
students = in.nextInt();
int price = in.nextInt();
items = new int[students];
for(int i = 0; i < students; i++) {
items[i] = in.nextInt() - price;
}
System.out.println(dp());
}
//implements kadane's algorithm
public static int dp() {
int maxEndingHere = 0;
int maxSoFar = 0;
for(int i = 0; i < students; i++) {
maxEndingHere += items[i];
if(maxEndingHere > maxSoFar) maxSoFar = maxEndingHere;
if(maxEndingHere < 0) maxEndingHere = 0;
}
return maxSoFar;
}
} | [
"[email protected]"
] | |
3713a6f56edc2c50f99cf81b6c657892dc27ca8d | 777b9f269ef36f620f4b07c193a057a997f377e8 | /javase_prj/src/day1207/Work.java | b8e93b2fd98fc7fa2a1a48b35a90ed230cc293f3 | [] | no_license | JeongTeacksung/-source-file_1 | 084a01c8211b123d6af1683aab8a7d3590dccd18 | fd0ec5546c36ec83917fce8e3be90177202b31a0 | refs/heads/master | 2020-04-22T19:09:53.819666 | 2019-02-14T08:51:31 | 2019-02-14T08:51:31 | 170,599,747 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,342 | java | package day1207;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
* 숙제<br>
* main method의 arguments로 날짜를 여러개 입력받아
* 입력받은 날짜의 요일을 저장하고 출력하는 method를
* 작성<br>
* 예)java Test 4 12 30 32 35 15 4 <br>
* 출력)<br>
* 4화<br>
* 12수<br>
* 15토<br>
* 30일 <br>
* @author Owner
*/
public class Work {
// Integer[] tempArr = null;
public Work() {
}//Work
public void day() {
}//day
public void setDay(String arg) {
StringTokenizer st = new StringTokenizer(arg," ");
// for(int i=0; i<args.length; i++) {
//
// tempArr[i]=Integer.parseInt(args[i]);
// }//end for
Set<String> set=new HashSet<>();
String temp=" ";
while(st.hasMoreTokens()) {
temp = st.nextToken();
if(Integer.parseInt(temp)<31) {
set.add(temp);
}
}
// System.out.println(set);
Map<String,String> map=new HashMap<>();
Iterator<String> ita = set.iterator();
String[] yoil = {"일","월","화","수","목","금","토"};
// Iterator<Integer> ita=set.iterator();
Calendar c=Calendar.getInstance();
String day= " ";
String dayOfWeek =" ";
while(ita.hasNext()) {
// int day =ita.next();
day = ita.next();
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
dayOfWeek= yoil[c.get(Calendar.DAY_OF_WEEK)-1];
map.put(day, dayOfWeek);
}//end while
// System.out.println(map);
Set<String> keyStore = map.keySet();
// System.out.println(keyStore);
String[] key = new String[map.size()];
keyStore.toArray(key);
String temp1;
for(int i=0; i<key.length; i++) {
for(int j=0; j<key.length; j++) {
if(Integer.parseInt(key[i])<Integer.parseInt(key[j])) {
temp1=key[i];
key[i]=key[j];
key[j]=temp1;
}//end if
}//end for
}//end for
for(int i=0;i<key.length;i++) {
System.out.print(key[i]+map.get(key[i])+" ");
}//end for
// while(ita.hasNext()) {
// map.get(ita.next());
// }//end while
}//set Day
public static void main(String[] args) {
new Work().setDay("4 12 30 32 35 15 4");
}//main
}//class
| [
"[email protected]"
] | |
d03a57e31229c6a8c40b792c53853155e5ddf4b9 | 1a31284ba378952c2cc29da91ee773ff7a7ca51d | /app/src/main/java/com/bw/movie/adapter/Paiqi_Adapter.java | ec7a4d0a470f58a9f51af242047e5ba028ba2fe8 | [] | no_license | zhanganheng/move | 5fcb29a086dce82f6405e24d45eb5a36f1c1eccd | 25c874ce684f3ad212775a8c89e12ad71b172f78 | refs/heads/master | 2020-09-27T08:06:19.599414 | 2019-12-07T07:10:03 | 2019-12-07T07:10:03 | 226,470,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,411 | java | package com.bw.movie.adapter;
/*
*@auther:张安恒
*@Date: 2019/11/18
*@Time:19:37
*@Description:${DESCRIPTION}
**/
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bw.movie.R;
import com.bw.movie.activity.FindInfo_Activity;
import com.bw.movie.activity.XiangAActivity;
import com.bw.movie.bean.FindCinemaBean;
import com.bw.movie.bean.PaiqiBean;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.List;
public class Paiqi_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<PaiqiBean.ResultBean> result;
Context context;
public Paiqi_Adapter(List<PaiqiBean.ResultBean> result, Context context) {
this.result = result;
this.context = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View inflate = LayoutInflater.from(context).inflate(R.layout.find_cinema_layout, null);
return new MyViewHolder(inflate);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {
MyViewHolder myViewHolder= (MyViewHolder) viewHolder;
if (viewHolder instanceof MyViewHolder){
myViewHolder.find_name.setText(result.get(i).getName());
myViewHolder.find_daoname.setText("导演:"+result.get(i).getDirector());
String starring = result.get(i).getStarring();
myViewHolder.find_zhuname.setText("主演:"+starring);
double score = result.get(i).getScore();
myViewHolder.find_num.setText("评分:"+score+"分");
myViewHolder.find_src.setImageURI(result.get(i).getImageUrl());
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(context, FindInfo_Activity.class);
int movieId = result.get(i).getMovieId();
String name = result.get(i).getName();
intent.putExtra("movidID",movieId);
intent.putExtra("moviedname",name);
Log.i("aaamovieId", "onClick: "+movieId);
context.startActivity(intent);
}
});
}
}
@Override
public int getItemCount() {
return result.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private final SimpleDraweeView find_src;
private final TextView find_name,find_daoname,find_zhuname,find_num;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
find_src = itemView.findViewById(R.id.find_src);
find_name = itemView.findViewById(R.id.find_name);
find_daoname = itemView.findViewById(R.id.find_daoname);
find_zhuname = itemView.findViewById(R.id.find_zhuname);
find_num = itemView.findViewById(R.id.find_num);
}
}
}
| [
"[email protected]"
] | |
54fe763bf45040016093fc85aa656f27fa3ecc91 | 08ec02ba2f8ea55b22114b3c000aaabde3440daa | /src/tests/LivreTest.java | 2181a9db35db50760ce4285fd610db83525e79ae | [] | no_license | Piersees/QualiteLogicielProject | 60d76b82afab38bc385f4be8481970dc33c00841 | 2595b0144f2f95cc3bef283c0d56211d976ee263 | refs/heads/master | 2021-05-15T15:29:26.842749 | 2017-10-18T09:26:31 | 2017-10-18T09:26:31 | 107,385,227 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 913 | java | package tests;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import mediatheque.OperationImpossible;
import mediatheque.document.Livre;
import util.InvariantBroken;
public class LivreTest {
Livre livreemprunteempruntable, livrenonemprunteempruntable, livrenonemprunnonempruntab, livreempruntenonempruntable;
@Test
public void emprunterTest1() throws InvariantBroken, OperationImpossible {
assertTrue(livrenonemprunteempruntable.emprunter());
}
@Test(expected = OperationImpossible.class)
public void emprunterTest2() throws InvariantBroken, OperationImpossible {
livreempruntenonempruntable.emprunter();
}
@Test(expected = OperationImpossible.class)
public void emprunterTest3() throws InvariantBroken, OperationImpossible {
livreemprunteempruntable.emprunter();
}
}
| [
"[email protected]"
] | |
c2a4738695ff3348f5aba22f3e27977d418cc235 | 0ed2a57aff973b8ebde83ff32ca55a979b2839c1 | /libjaqr/src/main/java/net/jambel/jaqr/Intents.java | 162067a58f9b803621beaf8b0caae0f4a486fac3 | [] | no_license | jambelnet/jaQR | 8d6fc7def89e21b03cb0abd6fdb624bd3939dc68 | 118db47223c724387c295163518cdb6c42df92f3 | refs/heads/master | 2020-12-24T21:12:08.303058 | 2016-04-20T13:44:28 | 2016-04-20T13:44:28 | 56,678,284 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,543 | java | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.jambel.jaqr;
/**
* This class provides the constants to use when sending an Intent to Barcode Scanner.
* These strings are effectively API and cannot be changed.
*
* @author [email protected] (Daniel Switkin)
*/
public final class Intents {
private Intents() {
}
public static final class Scan {
/**
* Send this intent to open the Barcodes app in scanning mode, find a barcode, and return
* the results.
*/
public static final String ACTION = "net.jambel.jaqr.SCAN";
/**
* By default, sending this will decode all barcodes that we understand. However it
* may be useful to limit scanning to certain formats. Use
* {@link android.content.Intent#putExtra(String, String)} with one of the values below.
*
* Setting this is effectively shorthand for setting explicit formats with {@link #FORMATS}.
* It is overridden by that setting.
*/
public static final String MODE = "SCAN_MODE";
/**
* Decode only UPC and EAN barcodes. This is the right choice for shopping apps which get
* prices, reviews, etc. for products.
*/
public static final String PRODUCT_MODE = "PRODUCT_MODE";
/**
* Decode only 1D barcodes.
*/
public static final String ONE_D_MODE = "ONE_D_MODE";
/**
* Decode only QR codes.
*/
public static final String QR_CODE_MODE = "QR_CODE_MODE";
/**
* Decode only Data Matrix codes.
*/
public static final String DATA_MATRIX_MODE = "DATA_MATRIX_MODE";
/**
* Comma-separated list of formats to scan for. The values must match the names of
* {@link com.google.zxing.BarcodeFormat}s, e.g. {@link com.google.zxing.BarcodeFormat#EAN_13}.
* Example: "EAN_13,EAN_8,QR_CODE". This overrides {@link #MODE}.
*/
public static final String FORMATS = "SCAN_FORMATS";
/**
* @see com.google.zxing.DecodeHintType#CHARACTER_SET
*/
public static final String CHARACTER_SET = "CHARACTER_SET";
/**
* Optional parameters to specify the width and height of the scanning rectangle in pixels.
* The app will try to honor these, but will clamp them to the size of the preview frame.
* You should specify both or neither, and pass the size as an int.
*/
public static final String WIDTH = "SCAN_WIDTH";
public static final String HEIGHT = "SCAN_HEIGHT";
/**
* Desired duration in milliseconds for which to pause after a successful scan before
* returning to the calling intent. Specified as a long, not an integer!
* For example: 1000L, not 1000.
*/
public static final String RESULT_DISPLAY_DURATION_MS = "RESULT_DISPLAY_DURATION_MS";
/**
* Prompt to show on-screen when scanning by intent. Specified as a {@link String}.
*/
public static final String PROMPT_MESSAGE = "PROMPT_MESSAGE";
/**
* If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to
* {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}
* of the app which requested the scan via
* {@link android.app.Activity#startActivityForResult(android.content.Intent, int)}
* The barcodes contents can be retrieved with
* {@link android.content.Intent#getStringExtra(String)}.
* If the user presses Back, the result code will be {@link android.app.Activity#RESULT_CANCELED}.
*/
public static final String RESULT = "SCAN_RESULT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_FORMAT}
* to determine which barcode format was found.
* See {@link com.google.zxing.BarcodeFormat} for possible values.
*/
public static final String RESULT_FORMAT = "SCAN_RESULT_FORMAT";
/**
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_UPC_EAN_EXTENSION}
* to return the content of any UPC extension barcode that was also found. Only applicable
* to {@link com.google.zxing.BarcodeFormat#UPC_A} and {@link com.google.zxing.BarcodeFormat#EAN_13}
* formats.
*/
public static final String RESULT_UPC_EAN_EXTENSION = "SCAN_RESULT_UPC_EAN_EXTENSION";
/**
* Call {@link android.content.Intent#getByteArrayExtra(String)} with {@link #RESULT_BYTES}
* to get a {@code byte[]} of raw bytes in the barcode, if available.
*/
public static final String RESULT_BYTES = "SCAN_RESULT_BYTES";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ORIENTATION}, if available.
* Call {@link android.content.Intent#getIntArrayExtra(String)} with {@link #RESULT_ORIENTATION}.
*/
public static final String RESULT_ORIENTATION = "SCAN_RESULT_ORIENTATION";
/**
* Key for the value of {@link com.google.zxing.ResultMetadataType#ERROR_CORRECTION_LEVEL}, if available.
* Call {@link android.content.Intent#getStringExtra(String)} with {@link #RESULT_ERROR_CORRECTION_LEVEL}.
*/
public static final String RESULT_ERROR_CORRECTION_LEVEL = "SCAN_RESULT_ERROR_CORRECTION_LEVEL";
/**
* Prefix for keys that map to the values of {@link com.google.zxing.ResultMetadataType#BYTE_SEGMENTS},
* if available. The actual values will be set under a series of keys formed by adding 0, 1, 2, ...
* to this prefix. So the first byte segment is under key "SCAN_RESULT_BYTE_SEGMENTS_0" for example.
* Call {@link android.content.Intent#getByteArrayExtra(String)} with these keys.
*/
public static final String RESULT_BYTE_SEGMENTS_PREFIX = "SCAN_RESULT_BYTE_SEGMENTS_";
/**
* Setting this to false will not save scanned codes in the history. Specified as a {@code boolean}.
*/
public static final String SAVE_HISTORY = "SAVE_HISTORY";
private Scan() {
}
}
public static final class History {
public static final String ITEM_NUMBER = "ITEM_NUMBER";
private History() {
}
}
public static final class Encode {
/**
* Send this intent to encode a piece of data as a QR code and display it full screen, so
* that another person can scan the barcode from your screen.
*/
public static final String ACTION = "net.jambel.jaqr.ENCODE";
/**
* The data to encode. Use {@link android.content.Intent#putExtra(String, String)} or
* {@link android.content.Intent#putExtra(String, android.os.Bundle)},
* depending on the type and format specified. Non-QR Code formats should
* just use a String here. For QR Code, see Contents for details.
*/
public static final String DATA = "ENCODE_DATA";
/**
* The type of data being supplied if the format is QR Code. Use
* {@link android.content.Intent#putExtra(String, String)} with one of {@link Contents.Type}.
*/
public static final String TYPE = "ENCODE_TYPE";
/**
* The barcode format to be displayed. If this isn't specified or is blank,
* it defaults to QR Code. Use {@link android.content.Intent#putExtra(String, String)}, where
* format is one of {@link com.google.zxing.BarcodeFormat}.
*/
public static final String FORMAT = "ENCODE_FORMAT";
/**
* Normally the contents of the barcode are displayed to the user in a TextView. Setting this
* boolean to false will hide that TextView, showing only the encode barcode.
*/
public static final String SHOW_CONTENTS = "ENCODE_SHOW_CONTENTS";
private Encode() {
}
}
public static final class SearchBookContents {
/**
* Use Google Book Search to search the contents of the book provided.
*/
public static final String ACTION = "net.jambel.jaqr.SEARCH_BOOK_CONTENTS";
/**
* The book to search, identified by ISBN number.
*/
public static final String ISBN = "ISBN";
/**
* An optional field which is the text to search for.
*/
public static final String QUERY = "QUERY";
private SearchBookContents() {
}
}
public static final class WifiConnect {
/**
* Internal intent used to trigger connection to a wi-fi network.
*/
public static final String ACTION = "net.jambel.jaqr.WIFI_CONNECT";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String SSID = "SSID";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String TYPE = "TYPE";
/**
* The network to connect to, all the configuration provided here.
*/
public static final String PASSWORD = "PASSWORD";
private WifiConnect() {
}
}
public static final class Share {
/**
* Give the user a choice of items to encode as a barcode, then render it as a QR Code and
* display onscreen for a friend to scan with their phone.
*/
public static final String ACTION = "net.jambel.jaqr.SHARE";
private Share() {
}
}
}
| [
"[email protected]"
] | |
a8576d3b340453a19993844d812927d5a5cdaebf | 3cd63aba77b753d85414b29279a77c0bc251cea9 | /main/plugins/org.talend.repository/src/main/java/org/talend/repository/preference/audit/SupportDBVersions.java | b18e5fc8208b66335e67fc217b830d7fa276e220 | [
"Apache-2.0"
] | permissive | 195858/tdi-studio-se | 249bcebb9700c6bbc8905ccef73032942827390d | 4fdb5cfb3aeee621eacfaef17882d92d65db42c3 | refs/heads/master | 2021-04-06T08:56:14.666143 | 2018-10-01T14:11:28 | 2018-10-01T14:11:28 | 124,540,962 | 1 | 0 | null | 2018-10-01T14:11:29 | 2018-03-09T12:59:25 | Java | UTF-8 | Java | false | false | 5,291 | java | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.repository.preference.audit;
import java.util.ArrayList;
import java.util.List;
/**
*
* created by hcyi on Jun 20, 2018 Detailled comment
*
*/
public enum SupportDBVersions {
H2_LOCAL(SupportDBUrlType.H2LOCALDEFAULTURL, "H2 Local", "H2_Local"), //$NON-NLS-1$ //$NON-NLS-2$
H2_REMOTE(SupportDBUrlType.H2REMOTEDEFAULTURL, "H2 Remote", "H2_Remote"), //$NON-NLS-1$ //$NON-NLS-2$
JTDS(SupportDBUrlType.MSSQLDEFAULTURL, "Open source JTDS", "JTDS"), //$NON-NLS-1$ //$NON-NLS-2$
MSSQL_PROP(SupportDBUrlType.MSSQLDEFAULTURL, "Microsoft", "MSSQL_PROP"), //$NON-NLS-1$ //$NON-NLS-2$
MARIADB(SupportDBUrlType.MARIADBDEFAULTURL, "MariaDB", "MARIADB"), //$NON-NLS-1$ //$NON-NLS-2$
MYSQL_8(SupportDBUrlType.MYSQLDEFAULTURL, "MySQL 8", "MYSQL_8"), //$NON-NLS-1$ //$NON-NLS-2$
MYSQL_5(SupportDBUrlType.MYSQLDEFAULTURL, "MySQL 5", "MYSQL_5"), //$NON-NLS-1$ //$NON-NLS-2$
MYSQL_4(SupportDBUrlType.MYSQLDEFAULTURL, "MySQL 4", "MYSQL_4"), //$NON-NLS-1$ //$NON-NLS-2$
ORACLE_12(SupportDBUrlType.ORACLEDEFAULTURL, "Oracle 12", "ORACLE_12"), //$NON-NLS-1$ //$NON-NLS-2$
ORACLE_11(SupportDBUrlType.ORACLEDEFAULTURL, "Oracle 11", "ORACLE_11"), //$NON-NLS-1$ //$NON-NLS-2$
ORACLE_10(SupportDBUrlType.ORACLEDEFAULTURL, "Oracle 10", "ORACLE_10"), //$NON-NLS-1$ //$NON-NLS-2$
ORACLE_9(SupportDBUrlType.ORACLEDEFAULTURL, "Oracle 9", "ORACLE_9"), //$NON-NLS-1$ //$NON-NLS-2$
ORACLE_8(SupportDBUrlType.ORACLEDEFAULTURL, "Oracle 8", "ORACLE_8"), //$NON-NLS-1$ //$NON-NLS-2$
PSQL_V9_X(SupportDBUrlType.POSTGRESQLEFAULTURL, "v9 and later", "V9_X"),
PSQL_PRIOR_TO_V9(SupportDBUrlType.POSTGRESQLEFAULTURL, "Prior to v9", "PRIOR_TO_V9"); //$NON-NLS-1$ //$NON-NLS-2$
//$NON-NLS-1$ //$NON-NLS-2$
private String versionDisplayName;
private String versionValue;
private SupportDBUrlType type;
SupportDBVersions(SupportDBUrlType type, String versionDisplayName, String versionValue) {
this.setType(type);
this.setVersionDisplayName(versionDisplayName);
this.setVersionValue(versionValue);
}
/**
* Getter for versionDisplayName.
*
* @return the versionDisplayName
*/
public String getVersionDisplayName() {
return versionDisplayName;
}
/**
* Sets the versionDisplayName.
*
* @param versionDisplayName the versionDisplayName to set
*/
public void setVersionDisplayName(String versionDisplayName) {
this.versionDisplayName = versionDisplayName;
}
/**
* Getter for versionValue.
*
* @return the versionValue
*/
public String getVersionValue() {
return versionValue;
}
/**
* Sets the versionValue.
*
* @param versionValue the versionValue to set
*/
public void setVersionValue(String versionValue) {
this.versionValue = versionValue;
}
/**
* Getter for type.
*
* @return the type
*/
public SupportDBUrlType getType() {
return type;
}
/**
* Sets the type.
*
* @param type the type to set
*/
public void setType(SupportDBUrlType type) {
this.type = type;
}
public static String getDisplayedVersion(SupportDBUrlType type, String versionValue) {
for (SupportDBVersions version : values()) {
if (version.getType().equals(type)) {
if (versionValue == null || "".equals(versionValue) //$NON-NLS-1$
|| versionValue.equals(version.getVersionValue())) {
return version.getVersionDisplayName();
}
}
}
return null;
}
public static String getVersionValue(SupportDBUrlType type, String versionDisplayName) {
for (SupportDBVersions version : values()) {
if (version.getType().equals(type)) {
if (versionDisplayName == null || "".equals(versionDisplayName) //$NON-NLS-1$
|| versionDisplayName.equals(version.getVersionDisplayName())) {
return version.getVersionValue();
}
}
}
return null;
}
public static String[] getDisplayedVersions(SupportDBUrlType type) {
List<String> versions = new ArrayList<String>();
for (SupportDBVersions version : values()) {
if (version.getType().equals(type)) {
versions.add(version.getVersionDisplayName());
}
}
return versions.toArray(new String[0]);
}
public static String[] getDisplayedVersions(String dbType) {
SupportDBUrlType urlType = SupportDBUrlStore.getInstance().getDBUrlType(dbType);
return getDisplayedVersions(urlType);
}
}
| [
"[email protected]"
] | |
f431c31cfd9b89d474179335ca88ffe55c78ac6b | a2bc06049969011354b1cdb96e6947631f0f9d1f | /core/src/main/java/org/uzlocoinj/jni/NativeWalletReorganizeEventListener.java | defe813e4dc248576335dd711cb4f840a0f00ae6 | [
"Apache-2.0"
] | permissive | uzlocoin/Uzlocoinj | 27f7093f615d83f93fcd19598c1d8c1f6b012a5b | 15efb1819ced28154926c7c36d13ec765b9911ec | refs/heads/master | 2023-05-09T09:38:05.328491 | 2021-06-03T10:26:35 | 2021-06-03T10:26:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,153 | java | /*
* Copyright 2013 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 org.uzlocoinj.jni;
import org.uzlocoinj.wallet.Wallet;
import org.uzlocoinj.wallet.listeners.WalletReorganizeEventListener;
/**
* An event listener that relays events to a native C++ object. A pointer to that object is stored in
* this class using JNI on the native side, thus several instances of this can point to different actual
* native implementations.
*/
public class NativeWalletReorganizeEventListener implements WalletReorganizeEventListener {
public long ptr;
@Override
public native void onReorganize(Wallet wallet);
}
| [
"[email protected]"
] | |
f26a43345d86066d0de21130ea9de6d946e26250 | 952b1f618dcc19f06f4c79544be91eabe2d15a3f | /src/main/java/com/denglu/entity/User.java | 2a2974f18ab3b519491b5ed7aa55bba0432c49f0 | [] | no_license | BIM-App/BIM-backend | d451492402828ff2d82fe3179d2804d5358b69a2 | 0f063eff1ac8e3054516457b2308e3573f6c72de | refs/heads/master | 2023-05-03T20:00:04.021577 | 2021-05-25T14:16:20 | 2021-05-25T14:16:20 | 297,077,340 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 246 | java | package com.denglu.entity;
public class User {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
| [
"[email protected]"
] | |
d85405f5ea9ba5d2e57d2d90aba76954a207a50b | f054905334dfd8a3f2ee283cfc505cc6c298b1ad | /Botsautos.java | c9fe327655700d7564bf23e70cc179883779ce5a | [] | no_license | Jonathan133/Kermis-tweede-doelstelling | 5924eb17f4b0dc054ac3875afc96bff54bc75069 | 5485ecf8301a86973a663d4cab67c907bf960999 | refs/heads/master | 2020-03-27T21:08:21.288747 | 2018-09-02T20:11:43 | 2018-09-02T20:11:43 | 147,117,808 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 363 | java |
public class Botsautos extends Attractie {
String naam = "Botsautos";
double prijs = 2.50;
double omzet = 0;
int verkochteKaartjes;
double oppervlakte;
void draaien () {
System.out.println("De attractie "+naam+" draait en heeft "+ ++verkochteKaartjes + " kaartjes verkocht" + " en een omzet gedraait van "+(omzet = verkochteKaartjes * prijs));
}
}
| [
"[email protected]"
] | |
5aae6f2a346454ffba10fa2e0bea82dcdab1e1c6 | 875abd4ba81841501dc64a8e3fdd844f7eebaf36 | /src/boundedgenerics/services/CalculationService.java | dd45c863336ebebe80f7360dc3469a722e9c1b3b | [] | no_license | robsonVargas/generics-set-map-devsuperior | cc42806248844b1a538b799dc5f65a7a8f17d0ec | 534d94235dae03165379e0662915be8368ad138a | refs/heads/main | 2023-08-28T03:56:37.922294 | 2021-10-28T23:44:34 | 2021-10-28T23:44:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 368 | java | package boundedgenerics.services;
import java.util.List;
public class CalculationService {
public static <T extends Comparable<T>> T max(List<T> list) {
if (list.isEmpty()) {
throw new IllegalStateException("List can't be empty");
}
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) {
max = item;
}
}
return max;
}
} | [
"[email protected]"
] | |
7223bb5a0b1b9b95ec6d9e6c5d2c2ad3b0c83fe2 | 9379f814ee57f03add28f7c9822ebb06078d3e78 | /src/main/java/com/java/features/MySinglton.java | 486bfe7738c7d431d215d3ea89006eedf95464b7 | [] | no_license | shankargundrelead/Sample | 305d537560093ee018397254a70392b779000185 | b31f40804d8688bb4e7aa0cfb564623cf68a831c | refs/heads/master | 2023-07-04T13:48:09.539907 | 2021-08-09T12:18:10 | 2021-08-09T12:18:10 | 394,272,383 | 0 | 0 | null | 2021-08-09T12:18:11 | 2021-08-09T11:54:43 | Java | UTF-8 | Java | false | false | 290 | java | package com.java.features;
public class MySinglton {
private static MySinglton singleton= null;
private MySinglton() {
}
public static MySinglton getSinglton() {
if(singleton ==null) {
singleton = new MySinglton();
}
return singleton;
}
}
| [
"Admin@DESKTOP-T53CDNQ"
] | Admin@DESKTOP-T53CDNQ |
a9b56cee41b4de4ca603d56f3938e197a1f79a25 | c53650d84544b4e59fa270beeb150851c98a6038 | /src/test/java/com/fastcampus/javaallinone/project3/mycontact/repository/PersonRepositoryTest.java | 6b08e1e3c4f7d7dbebd1195dbdc74b11cfaa2b0a | [] | no_license | jet2303/mycontact | 455928f922a9a0cf127eb9a413218019e1f65520 | 9d74d510b6b40a91d4efd427a5f8b04ad1c93e14 | refs/heads/master | 2023-04-10T02:03:48.684638 | 2021-04-25T14:51:24 | 2021-04-25T14:51:24 | 358,588,044 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,352 | java | package com.fastcampus.javaallinone.project3.mycontact.repository;
import com.fastcampus.javaallinone.project3.mycontact.domain.Person;
import com.fastcampus.javaallinone.project3.mycontact.domain.dto.Birthday;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
import javax.transaction.Transactional;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Transactional
@SpringBootTest
class PersonRepositoryTest {
@Autowired
private PersonRepository personRepository;
@Test
void findByName(){
List<Person> people = personRepository.findByName("tony");
Assertions.assertEquals(people.size(),1);
Person person = people.get(0);
Assertions.assertAll(
()-> Assertions.assertEquals(person.getName(), "tony"),
()-> Assertions.assertEquals(person.getHobby(), "reading"),
()->Assertions.assertEquals(person.getAddress(), "서울"),
()->Assertions.assertEquals(person.getBirthday(), Birthday.of(LocalDate.of(1991,7,10))),
()->Assertions.assertEquals(person.getJob(), "officer"),
()->Assertions.assertEquals(person.getPhoneNumber(), "010-2222-5555"),
()->Assertions.assertEquals(person.isDeleted(), false)
);
}
@Test
void findByNameIfDeleted(){
List<Person> people = personRepository.findByName("andrew");
Assertions.assertEquals(people.size(), 0);
}
@Test
void findByMonthOfBirthday(){
List<Person> people = personRepository.findByMonthOfBirthday(7);
Assertions.assertEquals(people.size(), 2);
Assertions.assertAll(
()-> Assertions.assertEquals(people.get(0).getName(), "david"),
()-> Assertions.assertEquals(people.get(1).getName(), "tony")
);
}
@Test
void findPeopleDeleted(){
List<Person> people = personRepository.findPeopleDeleted();
Assertions.assertEquals(people.size(), 1); //List를 반환할경우 size 체크는 필수.
Assertions.assertEquals(people.get(0).getName(), "andrew");
}
} | [
"[email protected]"
] | |
36511b31a012bb053591a995fa6e27c3f91e49da | 3ef55e152decb43bdd90e3de821ffea1a2ec8f75 | /large/module1050_public/tests/more/src/java/module1050_public_tests_more/a/IFoo3.java | aec3179bd94752a9808f8a5e71955c75eee56df1 | [
"BSD-3-Clause"
] | permissive | salesforce/bazel-ls-demo-project | 5cc6ef749d65d6626080f3a94239b6a509ef145a | 948ed278f87338edd7e40af68b8690ae4f73ebf0 | refs/heads/master | 2023-06-24T08:06:06.084651 | 2023-03-14T11:54:29 | 2023-03-14T11:54:29 | 241,489,944 | 0 | 5 | BSD-3-Clause | 2023-03-27T11:28:14 | 2020-02-18T23:30:47 | Java | UTF-8 | Java | false | false | 866 | java | package module1050_public_tests_more.a;
import javax.rmi.ssl.*;
import java.awt.datatransfer.*;
import java.beans.beancontext.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see javax.net.ssl.ExtendedSSLSession
* @see javax.rmi.ssl.SslRMIClientSocketFactory
* @see java.awt.datatransfer.DataFlavor
*/
@SuppressWarnings("all")
public interface IFoo3<B> extends module1050_public_tests_more.a.IFoo2<B> {
java.beans.beancontext.BeanContext f0 = null;
java.io.File f1 = null;
java.rmi.Remote f2 = null;
String getName();
void setName(String s);
B get();
void set(B e);
}
| [
"[email protected]"
] | |
fefd6afc51f7468e92a6077293d28d246e25a40e | 2fbd9b01fe38b213da451bfa52919a07abe08dd3 | /gmall-oms/src/main/java/com/atguigu/gmall/oms/controller/OrderOperateHistoryController.java | 31e5205909f4724431307de72a21321252891965 | [
"Apache-2.0"
] | permissive | wsmGo/gmall | dbc67bd7fc4cfb802e1514879b4414382dec5ba0 | e13a1377c091a947a6294f8cd3346903bf01ddaa | refs/heads/master | 2022-12-21T14:40:03.025186 | 2019-12-20T02:10:58 | 2019-12-20T02:10:58 | 225,277,926 | 0 | 0 | Apache-2.0 | 2019-12-02T03:54:17 | 2019-12-02T03:32:51 | JavaScript | UTF-8 | Java | false | false | 2,657 | java | package com.atguigu.gmall.oms.controller;
import java.util.Arrays;
import java.util.Map;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.core.bean.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.atguigu.gmall.oms.entity.OrderOperateHistoryEntity;
import com.atguigu.gmall.oms.service.OrderOperateHistoryService;
/**
* 订单操作历史记录
*
* @author 530
* @email [email protected]
* @date 2019-12-02 19:10:03
*/
@Api(tags = "订单操作历史记录 管理")
@RestController
@RequestMapping("oms/orderoperatehistory")
public class OrderOperateHistoryController {
@Autowired
private OrderOperateHistoryService orderOperateHistoryService;
/**
* 列表
*/
@ApiOperation("分页查询(排序)")
@GetMapping("/list")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:list')")
public Resp<PageVo> list(QueryCondition queryCondition) {
PageVo page = orderOperateHistoryService.queryPage(queryCondition);
return Resp.ok(page);
}
/**
* 信息
*/
@ApiOperation("详情查询")
@GetMapping("/info/{id}")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:info')")
public Resp<OrderOperateHistoryEntity> info(@PathVariable("id") Long id){
OrderOperateHistoryEntity orderOperateHistory = orderOperateHistoryService.getById(id);
return Resp.ok(orderOperateHistory);
}
/**
* 保存
*/
@ApiOperation("保存")
@PostMapping("/save")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:save')")
public Resp<Object> save(@RequestBody OrderOperateHistoryEntity orderOperateHistory){
orderOperateHistoryService.save(orderOperateHistory);
return Resp.ok(null);
}
/**
* 修改
*/
@ApiOperation("修改")
@PostMapping("/update")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:update')")
public Resp<Object> update(@RequestBody OrderOperateHistoryEntity orderOperateHistory){
orderOperateHistoryService.updateById(orderOperateHistory);
return Resp.ok(null);
}
/**
* 删除
*/
@ApiOperation("删除")
@PostMapping("/delete")
@PreAuthorize("hasAuthority('oms:orderoperatehistory:delete')")
public Resp<Object> delete(@RequestBody Long[] ids){
orderOperateHistoryService.removeByIds(Arrays.asList(ids));
return Resp.ok(null);
}
}
| [
"[email protected]"
] | |
edbae90dc7ad8f090571248f88406b7c0ccde0c2 | ad9abcccdff66f681339cca68f737862e5ea7730 | /src/test/bot/TestJoueur2.java | f8c3a83713eabbb8baf7a157657bc01b8ea696cf | [] | no_license | DeptInfoProjects/DFe | 0930beb0a1b2ec048a3808988ea3cdc3201ffbe1 | 09a592086ef783745a27a0e96379acd5540d26c5 | refs/heads/master | 2021-10-08T20:15:49.624284 | 2018-12-17T10:24:23 | 2018-12-17T10:24:23 | 153,093,330 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,423 | java |
package bot;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.evosuite.runtime.sandbox.Sandbox;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
@EvoSuiteClassExclude
public class TestJoueur2 {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "bot.Joueur";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
private static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/var/folders/66/43ls8qhd40zgxd4nt9mwyhg40000gr/T/");
java.lang.System.setProperty("user.country", "FR");
java.lang.System.setProperty("user.dir", "/Users/hide/Desktop/DFe034");
java.lang.System.setProperty("user.home", "/Users/hide");
java.lang.System.setProperty("user.language", "fr");
java.lang.System.setProperty("user.name", "hide");
java.lang.System.setProperty("user.timezone", "Europe/Paris");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(TestJoueur2.class.getClassLoader() ,
"de.De",
"iles.Sanctuaire",
"partie.Tours",
"iles.TypeEffet",
"bot.Joueur",
"bot.Inventaire",
"de.Type$2",
"de.Type$1",
"de.Type$3",
"bot.Choix",
"iles.Carte",
"de.Face",
"iles.Exploit",
"de.Ressource",
"de.Type",
"iles.Prix"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(TestJoueur2.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"bot.Joueur",
"de.De",
"de.Face",
"de.Type",
"de.Ressource",
"bot.Inventaire",
"partie.Tours",
"iles.TypeEffet",
"iles.Exploit",
"iles.Prix",
"iles.Carte",
"bot.Choix",
"iles.Sanctuaire"
);
}
}
| [
"[email protected]"
] | |
89e0934e75c41a2d3bf5de97ebf275526dbfc2cc | f9c0d83d99d04f755300a36f96bf38aa111f50d2 | /283.java | ac9e7d8a575a4eea50a3372e3736a7a978c780fe | [] | no_license | esperanzazwj/Leetcode | 82b78949d139b0358f51e81a2641763f72482a9e | 6fde500f7c012d3aadd92c1085e3c6dee91edacc | refs/heads/master | 2020-03-12T09:24:39.832055 | 2018-05-10T12:54:00 | 2018-05-10T12:54:00 | 130,371,582 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 259 | java | class Solution {
public void moveZeroes(int[] nums) {
int cnt=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0)
nums[cnt++]=nums[i];
}
for(;cnt<nums.length;cnt++)
nums[cnt]=0;
}
} | [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.