hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0fd5dbc39f2329c9f923ae4f8812f8ebdf1d7a
2,111
java
Java
src/test/java/org/orthodox/universel/exec/operators/unary/DecimalBigDecimalUnaryMinusTest.java
lamerexter/universel
aa48cfd1020df5110d6bed4b6aa18eab00eb32d6
[ "MIT" ]
1
2021-04-17T13:17:11.000Z
2021-04-17T13:17:11.000Z
src/test/java/org/orthodox/universel/exec/operators/unary/DecimalBigDecimalUnaryMinusTest.java
lamerexter/universel
aa48cfd1020df5110d6bed4b6aa18eab00eb32d6
[ "MIT" ]
null
null
null
src/test/java/org/orthodox/universel/exec/operators/unary/DecimalBigDecimalUnaryMinusTest.java
lamerexter/universel
aa48cfd1020df5110d6bed4b6aa18eab00eb32d6
[ "MIT" ]
null
null
null
58.638889
179
0.716248
6,729
package org.orthodox.universel.exec.operators.unary; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.orthodox.universel.Universal.execute; import static org.orthodox.universel.exec.operators.binary.impl.numeric.NumericOperatorDefaults.BIG_DECIMAL_PRECISION_DP; import static org.orthodox.universel.exec.operators.binary.impl.numeric.NumericOperatorDefaults.BIG_DECIMAL_ROUNDING_MODE; public class DecimalBigDecimalUnaryMinusTest { @Test public void literal_operand() { assertThat(execute("-0D"), equalTo(BigDecimal.valueOf(0).negate())); assertThat(execute("-1.5D"), equalTo(BigDecimal.valueOf(1.5).negate())); assertThat(execute("-10.2D"), equalTo(BigDecimal.valueOf(10.2).negate())); } @Test public void expression_operand() { assertThat(execute("-100D * 0D"), equalTo(new BigDecimal("-100").multiply(new BigDecimal("0")))); assertThat(execute("-100D * 1D"), equalTo(new BigDecimal("-100").multiply(new BigDecimal("1")))); assertThat(execute("-100D - 10D"), equalTo(new BigDecimal("-100").subtract(new BigDecimal("10")))); assertThat(execute("-100D + 10D"), equalTo(new BigDecimal("-100").add(new BigDecimal("10")))); assertThat(execute("-100D / 10D"), equalTo(new BigDecimal("-100").divide(new BigDecimal("10"), BIG_DECIMAL_PRECISION_DP, BIG_DECIMAL_ROUNDING_MODE))); assertThat(execute("-100D + -10D"), equalTo(new BigDecimal("-100").add(new BigDecimal("-10")))); assertThat(execute("-100D / -10D"), equalTo(new BigDecimal("-100").divide(new BigDecimal("-10"), BIG_DECIMAL_PRECISION_DP, BIG_DECIMAL_ROUNDING_MODE))); assertThat(execute("-100D / 20D"), equalTo(new BigDecimal("-100").divide(new BigDecimal("20"), BIG_DECIMAL_PRECISION_DP, BIG_DECIMAL_ROUNDING_MODE))); assertThat(execute("-2D * (-2D - -1D) * 10D"), equalTo(new BigDecimal("-2").multiply(new BigDecimal("-2").subtract(new BigDecimal("-1"))).multiply(new BigDecimal("10")))); } }
3e0fd61126f9d7fff9a9ec49dd99d02d7d7db2fc
5,218
java
Java
lifetime-ejb/src/main/java/lifetime/backend/persistence/jooq/tables/records/ProjectRecord.java
zuacaldeira/lifetime
c7082fc556cdc4f95ea62af0f473d3a4b9cc4a80
[ "Apache-2.0", "Unlicense" ]
null
null
null
lifetime-ejb/src/main/java/lifetime/backend/persistence/jooq/tables/records/ProjectRecord.java
zuacaldeira/lifetime
c7082fc556cdc4f95ea62af0f473d3a4b9cc4a80
[ "Apache-2.0", "Unlicense" ]
1
2015-07-16T09:46:19.000Z
2015-07-16T09:51:14.000Z
lifetime-ejb/src/main/java/lifetime/backend/persistence/jooq/tables/records/ProjectRecord.java
zuacaldeira/lifetime
c7082fc556cdc4f95ea62af0f473d3a4b9cc4a80
[ "Apache-2.0", "Unlicense" ]
null
null
null
20.382813
124
0.499617
6,730
/** * This class is generated by jOOQ */ package lifetime.backend.persistence.jooq.tables.records; import javax.annotation.Generated; import lifetime.backend.persistence.jooq.tables.Project; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record4; import org.jooq.Row4; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.1" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ProjectRecord extends UpdatableRecordImpl<ProjectRecord> implements Record4<Integer, String, String, Integer> { private static final long serialVersionUID = 1742684023; /** * Setter for <code>lifetime.project.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>lifetime.project.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>lifetime.project.title</code>. */ public void setTitle(String value) { set(1, value); } /** * Getter for <code>lifetime.project.title</code>. */ public String getTitle() { return (String) get(1); } /** * Setter for <code>lifetime.project.summary</code>. */ public void setSummary(String value) { set(2, value); } /** * Getter for <code>lifetime.project.summary</code>. */ public String getSummary() { return (String) get(2); } /** * Setter for <code>lifetime.project.work_id</code>. */ public void setWorkId(Integer value) { set(3, value); } /** * Getter for <code>lifetime.project.work_id</code>. */ public Integer getWorkId() { return (Integer) get(3); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record4 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row4<Integer, String, String, Integer> fieldsRow() { return (Row4) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row4<Integer, String, String, Integer> valuesRow() { return (Row4) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return Project.PROJECT.ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return Project.PROJECT.TITLE; } /** * {@inheritDoc} */ @Override public Field<String> field3() { return Project.PROJECT.SUMMARY; } /** * {@inheritDoc} */ @Override public Field<Integer> field4() { return Project.PROJECT.WORK_ID; } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public String value2() { return getTitle(); } /** * {@inheritDoc} */ @Override public String value3() { return getSummary(); } /** * {@inheritDoc} */ @Override public Integer value4() { return getWorkId(); } /** * {@inheritDoc} */ @Override public ProjectRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public ProjectRecord value2(String value) { setTitle(value); return this; } /** * {@inheritDoc} */ @Override public ProjectRecord value3(String value) { setSummary(value); return this; } /** * {@inheritDoc} */ @Override public ProjectRecord value4(Integer value) { setWorkId(value); return this; } /** * {@inheritDoc} */ @Override public ProjectRecord values(Integer value1, String value2, String value3, Integer value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ProjectRecord */ public ProjectRecord() { super(Project.PROJECT); } /** * Create a detached, initialised ProjectRecord */ public ProjectRecord(Integer id, String title, String summary, Integer workId) { super(Project.PROJECT); set(0, id); set(1, title); set(2, summary); set(3, workId); } }
3e0fd62d762a4bf523b28139d13152dd4eed18ef
2,639
java
Java
helper/src/main/java/me/lucko/helper/profiles/Profile.java
lucko/EventHelper
f7eb72dfd8315755f0d51f919ff78c6958e99dd3
[ "MIT" ]
355
2017-04-08T02:35:46.000Z
2022-03-29T20:43:54.000Z
helper/src/main/java/me/lucko/helper/profiles/Profile.java
lucko/EventHelper
f7eb72dfd8315755f0d51f919ff78c6958e99dd3
[ "MIT" ]
103
2017-10-21T13:35:38.000Z
2022-03-15T21:23:08.000Z
helper/src/main/java/me/lucko/helper/profiles/Profile.java
lucko/EventHelper
f7eb72dfd8315755f0d51f919ff78c6958e99dd3
[ "MIT" ]
134
2017-04-12T10:51:28.000Z
2022-03-30T21:00:13.000Z
29.277778
82
0.683871
6,731
/* * This file is part of helper, licensed under the MIT License. * * Copyright (c) lucko (Luck) <dycjh@example.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.helper.profiles; import org.bukkit.entity.HumanEntity; import java.util.Optional; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Represents a Player's profile */ public interface Profile { /** * Creates a new profile instance * * @param uniqueId the unique id * @param name the username * @return the profile */ @Nonnull static Profile create(@Nonnull UUID uniqueId, @Nullable String name) { return new SimpleProfile(uniqueId, name); } /** * Creates a new profile instance * * @param player the player to create a profile for * @return the profile */ @Nonnull static Profile create(HumanEntity player) { return new SimpleProfile(player.getUniqueId(), player.getName()); } /** * Gets the unique id associated with this profile * * @return the unique id */ @Nonnull UUID getUniqueId(); /** * Gets the username associated with this profile * * @return the username */ @Nonnull Optional<String> getName(); /** * Gets the timestamp when this Profile was created or last updated. * * <p>The returned value is a unix timestamp in milliseconds.</p> * * @return the profiles last update time */ long getTimestamp(); }
3e0fd796f51054a642ea7832eabb5e149240e698
1,387
java
Java
src/main/java/com/lge/plugins/metashift/analysis/StatementCoverageEvaluator.java
shift-left-test/meta-shift-plugin
d07a7284a598ebea8890de870fce1fbcf571fced
[ "MIT" ]
null
null
null
src/main/java/com/lge/plugins/metashift/analysis/StatementCoverageEvaluator.java
shift-left-test/meta-shift-plugin
d07a7284a598ebea8890de870fce1fbcf571fced
[ "MIT" ]
null
null
null
src/main/java/com/lge/plugins/metashift/analysis/StatementCoverageEvaluator.java
shift-left-test/meta-shift-plugin
d07a7284a598ebea8890de870fce1fbcf571fced
[ "MIT" ]
null
null
null
32.255814
100
0.776496
6,732
/* * Copyright (c) 2021 LG Electronics Inc. * SPDX-License-Identifier: MIT */ package com.lge.plugins.metashift.analysis; import com.lge.plugins.metashift.models.Configuration; import com.lge.plugins.metashift.models.CoverageData; import com.lge.plugins.metashift.models.Evaluation; import com.lge.plugins.metashift.models.PositiveEvaluation; import com.lge.plugins.metashift.models.StatementCoverageData; import com.lge.plugins.metashift.models.Streamable; import com.lge.plugins.metashift.models.TestData; /** * StatementCoverageEvaluator class. * * @author Sung Gon Kim */ public class StatementCoverageEvaluator implements Evaluator { private final Configuration configuration; /** * Default constructor. * * @param configuration for evaluation */ public StatementCoverageEvaluator(Configuration configuration) { this.configuration = configuration; } @Override public Evaluation parse(Streamable s) { boolean available = s.contains(TestData.class) && s.contains(StatementCoverageData.class); long denominator = s.objects(StatementCoverageData.class).count(); long numerator = s.objects(StatementCoverageData.class).filter(CoverageData::isCovered).count(); double threshold = (double) configuration.getStatementCoverageThreshold() / 100.0; return new PositiveEvaluation(available, denominator, numerator, threshold); } }
3e0fd7ed7a7450f7e47b83a70af501d2d107f6cb
696
java
Java
app/src/main/java/com/odysee/app/runnable/DeleteViewHistoryItem.java
ktprograms/odysee-android
f6cb52d6132dfa07b05173d1e46d6c15ea90664d
[ "MIT" ]
61
2021-10-21T00:11:15.000Z
2022-03-31T16:58:42.000Z
app/src/main/java/com/odysee/app/runnable/DeleteViewHistoryItem.java
ktprograms/odysee-android
f6cb52d6132dfa07b05173d1e46d6c15ea90664d
[ "MIT" ]
52
2021-11-02T18:29:10.000Z
2022-03-31T19:30:51.000Z
app/src/main/java/com/odysee/app/runnable/DeleteViewHistoryItem.java
ktprograms/odysee-android
f6cb52d6132dfa07b05173d1e46d6c15ea90664d
[ "MIT" ]
10
2021-11-15T17:16:45.000Z
2022-03-18T14:19:25.000Z
24.857143
63
0.613506
6,733
package com.odysee.app.runnable; import android.database.sqlite.SQLiteDatabase; import com.odysee.app.data.DatabaseHelper; public class DeleteViewHistoryItem implements Runnable { private final String url; public DeleteViewHistoryItem(String url) { this.url = url; } @Override public void run() { DatabaseHelper dbHelper = DatabaseHelper.getInstance(); SQLiteDatabase db = dbHelper.getWritableDatabase(); if (db != null) { try { DatabaseHelper.removeViewHistoryItem(db, url); } catch (Exception e) { e.printStackTrace(); } dbHelper.close(); } } }
3e0fd81a0a82c8dfd38141fd3b1bb531fdd624ac
3,777
java
Java
src/main/java/dev/tribos/wakandaacademy/wakander/application/api/wakanderTribe/WakanderTribeController.java
tribos-dev/wakanda-academy-be
9b878ee4ff7ce1a6c33a95ad2e3b492975c37201
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/tribos/wakandaacademy/wakander/application/api/wakanderTribe/WakanderTribeController.java
tribos-dev/wakanda-academy-be
9b878ee4ff7ce1a6c33a95ad2e3b492975c37201
[ "Apache-2.0" ]
null
null
null
src/main/java/dev/tribos/wakandaacademy/wakander/application/api/wakanderTribe/WakanderTribeController.java
tribos-dev/wakanda-academy-be
9b878ee4ff7ce1a6c33a95ad2e3b492975c37201
[ "Apache-2.0" ]
null
null
null
34.336364
103
0.751655
6,734
package dev.tribos.wakandaacademy.wakander.application.api.wakanderTribe; import java.util.Arrays; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import dev.tribos.wakandaacademy.wakander.domain.StatusWakanderTribe; import dev.tribos.wakandaacademy.wakander.domain.TipoAula; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; @RestController @Log4j2 @RequiredArgsConstructor public class WakanderTribeController implements WakanderTribeAPI { @Override @ResponseStatus(value = HttpStatus.OK) public List<WakanderTribeResponse> listaWakanderTribe(String wakanderCode) { log.info("[start] WakanderTribeController - listaWakanderTribe"); return Arrays.asList(buildLogicaTribe(),buildJavaRaizTribe()); } private WakanderTribeResponse buildLogicaTribe() { return WakanderTribeResponse.builder() .tribeCode("LOGICA") .name("LOGICA DE PROGRAMACAO") .description("PRIMEIROS PASSOS") .iconUrl("https://imagensemoldes.com.br/wp-content/uploads/2020/05/Engrenagem-Colorida-PNG.png") .status(StatusWakanderTribe.DOING) .build(); } private WakanderTribeResponse buildJavaRaizTribe() { return WakanderTribeResponse.builder() .tribeCode("JAVA-RAIZ") .name("JAVA RAIZ") .description("PRINCIPIOS JAVA") .iconUrl("https://cdn-icons-png.flaticon.com/512/226/226777.png") .status(StatusWakanderTribe.DONE) .build(); } @Override @ResponseStatus(value = HttpStatus.OK) public WakanderTribeDetailResponse listarDetailWakanderTribe(String wakanderCode, String tribeCode) { log.info("[start] WakanderTribeController - listarDetailWakanderTribe"); if (tribeCode.equals("LOGICA")) { return buildLogicaTribeDetail(); } else { return buildJavaRaizTribeDetail(); } } private WakanderTribeDetailResponse buildLogicaTribeDetail() { return WakanderTribeDetailResponse.builder() .name("LOGICA DE PROGRAMACAO") .wakanderTribeSkills(Arrays.asList(buildLogica1Skill())) .build(); } private WakanderTribeDetailResponse buildJavaRaizTribeDetail() { return WakanderTribeDetailResponse.builder() .name("JAVA RAIZ") .wakanderTribeSkills(Arrays.asList(buildJavaRaizSkill())) .build(); } private WakanderTribeSkillResponse buildLogica1Skill() { return WakanderTribeSkillResponse.builder() .skillCode("PROGRAMACAO-BASIC") .skillName("Jogos clássicos parte I - Iniciando no Javascript com Pong") .skillStatus(StatusWakanderTribe.DOING) .wakanderTribeSkillLessons(Arrays.asList(buildLogica1Lesson())) .build(); } private WakanderTribeSkillLessonResponse buildLogica1Lesson() { return WakanderTribeSkillLessonResponse.builder() .lessonCode("PARTE-I") .lessonName("Pong no Scratch") .status(StatusWakanderTribe.DONE) .link("https://drive.google.com/drive/folders/1C_lkJcIoDOc0G09AH1_8T7qdif2Orju9?usp=sharing") .tipo(TipoAula.GDRIVE) .build(); } private WakanderTribeSkillResponse buildJavaRaizSkill() { return WakanderTribeSkillResponse.builder() .skillCode("JAVA-VARIAVEIS") .skillName("Java Variaveis - Universidade XTI") .skillStatus(StatusWakanderTribe.DONE) .wakanderTribeSkillLessons(Arrays.asList(buildJavaRaizLesson())) .build(); } private WakanderTribeSkillLessonResponse buildJavaRaizLesson() { return WakanderTribeSkillLessonResponse.builder() .lessonCode("INTRODUÇÃO") .lessonName("Introdução") .status(StatusWakanderTribe.DONE) .link("https://www.youtube.com/embed/NZDzuve7kho") .tipo(TipoAula.YOUTUBE) .build(); } }
3e0fd8eecf9b5331f86523c4d34c70bb570bc53b
12,549
java
Java
src/main/java/ch.randelshofer.cubetwister/ch/randelshofer/cubetwister/doc/CubeBackgroundView.java
RakhithJK/Cube-Twister
b392b191cc83de52d1ab3e5638802156558f1aeb
[ "MIT" ]
16
2017-07-22T13:24:27.000Z
2021-09-11T14:22:39.000Z
src/main/java/ch.randelshofer.cubetwister/ch/randelshofer/cubetwister/doc/CubeBackgroundView.java
RakhithJK/Cube-Twister
b392b191cc83de52d1ab3e5638802156558f1aeb
[ "MIT" ]
3
2017-09-19T08:23:42.000Z
2020-06-12T08:21:24.000Z
src/main/java/ch.randelshofer.cubetwister/ch/randelshofer/cubetwister/doc/CubeBackgroundView.java
RakhithJK/Cube-Twister
b392b191cc83de52d1ab3e5638802156558f1aeb
[ "MIT" ]
2
2019-07-27T15:21:36.000Z
2021-03-04T02:03:25.000Z
46.477778
176
0.674556
6,735
/* * @(#)CubeBackgroundView.java * CubeTwister. Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.cubetwister.doc; import org.jhotdraw.annotation.Nonnull; import org.jhotdraw.gui.Dialogs; import javax.swing.JColorChooser; import javax.swing.JComponent; import java.awt.Color; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * CubeBackgroundView is used in the "Options &gt; Background" panel of CubeTwister. * * @author Werner Randelshofer */ public class CubeBackgroundView extends AbstractEntityView { private final static long serialVersionUID = 1L; private CubeModel model; private JColorChooser colorChooser; private class ModelHandler implements PropertyChangeListener { public void propertyChange(@Nonnull PropertyChangeEvent evt) { String name = evt.getPropertyName(); if (name == CubeModel.FRONT_BG_COLOR_PROPERTY) { frontViewColorWell.setBackground((Color) evt.getNewValue()); } else if (name == CubeModel.REAR_BG_COLOR_PROPERTY) { rearViewColorWell.setBackground((Color) evt.getNewValue()); } } } private ModelHandler modelHandler; /** Creates new form CubeBackgroundView */ public CubeBackgroundView() { initComponents(); frontViewColorWell.putClientProperty("Quaqua.Button.style", "colorWell"); rearViewColorWell.putClientProperty("Quaqua.Button.style", "colorWell"); scrollPane.getViewport().setOpaque(false); // XXX - We have not implemented this panel yet for (int i = 0, n = panel.getComponentCount(); i < n; i++) { panel.getComponent(i).setEnabled(false); } bgColorLabel.setEnabled(true); frontViewLabel.setEnabled(true); frontViewColorWell.setEnabled(true); rearViewColorWell.setEnabled(false); modelHandler = new ModelHandler(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. * XXX - Unfortunately the generated code below does use constant values for * indentation, and it does not support non-related distances between two * components. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); scrollPane = new javax.swing.JScrollPane(); panel = new javax.swing.JPanel(); bgColorLabel = new javax.swing.JLabel(); frontViewImageWell = new ch.randelshofer.gui.JImageWell(); frontViewLabel = new javax.swing.JLabel(); rearViewImageWell = new ch.randelshofer.gui.JImageWell(); rearViewLabel = new javax.swing.JLabel(); frontViewImageCheck = new javax.swing.JCheckBox(); frontViewColorWell = new javax.swing.JButton(); rearViewImageCheck = new javax.swing.JCheckBox(); rearViewColorWell = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); scrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); bgColorLabel.setText("Background Color"); javax.swing.GroupLayout frontViewImageWellLayout = new javax.swing.GroupLayout(frontViewImageWell); frontViewImageWell.setLayout(frontViewImageWellLayout); frontViewImageWellLayout.setHorizontalGroup( frontViewImageWellLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); frontViewImageWellLayout.setVerticalGroup( frontViewImageWellLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); frontViewLabel.setText("Front View"); javax.swing.GroupLayout rearViewImageWellLayout = new javax.swing.GroupLayout(rearViewImageWell); rearViewImageWell.setLayout(rearViewImageWellLayout); rearViewImageWellLayout.setHorizontalGroup( rearViewImageWellLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); rearViewImageWellLayout.setVerticalGroup( rearViewImageWellLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); rearViewLabel.setText("Rear View"); frontViewImageCheck.setSelected(true); frontViewImageCheck.setText("Background image in front view"); frontViewImageCheck.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { frontViewImageCheckChanged(evt); } }); frontViewColorWell.setText(" "); frontViewColorWell.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { frontViewColorWellPerformed(evt); } }); rearViewImageCheck.setSelected(true); rearViewImageCheck.setText("Background image in rear view"); rearViewImageCheck.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { rearViewImageCheckChanged(evt); } }); rearViewColorWell.setText(" "); rearViewColorWell.setEnabled(false); rearViewColorWell.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rearViewColorWellPerformed(evt); } }); javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel); panel.setLayout(panelLayout); panelLayout.setHorizontalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addContainerGap() .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(frontViewImageWell, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panelLayout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(rearViewImageWell, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(rearViewImageCheck) .addComponent(frontViewImageCheck) .addComponent(bgColorLabel) .addGroup(panelLayout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addComponent(rearViewColorWell) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rearViewLabel)) .addGroup(panelLayout.createSequentialGroup() .addComponent(frontViewColorWell) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(frontViewLabel))))) .addContainerGap(68, Short.MAX_VALUE)) ); panelLayout.setVerticalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelLayout.createSequentialGroup() .addContainerGap() .addComponent(bgColorLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(frontViewColorWell) .addComponent(frontViewLabel)) .addGap(2, 2, 2) .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rearViewColorWell) .addComponent(rearViewLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(frontViewImageCheck) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(frontViewImageWell, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(5, 5, 5) .addComponent(rearViewImageCheck) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rearViewImageWell, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); scrollPane.setViewportView(panel); add(scrollPane, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void rearViewImageCheckChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rearViewImageCheckChanged rearViewImageWell.setVisible(rearViewImageCheck.isSelected()); validate(); }//GEN-LAST:event_rearViewImageCheckChanged private void frontViewImageCheckChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_frontViewImageCheckChanged frontViewImageWell.setVisible(frontViewImageCheck.isSelected()); validate(); }//GEN-LAST:event_frontViewImageCheckChanged private void frontViewColorWellPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_frontViewColorWellPerformed if (colorChooser == null) { colorChooser = new JColorChooser(); } Color selectedColor = Dialogs.showColorChooserDialog(colorChooser, this, "Front View Background", model.getFrontBgColor()); if (selectedColor != null) { model.setFrontBgColor(selectedColor); } }//GEN-LAST:event_frontViewColorWellPerformed private void rearViewColorWellPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rearViewColorWellPerformed if (colorChooser == null) { colorChooser = new JColorChooser(); } Color selectedColor = Dialogs.showColorChooserDialog(colorChooser, this, "Rear View Background", model.getFrontBgColor()); if (selectedColor != null) { model.setRearBgColor(selectedColor); } }//GEN-LAST:event_rearViewColorWellPerformed public void setModel(EntityModel newValue) { if (model != null) { model.removePropertyChangeListener(modelHandler); } model = (CubeModel) newValue; if (model != null) { frontViewImageCheck.setSelected(false); rearViewImageCheck.setSelected(false); frontViewColorWell.setBackground(model.getFrontBgColor()); rearViewColorWell.setBackground(model.getRearBgColor()); model.addPropertyChangeListener(modelHandler); } } @Nonnull public JComponent getViewComponent() { return this; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bgColorLabel; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton frontViewColorWell; private javax.swing.JCheckBox frontViewImageCheck; private ch.randelshofer.gui.JImageWell frontViewImageWell; private javax.swing.JLabel frontViewLabel; private javax.swing.JPanel panel; private javax.swing.JButton rearViewColorWell; private javax.swing.JCheckBox rearViewImageCheck; private ch.randelshofer.gui.JImageWell rearViewImageWell; private javax.swing.JLabel rearViewLabel; private javax.swing.JScrollPane scrollPane; // End of variables declaration//GEN-END:variables }
3e0fd9e5f3169c5f98b2fd43485f101bd1acb529
1,290
java
Java
app/src/test/java/com/vartmp7/stalker/ui/organizations/OrganizationsFragmentTest.java
WenXiaowei/Stalker_App
c91e2e010bd412df4c7a856245fd8ee16894ae7b
[ "MIT" ]
null
null
null
app/src/test/java/com/vartmp7/stalker/ui/organizations/OrganizationsFragmentTest.java
WenXiaowei/Stalker_App
c91e2e010bd412df4c7a856245fd8ee16894ae7b
[ "MIT" ]
null
null
null
app/src/test/java/com/vartmp7/stalker/ui/organizations/OrganizationsFragmentTest.java
WenXiaowei/Stalker_App
c91e2e010bd412df4c7a856245fd8ee16894ae7b
[ "MIT" ]
null
null
null
39.090909
81
0.763566
6,736
/* * MIT License * * Copyright (c) 2020 VarTmp7 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vartmp7.stalker.ui.organizations; import org.junit.runner.RunWith; import static org.junit.Assert.*; public class OrganizationsFragmentTest { }
3e0fdabfbcf57c0e18ccffd88d52f01917d08ed7
147
java
Java
validation/src/main/java/com/hamdy/android/lib/validation/Errors/IError.java
hamdysaad/hamdy-android-validation
efe4454ac33c8d3dc788de138e38bdd89bef04ec
[ "MIT" ]
1
2019-08-19T22:54:17.000Z
2019-08-19T22:54:17.000Z
validation/src/main/java/com/hamdy/android/lib/validation/Errors/IError.java
hamdysaad/hamdy-android-validation
efe4454ac33c8d3dc788de138e38bdd89bef04ec
[ "MIT" ]
null
null
null
validation/src/main/java/com/hamdy/android/lib/validation/Errors/IError.java
hamdysaad/hamdy-android-validation
efe4454ac33c8d3dc788de138e38bdd89bef04ec
[ "MIT" ]
null
null
null
13.363636
48
0.687075
6,737
package com.hamdy.android.lib.validation.Errors; /** * Created by Hamdy on 4/23/2017. */ public interface IError { void displayError(); }
3e0fdb9b9c93fdab31ad596b56f95205a49cd12d
1,401
java
Java
projo/src/main/java/pro/projo/Factory.java
raner/projo
f011596d7db780955b287d0ea6713e49eecc20f0
[ "Apache-2.0" ]
1
2020-08-14T22:02:17.000Z
2020-08-14T22:02:17.000Z
projo/src/main/java/pro/projo/Factory.java
raner/projo
f011596d7db780955b287d0ea6713e49eecc20f0
[ "Apache-2.0" ]
79
2017-02-02T07:14:16.000Z
2022-03-29T05:57:20.000Z
projo/src/main/java/pro/projo/Factory.java
raner/projo
f011596d7db780955b287d0ea6713e49eecc20f0
[ "Apache-2.0" ]
null
null
null
51.888889
98
0.421842
6,738
// // // Copyright 2016 Mirko Raner // // // // 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 pro.projo; /** * The {@link Factory} interface is a marker interface that is implemented by all Projo factories. * * @author Mirko Raner */ public interface Factory { // This is a marker interface }
3e0fdbfdc19a68026406bdf04bbe9d6342379899
1,091
java
Java
core/src/main/java/io/two55/elex/dao/impl/LinkDetailsDAODefaultImpl.java
two55/elex-tinkerpop
df521b34d27e68a06ddf9c8a463f0c645d14118f
[ "Apache-2.0" ]
null
null
null
core/src/main/java/io/two55/elex/dao/impl/LinkDetailsDAODefaultImpl.java
two55/elex-tinkerpop
df521b34d27e68a06ddf9c8a463f0c645d14118f
[ "Apache-2.0" ]
5
2018-06-13T15:32:06.000Z
2018-06-25T20:16:56.000Z
core/src/main/java/io/two55/elex/dao/impl/LinkDetailsDAODefaultImpl.java
two55/elex-tinkerpop
df521b34d27e68a06ddf9c8a463f0c645d14118f
[ "Apache-2.0" ]
null
null
null
36.366667
89
0.757104
6,739
/* * Copyright 2018 ELEx 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 io.two55.elex.dao.impl; import io.two55.elex.dao.LinkDetailsDAO; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; @Service @ConditionalOnProperty(name = "graph.type", havingValue = "default", matchIfMissing=true) public class LinkDetailsDAODefaultImpl implements LinkDetailsDAO { public String detailsOf(String linkId) { return String.format("<h1>No details for link: %s</h1>", linkId); } }
3e0fde319df432484b4d71ed3dfc79edb0ee8864
1,488
java
Java
com.osgifx.console.api/src/main/java/com/osgifx/console/propertytypes/MainThread.java
amitjoy/osgifx
2f2b4849063b2ccfaf6cc92d034e915d6be6c38b
[ "Apache-2.0" ]
3
2022-01-14T05:04:33.000Z
2022-02-09T14:59:46.000Z
com.osgifx.console.api/src/main/java/com/osgifx/console/propertytypes/MainThread.java
amitjoy/osgifx-console
d0993637cc06befb4ec17228205f06d4eb55d1ba
[ "Apache-2.0" ]
3
2021-12-06T23:30:43.000Z
2021-12-06T23:32:44.000Z
com.osgifx.console.api/src/main/java/com/osgifx/console/propertytypes/MainThread.java
amitjoy/osgifx-console
d0993637cc06befb4ec17228205f06d4eb55d1ba
[ "Apache-2.0" ]
null
null
null
36.292683
80
0.682796
6,740
/******************************************************************************* * Copyright 2021-2022 Amit Kumar Mondal * * 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.osgifx.console.propertytypes; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.ComponentPropertyType; /** * Component Property Type for the {@code main.thread} service property. * <p> * This annotation can be used on a {@link Component} to declare the value of * the {@code main.thread} service property. * * @see "Component Property Types" */ @Target(TYPE) @Retention(CLASS) @ComponentPropertyType public @interface MainThread { String value() default "true"; }
3e0fe0350373104f80ed9af70fcd18a215d1a63a
7,295
java
Java
Ref-Finder/code/bin/tyRuBa/util/CountedHashMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/bin/tyRuBa/util/CountedHashMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
Ref-Finder/code/bin/tyRuBa/util/CountedHashMap.java
UCLA-SEAL/RefFinder
40849cf928b9a2425efe6c1ec5ffa465b1ee2a76
[ "BSD-3-Clause" ]
null
null
null
24.982877
143
0.55915
6,741
/* * Ref-Finder * Copyright (C) <2015> <PLSE_UCLA> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package tyRuBa.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; public class CountedHashMap implements Serializable { private static final int DEFAULT_INITIAL_SIZE = 32; private static final int MAX_CONCURRENCY = 32; private static final double DEFAULT_LOAD_FACTOR = 0.75D; private transient Object[] mutex = new Object[32]; private CountedHashMap.Entry[] table; private int size; private double loadFactor; private int threshold; private void rehash(boolean grow) { rehash(0, grow); } private void rehash(int obtained, boolean grow) { if (obtained == 32) { CountedHashMap.Entry[] ntable = grow ? new CountedHashMap.Entry[this.table.length * 2] : new CountedHashMap.Entry[this.table.length / 2]; int location = 0; while (location < this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { CountedHashMap.Entry next = bucket.next; int nlocation = (bucket.key % ntable.length + ntable.length) % ntable.length; bucket.next = ntable[nlocation]; ntable[nlocation] = bucket; bucket = next; } location++; } this.table = ntable; this.threshold = ((int)(this.table.length * this.loadFactor)); } else { synchronized (this.mutex[(obtained++)]) { rehash(obtained, grow); } } } public CountedHashMap() { this(32, 0.75D); } public CountedHashMap(int initialSize) { this(initialSize, 0.75D); } public CountedHashMap(double loadFactor) { this(32, loadFactor); } public CountedHashMap(int initialSize, double loadFactor) { int i = 32; while (i-- != 0) { this.mutex[i] = new Object(); } this.table = new CountedHashMap.Entry[initialSize]; this.size = 0; this.loadFactor = loadFactor; this.threshold = ((int)(this.table.length * loadFactor)); } public boolean containsKey(int key) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { return true; } bucket = bucket.next; } return false; } } return containsKey(key); } public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } public Object get(int key) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { return bucket.value; } bucket = bucket.next; } return null; } } return get(key); } public boolean isEmpty() { return this.size == 0; } public Object put(int key, Object value) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { Object previous = bucket.value; bucket.value = value; bucket.preIncrementCount(); return previous; } bucket = bucket.next; } this.table[location] = new CountedHashMap.Entry(key, value, this.table[location]); synchronized (this.mutex) { if (++this.size > this.threshold) { rehash(true); } } return null; } } return put(key, value); } public Object remove(int key) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry previous = null; CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { if (bucket.preDecrementCount() == 0) { if (previous == null) { this.table[location] = bucket.next; } else { previous.next = bucket.next; } synchronized (this.mutex) { if (--this.size < this.threshold / 3) { rehash(false); } } } return bucket.value; } previous = bucket; bucket = bucket.next; } return null; } } return remove(key); } public boolean setFlags(int key, int flags) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { bucket.setFlags(flags); return true; } bucket = bucket.next; } return false; } } return setFlags(key, flags); } public int getFlags(int key) { int length = this.table.length; int location = (key % length + length) % length; synchronized (this.mutex[(location % 32)]) { if (length == this.table.length) { CountedHashMap.Entry bucket = this.table[location]; while (bucket != null) { if (key == bucket.key) { return bucket.getFlags(); } bucket = bucket.next; } return 0; } } return getFlags(key); } public int size() { return this.size; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.mutex = new Object[32]; int i = 32; while (i-- != 0) { this.mutex[i] = new Object(); } } }
3e0fe0789e07e22e30778442b274859d44bb57f4
5,045
java
Java
src/main/java/com/microsoft/graph/requests/extensions/ThreatAssessmentRequestCollectionRequest.java
katestoycheva/msgraph-sdk-java
795362ad234efead2cd1c738abddee99b1a48dcc
[ "MIT" ]
1
2020-07-18T06:42:20.000Z
2020-07-18T06:42:20.000Z
src/main/java/com/microsoft/graph/requests/extensions/ThreatAssessmentRequestCollectionRequest.java
chriso1977/msgraph-sdk-java
14dad555e5fc5ac74067d1e3da34f3d44c20d1eb
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/ThreatAssessmentRequestCollectionRequest.java
chriso1977/msgraph-sdk-java
14dad555e5fc5ac74067d1e3da34f3d44c20d1eb
[ "MIT" ]
null
null
null
43.869565
221
0.694945
6,742
// ------------------------------------------------------------------------------ // 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.requests.extensions; 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.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Threat Assessment Request Collection Request. */ public class ThreatAssessmentRequestCollectionRequest extends BaseCollectionRequest<ThreatAssessmentRequestCollectionResponse, IThreatAssessmentRequestCollectionPage> implements IThreatAssessmentRequestCollectionRequest { /** * The request builder for this collection of ThreatAssessmentRequest * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public ThreatAssessmentRequestCollectionRequest(final String requestUrl, IBaseClient client, final java.util.List<? extends Option> requestOptions) { super(requestUrl, client, requestOptions, ThreatAssessmentRequestCollectionResponse.class, IThreatAssessmentRequestCollectionPage.class); } public void get(final ICallback<IThreatAssessmentRequestCollectionPage> callback) { final IExecutors executors = getBaseRequest().getClient().getExecutors(); executors.performOnBackground(new Runnable() { @Override public void run() { try { executors.performOnForeground(get(), callback); } catch (final ClientException e) { executors.performOnForeground(e, callback); } } }); } public IThreatAssessmentRequestCollectionPage get() throws ClientException { final ThreatAssessmentRequestCollectionResponse response = send(); return buildFromResponse(response); } public void post(final ThreatAssessmentRequest newThreatAssessmentRequest, final ICallback<ThreatAssessmentRequest> callback) { final String requestUrl = getBaseRequest().getRequestUrl().toString(); new ThreatAssessmentRequestRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null) .buildRequest(getBaseRequest().getOptions()) .post(newThreatAssessmentRequest, callback); } public ThreatAssessmentRequest post(final ThreatAssessmentRequest newThreatAssessmentRequest) throws ClientException { final String requestUrl = getBaseRequest().getRequestUrl().toString(); return new ThreatAssessmentRequestRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null) .buildRequest(getBaseRequest().getOptions()) .post(newThreatAssessmentRequest); } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ public IThreatAssessmentRequestCollectionRequest expand(final String value) { addQueryOption(new QueryOption("$expand", value)); return (ThreatAssessmentRequestCollectionRequest)this; } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ public IThreatAssessmentRequestCollectionRequest select(final String value) { addQueryOption(new QueryOption("$select", value)); return (ThreatAssessmentRequestCollectionRequest)this; } /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ public IThreatAssessmentRequestCollectionRequest top(final int value) { addQueryOption(new QueryOption("$top", value + "")); return (ThreatAssessmentRequestCollectionRequest)this; } public IThreatAssessmentRequestCollectionPage buildFromResponse(final ThreatAssessmentRequestCollectionResponse response) { final IThreatAssessmentRequestCollectionRequestBuilder builder; if (response.nextLink != null) { builder = new ThreatAssessmentRequestCollectionRequestBuilder(response.nextLink, getBaseRequest().getClient(), /* options */ null); } else { builder = null; } final ThreatAssessmentRequestCollectionPage page = new ThreatAssessmentRequestCollectionPage(response, builder); page.setRawObject(response.getSerializer(), response.getRawObject()); return page; } }
3e0fe173af4c6e8114262630c2257f6425f7a7c1
1,557
java
Java
VirtualApp/lib/src/main/java/com/lody/virtual/remote/vloc/VCell.java
PigLong/MoreApp
e7b3f7c637e84fbb0e22d86fbbd2ef346708a836
[ "Apache-2.0" ]
8
2017-12-25T01:42:03.000Z
2021-08-18T23:32:43.000Z
VirtualApp/lib/src/main/java/com/lody/virtual/remote/vloc/VCell.java
jackyhee/MoreApp
e7b3f7c637e84fbb0e22d86fbbd2ef346708a836
[ "Apache-2.0" ]
1
2022-03-27T00:12:31.000Z
2022-03-27T00:12:31.000Z
VirtualApp/lib/src/main/java/com/lody/virtual/remote/vloc/VCell.java
jackyhee/MoreApp
e7b3f7c637e84fbb0e22d86fbbd2ef346708a836
[ "Apache-2.0" ]
5
2018-04-23T10:09:02.000Z
2021-07-13T10:40:07.000Z
22.897059
93
0.591522
6,743
package com.lody.virtual.remote.vloc; import android.os.Parcel; import android.os.Parcelable; /** * @author Lody */ public class VCell implements Parcelable { public int type; public int mcc; public int mnc; public int psc; public int lac; public int cid; public int baseStationId; public int systemId; public int networkId; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.type); dest.writeInt(this.mcc); dest.writeInt(this.mnc); dest.writeInt(this.psc); dest.writeInt(this.lac); dest.writeInt(this.cid); dest.writeInt(this.baseStationId); dest.writeInt(this.systemId); dest.writeInt(this.networkId); } public VCell() { } public VCell(Parcel in) { this.type = in.readInt(); this.mcc = in.readInt(); this.mnc = in.readInt(); this.psc = in.readInt(); this.lac = in.readInt(); this.cid = in.readInt(); this.baseStationId = in.readInt(); this.systemId = in.readInt(); this.networkId = in.readInt(); } public static final Parcelable.Creator<VCell> CREATOR = new Parcelable.Creator<VCell>() { @Override public VCell createFromParcel(Parcel source) { return new VCell(source); } @Override public VCell[] newArray(int size) { return new VCell[size]; } }; }
3e0fe1dc6caacc6942a8fc2754bbc67b30182972
1,129
java
Java
vmidentity/platform/src/main/java/com/vmware/identity/interop/directory/DefaultAccountPasswordResetter.java
debojyoti-majumder/lightwave
1ff3beaafb7351140b9372e3a46b2a288f53832e
[ "Apache-2.0" ]
357
2015-04-20T00:16:30.000Z
2022-03-17T05:34:09.000Z
vmidentity/platform/src/main/java/com/vmware/identity/interop/directory/DefaultAccountPasswordResetter.java
WestCope/lightwave
baae9b03ddeeb6299ab891f9c1e2957b86d37cc5
[ "Apache-2.0" ]
38
2015-11-19T05:20:53.000Z
2022-03-31T07:21:59.000Z
vmidentity/platform/src/main/java/com/vmware/identity/interop/directory/DefaultAccountPasswordResetter.java
WestCope/lightwave
baae9b03ddeeb6299ab891f9c1e2957b86d37cc5
[ "Apache-2.0" ]
135
2015-04-21T15:23:21.000Z
2022-03-30T11:46:36.000Z
45.16
84
0.750221
6,744
/* * Copyright (c) 2018 VMware, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, without * warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the * License for the specific language governing permissions and limitations * under the License. */ package com.vmware.identity.interop.directory; public class DefaultAccountPasswordResetter implements IAccountPasswordResetter { public DefaultAccountPasswordResetter() {} public String ResetAccountPassword( String hostURI, String domainName, String accountUPN, String accountDN, String currentPwd, boolean bForceRefresh){ return DirectoryAdapter.getInstance().ResetAccountPassword( hostURI, domainName,accountUPN, accountDN,currentPwd,bForceRefresh); } }
3e0fe201ef155517c58efc9e849b287e208d4ed3
2,708
java
Java
killers/nokia/com.evenwell.powersaving.g3/sources/org/apache/commons/io/HexDump.java
jen801/dont-kill-my-app
4e4b0cf8503aefc54179da0b95c5102e662dca1c
[ "CC-BY-4.0" ]
806
2019-01-03T14:09:50.000Z
2022-03-31T15:10:02.000Z
killers/nokia/com.evenwell.powersaving.g3/sources/org/apache/commons/io/HexDump.java
jen801/dont-kill-my-app
4e4b0cf8503aefc54179da0b95c5102e662dca1c
[ "CC-BY-4.0" ]
368
2019-01-03T20:43:03.000Z
2022-03-30T17:09:55.000Z
killers/nokia/com.evenwell.powersaving.g3/sources/org/apache/commons/io/HexDump.java
jen801/dont-kill-my-app
4e4b0cf8503aefc54179da0b95c5102e662dca1c
[ "CC-BY-4.0" ]
555
2019-01-02T13:11:22.000Z
2022-03-30T08:44:03.000Z
39.246377
164
0.480428
6,745
package org.apache.commons.io; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; public class HexDump { public static final String EOL = System.getProperty("line.separator"); private static final char[] _hexcodes = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static final int[] _shifts = new int[]{28, 24, 20, 16, 12, 8, 4, 0}; public static void dump(byte[] data, long offset, OutputStream stream, int index) throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException { if (index < 0 || index >= data.length) { throw new ArrayIndexOutOfBoundsException("illegal index: " + index + " into array of length " + data.length); } else if (stream == null) { throw new IllegalArgumentException("cannot write to nullstream"); } else { long display_offset = offset + ((long) index); StringBuilder buffer = new StringBuilder(74); int j = index; while (j < data.length) { int k; int chars_read = data.length - j; if (chars_read > 16) { chars_read = 16; } dump(buffer, display_offset).append(' '); for (k = 0; k < 16; k++) { if (k < chars_read) { dump(buffer, data[k + j]); } else { buffer.append(" "); } buffer.append(' '); } k = 0; while (k < chars_read) { if (data[k + j] < (byte) 32 || data[k + j] >= Byte.MAX_VALUE) { buffer.append('.'); } else { buffer.append((char) data[k + j]); } k++; } buffer.append(EOL); stream.write(buffer.toString().getBytes(Charset.defaultCharset())); stream.flush(); buffer.setLength(0); display_offset += (long) chars_read; j += 16; } } } private static StringBuilder dump(StringBuilder _lbuffer, long value) { for (int j = 0; j < 8; j++) { _lbuffer.append(_hexcodes[((int) (value >> _shifts[j])) & 15]); } return _lbuffer; } private static StringBuilder dump(StringBuilder _cbuffer, byte value) { for (int j = 0; j < 2; j++) { _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]); } return _cbuffer; } }
3e0fe2a037e772edf4a7afbfd27f8ec9167d7900
3,007
java
Java
src/main/java/archimulator/uncore/coherence/msi/controller/Controller.java
mcai/Archimulator
039b8ba31d76a769e2bac84ed9c83e706a307e64
[ "MIT" ]
3
2016-08-04T05:01:36.000Z
2020-01-17T19:48:37.000Z
src/main/java/archimulator/uncore/coherence/msi/controller/Controller.java
mcai/Archimulator
039b8ba31d76a769e2bac84ed9c83e706a307e64
[ "MIT" ]
null
null
null
src/main/java/archimulator/uncore/coherence/msi/controller/Controller.java
mcai/Archimulator
039b8ba31d76a769e2bac84ed9c83e706a307e64
[ "MIT" ]
3
2015-08-05T13:18:11.000Z
2022-02-01T23:03:27.000Z
30.744898
92
0.642217
6,746
/** * **************************************************************************** * Copyright (c) 2010-2016 by Min Cai (anpch@example.com). * <p> * This file is part of the Archimulator multicore architectural simulator. * <p> * Archimulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p> * Archimulator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License * along with Archimulator. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************** */ package archimulator.uncore.coherence.msi.controller; import archimulator.uncore.MemoryDevice; import archimulator.uncore.MemoryHierarchy; import archimulator.uncore.cache.MemoryDeviceType; import archimulator.uncore.cache.replacement.CacheReplacementPolicyType; import archimulator.uncore.coherence.msi.message.CoherenceMessage; /** * Controller. * * @author Min Cai */ public abstract class Controller extends MemoryDevice { private MemoryDevice next; /** * Create a controller. * * @param memoryHierarchy the parent memory hierarchy * @param name the name * @param type the type */ public Controller(MemoryHierarchy memoryHierarchy, String name, MemoryDeviceType type) { super(memoryHierarchy, name, type); } /** * Receive a coherence message. * * @param message the coherence message */ public abstract void receive(CoherenceMessage message); /** * Transfer the specified message to the destination controller. * * @param to the destination controller * @param size the size of the message * @param message the message */ public void transfer(Controller to, int size, CoherenceMessage message) { this.getMemoryHierarchy().transfer(this, to, size, message); } /** * Get the next level memory device. * * @return the next level memory device */ public MemoryDevice getNext() { return next; } /** * Set the next level memory device. * * @param next the next level memory device */ public void setNext(MemoryDevice next) { this.next = next; } /** * Get the hit latency in cycles. * * @return the hit latency in cycles */ public abstract int getHitLatency(); /** * Get the cache replacement policy type. * * @return the cache replacement policy type */ public abstract CacheReplacementPolicyType getReplacementPolicyType(); }
3e0fe2a1a9394c6a1d49205db7dff6577b8af490
470
java
Java
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/giftCard/event/fulfillment/GiftCardFulfillmentUpdated.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
1
2020-09-28T08:23:11.000Z
2020-09-28T08:23:11.000Z
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/giftCard/event/fulfillment/GiftCardFulfillmentUpdated.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
plugins/eCommerce/src/main/java/com/skytala/eCommerce/domain/accounting/relations/giftCard/event/fulfillment/GiftCardFulfillmentUpdated.java
ArcticReal/eCommerce
ea4c82442acdc9e663571e2d07e1f1ddc844f135
[ "Apache-2.0" ]
null
null
null
24.736842
104
0.819149
6,747
package com.skytala.eCommerce.domain.accounting.relations.giftCard.event.fulfillment; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.domain.accounting.relations.giftCard.model.fulfillment.GiftCardFulfillment; public class GiftCardFulfillmentUpdated implements Event{ private boolean success; public GiftCardFulfillmentUpdated(boolean success) { this.success = success; } public boolean isSuccess() { return success; } }
3e0fe3f8a880198d92872bd60ef3abff677e589c
8,312
java
Java
Spigot/Spigot-Server/src/main/java/net/minecraft/nbt/NBTCompressedStreamTools.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
Spigot/Spigot-Server/src/main/java/net/minecraft/nbt/NBTCompressedStreamTools.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
Spigot/Spigot-Server/src/main/java/net/minecraft/nbt/NBTCompressedStreamTools.java
jacobo-mc/spigot_1.18
03d238eebaeab66357e75987e8fb4403e0c85960
[ "MIT" ]
null
null
null
32.724409
127
0.604187
6,748
// mc-dev import package net.minecraft.nbt; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.annotation.Nullable; import net.minecraft.CrashReport; import net.minecraft.CrashReportSystemDetails; import net.minecraft.ReportedException; public class NBTCompressedStreamTools { public NBTCompressedStreamTools() {} public static NBTTagCompound readCompressed(File file) throws IOException { FileInputStream fileinputstream = new FileInputStream(file); NBTTagCompound nbttagcompound; try { nbttagcompound = readCompressed((InputStream) fileinputstream); } catch (Throwable throwable) { try { fileinputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } fileinputstream.close(); return nbttagcompound; } public static NBTTagCompound readCompressed(InputStream inputstream) throws IOException { DataInputStream datainputstream = new DataInputStream(new BufferedInputStream(new GZIPInputStream(inputstream))); NBTTagCompound nbttagcompound; try { nbttagcompound = read(datainputstream, NBTReadLimiter.UNLIMITED); } catch (Throwable throwable) { try { datainputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } datainputstream.close(); return nbttagcompound; } public static void writeCompressed(NBTTagCompound nbttagcompound, File file) throws IOException { FileOutputStream fileoutputstream = new FileOutputStream(file); try { writeCompressed(nbttagcompound, (OutputStream) fileoutputstream); } catch (Throwable throwable) { try { fileoutputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } fileoutputstream.close(); } public static void writeCompressed(NBTTagCompound nbttagcompound, OutputStream outputstream) throws IOException { DataOutputStream dataoutputstream = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(outputstream))); try { write(nbttagcompound, (DataOutput) dataoutputstream); } catch (Throwable throwable) { try { dataoutputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } dataoutputstream.close(); } public static void write(NBTTagCompound nbttagcompound, File file) throws IOException { FileOutputStream fileoutputstream = new FileOutputStream(file); try { DataOutputStream dataoutputstream = new DataOutputStream(fileoutputstream); try { write(nbttagcompound, (DataOutput) dataoutputstream); } catch (Throwable throwable) { try { dataoutputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } dataoutputstream.close(); } catch (Throwable throwable2) { try { fileoutputstream.close(); } catch (Throwable throwable3) { throwable2.addSuppressed(throwable3); } throw throwable2; } fileoutputstream.close(); } @Nullable public static NBTTagCompound read(File file) throws IOException { if (!file.exists()) { return null; } else { FileInputStream fileinputstream = new FileInputStream(file); NBTTagCompound nbttagcompound; try { DataInputStream datainputstream = new DataInputStream(fileinputstream); try { nbttagcompound = read(datainputstream, NBTReadLimiter.UNLIMITED); } catch (Throwable throwable) { try { datainputstream.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } throw throwable; } datainputstream.close(); } catch (Throwable throwable2) { try { fileinputstream.close(); } catch (Throwable throwable3) { throwable2.addSuppressed(throwable3); } throw throwable2; } fileinputstream.close(); return nbttagcompound; } } public static NBTTagCompound read(DataInput datainput) throws IOException { return read(datainput, NBTReadLimiter.UNLIMITED); } public static NBTTagCompound read(DataInput datainput, NBTReadLimiter nbtreadlimiter) throws IOException { // Spigot start if ( datainput instanceof io.netty.buffer.ByteBufInputStream ) { datainput = new DataInputStream(new org.spigotmc.LimitStream((InputStream) datainput, nbtreadlimiter)); } // Spigot end NBTBase nbtbase = readUnnamedTag(datainput, 0, nbtreadlimiter); if (nbtbase instanceof NBTTagCompound) { return (NBTTagCompound) nbtbase; } else { throw new IOException("Root tag must be a named compound tag"); } } public static void write(NBTTagCompound nbttagcompound, DataOutput dataoutput) throws IOException { writeUnnamedTag(nbttagcompound, dataoutput); } public static void parse(DataInput datainput, StreamTagVisitor streamtagvisitor) throws IOException { NBTTagType<?> nbttagtype = NBTTagTypes.getType(datainput.readByte()); if (nbttagtype == NBTTagEnd.TYPE) { if (streamtagvisitor.visitRootEntry(NBTTagEnd.TYPE) == StreamTagVisitor.b.CONTINUE) { streamtagvisitor.visitEnd(); } } else { switch (streamtagvisitor.visitRootEntry(nbttagtype)) { case HALT: default: break; case BREAK: NBTTagString.skipString(datainput); nbttagtype.skip(datainput); break; case CONTINUE: NBTTagString.skipString(datainput); nbttagtype.parse(datainput, streamtagvisitor); } } } public static void writeUnnamedTag(NBTBase nbtbase, DataOutput dataoutput) throws IOException { dataoutput.writeByte(nbtbase.getId()); if (nbtbase.getId() != 0) { dataoutput.writeUTF(""); nbtbase.write(dataoutput); } } private static NBTBase readUnnamedTag(DataInput datainput, int i, NBTReadLimiter nbtreadlimiter) throws IOException { byte b0 = datainput.readByte(); if (b0 == 0) { return NBTTagEnd.INSTANCE; } else { NBTTagString.skipString(datainput); try { return NBTTagTypes.getType(b0).load(datainput, i, nbtreadlimiter); } catch (IOException ioexception) { CrashReport crashreport = CrashReport.forThrowable(ioexception, "Loading NBT data"); CrashReportSystemDetails crashreportsystemdetails = crashreport.addCategory("NBT Tag"); crashreportsystemdetails.setDetail("Tag type", (Object) b0); throw new ReportedException(crashreport); } } } }
3e0fe4404f78273a7b75aec83d7ed3b3fb959f29
3,648
java
Java
src/me/trefis/speedrunduel/Worker.java
etztrefis/SpeedrunDuel
8d4d4fd9dc0c9a5a4bbb56dfbc1a6f39e4fac086
[ "MIT" ]
1
2021-05-27T07:06:07.000Z
2021-05-27T07:06:07.000Z
src/me/trefis/speedrunduel/Worker.java
etztrefis/SpeedrunDuel
8d4d4fd9dc0c9a5a4bbb56dfbc1a6f39e4fac086
[ "MIT" ]
null
null
null
src/me/trefis/speedrunduel/Worker.java
etztrefis/SpeedrunDuel
8d4d4fd9dc0c9a5a4bbb56dfbc1a6f39e4fac086
[ "MIT" ]
null
null
null
38.808511
97
0.562226
6,749
package me.trefis.speedrunduel; import me.trefis.speedrunduel.context.Roles; import org.bukkit.*; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.CompassMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.util.Vector; import java.util.Comparator; import static org.bukkit.Bukkit.getLogger; public class Worker implements Runnable { private final Plugin plugin; private final PlayerData playerData; public Worker(Plugin plugin, PlayerData playerData) { this.plugin = plugin; this.playerData = playerData; } @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { updateCompass(player); } } private void updateCompass(Player player) { Player nearest = getNearest(player); PlayerInventory inv = player.getInventory(); for (int j = 0; j < inv.getSize(); j++) { ItemStack stack = inv.getItem(j); if (stack == null) continue; if (stack.getType() != Material.COMPASS) continue; stack.addUnsafeEnchantment(Enchantment.LUCK, 1); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName("forsenCD"); stack.setItemMeta(meta); } if (nearest == null) { float angle = (float) (Math.random() * Math.PI * 2); float dx = (float) (Math.cos(angle) * 5); float dz = (float) (Math.sin(angle) * 5); for (int j = 0; j < inv.getSize(); j++) { ItemStack stack = inv.getItem(j); if (stack == null) continue; if (stack.getType() != Material.COMPASS) continue; CompassMeta meta = (CompassMeta) stack.getItemMeta(); meta.setLodestone(player.getLocation().add(new Vector(dx, 0, dz))); meta.setLodestoneTracked(false); stack.setItemMeta(meta); } } else { for (int j = 0; j < inv.getSize(); j++) { ItemStack stack = inv.getItem(j); if (stack == null) continue; if (stack.getType() != Material.COMPASS) continue; CompassMeta meta = (CompassMeta) stack.getItemMeta(); meta.setLodestone(nearest.getLocation()); meta.setLodestoneTracked(false); stack.setItemMeta(meta); } } } private Player getNearest (Player player){ Location playerLocation = player.getLocation(); if (playerData.getRole(player) == Roles.LAVA) { return plugin.getServer().getOnlinePlayers().stream() .filter(p -> !p.equals(player)) .filter(p -> playerData.getRole(p) == Roles.WATER) .filter(p -> p.getWorld().equals(player.getWorld())) .min(Comparator.comparing(p -> p.getLocation().distance(playerLocation))) .orElse(null); } else { return plugin.getServer().getOnlinePlayers().stream() .filter(p -> !p.equals(player)) .filter(p -> playerData.getRole(p) == Roles.LAVA) .filter(p -> p.getWorld().equals(player.getWorld())) .min(Comparator.comparing(p -> p.getLocation().distance(playerLocation))) .orElse(null); } } }
3e0fe5714ea8f450ece32663e047b2acac89474d
138
java
Java
PEASUI/src/org/jax/peas/userinterface/Function.java
SiqiT/PEAS
03a79ce7a5934fa07a6070aadcaad07cc60e05a9
[ "MIT" ]
7
2018-12-08T04:55:06.000Z
2020-09-11T01:51:41.000Z
PEASUI/src/org/jax/peas/userinterface/Function.java
SiqiT/PEAS
03a79ce7a5934fa07a6070aadcaad07cc60e05a9
[ "MIT" ]
6
2019-06-27T20:55:39.000Z
2021-10-29T20:43:21.000Z
PEASUI/src/org/jax/peas/userinterface/Function.java
SiqiT/PEAS
03a79ce7a5934fa07a6070aadcaad07cc60e05a9
[ "MIT" ]
1
2021-10-21T03:08:27.000Z
2021-10-21T03:08:27.000Z
15.333333
40
0.782609
6,750
package org.jax.peas.userinterface; import java.io.IOException; public interface Function { public String run() throws IOException; }
3e0fe6acb0df4b25b548ef08ba6fcc2f3c9fcfb2
17
java
Java
Boroica Oana/Roata/src/module-info.java
asdftest45/ttest
c77547312f3c6eae10e9c47ca7e702e35c4cc948
[ "BSD-3-Clause" ]
null
null
null
Boroica Oana/Roata/src/module-info.java
asdftest45/ttest
c77547312f3c6eae10e9c47ca7e702e35c4cc948
[ "BSD-3-Clause" ]
null
null
null
Boroica Oana/Roata/src/module-info.java
asdftest45/ttest
c77547312f3c6eae10e9c47ca7e702e35c4cc948
[ "BSD-3-Clause" ]
null
null
null
5.666667
14
0.647059
6,751
module Roata { }
3e0fe6d8a7506b8ef8b3cd6bb77db3e9282276f9
7,636
java
Java
projects/core/src/test/java/com/opengamma/core/marketdatasnapshot/SnapshotDataBundleTest.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-18T09:32:40.000Z
2021-03-08T20:05:54.000Z
projects/core/src/test/java/com/opengamma/core/marketdatasnapshot/SnapshotDataBundleTest.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
10
2017-01-19T13:32:36.000Z
2021-09-20T20:41:48.000Z
projects/core/src/test/java/com/opengamma/core/marketdatasnapshot/SnapshotDataBundleTest.java
McLeodMoores/starling
7ae0689e06704f78fd9497f8ddb57ee82974a9c8
[ "Apache-2.0" ]
3
2017-12-14T12:46:18.000Z
2020-12-11T19:52:37.000Z
36.018868
128
0.692116
6,752
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. * * Modified by McLeod Moores Software Limited. * * Copyright (C) 2015-Present McLeod Moores Software Limited. All rights reserved. */ package com.opengamma.core.marketdatasnapshot; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.util.Map; import org.testng.annotations.Test; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.test.TestGroup; /** * Tests the {@link SnapshotDataBundle} class. */ @Test(groups = TestGroup.UNIT) public class SnapshotDataBundleTest { private static SnapshotDataBundle createObject() { final SnapshotDataBundle object = new SnapshotDataBundle(); object.setDataPoint(ExternalId.of("Foo", "1"), 1d); object.setDataPoint(ExternalId.of("Foo", "2"), 2d); object.setDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Bar", "Cow")), 3d); object.setDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "4"), ExternalId.of("Bar", "Dog")), 4d); assertEquals(object.size(), 4); return object; } /** * Tests getting data where all ids in the bunch match. */ public void testGetBundleExactMatch() { final SnapshotDataBundle object = createObject(); assertEquals(object.getDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "1"))), 1d, 1e-15); assertEquals(object.getDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Bar", "Cow"))), 3d, 1e-15); } /** * Tests getting data where some ids in the bundle match. */ public void testGetBundlePartialMatch() { final SnapshotDataBundle object = createObject(); assertEquals(object.getDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "2"), ExternalId.of("Missing", "1"))), 2d, 1e-15); } /** * Tests getting where where none of the ids match. */ public void testGetBundleNoMatch() { final SnapshotDataBundle object = createObject(); assertNull(object.getDataPoint(ExternalIdBundle.of(ExternalId.of("Missing", "2"), ExternalId.of("Missing", "1")))); } /** * Tests getting data where the one id matches. */ public void testGetSingleMatch() { final SnapshotDataBundle object = createObject(); assertEquals(object.getDataPoint(ExternalId.of("Foo", "1")), 1d, 1e-15); assertEquals(object.getDataPoint(ExternalId.of("Foo", "4")), 4d, 1e-15); } /** * Tests getting data where no id matches. */ public void testGetSingleNoMatch() { final SnapshotDataBundle object = createObject(); assertNull(object.getDataPoint(ExternalId.of("Missing", "1"))); } /** * Tests overwriting a data point. */ public void testSetBundleErasing() { final SnapshotDataBundle object = createObject(); object.setDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "2"), ExternalId.of("Bar", "Cow")), 42d); assertEquals(object.size(), 3); assertEquals(object.getDataPoint(ExternalId.of("Foo", "1")), 1d, 1e-15); assertEquals(object.getDataPoint(ExternalId.of("Foo", "2")), 42d, 1e-15); assertNull(object.getDataPoint(ExternalId.of("Foo", "3"))); assertEquals(object.getDataPoint(ExternalId.of("Foo", "4")), 4d, 1e-15); } /** * Tests overwriting a data point. */ public void testSetBundleReplacing() { final SnapshotDataBundle object = createObject(); object.setDataPoint(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Bar", "Cow")), 42d); assertEquals(object.size(), 4); assertEquals(object.getDataPoint(ExternalId.of("Foo", "3")), 42d, 1e-15); } /** * Tests overwriting a data point. */ public void testSetSingleReplacing() { final SnapshotDataBundle object = createObject(); object.setDataPoint(ExternalId.of("Foo", "3"), 42d); assertEquals(object.size(), 4); assertEquals(object.getDataPoint(ExternalId.of("Foo", "3")), 42d, 1e-15); assertEquals(object.getDataPoint(ExternalId.of("Bar", "Cow")), 42d, 1e-15); } /** * Tests removal of a point. */ public void testRemoveBundleExact() { final SnapshotDataBundle object = createObject(); object.removeDataPoints(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Bar", "Cow"))); assertEquals(object.size(), 3); assertNull(object.getDataPoint(ExternalId.of("Foo", "3"))); } /** * Tests removal of a point. */ public void testRemoveBundlePartial() { final SnapshotDataBundle object = createObject(); object.removeDataPoints(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Missing", "1"))); assertEquals(object.size(), 3); assertNull(object.getDataPoint(ExternalId.of("Foo", "3"))); } /** * Tests removal of a point. */ public void testRemoveBundleMultiple() { final SnapshotDataBundle object = createObject(); object.removeDataPoints(ExternalIdBundle.of(ExternalId.of("Foo", "3"), ExternalId.of("Bar", "Dog"))); assertEquals(object.size(), 2); assertNull(object.getDataPoint(ExternalId.of("Foo", "3"))); assertNull(object.getDataPoint(ExternalId.of("Foo", "4"))); } /** * Tests removal of a point. */ public void testRemoveSingleDirect() { final SnapshotDataBundle object = createObject(); object.removeDataPoint(ExternalId.of("Foo", "2")); assertEquals(object.size(), 3); assertNull(object.getDataPoint(ExternalId.of("Foo", "2"))); } /** * Tests removal of a point. */ public void testRemoveSingleCascade() { final SnapshotDataBundle object = createObject(); object.removeDataPoint(ExternalId.of("Bar", "Cow")); assertEquals(object.size(), 3); assertNull(object.getDataPoint(ExternalId.of("Bar", "Cow"))); assertNull(object.getDataPoint(ExternalId.of("Foo", "3"))); } /** * Tests setting a data point. */ public void testGetDataPointSet() { final SnapshotDataBundle object = new SnapshotDataBundle(); assertTrue(object.getDataPointSet().isEmpty()); object.setDataPoint(ExternalId.of("Foo", "Bar"), 42d); assertEquals(object.getDataPointSet().size(), 1); final Map.Entry<ExternalIdBundle, Double> e = object.getDataPointSet().iterator().next(); assertEquals(e.getKey(), ExternalIdBundle.of(ExternalId.of("Foo", "Bar"))); assertEquals(e.getValue(), 42d, 1e-15); } /** * Tests the equals method. */ public void testEquals() { final SnapshotDataBundle snap = new SnapshotDataBundle(); snap.setDataPoint(ExternalId.parse("Snap~Test"), 1234.56); final SnapshotDataBundle snap2 = new SnapshotDataBundle(); snap2.setDataPoint(ExternalId.parse("Snap~Test"), 1234.56); final SnapshotDataBundle snap3 = new SnapshotDataBundle(); snap3.setDataPoint(ExternalId.parse("Snap~Test1"), 1234); snap3.setDataPoint(ExternalId.parse("Snap~Test2"), 12340); assertEquals(snap, snap2); assertEquals(snap.hashCode(), snap2.hashCode()); assertNotEquals(snap, snap3); assertNotEquals(snap.hashCode(), snap3.hashCode()); assertNotEquals(null, snap); assertEquals(snap, snap); assertNotEquals(snap.getDataPoints(), snap); } /** * Tests the toString method. */ public void testToString() { final SnapshotDataBundle data = new SnapshotDataBundle(); data.setDataPoint(ExternalId.parse("Snap~Test1"), 1234.56); final String expected = "SnapshotDataBundle[Bundle[Snap~Test1]=1234.56]"; assertEquals(data.toString(), expected); } }
3e0fe6e5f621fe369a647cdaff434df4b5258faf
3,664
java
Java
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/error/AbstractOAuth2SecurityExceptionHandler.java
sangyuruo/spring-security-oauth
bc35ac29368b8962e584608c669affa1607c1d86
[ "Apache-2.0" ]
3
2017-08-17T14:46:47.000Z
2018-08-21T03:30:37.000Z
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/error/AbstractOAuth2SecurityExceptionHandler.java
sangyuruo/spring-security-oauth
bc35ac29368b8962e584608c669affa1607c1d86
[ "Apache-2.0" ]
5
2021-03-16T12:19:05.000Z
2021-03-16T12:19:07.000Z
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/error/AbstractOAuth2SecurityExceptionHandler.java
sangyuruo/spring-security-oauth
bc35ac29368b8962e584608c669affa1607c1d86
[ "Apache-2.0" ]
2
2016-07-02T01:34:43.000Z
2020-12-16T16:12:44.000Z
38.166667
120
0.789574
6,753
/* * Copyright 2006-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * 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.springframework.security.oauth2.provider.error; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; /** * Convenient base class containing utility methods and dependency setters for security error handling concerns specific * to OAuth2 resources. * * @author Dave Syer * */ public abstract class AbstractOAuth2SecurityExceptionHandler { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); private WebResponseExceptionTranslator exceptionTranslator = new DefaultWebResponseExceptionTranslator(); private OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer(); // This is from Spring MVC. private HandlerExceptionResolver handlerExceptionResolver = new DefaultHandlerExceptionResolver(); public void setExceptionTranslator(WebResponseExceptionTranslator exceptionTranslator) { this.exceptionTranslator = exceptionTranslator; } public void setExceptionRenderer(OAuth2ExceptionRenderer exceptionRenderer) { this.exceptionRenderer = exceptionRenderer; } protected final void doHandle(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException, ServletException { try { ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(authException); result = enhanceResponse(result, authException); exceptionRenderer.handleHttpEntityResponse(result, new ServletWebRequest(request, response)); response.flushBuffer(); } catch (ServletException e) { // Re-use some of the default Spring dispatcher behaviour - the exception came from the filter chain and // not from an MVC handler so it won't be caught by the dispatcher (even if there is one) if (handlerExceptionResolver.resolveException(request, response, this, e) == null) { throw e; } } catch (IOException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { // Wrap other Exceptions. These are not expected to happen throw new RuntimeException(e); } } /** * Allow subclasses to manipulate the response before it is rendered. * * @param result the response that was generated by the * {@link #setExceptionTranslator(WebResponseExceptionTranslator) exception translator}. * @param authException the authentication exception that is being handled */ protected ResponseEntity<OAuth2Exception> enhanceResponse(ResponseEntity<OAuth2Exception> result, Exception authException) { return result; } }
3e0fe7515455510a41629d4d50b113aade0c7fac
151
java
Java
src/main/java/com/qkx/test/message/service/MessageService.java
quekx/guice-test
f1c9ace0680f89bc5c0b8c296905ed7540ce8813
[ "Apache-2.0" ]
null
null
null
src/main/java/com/qkx/test/message/service/MessageService.java
quekx/guice-test
f1c9ace0680f89bc5c0b8c296905ed7540ce8813
[ "Apache-2.0" ]
null
null
null
src/main/java/com/qkx/test/message/service/MessageService.java
quekx/guice-test
f1c9ace0680f89bc5c0b8c296905ed7540ce8813
[ "Apache-2.0" ]
null
null
null
16.777778
37
0.708609
6,754
package com.qkx.test.message.service; /** * Created by qkx on 17/4/22. */ public interface MessageService { void sendMessage(String message); }
3e0fe901122aa60a37e4567ab3b0353a7112652c
6,744
java
Java
src/main/java/tokyo/nakanaka/buildVoxCore/particleGui/ParticleGui.java
nakanaka7/BuildVoxCore
2a6dd3a6c992fb63015e36ab422d7bb2a5866f30
[ "MIT" ]
null
null
null
src/main/java/tokyo/nakanaka/buildVoxCore/particleGui/ParticleGui.java
nakanaka7/BuildVoxCore
2a6dd3a6c992fb63015e36ab422d7bb2a5866f30
[ "MIT" ]
null
null
null
src/main/java/tokyo/nakanaka/buildVoxCore/particleGui/ParticleGui.java
nakanaka7/BuildVoxCore
2a6dd3a6c992fb63015e36ab422d7bb2a5866f30
[ "MIT" ]
null
null
null
37.466667
117
0.602758
6,755
package tokyo.nakanaka.buildVoxCore.particleGui; import tokyo.nakanaka.buildVoxCore.Scheduler; import tokyo.nakanaka.buildVoxCore.math.LineSegment3d; import tokyo.nakanaka.buildVoxCore.math.vector.Vector3d; import tokyo.nakanaka.buildVoxCore.math.region3d.Parallelepiped; import tokyo.nakanaka.buildVoxCore.world.World; import java.util.HashSet; import java.util.Set; /** * The object which draws particle lines. Setting a colored particle drawer is needed to spawn particles. */ public class ParticleGui implements AutoCloseable { private ColoredParticleSpawner out = (color, world, x, y, z) -> {}; private Scheduler scheduler; private Set<ParticleSpawnData> spawnDataSet = new HashSet<>(); private boolean drawing; /** * Constructs a new particle drawer. * @param scheduler a scheduler */ public ParticleGui(Scheduler scheduler) { this.scheduler = scheduler; drawing = true; tickTask(); } private static record ParticleSpawnData(Color color, World world, Set<Vector3d> posSet){ } /** * Set the output particle spawner of this drawer. * @param out the output particle spawner. */ public void setOut(ColoredParticleSpawner out){ this.out = out; } /** * Add a line between point 1 and 2. * @param color the color of the line. * @param world the world which the line is in. * @param x1 the x-coordinate of the point 1. * @param y1 the y-coordinate of the point 1. * @param z1 the z-coordinate of the point 1. * @param x2 the x-coordinate of the point 2. * @param y2 the y-coordinate of the point 2. * @param z2 the z-coordinate of the point 2. */ public void addLine(Color color, World world, double x1, double y1, double z1, double x2, double y2, double z2){ Set<Vector3d> posSet = calcParticlePosSetOfLine(new LineSegment3d(x1, y1, z1, x2, y2, z2)); ParticleSpawnData data = new ParticleSpawnData(color, world, posSet); this.spawnDataSet.add(data); } /** * Add lines which are borders of a block(1x1x1 cube). * @param color the color of the lines. * @param world the world which the line is in. * @param x the x-coordinate of the block. * @param y the y-coordinate of the block. * @param z the z-coordinate of the block. */ public void addBlockLines(Color color, World world, int x, int y, int z){ Vector3d p0 = new Vector3d(x, y, z); Vector3d p1 = new Vector3d(x + 0.5, y, z); Vector3d p2 = new Vector3d(x, y + 0.5, z); Vector3d p3 = new Vector3d(x, y, z + 0.5); Vector3d p4 = new Vector3d(x + 1, y, z); Vector3d p5 = new Vector3d(x, y + 1, z); Vector3d p6 = new Vector3d(x, y, z + 1); Vector3d p7 = new Vector3d(x + 1, y + 0.5, z); Vector3d p8 = new Vector3d(x + 1, y, z + 0.5); Vector3d p9 = new Vector3d(x + 0.5, y + 1, z); Vector3d p10 = new Vector3d(x, y + 1, z + 0.5); Vector3d p11 = new Vector3d(x + 0.5, y, z + 1); Vector3d p12 = new Vector3d(x, y + 0.5, z + 1); Vector3d p13 = new Vector3d(x, y + 1, z + 1); Vector3d p14 = new Vector3d(x + 1, y, z + 1); Vector3d p15 = new Vector3d(x + 1, y + 1, z); Vector3d p16 = new Vector3d(x + 0.5, y + 1, z + 1); Vector3d p17 = new Vector3d(x + 1, y + 0.5, z + 1); Vector3d p18 = new Vector3d(x + 1, y + 1, z + 0.5); Vector3d p19 = new Vector3d(x + 1, y + 1, z + 1); ParticleSpawnData data = new ParticleSpawnData(color, world, Set.of(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19)); this.spawnDataSet.add(data); } /** * Add lines which are borders of a parallelepiped. * @param color the color of the lines. * @param world the world which the line is in. * @param parallelepiped the parallelepiped. */ public void addParallelepipedLines(Color color, World world, Parallelepiped parallelepiped){ Set<LineSegment3d> lineSet = new HashSet<>(); Vector3d or = parallelepiped.vectorOR(); Vector3d ra = parallelepiped.vectorRA(); Vector3d rb = parallelepiped.vectorRB(); Vector3d rc = parallelepiped.vectorRC(); Vector3d oa = or.add(ra); Vector3d ob = or.add(rb); Vector3d oc = or.add(rc); Vector3d oad = or.add(rb).add(rc); Vector3d obd = or.add(rc).add(ra); Vector3d ocd = or.add(ra).add(rb); Vector3d ord = or.add(ra).add(rb).add(rc); lineSet.add(new LineSegment3d(or, oa)); lineSet.add(new LineSegment3d(or, ob)); lineSet.add(new LineSegment3d(or, oc)); lineSet.add(new LineSegment3d(oa, obd)); lineSet.add(new LineSegment3d(oa, ocd)); lineSet.add(new LineSegment3d(ob, ocd)); lineSet.add(new LineSegment3d(ob, oad)); lineSet.add(new LineSegment3d(oc, oad)); lineSet.add(new LineSegment3d(oc, obd)); lineSet.add(new LineSegment3d(oad, ord)); lineSet.add(new LineSegment3d(obd, ord)); lineSet.add(new LineSegment3d(ocd, ord)); Set<Vector3d> posSet = new HashSet<>(); for(var line : lineSet){ posSet.addAll(calcParticlePosSetOfLine(line)); } ParticleSpawnData data = new ParticleSpawnData(color, world, posSet); this.spawnDataSet.add(data); } private static Set<Vector3d> calcParticlePosSetOfLine(LineSegment3d line){ Set<Vector3d> set = new HashSet<>(); Vector3d pos1 = line.pos1(); Vector3d pos2 = line.pos2(); Vector3d v21 = pos2.subtract(pos1); if(v21.equals(Vector3d.ZERO)){ set.add(pos1); }else { Vector3d e = v21.normalize(); double d = 0; while (d <= v21.length()) { set.add(pos1.add(e.scalarMultiply(d))); d += 0.5; } } return set; } /** * Clear all the lines. */ public void clearAllLines() { this.spawnDataSet = new HashSet<>(); } /** * Disables the colored particle spawner to spawn particles. This instance will not access the scheduler from the * time when invoking this method. */ @Override public void close(){ drawing = false; } private void tickTask(){ if(!drawing){ return; } for(ParticleSpawnData data : spawnDataSet){ for(Vector3d pos : data.posSet) { out.spawnParticle(data.color, data.world, pos.x(), pos.y(), pos.z()); } } scheduler.schedule(this::tickTask, 5); } }
3e0fe94c96f2e75d37d5496e2ba93a789e0e4aec
15,413
java
Java
src/husaccttest/analyse/java/benchmark/domain/FoursquarealternativeWhrrl.java
senkz/HUSACCT
4888062b1a933c5e8458a6d087a3c6f3781207e7
[ "MIT" ]
null
null
null
src/husaccttest/analyse/java/benchmark/domain/FoursquarealternativeWhrrl.java
senkz/HUSACCT
4888062b1a933c5e8458a6d087a3c6f3781207e7
[ "MIT" ]
null
null
null
src/husaccttest/analyse/java/benchmark/domain/FoursquarealternativeWhrrl.java
senkz/HUSACCT
4888062b1a933c5e8458a6d087a3c6f3781207e7
[ "MIT" ]
1
2021-02-02T12:58:55.000Z
2021-02-02T12:58:55.000Z
42.227397
132
0.815026
6,756
package husaccttest.analyse.java.benchmark.domain; import java.util.HashMap; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; import husacct.common.dto.DependencyDTO; import husaccttest.analyse.java.benchmark.BenchmarkExtended; public class FoursquarealternativeWhrrl extends BenchmarkExtended{ @Test public void testDomainWhrrlBackgroundService(){ String from = "domain.foursquarealternative.whrrl.BackgroundService"; int expectedDependencies = 5; DependencyDTO[] dependencies = super.getOnlyDirectDependencies(service.getDependenciesFrom(from)); // super.printDependencies(dependencies); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.ServiceOne"; int linenumberImport1Expected = 3; String fromDeclaration1Expected = from; String toDeclaration1Expected = "domain.foursquarealternative.yelp.ServiceOne"; String typeDeclaration1Expected = super.DECLARATION; int linenumberDeclaration1Expected = 8; String fromDeclaration2Expected = from; String toDeclaration2Expected = "domain.foursquarealternative.yelp.ServiceOne"; String typeDeclaration2Expected = super.DECLARATION; int linenumberDeclaration2Expected = 9; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyDeclaration1Expected = createDependencyHashmap( fromDeclaration1Expected, toDeclaration1Expected, typeDeclaration1Expected, linenumberDeclaration1Expected); HashMap<String, Object> dependencyDeclaration2Expected = createDependencyHashmap( fromDeclaration2Expected, toDeclaration2Expected, typeDeclaration2Expected, linenumberDeclaration2Expected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundDeclaration1Dependency = compaireDTOWithValues(dependencyDeclaration1Expected, dependencies); boolean foundDeclaration2Dependency = compaireDTOWithValues(dependencyDeclaration2Expected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundDeclaration1Dependency); assertEquals(true, foundDeclaration2Dependency); } @Test public void testDomainWhrrlCheckCastTo(){ String from = "domain.foursquarealternative.whrrl.CheckCastTo"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.SameExtend"; int linenumberImport1Expected = 3; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.SameExtend"; String typeExtendsExpected = super.EXTENDSCONCRETE; int linenumberExtendsExpected = 8; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } @Test public void testDomainWhrrlFrontService(){ String from = "domain.foursquarealternative.whrrl.FrontService"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.IYelp"; int linenumberImport1Expected = 3; String fromDeclarationExpected = from; String toDeclarationExpected = "domain.foursquarealternative.yelp.IYelp"; String typeDeclarationExpected = super.DECLARATION; int linenumberDeclarationExpected = 8; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyDeclarationExpected = createDependencyHashmap( fromDeclarationExpected, toDeclarationExpected, typeDeclarationExpected, linenumberDeclarationExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundDeclarationDependency = compaireDTOWithValues(dependencyDeclarationExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundDeclarationDependency); HashMap<String, Object> indirectImportExpected = createDependencyHashmap( from, "domain.foursquarealternative.brightkite.IMap", super.IMPORT, 3, true); HashMap<String, Object> indirectImplementsExpected = createDependencyHashmap( from, "domain.foursquarealternative.brightkite.IMap", super.EXTENDSINTERFACE, 7, true); boolean foundindirectImport = compaireDTOWithValues(indirectImportExpected, dependencies); boolean foundindirectImplements = compaireDTOWithValues(indirectImplementsExpected, dependencies); // assertEquals(true, foundindirectImport); // assertEquals(true, foundindirectImplements); } @Test public void testDomainWhrrlIWhrrl(){ String from = "domain.foursquarealternative.whrrl.IWhrrl"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.IPreferences"; int linenumberImport1Expected = 3; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.yelp.IPreferences"; String typeExtendsExpected = super.EXTENDSINTERFACE; int linenumberExtendsExpected = 8; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } @Test public void testDomainWhrrlMapsService(){ String from = "domain.foursquarealternative.whrrl.MapsService"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.POI"; int linenumberImport1Expected = 2; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.yelp.POI"; String typeExtendsExpected = super.EXTENDSABSTRACT; int linenumberExtendsExpected = 6; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } @Ignore ("Cant analyse because class element is not defined") @Test public void testDomainWhrrlProfile(){ String from = "domain.foursquarealternative.whrrl.Profile"; int expectedDependencies = 1; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.IPreferences"; int linenumberImport1Expected = 2; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); assertEquals(true, foundImport1Dependency); } @Test public void testDomainWhrrlTips(){ String from = "domain.foursquarealternative.whrrl.Tips"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.POI"; int linenumberImport1Expected = 3; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.yelp.POI"; String typeExtendsExpected = super.EXTENDSABSTRACT; int linenumberExtendsExpected = 7; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } @Test public void testDomainWhrrlWhrrl(){ String from = "domain.foursquarealternative.whrrl.Whrrl"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.IPreferences"; int linenumberImport1Expected = 3; String fromImplementsExpected = from; String toImplementsExpected = "domain.foursquarealternative.yelp.IPreferences"; String typeImplementsExpected = super.IMPLEMENTS; int linenumberImplementsExpected = 8; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyImplementsExpected = createDependencyHashmap( fromImplementsExpected, toImplementsExpected, typeImplementsExpected, linenumberImplementsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundImplementsDependency = compaireDTOWithValues(dependencyImplementsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundImplementsDependency); } @Test public void testDomainWhrrlWhrrlComment(){ String from = "domain.foursquarealternative.whrrl.WhrrlComment"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.YelpComment"; int linenumberImport1Expected = 3; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.yelp.YelpComment"; String typeExtendsExpected = super.EXTENDSABSTRACT; int linenumberExtendsExpected = 7; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } @Test public void testDomainWhrrlWhrrlFuture(){ String from = "domain.foursquarealternative.whrrl.WhrrlFuture"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.MyFuture"; int linenumberImport1Expected = 3; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); assertEquals(true, foundImport1Dependency); HashMap<String, Object> indirectImportExpected = createDependencyHashmap( from, "domain.foursquarealternative.brightkite.IFuture", super.IMPORT, 3, true); HashMap<String, Object> indirectImplementsExpected = createDependencyHashmap( from, "domain.foursquarealternative.brightkite.IFuture", super.IMPLEMENTS, 7, true); boolean foundindirectImport = compaireDTOWithValues(indirectImportExpected, dependencies); boolean foundindirectImplements = compaireDTOWithValues(indirectImplementsExpected, dependencies); // assertEquals(true, foundindirectImport); // assertEquals(true, foundindirectImplements); } @Test public void testDomainWhrrlWhrrlHistory(){ String from = "domain.foursquarealternative.whrrl.WhrrlHistory"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.MyHistory"; int linenumberImport1Expected = 3; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); assertEquals(true, foundImport1Dependency); } @Test public void testDomainWhrrlWhrrlSettings(){ String from = "domain.foursquarealternative.whrrl.WhrrlSettings"; int expectedDependencies = 2; DependencyDTO[] dependencies = service.getDependenciesFrom(from); assertEquals(expectedDependencies, dependencies.length); String toImport1Expected = "domain.foursquarealternative.yelp.Yelp"; int linenumberImport1Expected = 3; String fromExtendsExpected = from; String toExtendsExpected = "domain.foursquarealternative.yelp.Yelp"; String typeExtendsExpected = super.EXTENDSABSTRACT; int linenumberExtendsExpected = 7; HashMap<String, Object> dependencyImport1Expected = super.createImportHashmap(from, toImport1Expected, linenumberImport1Expected); HashMap<String, Object> dependencyExtendsExpected = createDependencyHashmap( fromExtendsExpected, toExtendsExpected, typeExtendsExpected, linenumberExtendsExpected); boolean foundImport1Dependency = compaireDTOWithValues(dependencyImport1Expected, dependencies); boolean foundExtendsDependency = compaireDTOWithValues(dependencyExtendsExpected, dependencies); assertEquals(true, foundImport1Dependency); assertEquals(true, foundExtendsDependency); } }
3e0fe952507d8bd305c02a33c97ec143b4ca304a
4,427
java
Java
src/main/java/com/ocesclade/amisdeescalade/entities/Topo.java
rvallet/amis-de-escalade
971523baf6c46929bff2be5840c711da6f2e4a30
[ "MIT" ]
1
2020-07-15T13:41:32.000Z
2020-07-15T13:41:32.000Z
src/main/java/com/ocesclade/amisdeescalade/entities/Topo.java
rvallet/amis-de-escalade
971523baf6c46929bff2be5840c711da6f2e4a30
[ "MIT" ]
null
null
null
src/main/java/com/ocesclade/amisdeescalade/entities/Topo.java
rvallet/amis-de-escalade
971523baf6c46929bff2be5840c711da6f2e4a30
[ "MIT" ]
null
null
null
21.181818
118
0.690761
6,757
package com.ocesclade.amisdeescalade.entities; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity @Table(name="topo") public class Topo implements Serializable { private static final long serialVersionUID = 9115889704052440473L; @Id @Column(name="id_topo") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @NotNull @Size(min = 1, max = 75) private String name; @NotNull @Size(min = 1, max = 1000) private String description; private String shortDescription; private String location; private Date releaseDate; private Boolean isAvailableForLoan; private String belongTo; private Boolean isOnline; private String imgPathThAttribute; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_user") private User user; @OneToMany(mappedBy = "topo", fetch = FetchType.LAZY) private Collection<TopoLoan> topoLoan; public Topo() { super(); this.name=""; this.description=""; this.isOnline=false; this.releaseDate = new Date(); } public Topo(@NotNull @Size(min = 1, max = 75) String name, @NotNull @Size(min = 1, max = 1000) String description, String location, Boolean isAvailableForLoan, String belongTo, User user) { super(); this.name = name; this.description = description; this.location = location; this.releaseDate = new Date(); this.isAvailableForLoan = isAvailableForLoan; this.isOnline=true; this.belongTo = belongTo; this.user = user; this.setShortDescription(description); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public Boolean getIsAvailableForLoan() { return isAvailableForLoan; } public void setIsAvailableForLoan(Boolean isAvailableForLoan) { this.isAvailableForLoan = isAvailableForLoan; } public String getBelongTo() { return belongTo; } public void setBelongTo(String belongTo) { this.belongTo = belongTo; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription.length() > 75 ? shortDescription.substring(0, 72)+"...": shortDescription; } public Collection<TopoLoan> getTopoLoan() { return topoLoan; } public void setTopoLoan(Collection<TopoLoan> topoLoan) { this.topoLoan = topoLoan; } public Boolean getIsOnline() { return isOnline; } public void setIsOnline(Boolean isOnline) { this.isOnline = isOnline; } public String getImgPathThAttribute() { return imgPathThAttribute; } public void setImgPathThAttribute(String imgPathThAttribute) { this.imgPathThAttribute = imgPathThAttribute; } @Override public String toString() { return "Topo [id=" + id + ", name=" + name + ", description=" + description + ", shortDescription=" + shortDescription + ", location=" + location + ", releaseDate=" + releaseDate + ", isAvailableForLoan=" + isAvailableForLoan + ", belongTo=" + belongTo + ", isOnline=" + isOnline + ", imgPathThAttribute=" + imgPathThAttribute + ", user=" + user + ", topoLoan=" + topoLoan + "]"; } }
3e0fe95770185090c4938c278c7fae9d16163e47
1,506
java
Java
app/src/main/java/com/weygo/weygophone/pages/tabs/home/widget/WGHomeContentFloorTitleView.java
mumabinggan/WeygoPhone
15b6eb23160b010dc399fe54c923c48c6a0b737d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/weygo/weygophone/pages/tabs/home/widget/WGHomeContentFloorTitleView.java
mumabinggan/WeygoPhone
15b6eb23160b010dc399fe54c923c48c6a0b737d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/weygo/weygophone/pages/tabs/home/widget/WGHomeContentFloorTitleView.java
mumabinggan/WeygoPhone
15b6eb23160b010dc399fe54c923c48c6a0b737d
[ "Apache-2.0" ]
null
null
null
29.529412
107
0.719124
6,758
package com.weygo.weygophone.pages.tabs.home.widget; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.widget.TextView; import com.weygo.common.base.JHRelativeLayout; import com.weygo.common.tools.JHStringUtils; import com.weygo.weygophone.R; import com.weygo.weygophone.pages.tabs.home.model.WGHomeFloorItem; /** * Created by muma on 2017/6/4. */ public class WGHomeContentFloorTitleView extends JHRelativeLayout { TextView mNameTV; TextView mBreifDesTV; public WGHomeContentFloorTitleView(Context context) { super(context); } public WGHomeContentFloorTitleView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public WGHomeContentFloorTitleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onFinishInflate() { super.onFinishInflate(); mNameTV = (TextView) findViewById(R.id.nameTV); mBreifDesTV = (TextView) findViewById(R.id.breifDesTV); } public void showWithData(Object data) { if (data instanceof WGHomeFloorItem) { WGHomeFloorItem item = (WGHomeFloorItem) data; mNameTV.setText(item.name); mBreifDesTV.setText(item.breifDescription); mBreifDesTV.setVisibility(JHStringUtils.isNullOrEmpty(item.breifDescription) ? GONE : VISIBLE); } } }
3e0fe9ab2aee86e652ce7df6c104c8173bab1137
11,301
java
Java
app/src/main/java/com/marverenic/music/viewmodel/NowPlayingControllerViewModel.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/marverenic/music/viewmodel/NowPlayingControllerViewModel.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/marverenic/music/viewmodel/NowPlayingControllerViewModel.java
stefb965/Jockey
0466ef6790f9666fcdee5dffec133a06e2a3eafc
[ "Apache-2.0" ]
null
null
null
33.936937
99
0.619591
6,759
package com.marverenic.music.viewmodel; import android.content.Context; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.databinding.BindingAdapter; import android.databinding.ObservableInt; import android.graphics.drawable.Drawable; import android.os.Handler; import android.support.annotation.ColorInt; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v7.widget.PopupMenu; import android.view.Gravity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import com.marverenic.music.BR; import com.marverenic.music.JockeyApplication; import com.marverenic.music.R; import com.marverenic.music.activity.instance.AlbumActivity; import com.marverenic.music.activity.instance.ArtistActivity; import com.marverenic.music.data.store.MusicStore; import com.marverenic.music.data.store.ThemeStore; import com.marverenic.music.dialog.AppendPlaylistDialogFragment; import com.marverenic.music.fragments.BaseFragment; import com.marverenic.music.model.Song; import com.marverenic.music.player.PlayerController; import javax.inject.Inject; import timber.log.Timber; public class NowPlayingControllerViewModel extends BaseObservable { private static final String TAG_PLAYLIST_DIALOG = "AppendPlaylistDialog"; private Context mContext; private FragmentManager mFragmentManager; @Inject MusicStore mMusicStore; @Inject ThemeStore mThemeStore; @Inject PlayerController mPlayerController; @Nullable private Song mSong; private boolean mPlaying; private int mDuration; private boolean mUserTouchingProgressBar; private Animation mSeekBarThumbAnimation; private final ObservableInt mSeekbarPosition; private final ObservableInt mCurrentPositionObservable; public NowPlayingControllerViewModel(BaseFragment fragment) { mContext = fragment.getContext(); mFragmentManager = fragment.getFragmentManager(); mCurrentPositionObservable = new ObservableInt(); mSeekbarPosition = new ObservableInt(); JockeyApplication.getComponent(mContext).inject(this); mPlayerController.getCurrentPosition() .compose(fragment.bindToLifecycle()) .subscribe( position -> { mCurrentPositionObservable.set(position); if (!mUserTouchingProgressBar) { mSeekbarPosition.set(position); } }, throwable -> { Timber.e(throwable, "failed to update position"); }); mPlayerController.getNowPlaying() .compose(fragment.bindToLifecycle()) .subscribe(this::setSong, throwable -> Timber.e(throwable, "Failed to set song")); mPlayerController.isPlaying() .compose(fragment.bindToLifecycle()) .subscribe(this::setPlaying, throwable -> Timber.e(throwable, "Failed to set playing")); mPlayerController.getDuration() .compose(fragment.bindToLifecycle()) .subscribe(this::setDuration, throwable -> Timber.e(throwable, "Failed to set duration")); } private void setSong(@Nullable Song song) { mSong = song; notifyPropertyChanged(BR.songTitle); notifyPropertyChanged(BR.artistName); notifyPropertyChanged(BR.albumName); notifyPropertyChanged(BR.positionVisibility); notifyPropertyChanged(BR.seekbarEnabled); } private void setPlaying(boolean playing) { mPlaying = playing; notifyPropertyChanged(BR.togglePlayIcon); } private void setDuration(int duration) { mDuration = duration; notifyPropertyChanged(BR.songDuration); } @Bindable public String getSongTitle() { if (mSong == null) { return mContext.getResources().getString(R.string.nothing_playing); } else { return mSong.getSongName(); } } @Bindable public String getArtistName() { if (mSong == null) { return mContext.getResources().getString(R.string.unknown_artist); } else { return mSong.getArtistName(); } } @Bindable public String getAlbumName() { if (mSong == null) { return mContext.getString(R.string.unknown_album); } else { return mSong.getAlbumName(); } } @Bindable public int getSongDuration() { return mDuration; } @Bindable public boolean getSeekbarEnabled() { return mSong != null; } @Bindable public Drawable getTogglePlayIcon() { if (mPlaying) { return ContextCompat.getDrawable(mContext, R.drawable.ic_pause_36dp); } else { return ContextCompat.getDrawable(mContext, R.drawable.ic_play_arrow_36dp); } } public ObservableInt getSeekBarPosition() { return mSeekbarPosition; } public ObservableInt getCurrentPosition() { return mCurrentPositionObservable; } @Bindable public int getPositionVisibility() { if (mSong == null) { return View.INVISIBLE; } else { return View.VISIBLE; } } @ColorInt public int getSeekBarHeadTint() { return mThemeStore.getAccentColor(); } @Bindable public int getSeekBarHeadVisibility() { if (mUserTouchingProgressBar) { return View.VISIBLE; } else { return View.INVISIBLE; } } @Bindable public Animation getSeekBarHeadAnimation() { Animation animation = mSeekBarThumbAnimation; mSeekBarThumbAnimation = null; return animation; } private void animateSeekBarHeadOut() { mSeekBarThumbAnimation = AnimationUtils.loadAnimation(mContext, R.anim.slider_thumb_out); mSeekBarThumbAnimation.setInterpolator(mContext, android.R.interpolator.accelerate_quint); notifyPropertyChanged(BR.seekBarHeadAnimation); long duration = mSeekBarThumbAnimation.getDuration(); new Handler().postDelayed(() -> notifyPropertyChanged(BR.seekBarHeadVisibility), duration); } private void animateSeekBarHeadIn() { mSeekBarThumbAnimation = AnimationUtils.loadAnimation(mContext, R.anim.slider_thumb_in); mSeekBarThumbAnimation.setInterpolator(mContext, android.R.interpolator.decelerate_quint); notifyPropertyChanged(BR.seekBarHeadAnimation); notifyPropertyChanged(BR.seekBarHeadVisibility); } @Bindable public float getSeekBarHeadMarginLeft() { return mSeekbarPosition.get() / (float) getSongDuration(); } public View.OnClickListener onMoreInfoClick() { return v -> { if (mSong == null) { return; } PopupMenu menu = new PopupMenu(mContext, v, Gravity.END); menu.inflate(mSong.isInLibrary() ? R.menu.instance_song_now_playing : R.menu.instance_song_now_playing_remote); menu.setOnMenuItemClickListener(onMoreInfoItemClick(mSong)); menu.show(); }; } private PopupMenu.OnMenuItemClickListener onMoreInfoItemClick(Song song) { return item -> { switch (item.getItemId()) { case R.id.menu_item_navigate_to_artist: mMusicStore.findArtistById(song.getArtistId()).take(1).subscribe( artist -> { mContext.startActivity(ArtistActivity.newIntent(mContext, artist)); }, throwable -> { Timber.e(throwable, "Failed to find artist"); }); return true; case R.id.menu_item_navigate_to_album: mMusicStore.findAlbumById(song.getAlbumId()).take(1).subscribe( album -> { mContext.startActivity(AlbumActivity.newIntent(mContext, album)); }, throwable -> { Timber.e(throwable, "Failed to find album"); }); return true; case R.id.menu_item_add_to_playlist: new AppendPlaylistDialogFragment.Builder(mContext, mFragmentManager) .setSongs(song) .showSnackbarIn(R.id.now_playing_artwork) .show(TAG_PLAYLIST_DIALOG); return true; } return false; }; } public View.OnClickListener onSkipNextClick() { return v -> mPlayerController.skip(); } public View.OnClickListener onSkipBackClick() { return v -> mPlayerController.previous(); } public View.OnClickListener onTogglePlayClick() { return v -> mPlayerController.togglePlay(); } public OnSeekBarChangeListener onSeek() { return new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mSeekbarPosition.set(progress); if (fromUser) { notifyPropertyChanged(BR.seekBarHeadMarginLeft); if (!mUserTouchingProgressBar) { // For keyboards and non-touch based things onStartTrackingTouch(seekBar); onStopTrackingTouch(seekBar); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mUserTouchingProgressBar = true; animateSeekBarHeadIn(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { mUserTouchingProgressBar = false; animateSeekBarHeadOut(); mPlayerController.seek(seekBar.getProgress()); mCurrentPositionObservable.set(seekBar.getProgress()); } }; } @BindingAdapter("onSeekListener") public static void bindOnSeekListener(SeekBar seekBar, OnSeekBarChangeListener listener) { seekBar.setOnSeekBarChangeListener(listener); } @BindingAdapter("marginLeft_percent") public static void bindPercentMarginLeft(View view, float percent) { View parent = (View) view.getParent(); int leftOffset = (int) (parent.getWidth() * percent) - view.getWidth() / 2; leftOffset = Math.min(leftOffset, parent.getWidth() - view.getWidth()); leftOffset = Math.max(leftOffset, 0); BindingAdapters.bindLeftMargin(view, leftOffset); } }
3e0feb7b18663d08ebcc1e8ed3968ae9e40e2751
6,005
java
Java
legacy/src/advantra/shapes/Point.java
miroslavradojevic/advantra
a678c8ebae8e385ba81b82e2f918054d460e0650
[ "MIT" ]
null
null
null
legacy/src/advantra/shapes/Point.java
miroslavradojevic/advantra
a678c8ebae8e385ba81b82e2f918054d460e0650
[ "MIT" ]
null
null
null
legacy/src/advantra/shapes/Point.java
miroslavradojevic/advantra
a678c8ebae8e385ba81b82e2f918054d460e0650
[ "MIT" ]
null
null
null
28.459716
123
0.636303
6,760
package advantra.shapes; import advantra.general.ArrayHandling; import advantra.general.ImageConversions; import ij.process.ColorProcessor; import ij.ImagePlus; public class Point extends RegionOfInterest { public Point(){ // dummy construction super(0, 0, 0); this.roi_type = RoiType.POINT; } public Point(double x, double y, double z){ super(x, y, z); this.roi_type = RoiType.POINT; } public Point(double[] p){ super(p[0], p[1], p[2]); this.roi_type = RoiType.POINT; } public void setPoint(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } /* ################################## * EXTRACTION METHODS * ################################## */ /* ################################## * GRAPHICS * ################################## */ public void drawOverColorImageStack(ImagePlus template_image, int r, int g, int b){ if(template_image.getStack().getSize()==1){ System.err.println("Point:drawOverColorImageStack() takes image stack as argument!"); System.exit(1); } if((template_image.getType()!=ImagePlus.COLOR_RGB)){ template_image = ImageConversions.ImagePlusToRGB(template_image); System.out.println("converting ImagePlus to rgb..."); } int pt_x = (int) Math.round(x); int pt_y = (int) Math.round(y); int pt_z = (int) Math.round(z); boolean isIn = pt_x>=0 && pt_x <=template_image.getHeight()-1 && pt_y>=0 && pt_y <=template_image.getWidth()-1 && pt_z>=0 && pt_z <=template_image.getStack().getSize()-1; if(isIn){ int w = template_image.getWidth(); byte[] rgb_values = new byte[]{(byte)r, (byte)g, (byte)b}; byte[][][] img_array = ImageConversions.RgbToByteArray(template_image); img_array[0][pt_z][ArrayHandling.sub2index_2d(pt_x, pt_y, w)] = rgb_values[0]; img_array[1][pt_z][ArrayHandling.sub2index_2d(pt_x, pt_y, w)] = rgb_values[1]; img_array[2][pt_z][ArrayHandling.sub2index_2d(pt_x, pt_y, w)] = rgb_values[2]; for (int i = 1; i <= template_image.getStack().getSize(); i++) { ((ColorProcessor)template_image.getStack().getProcessor(i)).setRGB( img_array[0][i-1], img_array[1][i-1], img_array[2][i-1] ); } }else{ System.out.println("Point:drawOverColorImageStack()\n" + "Point was out of the image to be drawn!"); } } public static void drawOverColorImageStack( Point[] pts, ImagePlus template_image, int r, int g, int b){ for (int i = 0; i < pts.length; i++) { pts[i].drawOverColorImageStack(template_image, r, g, b); } } public ImagePlus drawOverGrayImageStack(ImagePlus template_image, int valueToDraw){ int wt = template_image.getStack().getWidth(); // check if it's grey image if(template_image.getType()==ImagePlus.GRAY8){ // expects 0-255 8-bit scale valueToDraw = (valueToDraw>255) ? 255 : valueToDraw ; valueToDraw = (valueToDraw< 0) ? 0 : valueToDraw ; } else if(template_image.getType()==ImagePlus.GRAY16){ // expects 0-65,535 16-bit scale valueToDraw = (valueToDraw>65535) ? 65535 : valueToDraw ; valueToDraw = (valueToDraw< 0 ) ? 0 : valueToDraw ; } else{ System.err.println("Point:drawOverImage()\nthis image format is not suported - possible to use gray8, gray16 or rgb!"); System.exit(-1); } int[][] template_image_array = ImageConversions.GraytoIntArray(template_image); int pt_x = (int) Math.round(x); int pt_y = (int) Math.round(y); int pt_z = (int) Math.round(z); boolean isIn = pt_x>=0 && pt_x <=template_image.getHeight()-1 && pt_y>=0 && pt_y <=template_image.getWidth()-1 && pt_z>=0 && pt_z <=template_image.getStack().getSize()-1; if(isIn){ template_image_array[pt_z][pt_y+pt_x*wt] = valueToDraw; }else{ System.out.println("Point:drawOverImage()\nThere was not enough points to draw anything!"); } // to ImagePlus if(template_image.getType()==ImagePlus.GRAY8){ return ImageConversions.toGray8(template_image_array, wt); } else if(template_image.getType()==ImagePlus.GRAY16){ return ImageConversions.toGray16(template_image_array, wt); } else{ System.err.println("Sphere:drawOverImage(): this image format is not suported - possible to use gray8, gray16 or rgb!"); System.exit(-1); return ImageConversions.toGray8(template_image_array, wt); // just a dummy line to avoid error } } } // public void drawOverColorImage(ImagePlus template_image, int valueToDraw){ // // int w = template_image.getWidth(); // // if((template_image.getType()!=ImagePlus.COLOR_RGB)){ // // set it to rgb // template_image = ImageConversions.ImagePlusToRGB(template_image); // System.out.println("converting ImagePlus to rgb..."); // } // // byte[] rgb_values = ColourTransf.Jet256(valueToDraw); // // byte[][][] img_array = ImageConversions.RgbToByteArray(template_image); // // // extract the points // int[][] cyl_coordinates = new int[3][Sphere.numberOfVoxInSphere((int)Math.ceil(r))]; // // int cnt = this.extractCoords(template_image, cyl_coordinates); // // if(cnt>0){ // // // change the spots, assign them with valueToDraw // for (int i = 0; i < cnt; i++) { // // int row = cyl_coordinates[0][i]; // int col = cyl_coordinates[1][i]; // int layer = cyl_coordinates[2][i]; // // img_array[0][layer][ArrayHandling.sub2index_2d(row, col, w)] = rgb_values[0]; // img_array[1][layer][ArrayHandling.sub2index_2d(row, col, w)] = rgb_values[1]; // img_array[2][layer][ArrayHandling.sub2index_2d(row, col, w)] = rgb_values[2]; // } // // }else{ // // System.out.println("Sphere:drawOverImage()\nThere was not enough points to draw anything!"); // // } // // for (int i = 1; i <= template_image.getStack().getSize(); i++) { // // ((ColorProcessor)template_image.getStack().getProcessor(i)).setRGB( // img_array[0][i-1], // img_array[1][i-1], // img_array[2][i-1] // ); // } // // }
3e0fed6fb74531deb661d974dd6b0787c5a10806
37,890
java
Java
app/src/main/java/com/smart/cloud/fire/retrofit/ApiStores.java
bingo1118/kaipingMS
76da24fbdebcbd7d1ff4bfa79335ca67f374c773
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/smart/cloud/fire/retrofit/ApiStores.java
bingo1118/kaipingMS
76da24fbdebcbd7d1ff4bfa79335ca67f374c773
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/smart/cloud/fire/retrofit/ApiStores.java
bingo1118/kaipingMS
76da24fbdebcbd7d1ff4bfa79335ca67f374c773
[ "Apache-2.0" ]
null
null
null
59.481947
186
0.63592
6,761
package com.smart.cloud.fire.retrofit; import com.smart.cloud.fire.activity.AssetManage.Tag.TagListEntity; import com.smart.cloud.fire.global.AllAssetListEntity; import com.smart.cloud.fire.global.AssetListEntity; import com.smart.cloud.fire.global.AssetManager; import com.smart.cloud.fire.global.CheckListEntity; import com.smart.cloud.fire.global.ChuangAnValue; import com.smart.cloud.fire.global.Electric; import com.smart.cloud.fire.global.ElectricInfo; import com.smart.cloud.fire.global.ElectricValue; import com.smart.cloud.fire.global.ProofGasHistoryEntity; import com.smart.cloud.fire.global.SafeScore; import com.smart.cloud.fire.global.SmokeSummary; import com.smart.cloud.fire.global.TagAlarmListEntity; import com.smart.cloud.fire.global.TemperatureTime; import com.smart.cloud.fire.mvp.fragment.ConfireFireFragment.ConfireFireModel; import com.smart.cloud.fire.mvp.fragment.MapFragment.HttpAreaResult; import com.smart.cloud.fire.mvp.fragment.MapFragment.HttpError; import com.smart.cloud.fire.mvp.login.model.LoginModel; import com.smart.cloud.fire.mvp.register.model.RegisterModel; import com.smart.cloud.fire.order.OrderInfoDetail.HttpOrderInfoEntity; import com.smart.cloud.fire.order.OrderList.HttpOrderListEntity; import java.util.List; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.adapter.rxjava.Result; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.Query; import rx.Observable; public interface ApiStores { //登录技威服务器 @FormUrlEncoded @POST("Users/LoginCheck.ashx") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<LoginModel> loginYooSee(@Field("User") String User, @Field("Pwd") String Pwd, @Field("VersionFlag") String VersionFlag, @Field("AppOS") String AppOS, @Field("AppVersion") String AppVersion); //登录本地服务器 @GET("login") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<LoginModel> login(@Query("userId") String userId); //登录本地服务器2,登陆新接口2017.5.16 @GET("login") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<LoginModel> login2(@Query("userId") String userId,@Query("pwd") String pwd ,@Query("cid") String cid,@Query("appId") String appId,@Query("ifregister") String ifregister); //获取短信验证码 @FormUrlEncoded @POST("Users/PhoneCheckCode.ashx") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<RegisterModel> getMesageCode(@Field("CountryCode") String countryCode, @Field("PhoneNO") String phoneNO , @Field("AppVersion") String appVersion); //检查短信验证码 @FormUrlEncoded @POST("Users/PhoneVerifyCodeCheck.ashx") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<RegisterModel> verifyPhoneCode(@Field("CountryCode") String countryCode,@Field("PhoneNO") String phoneNO ,@Field("VerifyCode") String verifyCode); //注册 @FormUrlEncoded @POST("Users/RegisterCheck.ashx") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<RegisterModel> register(@Field("VersionFlag") String versionFlag,@Field("Email") String email ,@Field("CountryCode") String countryCode,@Field("PhoneNO") String phoneNO ,@Field("Pwd") String pwd,@Field("RePwd") String rePwd ,@Field("VerifyCode") String verifyCode,@Field("IgnoreSafeWarning") String ignoreSafeWarning); //获取用户所有的烟感 @GET("getAllSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllSmoke(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //获取用户所有故障烟感 @GET("getAllDetailSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllDetailSmoke(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page,@Query("type") String type); //获取用户所有的有线终端@@6.29 @GET("getAllFaultinfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllFaultinfo(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //获取用户所有的有线终端下的烟感@@6.29 @GET("getEquipmentOfOneRepeater") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getEquipmentOfOneRepeater(@Query("userId") String userId, @Query("repeater") String repeater,@Query("page") String page); //获取用户某个烟感的历史报警记录@@7.3 // @GET("getAlarmOfRepeater") // @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") // Observable<HttpError> getAlarmOfRepeater(@Query("userId") String userId, @Query("repeater") String repeater // ,@Query("smokeMac") String smokeMac,@Query("startTime") String startTime // ,@Query("endTime") String endTime,@Query("page") String page,@Query("faultDesc") String faultDesc); //获取用户某个烟感的历史报警记录@@7.3 @FormUrlEncoded @POST("getAlarmOfRepeater") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAlarmOfRepeater(@Field("userId") String userId, @Field("repeater") String repeater ,@Field("smokeMac") String smokeMac,@Field("startTime") String startTime ,@Field("endTime") String endTime,@Field("page") String page,@Field("faultDesc") String faultDesc); //获取用户所有的设备 @GET("getAllDevice") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllDevice(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); // @FormUrlEncoded // @POST("getAllSmoke") // @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") // Observable<HttpError> getAllSmoke(@Field("userId") String userId, @Field("privilege") String privilege,@Field("page") String page); //获取用户所有的摄像头 @GET("getAllCamera") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllCamera(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //获取所有的店铺类型 @GET("getPlaceTypeId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getPlaceTypeId(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //获取所有的NFC设备类型 @GET("getNFCDeviceTypeId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNFCDeviceTypeId(); //获取所有的巡检设备类型 @GET("getNFCType") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNFCType(); //获取所有的巡检点类型 @GET("getPoints") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getPoints(@Query("userId") String userId, @Query("areaId") String areaId); //获取区域下的管理员 @GET("getManagersByAreaId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getManagersByAreaId(@Query("areaId") String areaId); //获取查找的巡检点类型 @GET("getItemsByName") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItemsByName(@Query("userId") String userId,@Query("pid") String pid, @Query("deviceName") String areaId); //获取查找任务中的巡检点类型 @GET("getItemsByName2") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItemsByName2(@Query("pid") String pid, @Query("deviceName") String areaId); //获取所有的巡检任务 @GET("getTasks") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getTasks(@Query("userId") String userId,@Query("tlevel") String tlevel ,@Query("state") String state,@Query("startDate") String startDate ,@Query("endDate") String endDate); //获取所有的巡检任务 @GET("getTaskCount") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getTaskCount(@Query("userId") String userId); //获取所有的巡检点下的巡检项目 @GET("getItemsByPid") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItemsByPid(@Query("pid") String pid); //获取所有的巡检项目的巡检历史 @GET("getRecordList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getRecordList(@Query("uid") String uid); @GET("getNoticeByUserId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNoticeByUserId(@Query("userId") String userId); //获取用户名下的巡检项目 @GET("getAllItems") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllItems(@Query("userId") String userid,@Query("pid") String pid); //获取用户名下的巡检项目 @GET("getItemsList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItemsList(@Query("userId") String userid,@Query("status") String status,@Query("taskType") String taskType); //获取用户名下的巡检项目 @GET("getItemInfoByAreaId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItemInfoByAreaId(@Query("userId") String userid,@Query("areaId") String areaId); //获取所有的巡检点下的巡检项目 @GET("getItems") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getItems(@Query("tid") String pid,@Query("state") String state); //获取所有的区域类型 @GET("getAreaId") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpAreaResult> getAreaId(@Query("userId") String userId, @Query("privilege") String privilege, @Query("page") String page); //根据条件查询用户烟感 @GET("getNeedSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedSmoke(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId); //根据条件查询用户设备 @GET("getNeedDev") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedDev(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId,@Query("devType") String devType); //根据条件查询资产盘点列表数据 @GET("getACheckList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<CheckListEntity> getACheckList(@Query("userId") String userId, @Query("privilege") String privilege, @Query("stateName") String page); //根据条件查询资产盘点清单 @GET("getAssetByCkey") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<AssetListEntity> getAssetByCkey(@Query("ckey") String ckey, @Query("atPid") String atPid, @Query("ifFinish") String ifFinish, @Query("startTime") String startTime, @Query("endTime") String endTime); //根据条件查询标签清单 @GET("getTagList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TagListEntity> getTagList(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId, @Query("mac") String mac, @Query("name") String name, @Query("netstate") String netstate, @Query("page") String page); //根据条件查询所有资产列表 @GET("getAssetList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<AllAssetListEntity> getAssetList(@Query("userId") String userId, @Query("privilege") String privilege, @Query("page") String page, @Query("akey") String akey, @Query("areaId") String areaId, @Query("atId") String atId, @Query("named") String named, @Query("state") String state); //根据底座报警列表 @GET("getTabAlarmList") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TagAlarmListEntity> getTabAlarmList(@Query("userId") String userId, @Query("privilege") String privilege, @Query("page") String page, @Query("ifDeal") String ifDeal); //根据条件查询用户设备(巡检) @GET("getNeedDev") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedDev2(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("page") String page, @Query("state") String placeTypeId,@Query("devType") String devType); //查询用户工单列表 @GET("getAllOrder") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpOrderListEntity> getAllOrder(@Query("userId") String userId, @Query("privilege") String privilege , @Query("state") String state); //查询用户工单详情 @GET("getOrderDetail") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpOrderInfoEntity> getOrderDetail(@Query("jkey") String jkey); //根据条件查询用户设备@@9.1 添加区域分级查询 @GET("getNeedDev") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedDev2(@Query("userId") String userId, @Query("privilege") String privilege,@Query("parentId") String parentId, @Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId,@Query("devType") String devType); //根据条件查询用户设备 @GET("getNeedLossDev") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedLossDev(@Query("userId") String userId, @Query("privilege") String privilege, @Query("parentId") String parentId,@Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId,@Query("devType") String devType); //根据条件查询用户所有设备(设备类型<11) @GET("getNeedDevice") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedDevice(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId); //根据查询内容查询用户烟感 @GET("getSmokeBySearch") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getSearchSmoke(@Query("userId") String userId, @Query("privilege") String privilege, @Query("search") String search); //处理报警消息 @GET("dealAlarm") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> dealAlarm(@Query("userId") String userId, @Query("smokeMac") String smokeMac); //处理报警消息详情 @GET("dealAlarmDetail") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> dealAlarmDetail(@Query("userId") String userId, @Query("smokeMac") String smokeMac, @Query("dealPeople") String dealPeople, @Query("alarmTruth") String alarmTruth, @Query("dealDetail") String dealDetail, @Query("image_path") String image_path, @Query("video_path") String video_path); //获取单个烟感信息 @GET("getOneSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> getOneSmoke(@Query("userId") String userId, @Query("smokeMac") String smokeMac, @Query("privilege") String privilege); //获取燃气历史数据 @GET("getGasHistoryInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ProofGasHistoryEntity> getGasHistoryInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac, @Query("page") String page); //添加烟感 @FormUrlEncoded @POST("addSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> addSmoke(@Field("userId") String userId, @Field("smokeName") String smokeName, @Field("privilege") String privilege, @Field("smokeMac") String smokeMac, @Field("address") String address, @Field("longitude") String longitude, @Field("latitude") String latitude, @Field("placeAddress") String placeAddress, @Field("placeTypeId") String placeTypeId, @Field("principal1") String principal1, @Field("principal1Phone") String principal1Phone, @Field("principal2") String principal2, @Field("principal2Phone") String principal2Phone, @Field("areaId") String areaId, @Field("repeater") String repeater,@Field("camera") String camera,@Field("deviceType") String deviceType, @Field("electrState") String electrState,@Field("image") String image); //添加烟感 @FormUrlEncoded @POST("addHeiMenSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> addHeiMenSmoke(@Field("userId") String userId, @Field("smokeName") String smokeName, @Field("privilege") String privilege, @Field("smokeMac") String smokeMac, @Field("address") String address, @Field("longitude") String longitude, @Field("latitude") String latitude, @Field("placeAddress") String placeAddress, @Field("placeTypeId") String placeTypeId, @Field("principal1") String principal1, @Field("principal1Phone") String principal1Phone, @Field("principal2") String principal2, @Field("principal2Phone") String principal2Phone, @Field("areaId") String areaId, @Field("repeater") String repeater,@Field("camera") String camera,@Field("deviceType") String deviceType, @Field("electrState") String electrState); //添加烟感 // @FormUrlEncoded // @GET("addSmoke") // @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") // Observable<ConfireFireModel> addSmoke(@Query("userId") String userId, @Query("smokeName") String smokeName, // @Query("privilege") String privilege, @Query("smokeMac") String smokeMac, // @Query("address") String address, @Query("longitude") String longitude, // @Query("latitude") String latitude, @Query("placeAddress") String placeAddress, // @Query("placeTypeId") String placeTypeId, @Query("principal1") String principal1, // @Query("principal1Phone") String principal1Phone, @Query("principal2") String principal2, // @Query("principal2Phone") String principal2Phone, @Query("areaId") String areaId, // @Query("repeater") String repeater,@Query("camera") String camera,@Query("deviceType") String deviceType, // @Query("electrState") String electrState); // @FormUrlEncoded // @POST("addSmoke") // @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") // Observable<ConfireFireModel> addSmoke(@Field("userId") String userId, @Field("smokeName") String smokeName, // @Field("privilege") String privilege, @Field("smokeMac") String smokeMac, // @Field("address") String address, @Field("longitude") String longitude, // @Field("latitude") String latitude, @Field("placeAddress") String placeAddress, // @Field("placeTypeId") String placeTypeId, @Field("principal1") String principal1, // @Field("principal1Phone") String principal1Phone, @Field("principal2") String principal2, // @Field("principal2Phone") String principal2Phone, @Field("areaId") String areaId, // @Field("repeater") String repeater,@Field("camera") String camera,@Field("deviceType") String deviceType); //获取用户报警消息 @GET("getAllAlarm") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getAllAlarm(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //条件查询获取用户报警消息 @GET("getNeedAlarm") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedAlarm(@Query("userId") String userId, @Query("privilege") String privilege ,@Query("startTime") String startTime,@Query("endTime") String endTime ,@Query("areaId") String areaId,@Query("placeTypeId") String placeTypeId ,@Query("page") String page,@Query("parentId") String parentId); //条件查询获取用户报警任务 @GET("getNeedAlarmMessage") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedAlarmMsg(@Query("userId") String userId, @Query("privilege") String privilege ,@Query("startTime") String startTime,@Query("endTime") String endTime ,@Query("areaId") String areaId,@Query("placeTypeId") String placeTypeId ,@Query("page") String page,@Query("parentId") String parentId,@Query("grade") String grade ,@Query("distance") String distance,@Query("progress") String progress); //条件查询获取用户报警任务2.0 @GET("getNeedOrderMsg") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedOrderMsg(@Query("userId") String userId, @Query("privilege") String privilege ,@Query("page") String page,@Query("grade") String grade ,@Query("progress") String progress); //添加摄像头 @GET("addCamera") Observable<HttpError> addCamera(@Query("cameraId") String cameraId, @Query("cameraName") String cameraName, @Query("cameraPwd") String cameraPwd, @Query("cameraAddress") String cameraAddress, @Query("longitude") String longitude, @Query("latitude") String latitude, @Query("principal1") String principal1, @Query("principal1Phone") String principal1Phone, @Query("principal2") String principal2, @Query("principal2Phone") String principal2Phone, @Query("areaId") String areaId, @Query("placeTypeId") String placeTypeId); //绑定烟感与摄像头 @GET("bindCameraSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> bindCameraSmoke(@Query("cameraId") String cameraId, @Query("smoke") String smoke); @GET("getCid") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> bindAlias(@Query("alias") String alias, @Query("cid") String cid,@Query("projectName") String projectName); //一键报警 @GET("textAlarm") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> textAlarm(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac,@Query("info") String info); //一键报警确认回复 @GET("textAlarmAck") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> textAlarmAck(@Query("userId") String userId, @Query("alarmSerialNumber") String alarmSerialNumber); @GET("getNeedLossSmoke") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedLossSmoke(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("page") String page, @Query("placeTypeId") String placeTypeId); @GET("getSmokeSummary") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<SmokeSummary> getSmokeSummary(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId); @GET("getDevSummary") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<SmokeSummary> getDevSummary(@Query("userId") String userId, @Query("privilege") String privilege, @Query("parentId") String parentId,@Query("areaId") String areaId,@Query("placeTypeId") String placeTypeId ,@Query("devType") String devType); @GET("getSafeScore") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<SafeScore> getSafeScore(@Query("userId") String userId, @Query("privilege") String privilege); @GET("getNFCSummary") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<SmokeSummary> getNFCSummary(@Query("userId") String userId, @Query("privilege") String privilege, @Query("areaId") String areaId,@Query("period") String period, @Query("devicetype") String devicetype); @GET("getAllElectricInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ElectricInfo<Electric>> getAllElectricInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("page") String page); // getOneElectricInfo?userId=13428282520&privilege=2&smokeMac=32110533 @GET("getOneElectricInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ElectricInfo<ElectricValue>> getOneElectricInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac,@Query("devType") String devType); @GET("getOneChuangAnInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ElectricInfo<ChuangAnValue.ChuangAnValueBean>> getOneChuangAnInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac); // getElectricTypeInfo?userId=13428282520&privilege=2&smokeMac=32110533&electricType=6&electricNum=1&page=post @GET("getWaterHistoryInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TemperatureTime> getWaterHistoryInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac, @Query("page") String page); @GET("getTHDevInfoHistoryInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TemperatureTime> getTHDevInfoHistoryInfo(@Query("mac") String smokeMac, @Query("page") String page, @Query("type") String tepe); @GET("getElectricTypeInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TemperatureTime> getElectricTypeInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac, @Query("electricType") String electricType, @Query("electricNum") String electricNum, @Query("page") String page, @Query("devType") int devType); @GET("getChuanganHistoryInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<TemperatureTime> getChuanganHistoryInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("smokeMac") String smokeMac, @Query("electricNum") String electricNum, @Query("page") String page); // getNeedElectricInfo?userId=13622215085&privilege=2&areaId=14&placeTypeId=2&page @GET("getNeedElectricInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ElectricInfo<Electric>> getNeedElectricInfo(@Query("userId") String userId, @Query("privilege") String privilege, @Query("parentId") String parentId,@Query("areaId") String areaId, @Query("placeTypeId") String placeTypeId, @Query("page") String page); @FormUrlEncoded @POST("changeCameraPwd") Observable<HttpError> changeCameraPwd(@Field("cameraId") String cameraId, @Field("cameraPwd") String cameraPwd); //@@7.19获取用户安防设备列表 @GET("getSecurityInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getSecurityInfo(@Query("userId") String userId, @Query("privilege") String privilege,@Query("page") String page); //@@7.19根据条件查询用户安防设备列表 @GET("getNeedSecurity") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNeedSecurity(@Query("userId") String userId, @Query("privilege") String privilege, @Query("page") String page,@Query("areaId") String areaId, @Query("placeTypeId") String placeTypeId); //添加烟感 @FormUrlEncoded @POST("addNFC") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> addNFC(@Field("userId") String userId, @Field("privilege") String privilege, @Field("smokeName") String smokeName, @Field("uid") String uid, @Field("address") String address, @Field("longitude") String longitude, @Field("latitude") String latitude, @Field("deviceType") String deviceType,@Field("areaId") String areaId, @Field("producer") String producer, @Field("makeTime") String makeTime,@Field("workerPhone") String workerPhone, @Field("makeAddress") String makeAddress); //巡检隐患上报 @FormUrlEncoded @POST("uploadHiddenDanger") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> uploadHiddenDanger(@Field("title") String title, @Field("address") String address, @Field("managers") String managers, @Field("workerId") String workerId, @Field("areaId") String areaId, @Field("desc") String desc, @Field("imgs") String imgs); //添加巡检项目 @FormUrlEncoded @POST("addNFCInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> addNFCInfo(@Field("userId") String userId, @Field("privilege") String privilege, @Field("smokeName") String smokeName, @Field("uid") String uid, @Field("address") String address, @Field("longitude") String longitude, @Field("latitude") String latitude, @Field("deviceType") String deviceType,@Field("areaId") String areaId, @Field("producer") String producer, @Field("makeTime") String makeTime,@Field("memo") String memo, @Field("makeAddress") String makeAddress,@Field("pid") String pid, @Field("photo1") String photo1); //修改巡检项目 @FormUrlEncoded @POST("updateItemInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<ConfireFireModel> updateItemInfo(@Field("userId") String userId, @Field("smokeName") String smokeName, @Field("uid") String uid, @Field("address") String address, @Field("deviceType") String deviceType,@Field("memo") String memo); //获取NFC @GET("getNFCInfo") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getNFCInfo(@Query("userId") String userId, @Query("areaId") String areaId, @Query("page") String page,@Query("period") String period, @Query("devicetype") String devicetype,@Query("devicestate") String devicestate); //获取电气设备切换设备 @GET("getEleNeedHis") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> getEleNeedHis(@Query("smokeMac") String smokeMac,@Query("page") String page); //确认报警上报 @GET("makeSureAlarm") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> makeSureAlarm(@Query("userId") String userId,@Query("smokeMac") String smokeMac,@Query("alarmType") String alarmType); //处理报警提交 @GET("submitOrder") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> submitOrder(@Query("userId") String userId,@Query("smokeMac") String smokeMac ,@Query("alarmTruth") String alarmTruth,@Query("dealDetail") String dealDetail ,@Query("imagePath") String imagePath,@Query("videoPath") String videoPath); //设备消音 @GET("ackNB_IOT_Control") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<HttpError> ackNB_IOT_Control(@Query("userId") String userId,@Query("smokeMac") String smokeMac,@Query("eleState") String eleState); @Multipart @POST("UploadFileAction") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Observable<Result<String>> uploadImege(@Part("partList") List<MultipartBody.Part> partList); @GET("nanjing_jiade_cancel") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Call<HttpError> nanjing_jiade_cancel(@Query("imeiValue") String imeiValue,@Query("deviceType") String deviceType,@Query("cancelState") String cancelState);//cancelState 1 单次消音 2 连续消音 @GET("ackNB_IOT_Control") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Call<HttpError> NB_IOT_Control(@Query("userId") String userId,@Query("smokeMac") String smokeMac,@Query("eleState") String eleState); @GET("EasyIot_erasure_control") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Call<HttpError> EasyIot_erasure_control(@Query("userId") String userId,@Query("devSerial") String devSerial,@Query("appId") String appId); @GET("cancelSound") @Headers("Content-Type: application/x-www-form-urlencoded;charset=utf-8") Call<HttpError> cancelSound(@Query("repeaterMac") String repeaterMac); }
3e0fee249c79348f5de6a7cebf94bd1eeec4259b
1,437
java
Java
src/main/java/seedu/address/model/account/entry/Entry.java
jordanyoong/tp
96d32f80a76bd68a4d1f276ac81ad4790aa72aea
[ "MIT" ]
null
null
null
src/main/java/seedu/address/model/account/entry/Entry.java
jordanyoong/tp
96d32f80a76bd68a4d1f276ac81ad4790aa72aea
[ "MIT" ]
null
null
null
src/main/java/seedu/address/model/account/entry/Entry.java
jordanyoong/tp
96d32f80a76bd68a4d1f276ac81ad4790aa72aea
[ "MIT" ]
null
null
null
26.127273
87
0.683368
6,762
package seedu.address.model.account.entry; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import seedu.address.model.tag.Tag; /** * Represents the skeleton of an entry in Common Cents. * Guarantees: details are present and not null, field values are validated, immutable. */ public abstract class Entry { private final Description description; private final Amount amount; private final Set<Tag> tags = new HashSet<>(); /** * Every field must be present and not null. */ public Entry(Description description, Amount amount, Set<Tag> tags) { requireAllNonNull(description, amount, tags); this.description = description; this.amount = amount; this.tags.addAll(tags); } public Description getDescription() { return description; } public Amount getAmount() { return amount; } /** * Returns an immutable tag set, which throws {@code UnsupportedOperationException} * if modification is attempted. */ public Set<Tag> getTags() { return Collections.unmodifiableSet(tags); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(description, amount, tags); } }
3e0fee5dc41b571ef16b1bc73a41f93b8407cffb
4,938
java
Java
src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java
Kobee1203/equalsverifier
6d62d6e98b28d5c6e3da84bbfb9ad0d17f19a433
[ "Apache-2.0" ]
613
2015-01-30T03:25:37.000Z
2022-03-22T17:20:05.000Z
src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java
Kobee1203/equalsverifier
6d62d6e98b28d5c6e3da84bbfb9ad0d17f19a433
[ "Apache-2.0" ]
345
2015-03-18T09:12:14.000Z
2022-03-25T11:51:10.000Z
src/test/java/nl/jqno/equalsverifier/integration/extended_contract/NullFieldsWithExceptionsTest.java
Kobee1203/equalsverifier
6d62d6e98b28d5c6e3da84bbfb9ad0d17f19a433
[ "Apache-2.0" ]
124
2015-03-01T10:27:09.000Z
2022-02-11T19:06:20.000Z
31.653846
106
0.659579
6,763
package nl.jqno.equalsverifier.integration.extended_contract; import static nl.jqno.equalsverifier.testhelpers.Util.defaultEquals; import static nl.jqno.equalsverifier.testhelpers.Util.defaultHashCode; import java.util.Objects; import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.testhelpers.ExpectedException; import org.junit.jupiter.api.Test; public class NullFieldsWithExceptionsTest { private static final String EQUALS = "equals"; private static final String HASH_CODE = "hashCode"; private static final String THROWS = "throws"; private static final String ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException"; private static final String ILLEGAL_STATE_EXCEPTION = "IllegalStateException"; private static final String WHEN_FOO_IS_NULL = "when field foo is null"; @Test public void recogniseUnderlyingNpe_whenIllegalArgumentExceptionIsThrownInEquals_givenFieldIsNull() { ExpectedException .when(() -> EqualsVerifier.forClass(EqualsIllegalArgumentThrower.class).verify()) .assertFailure() .assertCause(IllegalArgumentException.class) .assertMessageContains(EQUALS, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalStateExceptionIsThrownInEquals_givenFieldIsNull() { ExpectedException .when(() -> EqualsVerifier.forClass(EqualsIllegalStateThrower.class).verify()) .assertFailure() .assertCause(IllegalStateException.class) .assertMessageContains(EQUALS, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalArgumentExceptionIsThrownInHashCode_givenFieldIsNull() { ExpectedException .when(() -> EqualsVerifier.forClass(HashCodeIllegalArgumentThrower.class).verify()) .assertFailure() .assertCause(IllegalArgumentException.class) .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_ARGUMENT_EXCEPTION, WHEN_FOO_IS_NULL); } @Test public void recogniseUnderlyingNpe_whenIllegalStateExceptionIsThrownInHashCode_givenFieldIsNull() { ExpectedException .when(() -> EqualsVerifier.forClass(HashCodeIllegalStateThrower.class).verify()) .assertFailure() .assertCause(IllegalStateException.class) .assertMessageContains(HASH_CODE, THROWS, ILLEGAL_STATE_EXCEPTION, WHEN_FOO_IS_NULL); } abstract static class EqualsThrower { private final String foo; public EqualsThrower(String foo) { this.foo = foo; } protected abstract RuntimeException throwable(); @Override public final boolean equals(Object obj) { if (!(obj instanceof EqualsThrower)) { return false; } EqualsThrower other = (EqualsThrower) obj; if (foo == null) { throw throwable(); } return Objects.equals(foo, other.foo); } @Override public final int hashCode() { return defaultHashCode(this); } } static class EqualsIllegalArgumentThrower extends EqualsThrower { public EqualsIllegalArgumentThrower(String foo) { super(foo); } @Override protected RuntimeException throwable() { return new IllegalArgumentException(); } } static class EqualsIllegalStateThrower extends EqualsThrower { public EqualsIllegalStateThrower(String foo) { super(foo); } @Override protected RuntimeException throwable() { return new IllegalStateException(); } } abstract static class HashCodeThrower { private final String foo; public HashCodeThrower(String foo) { this.foo = foo; } protected abstract RuntimeException throwable(); @Override public final boolean equals(Object obj) { return defaultEquals(this, obj); } @Override public final int hashCode() { if (foo == null) { throw throwable(); } return foo.hashCode(); } } static class HashCodeIllegalArgumentThrower extends HashCodeThrower { public HashCodeIllegalArgumentThrower(String foo) { super(foo); } @Override protected RuntimeException throwable() { return new IllegalArgumentException(); } } static class HashCodeIllegalStateThrower extends HashCodeThrower { public HashCodeIllegalStateThrower(String foo) { super(foo); } @Override protected RuntimeException throwable() { return new IllegalStateException(); } } }
3e0ff024433d20f9bbc7012277e8bac1418ed79e
1,513
java
Java
tikv-client/src/test/java/com/pingcap/tikv/types/RealTypeTest.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
834
2017-07-07T03:30:38.000Z
2022-03-28T03:39:13.000Z
tikv-client/src/test/java/com/pingcap/tikv/types/RealTypeTest.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
1,738
2017-07-06T10:42:57.000Z
2022-03-31T10:32:18.000Z
tikv-client/src/test/java/com/pingcap/tikv/types/RealTypeTest.java
purelind/tispark
7154ce36c5f0d320cf0657e49213334f6e64d049
[ "Apache-2.0" ]
241
2017-07-24T08:28:44.000Z
2022-03-29T07:31:31.000Z
29.666667
82
0.721084
6,765
/* * * Copyright 2017 PingCAP, 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, * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pingcap.tikv.types; import static org.junit.Assert.assertEquals; import com.pingcap.tikv.codec.CodecDataInput; import com.pingcap.tikv.codec.CodecDataOutput; import com.pingcap.tikv.types.DataType.EncodeType; import org.junit.Test; public class RealTypeTest { private static byte[] encode(Object val, EncodeType encodeType, DataType type) { CodecDataOutput cdo = new CodecDataOutput(); type.encode(cdo, encodeType, val); return cdo.toBytes(); } private static Object decode(byte[] val, DataType type) { return type.decode(new CodecDataInput(val)); } @Test public void encodeTest() { DataType type = RealType.DOUBLE; double originalVal = 666.66; byte[] encodedKey = encode(originalVal, EncodeType.KEY, type); Object val = decode(encodedKey, type); assertEquals(originalVal, (double) val, 0.01); encodedKey = encode(null, EncodeType.KEY, type); val = decode(encodedKey, type); assertEquals(null, val); } }
3e0ff060048454fd51d8e54da39f0396492a7518
8,625
java
Java
src/main/java/com/glaf/matrix/transform/query/RowDenormaliserQuery.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
2
2017-10-20T12:29:56.000Z
2018-03-04T02:20:38.000Z
src/main/java/com/glaf/matrix/transform/query/RowDenormaliserQuery.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
14
2019-11-13T03:15:50.000Z
2022-03-31T18:46:48.000Z
src/main/java/com/glaf/matrix/transform/query/RowDenormaliserQuery.java
gitee2008/crowd
dde77987c8045a7b819d2917a8f9ff08fcdb5d73
[ "Apache-2.0" ]
4
2018-08-14T04:40:43.000Z
2022-03-27T04:43:01.000Z
27.555911
100
0.737391
6,766
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.matrix.transform.query; import java.util.*; import com.glaf.core.query.DataQuery; public class RowDenormaliserQuery extends DataQuery { private static final long serialVersionUID = 1L; protected String titleLike; protected Integer transformStatus; protected Date transformTimeGreaterThanOrEqual; protected Date transformTimeLessThanOrEqual; protected String transformFlag; protected String scheduleFlag; protected String targetTableName; protected String targetTableNameLike; protected Date createTimeGreaterThanOrEqual; protected Date createTimeLessThanOrEqual; public RowDenormaliserQuery() { } public RowDenormaliserQuery createTimeGreaterThanOrEqual(Date createTimeGreaterThanOrEqual) { if (createTimeGreaterThanOrEqual == null) { throw new RuntimeException("createTime is null"); } this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual; return this; } public RowDenormaliserQuery createTimeLessThanOrEqual(Date createTimeLessThanOrEqual) { if (createTimeLessThanOrEqual == null) { throw new RuntimeException("createTime is null"); } this.createTimeLessThanOrEqual = createTimeLessThanOrEqual; return this; } public String getCreateBy() { return createBy; } public Date getCreateTimeGreaterThanOrEqual() { return createTimeGreaterThanOrEqual; } public Date getCreateTimeLessThanOrEqual() { return createTimeLessThanOrEqual; } public String getOrderBy() { if (sortColumn != null) { String a_x = " asc "; if (sortOrder != null) { a_x = sortOrder; } if ("title".equals(sortColumn)) { orderBy = "E.TITLE_" + a_x; } if ("databaseIds".equals(sortColumn)) { orderBy = "E.DATABASEIDS_" + a_x; } if ("primaryKey".equals(sortColumn)) { orderBy = "E.PRIMARYKEY_" + a_x; } if ("transformColumn".equals(sortColumn)) { orderBy = "E.TRANSFORMCOLUMN_" + a_x; } if ("sort".equals(sortColumn)) { orderBy = "E.SORT_" + a_x; } if ("transformStatus".equals(sortColumn)) { orderBy = "E.TRANSFORMSTATUS_" + a_x; } if ("transformTime".equals(sortColumn)) { orderBy = "E.TRANSFORMTIME_" + a_x; } if ("transformFlag".equals(sortColumn)) { orderBy = "E.TRANSFORMFLAG_" + a_x; } if ("targetTableName".equals(sortColumn)) { orderBy = "E.TARGETTABLENAME_" + a_x; } if ("targetColumn".equals(sortColumn)) { orderBy = "E.TARGETCOLUMN_" + a_x; } if ("locked".equals(sortColumn)) { orderBy = "E.LOCKED_" + a_x; } if ("createBy".equals(sortColumn)) { orderBy = "E.CREATEBY_" + a_x; } if ("createTime".equals(sortColumn)) { orderBy = "E.CREATETIME_" + a_x; } if ("updateBy".equals(sortColumn)) { orderBy = "E.UPDATEBY_" + a_x; } if ("updateTime".equals(sortColumn)) { orderBy = "E.UPDATETIME_" + a_x; } } return orderBy; } public String getScheduleFlag() { return scheduleFlag; } public String getTargetTableName() { return targetTableName; } public String getTargetTableNameLike() { if (targetTableNameLike != null && targetTableNameLike.trim().length() > 0) { if (!targetTableNameLike.startsWith("%")) { targetTableNameLike = "%" + targetTableNameLike; } if (!targetTableNameLike.endsWith("%")) { targetTableNameLike = targetTableNameLike + "%"; } } return targetTableNameLike; } public String getTitleLike() { if (titleLike != null && titleLike.trim().length() > 0) { if (!titleLike.startsWith("%")) { titleLike = "%" + titleLike; } if (!titleLike.endsWith("%")) { titleLike = titleLike + "%"; } } return titleLike; } public String getTransformFlag() { return transformFlag; } public Integer getTransformStatus() { return transformStatus; } public Date getTransformTimeGreaterThanOrEqual() { return transformTimeGreaterThanOrEqual; } public Date getTransformTimeLessThanOrEqual() { return transformTimeLessThanOrEqual; } @Override public void initQueryColumns() { super.initQueryColumns(); addColumn("id", "ID_"); addColumn("title", "TITLE_"); addColumn("databaseIds", "DATABASEIDS_"); addColumn("primaryKey", "PRIMARYKEY_"); addColumn("transformColumn", "TRANSFORMCOLUMN_"); addColumn("sort", "SORT_"); addColumn("transformStatus", "TRANSFORMSTATUS_"); addColumn("transformTime", "TRANSFORMTIME_"); addColumn("transformFlag", "TRANSFORMFLAG_"); addColumn("targetTableName", "TARGETTABLENAME_"); addColumn("targetColumn", "TARGETCOLUMN_"); addColumn("locked", "LOCKED_"); addColumn("createBy", "CREATEBY_"); addColumn("createTime", "CREATETIME_"); addColumn("updateBy", "UPDATEBY_"); addColumn("updateTime", "UPDATETIME_"); } public RowDenormaliserQuery scheduleFlag(String scheduleFlag) { if (scheduleFlag == null) { throw new RuntimeException("scheduleFlag is null"); } this.scheduleFlag = scheduleFlag; return this; } public void setCreateTimeGreaterThanOrEqual(Date createTimeGreaterThanOrEqual) { this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual; } public void setCreateTimeLessThanOrEqual(Date createTimeLessThanOrEqual) { this.createTimeLessThanOrEqual = createTimeLessThanOrEqual; } public void setScheduleFlag(String scheduleFlag) { this.scheduleFlag = scheduleFlag; } public void setTargetTableName(String targetTableName) { this.targetTableName = targetTableName; } public void setTargetTableNameLike(String targetTableNameLike) { this.targetTableNameLike = targetTableNameLike; } public void setTitleLike(String titleLike) { this.titleLike = titleLike; } public void setTransformFlag(String transformFlag) { this.transformFlag = transformFlag; } public void setTransformStatus(Integer transformStatus) { this.transformStatus = transformStatus; } public void setTransformTimeGreaterThanOrEqual(Date transformTimeGreaterThanOrEqual) { this.transformTimeGreaterThanOrEqual = transformTimeGreaterThanOrEqual; } public void setTransformTimeLessThanOrEqual(Date transformTimeLessThanOrEqual) { this.transformTimeLessThanOrEqual = transformTimeLessThanOrEqual; } public RowDenormaliserQuery targetTableName(String targetTableName) { if (targetTableName == null) { throw new RuntimeException("targetTableName is null"); } this.targetTableName = targetTableName; return this; } public RowDenormaliserQuery targetTableNameLike(String targetTableNameLike) { if (targetTableNameLike == null) { throw new RuntimeException("targetTableName is null"); } this.targetTableNameLike = targetTableNameLike; return this; } public RowDenormaliserQuery titleLike(String titleLike) { if (titleLike == null) { throw new RuntimeException("title is null"); } this.titleLike = titleLike; return this; } public RowDenormaliserQuery transformFlag(String transformFlag) { if (transformFlag == null) { throw new RuntimeException("transformFlag is null"); } this.transformFlag = transformFlag; return this; } public RowDenormaliserQuery transformStatus(Integer transformStatus) { if (transformStatus == null) { throw new RuntimeException("transformStatus is null"); } this.transformStatus = transformStatus; return this; } public RowDenormaliserQuery transformTimeGreaterThanOrEqual(Date transformTimeGreaterThanOrEqual) { if (transformTimeGreaterThanOrEqual == null) { throw new RuntimeException("transformTime is null"); } this.transformTimeGreaterThanOrEqual = transformTimeGreaterThanOrEqual; return this; } public RowDenormaliserQuery transformTimeLessThanOrEqual(Date transformTimeLessThanOrEqual) { if (transformTimeLessThanOrEqual == null) { throw new RuntimeException("transformTime is null"); } this.transformTimeLessThanOrEqual = transformTimeLessThanOrEqual; return this; } }
3e0ff13add545f5f9c70abdcc729e0e4622aa108
33,506
java
Java
src/main/java/org/xbill/DNS/dnssec/ValUtils.java
spwei/dnsjava
c3942d1c9f7a124dbbbc27cb9745eb8fa8211d92
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/xbill/DNS/dnssec/ValUtils.java
spwei/dnsjava
c3942d1c9f7a124dbbbc27cb9745eb8fa8211d92
[ "BSD-2-Clause" ]
null
null
null
src/main/java/org/xbill/DNS/dnssec/ValUtils.java
spwei/dnsjava
c3942d1c9f7a124dbbbc27cb9745eb8fa8211d92
[ "BSD-2-Clause" ]
null
null
null
36.027957
100
0.652868
6,767
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2005 VeriSign. All rights reserved. // Copyright (c) 2013-2021 Ingo Bauersachs package org.xbill.DNS.dnssec; import java.security.Security; import java.time.Instant; import java.util.List; import java.util.Properties; import lombok.extern.slf4j.Slf4j; import org.xbill.DNS.DClass; import org.xbill.DNS.DNSKEYRecord; import org.xbill.DNS.DNSSEC; import org.xbill.DNS.DNSSEC.Algorithm; import org.xbill.DNS.DSRecord; import org.xbill.DNS.ExtendedErrorCodeOption; import org.xbill.DNS.Flags; import org.xbill.DNS.Message; import org.xbill.DNS.NSECRecord; import org.xbill.DNS.Name; import org.xbill.DNS.NameTooLongException; import org.xbill.DNS.RRSIGRecord; import org.xbill.DNS.RRset; import org.xbill.DNS.Rcode; import org.xbill.DNS.Record; import org.xbill.DNS.Section; import org.xbill.DNS.Type; /** * This is a collection of routines encompassing the logic of validating different message types. * * @since 3.5 */ @Slf4j final class ValUtils { public static final String DIGEST_PREFERENCE = "dnsjava.dnssec.digest_preference"; public static final String DIGEST_ENABLED = "dnsjava.dnssec.digest"; public static final String DIGEST_HARDEN_DOWNGRADE = "dnsjava.dnssec.harden_algo_downgrade"; public static final String ALGORITHM_ENABLED = "dnsjava.dnssec.algorithm"; private static final Name WILDCARD = Name.fromConstantString("*"); /** A local copy of the verifier object. */ private final DnsSecVerifier verifier; private int[] digestPreference = null; private Properties config = null; private boolean digestHardenDowngrade = true; private boolean hasGost; private boolean hasEd25519; private boolean hasEd448; /** Creates a new instance of this class. */ public ValUtils() { this.verifier = new DnsSecVerifier(); hasGost = Security.getProviders("MessageDigest.GOST3411") != null; hasEd25519 = Security.getProviders("KeyFactory.Ed25519") != null; hasEd448 = Security.getProviders("KeyFactory.Ed448") != null; } /** * Set the owner name of NSEC RRsets to the canonical name, i.e. the name that is <b>not</b> * expanded from a wildcard label. * * @param set The RRset to canonicalize. * @param sig The signature that validated this RRset. */ public static void setCanonicalNsecOwner(SRRset set, RRSIGRecord sig) { if (set.getType() != Type.NSEC) { return; } Record nsec = set.first(); int fqdnLabelCount = nsec.getName().labels() - 1; // don't count the root label if (nsec.getName().isWild()) { --fqdnLabelCount; // don't count the wildcard label } if (sig.getLabels() == fqdnLabelCount) { set.setName(nsec.getName()); } else if (sig.getLabels() < fqdnLabelCount) { set.setName(nsec.getName().wild(sig.getSigner().labels() - sig.getLabels())); } else { throw new IllegalArgumentException("invalid nsec record"); } } /** * Initialize the module. The recognized configuration values are: * * <ul> * <li>{@link #DIGEST_PREFERENCE} * <li>{@link #DIGEST_HARDEN_DOWNGRADE} * <li>{@link #DIGEST_ENABLED} * <li>{@link #ALGORITHM_ENABLED} * </ul> * * @param config The configuration data for this module. */ public void init(Properties config) { hasGost = Security.getProviders("MessageDigest.GOST3411") != null; hasEd25519 = Security.getProviders("KeyFactory.Ed25519") != null; hasEd448 = Security.getProviders("KeyFactory.Ed448") != null; this.config = config; String dp = config.getProperty(DIGEST_PREFERENCE); if (dp != null) { String[] dpdata = dp.split(","); this.digestPreference = new int[dpdata.length]; for (int i = 0; i < dpdata.length; i++) { this.digestPreference[i] = Integer.parseInt(dpdata[i]); if (!isDigestSupported(this.digestPreference[i])) { throw new IllegalArgumentException( "Unsupported or disabled digest ID in digest preferences"); } } } this.digestHardenDowngrade = Boolean.parseBoolean(config.getProperty(DIGEST_HARDEN_DOWNGRADE)); } /** * Given a response, classify ANSWER responses into a subtype. * * @param request The original query message. * @param m The response to classify. * @return A subtype ranging from UNKNOWN to NAMEERROR. */ public static ResponseClassification classifyResponse(Message request, SMessage m) { // Normal Name Error's are easy to detect -- but don't mistake a CNAME // chain ending in NXDOMAIN. if (m.getRcode() == Rcode.NXDOMAIN && m.getCount(Section.ANSWER) == 0) { return ResponseClassification.NAMEERROR; } // check for referral: nonRD query and it looks like a nodata if (!request.getHeader().getFlag(Flags.RD) && m.getCount(Section.ANSWER) == 0 && m.getRcode() != Rcode.NOERROR) { // SOA record in auth indicates it is NODATA instead. // All validation requiring NODATA messages have SOA in // authority section. // uses fact that answer section is empty boolean sawNs = false; for (RRset set : m.getSectionRRsets(Section.AUTHORITY)) { if (set.getType() == Type.SOA) { return ResponseClassification.NODATA; } if (set.getType() == Type.DS) { return ResponseClassification.REFERRAL; } if (set.getType() == Type.NS) { sawNs = true; } } return sawNs ? ResponseClassification.REFERRAL : ResponseClassification.NODATA; } // root referral where NS set is in the answer section if (m.getSectionRRsets(Section.AUTHORITY).isEmpty() && m.getSectionRRsets(Section.ANSWER).size() == 1 && m.getRcode() == Rcode.NOERROR && m.getSectionRRsets(Section.ANSWER).get(0).getType() == Type.NS && !m.getSectionRRsets(Section.ANSWER) .get(0) .getName() .equals(request.getQuestion().getName())) { return ResponseClassification.REFERRAL; } // dump bad messages if (m.getRcode() != Rcode.NOERROR && m.getRcode() != Rcode.NXDOMAIN) { return ResponseClassification.UNKNOWN; } // Next is NODATA if (m.getRcode() == Rcode.NOERROR && m.getCount(Section.ANSWER) == 0) { return ResponseClassification.NODATA; } // We distinguish between CNAME response and other positive/negative // responses because CNAME answers require extra processing. int qtype = m.getQuestion().getType(); // We distinguish between ANY and CNAME or POSITIVE because ANY // responses are validated differently. if (qtype == Type.ANY) { return ResponseClassification.ANY; } boolean hadCname = false; for (RRset set : m.getSectionRRsets(Section.ANSWER)) { if (set.getType() == qtype) { return ResponseClassification.POSITIVE; } if (set.getType() == Type.CNAME || set.getType() == Type.DNAME) { hadCname = true; if (qtype == Type.DS) { return ResponseClassification.CNAME; } } } if (hadCname) { if (m.getRcode() == Rcode.NXDOMAIN) { return ResponseClassification.CNAME_NAMEERROR; } else { return ResponseClassification.CNAME_NODATA; } } log.warn("Failed to classify response message:\n{}", m); return ResponseClassification.UNKNOWN; } /** * Given a DS rrset and a DNSKEY rrset, match the DS to a DNSKEY and verify the DNSKEY rrset with * that key. * * @param dnskeyRrset The DNSKEY rrset to match against. The security status of this rrset will be * updated on a successful verification. * @param dsRrset The DS rrset to match with. This rrset must already be trusted. * @param badKeyTTL The TTL [s] for keys determined to be bad. * @param date The date against which to verify the rrset. * @return a KeyEntry. This will either contain the now trusted dnskey RRset, a "null" key entry * indicating that this DS rrset/DNSKEY pair indicate an secure end to the island of trust * (i.e., unknown algorithms), or a "bad" KeyEntry if the dnskey RRset fails to verify. Note * that the "null" response should generally only occur in a private algorithm scenario: * normally this sort of thing is checked before fetching the matching DNSKEY rrset. */ public KeyEntry verifyNewDNSKEYs( SRRset dnskeyRrset, SRRset dsRrset, long badKeyTTL, Instant date) { if (!atLeastOneDigestSupported(dsRrset)) { KeyEntry ke = KeyEntry.newNullKeyEntry(dsRrset.getName(), dsRrset.getDClass(), dsRrset.getTTL()); ke.setBadReason( ExtendedErrorCodeOption.UNSUPPORTED_DS_DIGEST_TYPE, R.get("failed.ds.nodigest", dsRrset.getName())); return ke; } if (!atLeastOneSupportedAlgorithm(dsRrset)) { KeyEntry ke = KeyEntry.newNullKeyEntry(dsRrset.getName(), dsRrset.getDClass(), dsRrset.getTTL()); ke.setBadReason( ExtendedErrorCodeOption.UNSUPPORTED_DNSKEY_ALGORITHM, R.get("failed.ds.noalg", dsRrset.getName())); return ke; } int favoriteDigestID = this.favoriteDSDigestID(dsRrset); KeyEntry ke = null; for (Record dsr : dsRrset.rrs()) { DSRecord ds = (DSRecord) dsr; if (this.digestHardenDowngrade && ds.getDigestID() != favoriteDigestID) { continue; } for (Record dsnkeyr : dnskeyRrset.rrs()) { DNSKEYRecord dnskey = (DNSKEYRecord) dsnkeyr; // Skip DNSKEYs that don't match the basic criteria. if (ds.getFootprint() != dnskey.getFootprint() || ds.getAlgorithm() != dnskey.getAlgorithm()) { continue; } ke = getKeyEntry(dnskeyRrset, date, ds, dnskey); if (ke.isGood()) { return ke; } // If it didn't validate with the DNSKEY, try the next one! } } // If any were understandable, then it is bad. if (ke == null) { ke = KeyEntry.newBadKeyEntry(dsRrset.getName(), dsRrset.getDClass(), badKeyTTL); ke.setBadReason(ExtendedErrorCodeOption.DNSKEY_MISSING, R.get("dnskey.no_ds_match")); } return ke; } private KeyEntry getKeyEntry(SRRset dnskeyRrset, Instant date, DSRecord ds, DNSKEYRecord dnskey) { // Convert the candidate DNSKEY into a hash using the same DS // hash algorithm. DSRecord keyDigest = new DSRecord(Name.root, ds.getDClass(), 0, ds.getDigestID(), dnskey); byte[] keyHash = keyDigest.getDigest(); byte[] dsHash = ds.getDigest(); // see if there is a length mismatch (unlikely) KeyEntry ke; if (keyHash.length != dsHash.length) { ke = KeyEntry.newBadKeyEntry(ds.getName(), ds.getDClass(), ds.getTTL()); ke.setBadReason(ExtendedErrorCodeOption.DNSSEC_BOGUS, R.get("dnskey.invalid")); return ke; } for (int k = 0; k < keyHash.length; k++) { if (keyHash[k] != dsHash[k]) { ke = KeyEntry.newBadKeyEntry(ds.getName(), ds.getDClass(), ds.getTTL()); ke.setBadReason(ExtendedErrorCodeOption.DNSSEC_BOGUS, R.get("dnskey.invalid")); return ke; } } // Otherwise, we have a match! Make sure that the DNSKEY // verifies *with this key*. JustifiedSecStatus res = this.verifier.verify(dnskeyRrset, dnskey, date); switch (res.status) { case SECURE: dnskeyRrset.setSecurityStatus(SecurityStatus.SECURE); ke = KeyEntry.newKeyEntry(dnskeyRrset); break; case BOGUS: ke = KeyEntry.newBadKeyEntry(ds.getName(), ds.getDClass(), ds.getTTL()); ke.setBadReason(res.edeReason, res.reason); break; default: throw new IllegalStateException("Unexpected security status"); } return ke; } /** * Gets the digest ID for the favorite (best) algorithm that is support in a given DS set. * * <p>The order of preference can be configured with the property {@value #DIGEST_PREFERENCE}. If * the property is not set, the highest supported number is returned. * * @param dsset The DS set to check for the favorite algorithm. * @return The favorite digest ID or 0 if none is supported. 0 is not a known digest ID. */ int favoriteDSDigestID(SRRset dsset) { if (this.digestPreference == null) { int max = 0; for (Record r : dsset.rrs()) { DSRecord ds = (DSRecord) r; if (ds.getDigestID() > max && isDigestSupported(ds.getDigestID()) && isAlgorithmSupported(ds.getAlgorithm())) { max = ds.getDigestID(); } } return max; } else { for (int preference : this.digestPreference) { for (Record r : dsset.rrs()) { DSRecord ds = (DSRecord) r; if (ds.getDigestID() == preference) { return ds.getDigestID(); } } } } return 0; } /** * Given an SRRset that is signed by a DNSKEY found in the key_rrset, verify it. This will return * the status (either BOGUS or SECURE) and set that status in rrset. * * @param rrset The SRRset to verify. * @param keyRrset The set of keys to verify against. * @param date The date against which to verify the rrset. * @return The status (BOGUS or SECURE). */ public JustifiedSecStatus verifySRRset(SRRset rrset, SRRset keyRrset, Instant date) { if (rrset.getSecurityStatus() == SecurityStatus.SECURE) { log.trace( "RRset <{}/{}/{}> previously found to be SECURE", rrset.getName(), Type.string(rrset.getType()), DClass.string(rrset.getDClass())); return new JustifiedSecStatus(SecurityStatus.SECURE, -1, null); } JustifiedSecStatus res = this.verifier.verify(rrset, keyRrset, date); rrset.setSecurityStatus(res.status); return res; } /** * Determine by looking at a signed RRset whether or not the RRset name was the result of a * wildcard expansion. If so, return the name of the generating wildcard. * * @param rrset The rrset to chedck. * @return the wildcard name, if the rrset was synthesized from a wildcard. null if not. */ public static Name rrsetWildcard(RRset rrset) { List<RRSIGRecord> sigs = rrset.sigs(); RRSIGRecord firstSig = sigs.get(0); // check rest of signatures have identical label count for (int i = 1; i < sigs.size(); i++) { if (sigs.get(i).getLabels() != firstSig.getLabels()) { throw new IllegalArgumentException("failed.wildcard.label_count_mismatch"); } } // if the RRSIG label count is shorter than the number of actual labels, // then this rrset was synthesized from a wildcard. // Note that the RRSIG label count doesn't count the root label. Name wn = rrset.getName(); // skip a leading wildcard label in the dname (RFC4035 2.2) if (rrset.getName().isWild()) { wn = new Name(wn, 1); } int labelDiff = (wn.labels() - 1) - firstSig.getLabels(); if (labelDiff > 0) { return wn.wild(labelDiff); } return null; } /** * Finds the longest domain name in common with the given name. * * @param domain1 The first domain to process. * @param domain2 The second domain to process. * @return The longest label in common of domain1 and domain2. The least common name is the root. */ public static Name longestCommonName(Name domain1, Name domain2) { int l = Math.min(domain1.labels(), domain2.labels()); domain1 = new Name(domain1, domain1.labels() - l); domain2 = new Name(domain2, domain2.labels() - l); for (int i = 0; i < l - 1; i++) { Name ns1 = new Name(domain1, i); if (ns1.equals(new Name(domain2, i))) { return ns1; } } return Name.root; } /** * Is the first Name strictly a subdomain of the second name (i.e., below but not equal to). * * @param domain1 The first domain to process. * @param domain2 The second domain to process. * @return True when domain1 is a strict subdomain of domain2. */ public static boolean strictSubdomain(Name domain1, Name domain2) { if (domain1.labels() <= domain2.labels()) { return false; } return new Name(domain1, domain1.labels() - domain2.labels()).equals(domain2); } /** * Determines the 'closest encloser' - the name that has the most common labels between <code> * domain</code> and ({@link NSECRecord#getName()} or {@link NSECRecord#getNext()}). * * @param domain The name for which the closest encloser is queried. * @param owner The beginning of the covering {@link Name} to check. * @param next The end of the covering {@link Name} to check. * @return The closest encloser name of <code>domain</code> as defined by {@code owner} and {@code * next}. */ public static Name closestEncloser(Name domain, Name owner, Name next) { Name n1 = longestCommonName(domain, owner); Name n2 = longestCommonName(domain, next); return (n1.labels() > n2.labels()) ? n1 : n2; } /** * Gets the closest encloser of <code>domain</code> prepended with a wildcard label. * * @param domain The name for which the wildcard closest encloser is demanded. * @param set The RRset containing {@code nsec} to check. * @param nsec The covering NSEC that defines the encloser. * @return The wildcard closest encloser name of <code>domain</code> as defined by <code>nsec * </code>. * @throws NameTooLongException If adding the wildcard label to the closest encloser results in an * invalid name. */ public static Name nsecWildcard(Name domain, SRRset set, NSECRecord nsec) throws NameTooLongException { Name origin = closestEncloser(domain, set.getName(), nsec.getNext()); return Name.concatenate(WILDCARD, origin); } /** * Determine if the given NSEC proves a NameError (NXDOMAIN) for a given qname. * * @param set The RRset that contains the NSEC. * @param nsec The NSEC to check. * @param qname The qname to check against. * @return true if the NSEC proves the condition. */ public static boolean nsecProvesNameError(SRRset set, NSECRecord nsec, Name qname) { Name owner = set.getName(); Name next = nsec.getNext(); // If NSEC owner == qname, then this NSEC proves that qname exists. if (qname.equals(owner)) { return false; } // deny overreaching NSECs if (!next.subdomain(set.getSignerName())) { return false; } // If NSEC is a parent of qname, we need to check the type map // If the parent name has a DNAME or is a delegation point, then this // NSEC is being misused. if (qname.subdomain(owner)) { if (nsec.hasType(Type.DNAME)) { return false; } if (nsec.hasType(Type.NS) && !nsec.hasType(Type.SOA)) { return false; } } if (owner.equals(next)) { // this nsec is the only nsec: zone.name NSEC zone.name // it disproves everything else but only for subdomains of that zone return strictSubdomain(qname, next); } else if (owner.compareTo(next) > 0) { // this is the last nsec, ....(bigger) NSEC zonename(smaller) // the names after the last (owner) name do not exist // there are no names before the zone name in the zone // but the qname must be a subdomain of the zone name(next). return owner.compareTo(qname) < 0 && strictSubdomain(qname, next); } else { // regular NSEC, (smaller) NSEC (larger) return owner.compareTo(qname) < 0 && qname.compareTo(next) < 0; } } /** * Determine if a NSEC record proves the non-existence of a wildcard that could have produced * qname. * * @param set The RRset of the NSEC record. * @param nsec The nsec record to check. * @param qname The qname to check against. * @return true if the NSEC proves the condition. */ public static boolean nsecProvesNoWC(SRRset set, NSECRecord nsec, Name qname) { Name ce = closestEncloser(qname, set.getName(), nsec.getNext()); int labelsToStrip = qname.labels() - ce.labels(); if (labelsToStrip > 0) { Name wcName = qname.wild(labelsToStrip); return nsecProvesNameError(set, nsec, wcName); } return false; } /** * Container for responses of {@link ValUtils#nsecProvesNodata(SRRset, NSECRecord, Name, int)}. */ public static class NsecProvesNodataResponse { boolean result; Name wc; } /** * Determine if a NSEC proves the NOERROR/NODATA conditions. This will also handle the empty * non-terminal (ENT) case and partially handle the wildcard case. If the ownername of 'nsec' is a * wildcard, the validator must still be provided proof that qname did not directly exist and that * the wildcard is, in fact, *.closest_encloser. * * @param set The RRset of the NSEC record. * @param nsec The NSEC to check * @param qname The query name to check against. * @param qtype The query type to check against. * @return true if the NSEC proves the condition. */ public static NsecProvesNodataResponse nsecProvesNodata( SRRset set, NSECRecord nsec, Name qname, int qtype) { NsecProvesNodataResponse result = new NsecProvesNodataResponse(); if (!set.getName().equals(qname)) { // empty-non-terminal checking. // Done before wildcard, because this is an exact match, // and would prevent a wildcard from matching. // If the nsec is proving that qname is an ENT, the nsec owner will // be less than qname, and the next name will be a child domain of // the qname. if (strictSubdomain(nsec.getNext(), qname) && set.getName().compareTo(qname) < 0) { result.result = true; return result; } // Wildcard checking: // If this is a wildcard NSEC, make sure that a) it was possible to // have generated qname from the wildcard and b) the type map does // not contain qtype. Note that this does NOT prove that this // wildcard was the applicable wildcard. if (set.getName().isWild()) { // the is the purported closest encloser. Name ce = new Name(set.getName(), 1); // The qname must be a strict subdomain of the closest encloser, // and the qtype must be absent from the type map. if (strictSubdomain(qname, ce)) { if (nsec.hasType(Type.CNAME)) { // should have gotten the wildcard CNAME log.debug("NSEC proofed wildcard CNAME"); result.result = false; return result; } if (nsec.hasType(Type.NS) && !nsec.hasType(Type.SOA)) { // wrong parentside (wildcard) NSEC used, and it really // should not exist anyway: // http://tools.ietf.org/html/rfc4592#section-4.2 log.debug("Wrong parent (wildcard) NSEC used"); result.result = false; return result; } if (nsec.hasType(qtype)) { log.debug("NSEC proofed that {} exists", Type.string(qtype)); result.result = false; return result; } } result.wc = ce; result.result = true; return result; } // Otherwise, this NSEC does not prove ENT, so it does not prove // NODATA. result.result = false; return result; } // If the qtype exists, then we should have gotten it. if (nsec.hasType(qtype)) { log.debug("NSEC proofed that {} exists", Type.string(qtype)); result.result = false; return result; } // if the name is a CNAME node, then we should have gotten the CNAME if (nsec.hasType(Type.CNAME)) { log.debug("NSEC proofed CNAME"); result.result = false; return result; } // If an NS set exists at this name, and NOT a SOA (so this is a zone // cut, not a zone apex), then we should have gotten a referral (or we // just got the wrong NSEC). // The reverse of this check is used when qtype is DS, since that // must use the NSEC from above the zone cut. if (qtype != Type.DS && nsec.hasType(Type.NS) && !nsec.hasType(Type.SOA)) { log.debug("NSEC proofed missing referral"); result.result = false; return result; } if (qtype == Type.DS && nsec.hasType(Type.SOA) && !Name.root.equals(qname)) { log.debug("NSEC from wrong zone"); result.result = false; return result; } result.result = true; return result; } /** * Check DS absence. There is a NODATA reply to a DS that needs checking. NSECs can prove this is * not a delegation point, or successfully prove that there is no DS. Or this fails. * * @param request The request that generated this response. * @param response The response to validate. * @param keyRrset The key that validate the NSECs. * @param date The date against which to verify the response. * @return The NODATA proof along with the reason of the result. */ public JustifiedSecStatus nsecProvesNodataDsReply( Message request, SMessage response, SRRset keyRrset, Instant date) { Name qname = request.getQuestion().getName(); int qclass = request.getQuestion().getDClass(); // If we have a NSEC at the same name, it must prove one of two things: // 1) this is a delegation point and there is no DS // 2) this is not a delegation point SRRset nsecRrset = response.findRRset(qname, Type.NSEC, qclass, Section.AUTHORITY); if (nsecRrset != null) { // The NSEC must verify, first of all. JustifiedSecStatus res = this.verifySRRset(nsecRrset, keyRrset, date); if (res.status != SecurityStatus.SECURE) { return new JustifiedSecStatus( SecurityStatus.BOGUS, ExtendedErrorCodeOption.DNSSEC_BOGUS, R.get("failed.ds.nsec", res.reason)); } NSECRecord nsec = (NSECRecord) nsecRrset.first(); SecurityStatus status = ValUtils.nsecProvesNoDS(nsec, qname); switch (status) { case INSECURE: // this wasn't a delegation point. return new JustifiedSecStatus(status, -1, R.get("failed.ds.nodelegation")); case SECURE: // this proved no DS. return new JustifiedSecStatus(status, -1, R.get("insecure.ds.nsec")); default: // something was wrong. return new JustifiedSecStatus( status, ExtendedErrorCodeOption.DNSSEC_BOGUS, R.get("failed.ds.nsec.hasdata")); } } // Otherwise, there is no NSEC at qname. This could be an ENT. // If not, this is broken. NsecProvesNodataResponse ndp = new NsecProvesNodataResponse(); Name ce = null; boolean hasValidNSEC = false; NSECRecord wcNsec = null; for (SRRset set : response.getSectionRRsets(Section.AUTHORITY, Type.NSEC)) { JustifiedSecStatus res = this.verifySRRset(set, keyRrset, date); if (res.status != SecurityStatus.SECURE) { return new JustifiedSecStatus(res.status, res.edeReason, R.get("failed.ds.nsec.ent")); } NSECRecord nsec = (NSECRecord) set.rrs().get(0); ndp = ValUtils.nsecProvesNodata(set, nsec, qname, Type.DS); if (ndp.result) { hasValidNSEC = true; if (ndp.wc != null && nsec.getName().isWild()) { wcNsec = nsec; } } if (ValUtils.nsecProvesNameError(set, nsec, qname)) { ce = closestEncloser(qname, set.getName(), nsec.getNext()); } } // The wildcard NODATA is 1 NSEC proving that qname does not exists (and // also proving what the closest encloser is), and 1 NSEC showing the // matching wildcard, which must be *.closest_encloser. if (ndp.wc != null && (ce == null || !ce.equals(ndp.wc))) { hasValidNSEC = false; } if (hasValidNSEC) { if (ndp.wc != null) { SecurityStatus status = nsecProvesNoDS(wcNsec, qname); return new JustifiedSecStatus( status, ExtendedErrorCodeOption.NSEC_MISSING, R.get("failed.ds.nowildcardproof")); } return new JustifiedSecStatus(SecurityStatus.INSECURE, -1, R.get("insecure.ds.nsec.ent")); } return new JustifiedSecStatus( SecurityStatus.UNCHECKED, ExtendedErrorCodeOption.DNSSEC_INDETERMINATE, R.get("failed.ds.nonconclusive")); } /** * Checks if the authority section of a message contains at least one signed NSEC or NSEC3 record. * * @param message The message to inspect. * @return True if at least one record is found, false otherwise. */ public boolean hasSignedNsecs(SMessage message) { for (SRRset set : message.getSectionRRsets(Section.AUTHORITY)) { if ((set.getType() == Type.NSEC || set.getType() == Type.NSEC3) && !set.sigs().isEmpty()) { return true; } } return false; } /** * Determines whether the given {@link NSECRecord} proves that there is no {@link DSRecord} for * <code>qname</code>. * * @param nsec The NSEC that should prove the non-existence. * @param qname The name for which the prove is made. * @return {@link SecurityStatus#BOGUS} when the NSEC is from the child domain or indicates that * there indeed is a DS record, {@link SecurityStatus#INSECURE} when there is not even a prove * for a NS record, {@link SecurityStatus#SECURE} when there is no DS record. */ public static SecurityStatus nsecProvesNoDS(NSECRecord nsec, Name qname) { // Could check to make sure the qname is a subdomain of nsec if ((nsec.hasType(Type.SOA) && !Name.root.equals(qname)) || nsec.hasType(Type.DS)) { // SOA present means that this is the NSEC from the child, not the // parent (so it is the wrong one) -> cannot happen because the // keyset is always from the parent zone and doesn't validate the // NSEC // DS present means that there should have been a positive response // to the DS query, so there is something wrong. return SecurityStatus.BOGUS; } if (!nsec.hasType(Type.NS)) { // If there is no NS at this point at all, then this doesn't prove // anything one way or the other. return SecurityStatus.INSECURE; } // Otherwise, this proves no DS. return SecurityStatus.SECURE; } /** * Determines if at least one of the DS records in the RRset has a supported algorithm. * * @param dsRRset The RR set to search in. * @return True when at least one DS record uses a supported algorithm, false otherwise. */ boolean atLeastOneSupportedAlgorithm(RRset dsRRset) { for (Record r : dsRRset.rrs()) { if (isAlgorithmSupported(((DSRecord) r).getAlgorithm())) { return true; } // do nothing, there could be another DS we understand } return false; } /** * Determines if the algorithm is supported. * * @param alg The algorithm to check. * @return True when the algorithm is supported, false otherwise. */ boolean isAlgorithmSupported(int alg) { String configKey = ALGORITHM_ENABLED + "." + alg; switch (alg) { case Algorithm.RSAMD5: return false; // obsoleted by rfc6725 case Algorithm.DSA: case Algorithm.DSA_NSEC3_SHA1: if (config == null) { return false; } return Boolean.parseBoolean(config.getProperty(configKey, Boolean.FALSE.toString())); case Algorithm.RSASHA1: case Algorithm.RSA_NSEC3_SHA1: case Algorithm.RSASHA256: case Algorithm.RSASHA512: case Algorithm.ECDSAP256SHA256: case Algorithm.ECDSAP384SHA384: return propertyOrTrueWithPrecondition(configKey, true); case Algorithm.ECC_GOST: return propertyOrTrueWithPrecondition(configKey, hasGost); case Algorithm.ED25519: return propertyOrTrueWithPrecondition(configKey, hasEd25519); case Algorithm.ED448: return propertyOrTrueWithPrecondition(configKey, hasEd448); default: return false; } } /** * Determines if at least one of the DS records in the RRset has a supported digest algorithm. * * @param dsRRset The RR set to search in. * @return True when at least one DS record uses a supported digest algorithm, false otherwise. */ boolean atLeastOneDigestSupported(RRset dsRRset) { for (Record r : dsRRset.rrs()) { if (isDigestSupported(((DSRecord) r).getDigestID())) { return true; } // do nothing, there could be another DS we understand } return false; } /** * Determines if the digest algorithm is supported. * * @param digestID the algorithm to check. * @return True when the digest algorithm is supported, false otherwise. */ boolean isDigestSupported(int digestID) { String configKey = DIGEST_ENABLED + "." + digestID; switch (digestID) { case DNSSEC.Digest.SHA1: case DNSSEC.Digest.SHA256: case DNSSEC.Digest.SHA384: if (config == null) { return true; } return Boolean.parseBoolean(config.getProperty(configKey, Boolean.TRUE.toString())); case DNSSEC.Digest.GOST3411: return propertyOrTrueWithPrecondition(configKey, hasGost); default: return false; } } private boolean propertyOrTrueWithPrecondition(String configKey, boolean precondition) { if (!precondition) { return false; } if (config == null) { return true; } return Boolean.parseBoolean(config.getProperty(configKey, Boolean.TRUE.toString())); } }
3e0ff17d7d58bca9eb82c3f05c18f71acd4e2039
3,092
java
Java
canal-glue-example/src/test/java/cn/throwx/canal/gule/example/ch5/Client5App.java
zjcscut/canal-glue
65cf346a93788d375ee0e987d67d81ea4f039bb6
[ "MIT" ]
13
2020-10-07T04:08:58.000Z
2022-01-25T07:21:14.000Z
canal-glue-example/src/test/java/cn/throwx/canal/gule/example/ch5/Client5App.java
zjcscut/canal-glue
65cf346a93788d375ee0e987d67d81ea4f039bb6
[ "MIT" ]
null
null
null
canal-glue-example/src/test/java/cn/throwx/canal/gule/example/ch5/Client5App.java
zjcscut/canal-glue
65cf346a93788d375ee0e987d67d81ea4f039bb6
[ "MIT" ]
2
2020-10-17T01:15:24.000Z
2021-12-16T07:18:14.000Z
40.684211
128
0.742238
6,768
package cn.throwx.canal.gule.example.ch5; import cn.throwx.canal.gule.DefaultCanalGlue; import cn.throwx.canal.gule.annotation.CanalModel; import cn.throwx.canal.gule.common.FieldNamingPolicy; import cn.throwx.canal.gule.model.CanalBinLogResult; import cn.throwx.canal.gule.support.parser.*; import cn.throwx.canal.gule.support.parser.converter.CanalFieldConverterFactory; import cn.throwx.canal.gule.support.parser.converter.InMemoryCanalFieldConverterFactory; import cn.throwx.canal.gule.support.processor.BaseCanalBinlogEventProcessor; import cn.throwx.canal.gule.support.processor.CanalBinlogEventProcessorFactory; import cn.throwx.canal.gule.support.processor.InMemoryCanalBinlogEventProcessorFactory; import com.alibaba.fastjson.JSON; import lombok.Data; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ClassPathResource; import org.springframework.util.StreamUtils; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; /** * @author throwable * @version v1 * @description * @since 2020/9/28 23:16 */ public class Client5App { public static void main(String[] args) throws Exception { String event = StreamUtils.copyToString(new ClassPathResource("ch5.json").getInputStream(), StandardCharsets.UTF_8); CanalBinlogEventProcessorFactory processorFactory = InMemoryCanalBinlogEventProcessorFactory.of(); DefaultCanalGlue canalGlue = DefaultCanalGlue.of(processorFactory); CanalFieldConverterFactory converterFactory = InMemoryCanalFieldConverterFactory.of(); CanalBinLogEventParser binLogEventParser = DefaultCanalBinLogEventParser.of(); ModelTableMetadataManager modelTableMetadataManager = InMemoryModelTableMetadataManager.of(converterFactory); ParseResultInterceptorManager interceptorManager = InMemoryParseResultInterceptorManager.of(modelTableMetadataManager); OrderProcessor orderProcessor = new OrderProcessor(); orderProcessor.init( binLogEventParser, modelTableMetadataManager, processorFactory, interceptorManager ); canalGlue.process(event); } @Data @CanalModel(database = "db_order_service", table = "t_order", fieldNamingPolicy = FieldNamingPolicy.LOWER_UNDERSCORE) public static class OrderModel { private Long id; private String orderId; private OffsetDateTime createTime; private BigDecimal amount; } public static class OrderProcessor extends BaseCanalBinlogEventProcessor<OrderModel> { @Override protected void processInsertInternal(CanalBinLogResult<OrderModel> result) { OrderModel orderModel = result.getAfterData(); logger.info("接收到订单保存binlog,主键:{},写入数据:{}", result.getPrimaryKey(), JSON.toJSONString(orderModel)); } } @Bean public OrderProcessor orderProcessor() { return new OrderProcessor(); } }
3e0ff2705ee66929fae780c3616a660d9d1a6d3e
1,308
java
Java
kratos-shard/src/main/java/com/gxl/kratos/sql/dialect/mysql/ast/clause/MySqlIterateStatement.java
XHidamariSketchX/kratos
674b82ccfe4dc31b7f1c4db88ad5c1a5b5751e02
[ "Apache-2.0" ]
null
null
null
kratos-shard/src/main/java/com/gxl/kratos/sql/dialect/mysql/ast/clause/MySqlIterateStatement.java
XHidamariSketchX/kratos
674b82ccfe4dc31b7f1c4db88ad5c1a5b5751e02
[ "Apache-2.0" ]
null
null
null
kratos-shard/src/main/java/com/gxl/kratos/sql/dialect/mysql/ast/clause/MySqlIterateStatement.java
XHidamariSketchX/kratos
674b82ccfe4dc31b7f1c4db88ad5c1a5b5751e02
[ "Apache-2.0" ]
null
null
null
27.808511
75
0.737567
6,769
/* * Copyright 1999-2101 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gxl.kratos.sql.dialect.mysql.ast.clause; import com.gxl.kratos.sql.dialect.mysql.ast.statement.MySqlStatementImpl; import com.gxl.kratos.sql.dialect.mysql.visitor.MySqlASTVisitor; /** * * @Description: MySql procedure iterate statement * @author zz email:upchh@example.com * @date 2015-9-14 * @version V1.0 */ public class MySqlIterateStatement extends MySqlStatementImpl { private String labelName; @Override public void accept0(MySqlASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } }
3e0ff3ea779b357643353e9e5f5644f39488ab53
4,683
java
Java
src/main/java/tamaized/frostfell/world/FrostfellChunkGenerator.java
Tamaized/Frostfell
6ac23bc95192bd435be372aeffde0e2c171d1e78
[ "MIT" ]
null
null
null
src/main/java/tamaized/frostfell/world/FrostfellChunkGenerator.java
Tamaized/Frostfell
6ac23bc95192bd435be372aeffde0e2c171d1e78
[ "MIT" ]
null
null
null
src/main/java/tamaized/frostfell/world/FrostfellChunkGenerator.java
Tamaized/Frostfell
6ac23bc95192bd435be372aeffde0e2c171d1e78
[ "MIT" ]
1
2019-10-25T21:35:43.000Z
2019-10-25T21:35:43.000Z
38.702479
312
0.801836
6,770
package tamaized.frostfell.world; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import it.unimi.dsi.fastutil.ints.IntArraySet; import it.unimi.dsi.fastutil.ints.IntSet; import net.minecraft.CrashReport; import net.minecraft.ReportedException; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.core.SectionPos; import net.minecraft.resources.RegistryLookupCodec; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.StructureFeatureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.TerrainShaper; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.NoiseSamplingSettings; import net.minecraft.world.level.levelgen.NoiseSettings; import net.minecraft.world.level.levelgen.NoiseSlider; import net.minecraft.world.level.levelgen.WorldgenRandom; import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.synth.NormalNoise; import tamaized.frostfell.asm.ASMHooks; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; public class FrostfellChunkGenerator extends NoiseBasedChunkGenerator { public static final Codec<FrostfellChunkGenerator> codec = RecordCodecBuilder.create((p_236091_0_) -> p_236091_0_. group(RegistryLookupCodec.create(Registry.NOISE_REGISTRY). forGetter((p_188716_) -> p_188716_.noises), BiomeSource.CODEC. fieldOf("biome_source"). forGetter(ChunkGenerator::getBiomeSource), Codec.LONG. fieldOf("seed").orElseGet(() -> ASMHooks.SEED). forGetter(gen -> gen.seed), NoiseGeneratorSettings.CODEC. fieldOf("settings"). forGetter(FrostfellChunkGenerator::getDimensionSettings)). apply(p_236091_0_, p_236091_0_.stable(FrostfellChunkGenerator::new))); private final Registry<NormalNoise.NoiseParameters> noises; private long seed; private FrostfellChunkGenerator(Registry<NormalNoise.NoiseParameters> noiseRegistry, BiomeSource biomeProvider1, long seed, Supplier<NoiseGeneratorSettings> dimensionSettings) { super(noiseRegistry, biomeProvider1, seed, fixSettings(dimensionSettings)); this.noises = noiseRegistry; this.seed = seed; } /** * Lazy load the ASM changes */ private static Supplier<NoiseGeneratorSettings> fixSettings(Supplier<NoiseGeneratorSettings> settings) { return () -> fixSettings(settings.get()); } /** * This is altered via ASM to use {@link CorrectedNoiseSettings} instead of {@link NoiseSettings} */ private static NoiseGeneratorSettings fixSettings(NoiseGeneratorSettings settings) { NoiseSettings s = settings.noiseSettings(); settings.noiseSettings = new NoiseSettings(s.minY(), s.height(), s.noiseSamplingSettings(), s.topSlideSettings(), s.bottomSlideSettings(), s.noiseSizeHorizontal(), s.noiseSizeVertical(), s.islandNoiseOverride(), s.isAmplified(), s.largeBiomes(), s.terrainShaper()); return settings; } @Override protected Codec<? extends ChunkGenerator> codec() { return codec; } @Override public ChunkGenerator withSeed(long seed) { return new FrostfellChunkGenerator(noises, biomeSource.withSeed(seed), seed, getDimensionSettings()); } private Supplier<NoiseGeneratorSettings> getDimensionSettings() { return settings; } /** * Extends {@link NoiseSettings)} via asm */ @SuppressWarnings("unused") private static class CorrectedNoiseSettings { private final int noiseSizeHorizontal; private CorrectedNoiseSettings(int minY, int height, NoiseSamplingSettings noiseSamplingSettings, NoiseSlider topSlideSettings, NoiseSlider bottomSlideSettings, int noiseSizeHorizontal, int noiseSizeVertical, boolean islandNoiseOverride, boolean isAmplified, boolean largeBiomes, TerrainShaper terrainShaper) { this.noiseSizeHorizontal = noiseSizeHorizontal; } public int getCellWidth() { return noiseSizeHorizontal << 1; } } }
3e0ff46a1a1be7098f5b70d27d341168568c3964
325
java
Java
src/blobs/Main.java
carlriis/Blobs
9f5b73cbaf03f797455c7c07390fd39d73d9b3dd
[ "MIT" ]
2
2019-09-24T20:52:47.000Z
2020-02-10T15:19:24.000Z
src/blobs/Main.java
carlriis/Blobs
9f5b73cbaf03f797455c7c07390fd39d73d9b3dd
[ "MIT" ]
null
null
null
src/blobs/Main.java
carlriis/Blobs
9f5b73cbaf03f797455c7c07390fd39d73d9b3dd
[ "MIT" ]
null
null
null
20.3125
56
0.735385
6,771
package blobs; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame window = new JFrame("Blobs"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setContentPane(new MainPanel()); window.pack(); window.setVisible(true); window.setResizable(false); } }
3e0ff56ff347a1b6aaa99846e82e52c4683f4e31
1,296
java
Java
app/src/main/java/com/aspsine/zhihu/daily/respository/interfaces/Repository.java
Aspsine/DailyMaster
94a470bc37aa0a6b5663a7f5f473c99de3d0d73e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/aspsine/zhihu/daily/respository/interfaces/Repository.java
Aspsine/DailyMaster
94a470bc37aa0a6b5663a7f5f473c99de3d0d73e
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/aspsine/zhihu/daily/respository/interfaces/Repository.java
Aspsine/DailyMaster
94a470bc37aa0a6b5663a7f5f473c99de3d0d73e
[ "Apache-2.0" ]
null
null
null
27
106
0.698302
6,772
package com.aspsine.zhihu.daily.respository.interfaces; import com.aspsine.zhihu.daily.model.DailyStories; import com.aspsine.zhihu.daily.model.StartImage; import com.aspsine.zhihu.daily.model.Story; import com.aspsine.zhihu.daily.model.Theme; import com.aspsine.zhihu.daily.model.Themes; import com.nostra13.universalimageloader.core.DisplayImageOptions; /** * Created by Aspsine on 2015/4/21. */ public interface Repository { void getStartImage(int width, int height, DisplayImageOptions options, Callback<StartImage> callback); void getLatestDailyStories(Callback<DailyStories> callback); void getBeforeDailyStories(String date, Callback<DailyStories> callback); void getStoryDetail(String storyId, Callback<Story> callback); void getThemes(Callback<Themes> callback); void getTheme(String themeId, Callback<Theme> callback); void getThemeBeforeStory(String themeId, String storyId, Callback<Theme> callback); public interface Callback<T> { /** * Successful * * @param t * @param outDate */ public void success(T t, boolean outDate); /** * Unsuccessful * * @param e unexpected exception. */ public void failure(Exception e); } }
3e0ff5eba569510b47ca3c28d149df64a9aaba75
1,829
java
Java
board/board-service/src/main/java/com/welab/wefe/board/service/api/account/ResetPasswordApi.java
rinceyuan/WeFe
8482cb737cb7ba37b2856d184cd42c1bd35a6318
[ "Apache-2.0" ]
39
2021-10-12T01:43:27.000Z
2022-03-28T04:46:35.000Z
board/board-service/src/main/java/com/welab/wefe/board/service/api/account/ResetPasswordApi.java
rinceyuan/WeFe
8482cb737cb7ba37b2856d184cd42c1bd35a6318
[ "Apache-2.0" ]
6
2021-10-14T02:11:47.000Z
2022-03-23T02:41:50.000Z
board/board-service/src/main/java/com/welab/wefe/board/service/api/account/ResetPasswordApi.java
rinceyuan/WeFe
8482cb737cb7ba37b2856d184cd42c1bd35a6318
[ "Apache-2.0" ]
10
2021-10-14T09:36:03.000Z
2022-02-10T11:05:12.000Z
32.087719
84
0.727173
6,773
/** * Copyright 2021 Tianmian Tech. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.welab.wefe.board.service.api.account; import com.welab.wefe.board.service.service.account.AccountService; import com.welab.wefe.common.exception.StatusCodeWithException; import com.welab.wefe.common.fieldvalidate.annotation.Check; import com.welab.wefe.common.web.api.base.AbstractApi; import com.welab.wefe.common.web.api.base.Api; import com.welab.wefe.common.web.dto.AbstractApiInput; import com.welab.wefe.common.web.dto.ApiResult; import org.springframework.beans.factory.annotation.Autowired; /** * @author lonnie */ @Api(path = "account/reset/password", name = "reset account password") public class ResetPasswordApi extends AbstractApi<ResetPasswordApi.Input, String> { @Autowired private AccountService accountService; @Override protected ApiResult<String> handle(Input input) throws StatusCodeWithException { return success(accountService.resetPassword(input)); } public static class Input extends AbstractApiInput { @Check(name = "用户唯一标识", require = true) private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } } }
3e0ff68e63e28fad4ba3a079e9a57513b7595483
2,113
java
Java
extensions/api/data-management/contractnegotiation/src/test/java/org/eclipse/dataspaceconnector/api/datamanagement/contractnegotiation/transform/NegotiationInitiateRequestDtoToDataRequestTransformerTest.java
florianrusch-zf/DataSpaceConnector
e7929562e592f5fc3a5fedf2e3913f92b935b90f
[ "Apache-2.0" ]
null
null
null
extensions/api/data-management/contractnegotiation/src/test/java/org/eclipse/dataspaceconnector/api/datamanagement/contractnegotiation/transform/NegotiationInitiateRequestDtoToDataRequestTransformerTest.java
florianrusch-zf/DataSpaceConnector
e7929562e592f5fc3a5fedf2e3913f92b935b90f
[ "Apache-2.0" ]
null
null
null
extensions/api/data-management/contractnegotiation/src/test/java/org/eclipse/dataspaceconnector/api/datamanagement/contractnegotiation/transform/NegotiationInitiateRequestDtoToDataRequestTransformerTest.java
florianrusch-zf/DataSpaceConnector
e7929562e592f5fc3a5fedf2e3913f92b935b90f
[ "Apache-2.0" ]
null
null
null
38.418182
146
0.734974
6,774
/* * Copyright (c) 2022 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 * * Contributors: * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation * */ package org.eclipse.dataspaceconnector.api.datamanagement.contractnegotiation.transform; import org.eclipse.dataspaceconnector.api.datamanagement.contractnegotiation.model.NegotiationInitiateRequestDto; import org.eclipse.dataspaceconnector.spi.transformer.TransformerContext; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.dataspaceconnector.spi.types.domain.contract.negotiation.ContractOfferRequest.Type.INITIAL; import static org.mockito.Mockito.mock; class NegotiationInitiateRequestDtoToDataRequestTransformerTest { private final NegotiationInitiateRequestDtoToDataRequestTransformer transformer = new NegotiationInitiateRequestDtoToDataRequestTransformer(); @Test void inputOutputType() { assertThat(transformer.getInputType()).isNotNull(); assertThat(transformer.getOutputType()).isNotNull(); } @Test void transform() { var context = mock(TransformerContext.class); var dto = NegotiationInitiateRequestDto.Builder.newInstance() .connectorId("connectorId") .connectorAddress("address") .protocol("protocol") .offerId("offerId") .build(); var request = transformer.transform(dto, context); assertThat(request.getConnectorId()).isEqualTo("connectorId"); assertThat(request.getConnectorAddress()).isEqualTo("address"); assertThat(request.getProtocol()).isEqualTo("protocol"); assertThat(request.getType()).isEqualTo(INITIAL); assertThat(request.getContractOffer().getId()).isEqualTo("offerId"); } }
3e0ff99278042ec6f3fe1f0d1cf4ce1371b7eef7
1,074
java
Java
bible-services/src/main/java/org/sacredscripture/platform/internal/bible/dao/package-info.java
SacredScriptureFoundation/sacredscripture
29a4f239c9ad564b084ebef9fd1c2c3fd238a04e
[ "Apache-2.0" ]
null
null
null
bible-services/src/main/java/org/sacredscripture/platform/internal/bible/dao/package-info.java
SacredScriptureFoundation/sacredscripture
29a4f239c9ad564b084ebef9fd1c2c3fd238a04e
[ "Apache-2.0" ]
null
null
null
bible-services/src/main/java/org/sacredscripture/platform/internal/bible/dao/package-info.java
SacredScriptureFoundation/sacredscripture
29a4f239c9ad564b084ebef9fd1c2c3fd238a04e
[ "Apache-2.0" ]
null
null
null
39.777778
76
0.723464
6,775
/* * Copyright (c) 2014 Sacred Scripture Foundation. * "All scripture is given by inspiration of God, and is profitable for * doctrine, for reproof, for correction, for instruction in righteousness: * That the man of God may be perfect, throughly furnished unto all good * works." (2 Tim 3:16-17) * * 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. */ /** * Data access objects for bible-related entities. * * @author Paul Benedict * @since Sacred Scripture Platform 1.0 */ package org.sacredscripture.platform.internal.bible.dao;
3e0ffa66a9154a5757f6273abd20f680720cde4f
1,352
java
Java
izpack-util/src/main/java/com/izforge/izpack/util/xmlmerge/action/PreserveAction.java
spyrkob/izpack
618b6601317832e1420e01e25b3a139c32f49023
[ "Apache-2.0" ]
236
2015-01-13T02:31:06.000Z
2022-03-31T01:47:11.000Z
izpack-util/src/main/java/com/izforge/izpack/util/xmlmerge/action/PreserveAction.java
spyrkob/izpack
618b6601317832e1420e01e25b3a139c32f49023
[ "Apache-2.0" ]
283
2015-01-15T20:56:32.000Z
2022-03-28T07:00:31.000Z
izpack-util/src/main/java/com/izforge/izpack/util/xmlmerge/action/PreserveAction.java
spyrkob/izpack
618b6601317832e1420e01e25b3a139c32f49023
[ "Apache-2.0" ]
209
2015-01-13T14:55:50.000Z
2022-02-09T14:42:39.000Z
28.166667
99
0.716716
6,776
/* * IzPack - Copyright 2001-2010 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2009 Laurent Bovet, Alex Mathey * Copyright 2010, 2012 René Krell * * 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.izforge.izpack.util.xmlmerge.action; import org.jdom2.Element; import com.izforge.izpack.util.xmlmerge.Action; /** * Copies the original regardless of the existence of patch element. * * @author Laurent Bovet (LBO) * @author Alex Mathey (AMA) */ public class PreserveAction implements Action { @Override public void perform(Element originalElement, Element patchElement, Element outputParentElement) { if (originalElement != null) { outputParentElement.addContent((Element) originalElement.clone()); } } }
3e0ffa71e9ff95daab2b011c49e3efa968c3e157
556
java
Java
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/healthLifesci/clazz/MuscleConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
1
2020-02-18T01:55:36.000Z
2020-02-18T01:55:36.000Z
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/healthLifesci/clazz/MuscleConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
schemaOrgDomaConv/src/org/kyojo/schemaorg/m3n4/doma/healthLifesci/clazz/MuscleConverter.java
nagaikenshin/schemaOrg
4c9d6d098a2741c2dc2a814f1c708ee55c36e9a8
[ "Apache-2.0" ]
null
null
null
24.173913
73
0.805755
6,777
package org.kyojo.schemaorg.m3n4.doma.healthLifesci.clazz; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n4.healthLifesci.impl.MUSCLE; import org.kyojo.schemaorg.m3n4.healthLifesci.Clazz.Muscle; @ExternalDomain public class MuscleConverter implements DomainConverter<Muscle, String> { @Override public String fromDomainToValue(Muscle domain) { return domain.getNativeValue(); } @Override public Muscle fromValueToDomain(String value) { return new MUSCLE(value); } }
3e0ffaec8f7c67822dfbfc696569e881262a330a
70,816
java
Java
elide-core/src/main/java/com/yahoo/elide/core/PersistentResource.java
dvarshney1/elide
e14c3fb136900171a392092a9bd9569dab1cddbb
[ "Apache-2.0" ]
null
null
null
elide-core/src/main/java/com/yahoo/elide/core/PersistentResource.java
dvarshney1/elide
e14c3fb136900171a392092a9bd9569dab1cddbb
[ "Apache-2.0" ]
null
null
null
elide-core/src/main/java/com/yahoo/elide/core/PersistentResource.java
dvarshney1/elide
e14c3fb136900171a392092a9bd9569dab1cddbb
[ "Apache-2.0" ]
null
null
null
39.941342
120
0.636382
6,778
/* * Copyright 2018, Yahoo Inc. * Licensed under the Apache License, Version 2.0 * See LICENSE file in project root for terms. */ package com.yahoo.elide.core; import com.yahoo.elide.annotation.Audit; import com.yahoo.elide.annotation.CreatePermission; import com.yahoo.elide.annotation.DeletePermission; import com.yahoo.elide.annotation.ReadPermission; import com.yahoo.elide.annotation.SharePermission; import com.yahoo.elide.annotation.UpdatePermission; import com.yahoo.elide.audit.InvalidSyntaxException; import com.yahoo.elide.audit.LogMessage; import com.yahoo.elide.core.exceptions.BadRequestException; import com.yahoo.elide.core.exceptions.ForbiddenAccessException; import com.yahoo.elide.core.exceptions.InternalServerErrorException; import com.yahoo.elide.core.exceptions.InvalidAttributeException; import com.yahoo.elide.core.exceptions.InvalidEntityBodyException; import com.yahoo.elide.core.exceptions.InvalidObjectIdentifierException; import com.yahoo.elide.core.filter.InPredicate; import com.yahoo.elide.core.filter.expression.AndFilterExpression; import com.yahoo.elide.core.filter.expression.FilterExpression; import com.yahoo.elide.core.pagination.Pagination; import com.yahoo.elide.core.sort.Sorting; import com.yahoo.elide.jsonapi.models.Data; import com.yahoo.elide.jsonapi.models.Relationship; import com.yahoo.elide.jsonapi.models.Resource; import com.yahoo.elide.jsonapi.models.ResourceIdentifier; import com.yahoo.elide.jsonapi.models.SingleElementSet; import com.yahoo.elide.parsers.expression.CanPaginateVisitor; import com.yahoo.elide.security.ChangeSpec; import com.yahoo.elide.security.permissions.ExpressionResult; import com.yahoo.elide.utils.coerce.CoerceUtil; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IterableUtils; import org.apache.commons.lang3.StringUtils; import lombok.NonNull; import java.io.Serializable; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Resource wrapper around Entity bean. * * @param <T> type of resource */ public class PersistentResource<T> implements com.yahoo.elide.security.PersistentResource<T> { protected T obj; private final String type; private final ResourceLineage lineage; private final Optional<String> uuid; private final DataStoreTransaction transaction; private final RequestScope requestScope; private int hashCode = 0; static final String CLASS_NO_FIELD = ""; /** * The Dictionary. */ protected final EntityDictionary dictionary; /* Sort strings first by length then contents */ private final Comparator<String> lengthFirstComparator = (string1, string2) -> { int diff = string1.length() - string2.length(); return diff == 0 ? string1.compareTo(string2) : diff; }; @Override public String toString() { return String.format("PersistentResource{type=%s, id=%s}", type, uuid.orElse(getId())); } /** * Create a resource in the database. * @param parent - The immediate ancestor in the lineage or null if this is a root. * @param entityClass the entity class * @param requestScope the request scope * @param uuid the (optional) uuid * @param <T> object type * @return persistent resource */ public static <T> PersistentResource<T> createObject( PersistentResource<?> parent, Class<T> entityClass, RequestScope requestScope, Optional<String> uuid) { //instead of calling transcation.createObject, create the new object here. T obj = requestScope.getTransaction().createNewObject(entityClass); String id = uuid.orElse(null); PersistentResource<T> newResource = new PersistentResource<>(obj, parent, id, requestScope); //The ID must be assigned before we add it to the new resources set. Persistent resource //hashcode and equals are only based on the ID/UUID & type. assignId(newResource, id); // Keep track of new resources for non shareable resources requestScope.getNewPersistentResources().add(newResource); checkPermission(CreatePermission.class, newResource); newResource.auditClass(Audit.Action.CREATE, new ChangeSpec(newResource, null, null, newResource.getObject())); requestScope.publishLifecycleEvent(newResource, CRUDEvent.CRUDAction.CREATE); String type = newResource.getType(); requestScope.setUUIDForObject(type, id, newResource.getObject()); // Initialize null ToMany collections requestScope.getDictionary().getRelationships(entityClass).stream() .filter(relationName -> newResource.getRelationshipType(relationName).isToMany() && newResource.getValueUnchecked(relationName) == null) .forEach(relationName -> newResource.setValue(relationName, new LinkedHashSet<>())); newResource.markDirty(); return newResource; } /** * Construct a new resource from the ID provided. * * @param obj the obj * @param parent the parent * @param id the id * @param scope the request scope */ public PersistentResource(@NonNull T obj, PersistentResource parent, String id, @NonNull RequestScope scope) { this.obj = obj; this.uuid = Optional.ofNullable(id); this.lineage = parent != null ? new ResourceLineage(parent.lineage, parent) : new ResourceLineage(); this.dictionary = scope.getDictionary(); this.type = dictionary.getJsonAliasFor(obj.getClass()); this.transaction = scope.getTransaction(); this.requestScope = scope; dictionary.initializeEntity(obj); } /** * Check whether an id matches for this persistent resource. * * @param checkId the check id * @return True if matches false otherwise */ @Override public boolean matchesId(String checkId) { if (checkId == null) { return false; } return uuid .map(checkId::equals) .orElseGet(() -> { String id = getId(); return !"0".equals(id) && !"null".equals(id) && checkId.equals(id); }); } /** * Load an single entity from the DB. * * @param loadClass resource type * @param id the id * @param requestScope the request scope * @param <T> type of resource * @return resource persistent resource * @throws InvalidObjectIdentifierException the invalid object identifier exception */ @SuppressWarnings("resource") @NonNull public static <T> PersistentResource<T> loadRecord( Class<T> loadClass, String id, RequestScope requestScope) throws InvalidObjectIdentifierException { Preconditions.checkNotNull(loadClass); Preconditions.checkNotNull(id); Preconditions.checkNotNull(requestScope); DataStoreTransaction tx = requestScope.getTransaction(); EntityDictionary dictionary = requestScope.getDictionary(); // Check the resource cache if exists Object obj = requestScope.getObjectById(dictionary.getJsonAliasFor(loadClass), id); if (obj == null) { // try to load object Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(loadClass, requestScope); Class<?> idType = dictionary.getIdType(loadClass); obj = tx.loadObject(loadClass, (Serializable) CoerceUtil.coerce(id, idType), permissionFilter, requestScope); if (obj == null) { throw new InvalidObjectIdentifierException(id, dictionary.getJsonAliasFor(loadClass)); } } PersistentResource<T> resource = new PersistentResource<>( loadClass.cast(obj), null, requestScope.getUUIDFor(obj), requestScope); // No need to have read access for a newly created object if (!requestScope.getNewResources().contains(resource)) { resource.checkFieldAwarePermissions(ReadPermission.class); } return resource; } /** * Get a FilterExpression parsed from FilterExpressionCheck. * * @param <T> the type parameter * @param loadClass the load class * @param requestScope the request scope * @return a FilterExpression defined by FilterExpressionCheck. */ private static <T> Optional<FilterExpression> getPermissionFilterExpression(Class<T> loadClass, RequestScope requestScope) { try { return requestScope.getPermissionExecutor().getReadPermissionFilter(loadClass); } catch (ForbiddenAccessException e) { return Optional.empty(); } } /** * Load a collection from the datastore. * * @param loadClass the load class * @param requestScope the request scope * @param ids a list of object identifiers to optionally load. Can be empty. * @return a filtered collection of resources loaded from the datastore. */ public static Set<PersistentResource> loadRecords( Class<?> loadClass, List<String> ids, Optional<FilterExpression> filter, Optional<Sorting> sorting, Optional<Pagination> pagination, RequestScope requestScope) { EntityDictionary dictionary = requestScope.getDictionary(); FilterExpression filterExpression; DataStoreTransaction tx = requestScope.getTransaction(); if (shouldSkipCollection(loadClass, ReadPermission.class, requestScope)) { if (ids.isEmpty()) { return Collections.emptySet(); } throw new InvalidObjectIdentifierException(ids.toString(), dictionary.getJsonAliasFor(loadClass)); } if (pagination.isPresent() && !pagination.get().isDefaultInstance() && !CanPaginateVisitor.canPaginate(loadClass, dictionary, requestScope)) { throw new BadRequestException(String.format("Cannot paginate %s", dictionary.getJsonAliasFor(loadClass))); } Set<PersistentResource> newResources = new LinkedHashSet<>(); if (!ids.isEmpty()) { String typeAlias = dictionary.getJsonAliasFor(loadClass); newResources = requestScope.getNewPersistentResources().stream() .filter(resource -> typeAlias.equals(resource.getType()) && ids.contains(resource.getUUID().orElse(""))) .collect(Collectors.toSet()); FilterExpression idExpression = buildIdFilterExpression(ids, loadClass, dictionary, requestScope); // Combine filters if necessary filterExpression = filter .map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)) .orElse(idExpression); } else { filterExpression = filter.orElse(null); } Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(loadClass, requestScope); if (permissionFilter.isPresent()) { if (filterExpression != null) { filterExpression = new AndFilterExpression(filterExpression, permissionFilter.get()); } else { filterExpression = permissionFilter.get(); } } Set<PersistentResource> existingResources = filter(ReadPermission.class, filter, new PersistentResourceSet(tx.loadObjects(loadClass, Optional.ofNullable(filterExpression), sorting, pagination.map(p -> p.evaluate(loadClass)), requestScope), requestScope)); Set<PersistentResource> allResources = Sets.union(newResources, existingResources); Set<String> allExpectedIds = allResources.stream() .map(resource -> (String) resource.getUUID().orElseGet(resource::getId)) .collect(Collectors.toSet()); Set<String> missedIds = Sets.difference(new HashSet<>(ids), allExpectedIds); if (!missedIds.isEmpty()) { throw new InvalidObjectIdentifierException(missedIds.toString(), dictionary.getJsonAliasFor(loadClass)); } return allResources; } /** * Update attribute in existing resource. * * @param fieldName the field name * @param newVal the new val * @return true if object updated, false otherwise */ public boolean updateAttribute(String fieldName, Object newVal) { Class<?> fieldClass = dictionary.getType(getResourceClass(), fieldName); newVal = dictionary.coerce(obj, newVal, fieldName, fieldClass); Object val = getValueUnchecked(fieldName); checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, newVal, val); if (!Objects.equals(val, newVal)) { this.setValueChecked(fieldName, newVal); this.markDirty(); //Hooks for customize logic for setAttribute/Relation if (dictionary.isAttribute(obj.getClass(), fieldName)) { transaction.setAttribute(obj, fieldName, newVal, requestScope); } return true; } return false; } /** * Perform a full replacement on relationships. * Here is an example: * The following are ids for a hypothetical relationship. * GIVEN: * all (all the ids in the DB) = 1,2,3,4,5 * mine (everything the current user has access to) = 1,2,3 * requested (what the user wants to change to) = 3,6 * THEN: * deleted (what gets removed from the DB) = 1,2 * final (what get stored in the relationship) = 3,4,5,6 * BECAUSE: * notMine = all - mine * updated = (requested UNION mine) - (requested INTERSECT mine) * deleted = (mine - requested) * final = (notMine) UNION requested * @param fieldName the field name * @param resourceIdentifiers the resource identifiers * @return True if object updated, false otherwise */ public boolean updateRelation(String fieldName, Set<PersistentResource> resourceIdentifiers) { RelationshipType type = getRelationshipType(fieldName); Set<PersistentResource> resources = filter(ReadPermission.class, Optional.empty(), getRelationUncheckedUnfiltered(fieldName)); boolean isUpdated; if (type.isToMany()) { List<Object> modifiedResources = CollectionUtils.isEmpty(resourceIdentifiers) ? Collections.emptyList() : resourceIdentifiers.stream().map(PersistentResource::getObject).collect(Collectors.toList()); checkFieldAwareDeferPermissions( UpdatePermission.class, fieldName, modifiedResources, resources.stream().map(PersistentResource::getObject).collect(Collectors.toList()) ); isUpdated = updateToManyRelation(fieldName, resourceIdentifiers, resources); } else { // To One Relationship PersistentResource resource = firstOrNullIfEmpty(resources); Object original = (resource == null) ? null : resource.getObject(); PersistentResource modifiedResource = firstOrNullIfEmpty(resourceIdentifiers); Object modified = (modifiedResource == null) ? null : modifiedResource.getObject(); checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, modified, original); isUpdated = updateToOneRelation(fieldName, resourceIdentifiers, resources); } return isUpdated; } /** * Updates a to-many relationship. * @param fieldName the field name * @param resourceIdentifiers the resource identifiers * @param mine Existing, filtered relationships for field name * @return true if updated. false otherwise */ protected boolean updateToManyRelation(String fieldName, Set<PersistentResource> resourceIdentifiers, Set<PersistentResource> mine) { Set<PersistentResource> requested; Set<PersistentResource> updated; Set<PersistentResource> deleted; Set<PersistentResource> added; if (resourceIdentifiers == null) { throw new InvalidEntityBodyException("Bad relation data"); } if (resourceIdentifiers.isEmpty()) { requested = new LinkedHashSet<>(); } else { // TODO - this resource does not include a lineage. This could cause issues for audit. requested = resourceIdentifiers; } // deleted = mine - requested deleted = Sets.difference(mine, requested); // updated = (requested UNION mine) - (requested INTERSECT mine) updated = Sets.difference( Sets.union(mine, requested), Sets.intersection(mine, requested) ); added = Sets.difference(updated, deleted); checkSharePermission(added); Collection collection = (Collection) this.getValueUnchecked(fieldName); if (collection == null) { this.setValue(fieldName, mine); } Set<Object> newRelationships = new LinkedHashSet<>(); Set<Object> deletedRelationships = new LinkedHashSet<>(); deleted .stream() .forEach(toDelete -> { delFromCollection(collection, fieldName, toDelete, false); deleteInverseRelation(fieldName, toDelete.getObject()); deletedRelationships.add(toDelete.getObject()); }); added .stream() .forEach(toAdd -> { addToCollection(collection, fieldName, toAdd); addInverseRelation(fieldName, toAdd.getObject()); newRelationships.add(toAdd.getObject()); }); if (!updated.isEmpty()) { this.markDirty(); } //hook for updateRelation transaction.updateToManyRelation(transaction, obj, fieldName, newRelationships, deletedRelationships, requestScope); return !updated.isEmpty(); } /** * Update a 2-one relationship. * * @param fieldName the field name * @param resourceIdentifiers the resource identifiers * @param mine Existing, filtered relationships for field name * @return true if updated. false otherwise */ protected boolean updateToOneRelation(String fieldName, Set<PersistentResource> resourceIdentifiers, Set<PersistentResource> mine) { Object newValue = null; PersistentResource newResource = null; if (CollectionUtils.isNotEmpty(resourceIdentifiers)) { newResource = IterableUtils.first(resourceIdentifiers); newValue = newResource.getObject(); } PersistentResource oldResource = firstOrNullIfEmpty(mine); if (oldResource == null) { if (newValue == null) { return false; } checkSharePermission(resourceIdentifiers); } else if (oldResource.getObject().equals(newValue)) { return false; } else { checkSharePermission(resourceIdentifiers); if (hasInverseRelation(fieldName)) { deleteInverseRelation(fieldName, oldResource.getObject()); oldResource.markDirty(); } } if (newResource != null) { if (hasInverseRelation(fieldName)) { addInverseRelation(fieldName, newValue); newResource.markDirty(); } } this.setValueChecked(fieldName, newValue); //hook for updateToOneRelation transaction.updateToOneRelation(transaction, obj, fieldName, newValue, requestScope); this.markDirty(); return true; } /** * Clear all elements from a relation. * * @param relationName Name of relation to clear * @return True if object updated, false otherwise */ public boolean clearRelation(String relationName) { Set<PersistentResource> mine = filter(ReadPermission.class, Optional.empty(), getRelationUncheckedUnfiltered(relationName)); checkFieldAwareDeferPermissions(UpdatePermission.class, relationName, Collections.emptySet(), mine.stream().map(PersistentResource::getObject).collect(Collectors.toSet())); if (mine.isEmpty()) { return false; } RelationshipType type = getRelationshipType(relationName); mine.stream() .forEach(toDelete -> { if (hasInverseRelation(relationName)) { deleteInverseRelation(relationName, toDelete.getObject()); toDelete.markDirty(); } }); if (type.isToOne()) { PersistentResource oldValue = IterableUtils.first(mine); if (oldValue != null && oldValue.getObject() != null) { this.nullValue(relationName, oldValue); oldValue.markDirty(); this.markDirty(); //hook for updateToOneRelation transaction.updateToOneRelation(transaction, obj, relationName, null, requestScope); } } else { Collection collection = (Collection) getValueUnchecked(relationName); if (CollectionUtils.isNotEmpty(collection)) { Set<Object> deletedRelationships = new LinkedHashSet<>(); mine.stream() .forEach(toDelete -> { delFromCollection(collection, relationName, toDelete, false); if (hasInverseRelation(relationName)) { toDelete.markDirty(); } deletedRelationships.add(toDelete.getObject()); }); this.markDirty(); //hook for updateToManyRelation transaction.updateToManyRelation(transaction, obj, relationName, new LinkedHashSet<>(), deletedRelationships, requestScope); } } return true; } /** * Remove a relationship. * * @param fieldName the field name * @param removeResource the remove resource */ public void removeRelation(String fieldName, PersistentResource removeResource) { Object relation = getValueUnchecked(fieldName); Object original = relation; Object modified = null; if (relation instanceof Collection) { original = copyCollection((Collection) relation); } if (relation instanceof Collection && removeResource != null) { modified = CollectionUtils.disjunction( (Collection) relation, Collections.singleton(removeResource.getObject()) ); } checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, modified, original); if (relation instanceof Collection) { if (removeResource == null || !((Collection) relation).contains(removeResource.getObject())) { //Nothing to do return; } delFromCollection((Collection) relation, fieldName, removeResource, false); } else { if (relation == null || removeResource == null || !relation.equals(removeResource.getObject())) { //Nothing to do return; } this.nullValue(fieldName, removeResource); } if (hasInverseRelation(fieldName)) { deleteInverseRelation(fieldName, removeResource.getObject()); removeResource.markDirty(); } if (!Objects.equals(original, modified)) { this.markDirty(); } RelationshipType type = getRelationshipType(fieldName); if (type.isToOne()) { //hook for updateToOneRelation transaction.updateToOneRelation(transaction, obj, fieldName, null, requestScope); } else { //hook for updateToManyRelation transaction.updateToManyRelation(transaction, obj, fieldName, new LinkedHashSet<>(), Sets.newHashSet(removeResource.getObject()), requestScope); } } /** * Checks whether the new entity is already a part of the relationship * @param fieldName which relation link * @param toAdd the new relation * @return boolean representing the result of the check * * This method does not handle the case where the toAdd entity is newly created, * since newly created entities have null id there is no easy way to check for identity */ public boolean relationshipAlreadyExists(String fieldName, PersistentResource toAdd) { Object relation = this.getValueUnchecked(fieldName); String toAddId = toAdd.getId(); if (toAddId == null) { return false; } if (relation instanceof Collection) { return ((Collection) relation).stream().anyMatch((obj -> toAddId.equals(dictionary.getId(obj)))); } return toAddId.equals(dictionary.getId(relation)); } /** * Add relation link from a given parent resource to a child resource. * * @param fieldName which relation link * @param newRelation the new relation */ public void addRelation(String fieldName, PersistentResource newRelation) { if (!newRelation.isNewlyCreated() && relationshipAlreadyExists(fieldName, newRelation)) { return; } checkSharePermission(Collections.singleton(newRelation)); Object relation = this.getValueUnchecked(fieldName); if (relation instanceof Collection) { if (addToCollection((Collection) relation, fieldName, newRelation)) { this.markDirty(); } //Hook for updateToManyRelation transaction.updateToManyRelation(transaction, obj, fieldName, Sets.newHashSet(newRelation.getObject()), new LinkedHashSet<>(), requestScope); addInverseRelation(fieldName, newRelation.getObject()); } else { // Not a collection, but may be trying to create a ToOne relationship. // NOTE: updateRelation marks dirty. updateRelation(fieldName, Collections.singleton(newRelation)); } } /** * Check if adding or updating a relation is allowed. * * @param resourceIdentifiers The persistent resources that are being added */ protected void checkSharePermission(Set<PersistentResource> resourceIdentifiers) { if (resourceIdentifiers == null) { return; } final Set<PersistentResource> newResources = getRequestScope().getNewPersistentResources(); for (PersistentResource persistentResource : resourceIdentifiers) { if (!newResources.contains(persistentResource) && !lineage.getRecord(persistentResource.getType()).contains(persistentResource)) { checkPermission(SharePermission.class, persistentResource); } } } /** * Delete an existing entity. * * @throws ForbiddenAccessException the forbidden access exception */ public void deleteResource() throws ForbiddenAccessException { checkPermission(DeletePermission.class, this); /* * Search for bidirectional relationships. For each bidirectional relationship, * we need to remove ourselves from that relationship */ Map<String, Relationship> relations = getRelationships(); for (Map.Entry<String, Relationship> entry : relations.entrySet()) { String relationName = entry.getKey(); /* Skip updating inverse relationships for deletes which are cascaded */ if (dictionary.cascadeDeletes(getResourceClass(), relationName)) { continue; } String inverseRelationName = dictionary.getRelationInverse(getResourceClass(), relationName); if (!"".equals(inverseRelationName)) { for (PersistentResource inverseResource : getRelationCheckedUnfiltered(relationName)) { if (hasInverseRelation(relationName)) { deleteInverseRelation(relationName, inverseResource.getObject()); inverseResource.markDirty(); } } } } transaction.delete(getObject(), requestScope); auditClass(Audit.Action.DELETE, new ChangeSpec(this, null, getObject(), null)); requestScope.publishLifecycleEvent(this, CRUDEvent.CRUDAction.DELETE); requestScope.getDeletedResources().add(this); } /** * Get resource ID. * * @return ID id */ @Override public String getId() { return dictionary.getId(getObject()); } /** * Set resource ID. * * @param id resource id */ public void setId(String id) { this.setValue(dictionary.getIdFieldName(getResourceClass()), id); } /** * Indicates if the ID is generated or not. * * @return Boolean */ public boolean isIdGenerated() { return dictionary.getEntityBinding( getObject().getClass() ).isIdGenerated(); } /** * Gets UUID. * @return the UUID */ @Override public Optional<String> getUUID() { return uuid; } /** * Get relation looking for a _single_ id. * * NOTE: Filter expressions for this type are _not_ applied at this level. * * @param relation relation name * @param id single id to lookup * @return The PersistentResource of the sought id or null if does not exist. */ public PersistentResource getRelation(String relation, String id) { Set<PersistentResource> resources = getRelation(relation, Collections.singletonList(id), Optional.empty(), Optional.empty(), Optional.empty()); if (resources.isEmpty()) { return null; } // If this is an in-memory object (i.e. UUID being created within tx), datastore may not be able to filter. // If we get multiple results back, make sure we find the right id first. for (PersistentResource resource : resources) { if (resource.matchesId(id)) { return resource; } } return null; } /** * Load a single entity relation from the PersistentResource. Example: GET /book/2 * * @param relation the relation * @param ids a list of object identifiers to optionally load. Can be empty. * @return PersistentResource relation */ public Set<PersistentResource> getRelation(String relation, List<String> ids, Optional<FilterExpression> filter, Optional<Sorting> sorting, Optional<Pagination> pagination) { FilterExpression filterExpression; Class<?> entityType = dictionary.getParameterizedType(getResourceClass(), relation); Set<PersistentResource> newResources = new LinkedHashSet<>(); /* If this is a bulk edit request and the ID we are fetching for is newly created... */ if (entityType == null) { throw new InvalidAttributeException(relation, type); } if (!ids.isEmpty()) { // Fetch our set of new resources that we know about since we can't find them in the datastore newResources = requestScope.getNewPersistentResources().stream() .filter(resource -> entityType.isAssignableFrom(resource.getResourceClass()) && ids.contains(resource.getUUID().orElse(""))) .collect(Collectors.toSet()); FilterExpression idExpression = buildIdFilterExpression(ids, entityType, dictionary, requestScope); // Combine filters if necessary filterExpression = filter .map(fe -> (FilterExpression) new AndFilterExpression(idExpression, fe)) .orElse(idExpression); } else { filterExpression = filter.orElse(null); } // TODO: Filter on new resources? // TODO: Update pagination to subtract the number of new resources created? Set<PersistentResource> existingResources = filter(ReadPermission.class, filter, getRelation(relation, Optional.ofNullable(filterExpression), sorting, pagination, true)); // TODO: Sort again in memory now that two sets are glommed together? Set<PersistentResource> allResources = Sets.union(newResources, existingResources); Set<String> allExpectedIds = allResources.stream() .map(resource -> (String) resource.getUUID().orElseGet(resource::getId)) .collect(Collectors.toSet()); Set<String> missedIds = Sets.difference(new HashSet<>(ids), allExpectedIds); if (!missedIds.isEmpty()) { throw new InvalidObjectIdentifierException(missedIds.toString(), relation); } return allResources; } /** * Build an id filter expression for a particular entity type. * * @param ids Ids to include in the filter expression * @param entityType Type of entity * @return Filter expression for given ids and type. */ private static FilterExpression buildIdFilterExpression(List<String> ids, Class<?> entityType, EntityDictionary dictionary, RequestScope scope) { Class<?> idType = dictionary.getIdType(entityType); String idField = dictionary.getIdFieldName(entityType); String typeAlias = dictionary.getJsonAliasFor(entityType); List<Object> coercedIds = ids.stream() .filter(id -> scope.getObjectById(typeAlias, id) == null) // these don't exist yet .map(id -> CoerceUtil.coerce(id, idType)) .collect(Collectors.toList()); /* construct a new SQL like filter expression, eg: book.id IN [1,2] */ FilterExpression idFilter = new InPredicate( new Path.PathElement( entityType, idType, idField), coercedIds); return idFilter; } /** * Get collection of resources from relation field. * * @param relationName field * @return collection relation */ public Set<PersistentResource> getRelationCheckedFiltered(String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) { return filter(ReadPermission.class, filterExpression, getRelation(relationName, filterExpression, sorting, pagination, true)); } private Set<PersistentResource> getRelationUncheckedUnfiltered(String relationName) { return getRelation(relationName, Optional.empty(), Optional.empty(), Optional.empty(), false); } private Set<PersistentResource> getRelationCheckedUnfiltered(String relationName) { return getRelation(relationName, Optional.empty(), Optional.empty(), Optional.empty(), true); } private Set<PersistentResource> getRelation(String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination, boolean checked) { if (checked && !checkRelation(relationName)) { return Collections.emptySet(); } final Class<?> relationClass = dictionary.getParameterizedType(obj, relationName); if (pagination.isPresent() && !pagination.get().isDefaultInstance() && !CanPaginateVisitor.canPaginate(relationClass, dictionary, requestScope)) { throw new BadRequestException(String.format("Cannot paginate %s", dictionary.getJsonAliasFor(relationClass))); } return getRelationUnchecked(relationName, filterExpression, sorting, pagination); } /** * Check the permissions of the relationship, and return true or false. * @param relationName The relationship to the entity * @return True if the relationship to the entity has valid permissions for the user */ protected boolean checkRelation(String relationName) { List<String> relations = dictionary.getRelationships(obj); String realName = dictionary.getNameFromAlias(obj, relationName); relationName = (realName == null) ? relationName : realName; if (relationName == null || relations == null || !relations.contains(relationName)) { throw new InvalidAttributeException(relationName, type); } checkFieldAwareDeferPermissions(ReadPermission.class, relationName, null, null); return !shouldSkipCollection( dictionary.getParameterizedType(obj, relationName), ReadPermission.class, requestScope); } /** * Get collection of resources from relation field. * * @param relationName field * @param filterExpression An optional filter expression * @return collection relation */ protected Set<PersistentResource> getRelationChecked(String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) { if (!checkRelation(relationName)) { return Collections.emptySet(); } return getRelationUnchecked(relationName, filterExpression, sorting, pagination); } /** * Retrieve an uncheck set of relations. * * @param relationName field * @param filterExpression An optional filter expression * @param sorting the sorting clause * @param pagination the pagination params * @return the resources in the relationship */ private Set<PersistentResource> getRelationUnchecked(String relationName, Optional<FilterExpression> filterExpression, Optional<Sorting> sorting, Optional<Pagination> pagination) { RelationshipType type = getRelationshipType(relationName); final Class<?> relationClass = dictionary.getParameterizedType(obj, relationName); if (relationClass == null) { throw new InvalidAttributeException(relationName, this.getType()); } Optional<Pagination> computedPagination = pagination.map(p -> p.evaluate(relationClass)); //Invoke filterExpressionCheck and then merge with filterExpression. Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(relationClass, requestScope); Optional<FilterExpression> computedFilters = filterExpression; if (permissionFilter.isPresent() && filterExpression.isPresent()) { FilterExpression mergedExpression = new AndFilterExpression(filterExpression.get(), permissionFilter.get()); computedFilters = Optional.of(mergedExpression); } else if (permissionFilter.isPresent()) { computedFilters = permissionFilter; } Object val = transaction.getRelation(transaction, obj, relationName, computedFilters, sorting, computedPagination, requestScope); if (val == null) { return Collections.emptySet(); } Set<PersistentResource> resources = Sets.newLinkedHashSet(); if (val instanceof Iterable) { Iterable filteredVal = (Iterable) val; resources = new PersistentResourceSet(this, filteredVal, requestScope); } else if (type.isToOne()) { resources = new SingleElementSet<>( new PersistentResource<>(val, this, requestScope.getUUIDFor(val), requestScope)); } else { resources.add(new PersistentResource<>(val, this, requestScope.getUUIDFor(val), requestScope)); } return resources; } /** * Determine whether or not to skip loading a collection. * * @param resourceClass Resource class * @param annotationClass Annotation class * @param requestScope Request scope * @return True if collection should be skipped (i.e. denied access), false otherwise */ private static boolean shouldSkipCollection(Class<?> resourceClass, Class<? extends Annotation> annotationClass, RequestScope requestScope) { try { requestScope.getPermissionExecutor().checkUserPermissions(resourceClass, annotationClass); } catch (ForbiddenAccessException e) { return true; } return false; } /** * Get a relationship type. * * @param relation Name of relationship * @return Relationship type. RelationshipType.NONE if not found. */ public RelationshipType getRelationshipType(String relation) { return dictionary.getRelationshipType(obj, relation); } /** * Get the value for a particular attribute (i.e. non-relational field) * @param attr Attribute name * @return Object value for attribute */ public Object getAttribute(String attr) { return this.getValueChecked(attr); } /** * Wrapped Entity bean. * * @return bean object */ @Override public T getObject() { return obj; } /** * Sets object. * @param obj the obj */ public void setObject(T obj) { this.obj = obj; } /** * Entity type. * * @return type resource class */ @Override @JsonIgnore public Class<T> getResourceClass() { return (Class) dictionary.lookupBoundClass(obj.getClass()); } /** * Gets type. * @return the type */ @Override public String getType() { return type; } @Override public int hashCode() { if (hashCode == 0) { // NOTE: UUID's are only present in the case of newly created objects. // Consequently, a known ID will never be present during processing (only after commit // assigned by the DB) and so we can assume that any newly created object can be fully // addressed by its UUID. It is possible for UUID and id to be unset upon a POST or PATCH // ext request, but it is safe to ignore these edge cases. // (1) In a POST request, you would not be referencing this newly created object in any way // so this is not an issue. // (2) In a PATCH ext request, this is also acceptable (assuming request is accepted) in the way // that it is acceptable in a POST. If you do not specify a UUID, there is no way to reference // that newly created object within the context of the request. Thus, if any such action was // required, the user would be forced to provide a UUID anyway. String id = dictionary.getId(getObject()); if (uuid.isPresent() && ("0".equals(id) || "null".equals(id))) { hashCode = Objects.hashCode(uuid); } else { hashCode = Objects.hashCode(id); } } return hashCode; } @Override public boolean equals(Object obj) { if (obj instanceof PersistentResource) { PersistentResource that = (PersistentResource) obj; if (this.getObject() == that.getObject()) { return true; } String theirId = dictionary.getId(that.getObject()); return this.matchesId(theirId) && Objects.equals(this.type, that.type); } return false; } /** * Gets lineage. * @return the lineage */ public ResourceLineage getLineage() { return this.lineage; } /** * Gets dictionary. * @return the dictionary */ public EntityDictionary getDictionary() { return dictionary; } /** * Gets request scope. * @return the request scope */ @Override public RequestScope getRequestScope() { return requestScope; } /** * Convert a persistent resource to a resource. * * @return a resource */ public Resource toResource() { return toResource(this::getRelationships, this::getAttributes); } /** * Fetch a resource with support for lambda function for getting relationships and attributes. * @return The Resource */ public Resource toResourceWithSortingAndPagination() { return toResource(this::getRelationshipsWithSortingAndPagination, this::getAttributes); } /** * Fetch a resource with support for lambda function for getting relationships and attributes. * @param relationshipSupplier The relationship supplier (getRelationships()) * @param attributeSupplier The attribute supplier * @return The Resource */ public Resource toResource(final Supplier<Map<String, Relationship>> relationshipSupplier, final Supplier<Map<String, Object>> attributeSupplier) { final Resource resource = new Resource(type, (obj == null) ? uuid.orElseThrow( () -> new InvalidEntityBodyException("No id found on object")) : dictionary.getId(obj)); resource.setRelationships(relationshipSupplier.get()); resource.setAttributes(attributeSupplier.get()); if (requestScope.getElideSettings().isEnableJsonLinks()) { resource.setLinks(requestScope.getElideSettings().getJsonApiLinks().getResourceLevelLinks(this)); } return resource; } /** * Get relationship mappings. * * @return Relationship mapping */ protected Map<String, Relationship> getRelationships() { return getRelationshipsWithRelationshipFunction((relationName) -> { Optional<FilterExpression> filterExpression = requestScope.getExpressionForRelation(this, relationName); return getRelationCheckedFiltered(relationName, filterExpression, Optional.empty(), Optional.empty()); }); } /** * Get relationship mappings. * * @return Relationship mapping */ protected Map<String, Relationship> getRelationshipsWithSortingAndPagination() { return getRelationshipsWithRelationshipFunction((relationName) -> { Optional<FilterExpression> filterExpression = requestScope.getExpressionForRelation(this, relationName); Optional<Sorting> sorting = Optional.ofNullable(requestScope.getSorting()); Optional<Pagination> pagination = Optional.ofNullable(requestScope.getPagination()); return getRelationCheckedFiltered(relationName, filterExpression, sorting, pagination); }); } /** * Get relationship mappings. * * @param relationshipFunction a function to load the value of a relationship. Takes a string of the relationship * name and returns the relationship's value. * @return Relationship mapping */ protected Map<String, Relationship> getRelationshipsWithRelationshipFunction( final Function<String, Set<PersistentResource>> relationshipFunction) { final Map<String, Relationship> relationshipMap = new LinkedHashMap<>(); final Set<String> relationshipFields = filterFields(dictionary.getRelationships(obj)); for (String field : relationshipFields) { TreeMap<String, Resource> orderedById = new TreeMap<>(lengthFirstComparator); for (PersistentResource relationship : relationshipFunction.apply(field)) { orderedById.put(relationship.getId(), new ResourceIdentifier(relationship.getType(), relationship.getId()).castToResource()); } Collection<Resource> resources = orderedById.values(); Data<Resource> data; RelationshipType relationshipType = getRelationshipType(field); if (relationshipType.isToOne()) { data = new Data<>(firstOrNullIfEmpty(resources)); } else { data = new Data<>(resources); } Map<String, String> links = null; if (requestScope.getElideSettings().isEnableJsonLinks()) { links = requestScope.getElideSettings() .getJsonApiLinks() .getRelationshipLinks(this, field); } relationshipMap.put(field, new Relationship(links, data)); } return relationshipMap; } /** * Get attributes mapping from entity. * * @return Mapping of attributes to objects */ protected Map<String, Object> getAttributes() { final Map<String, Object> attributes = new LinkedHashMap<>(); final Set<String> attrFields = filterFields(dictionary.getAttributes(obj)); for (String field : attrFields) { Object val = getAttribute(field); attributes.put(field, val); } return attributes; } /** * Sets value. * @param fieldName the field name * @param newValue the new value */ protected void setValueChecked(String fieldName, Object newValue) { Object existingValue = getValueUnchecked(fieldName); // TODO: Need to refactor this logic. For creates this is properly converted in the executor. This logic // should be explicitly encapsulated here, not there. checkFieldAwareDeferPermissions(UpdatePermission.class, fieldName, newValue, existingValue); setValue(fieldName, newValue); } /** * Nulls the relationship or attribute and checks update permissions. * Invokes the set[fieldName] method on the target object OR set the field with the corresponding name. * @param fieldName the field name to set or invoke equivalent set method * @param oldValue the old value */ protected void nullValue(String fieldName, PersistentResource oldValue) { if (oldValue == null) { return; } String inverseField = getInverseRelationField(fieldName); if (!inverseField.isEmpty()) { oldValue.checkFieldAwareDeferPermissions(UpdatePermission.class, inverseField, null, getObject()); } this.setValueChecked(fieldName, null); } /** * Gets a value from an entity and checks read permissions. * @param fieldName the field name * @return value value */ protected Object getValueChecked(String fieldName) { requestScope.publishLifecycleEvent(this, CRUDEvent.CRUDAction.READ); requestScope.publishLifecycleEvent(this, fieldName, CRUDEvent.CRUDAction.READ, Optional.empty()); checkFieldAwareDeferPermissions(ReadPermission.class, fieldName, (Object) null, (Object) null); return getValue(getObject(), fieldName, requestScope); } /** * Retrieve an object without checking read permissions (i.e. value is used internally and not sent to others) * * @param fieldName the field name * @return Value */ protected Object getValueUnchecked(String fieldName) { requestScope.publishLifecycleEvent(this, CRUDEvent.CRUDAction.READ); requestScope.publishLifecycleEvent(this, fieldName, CRUDEvent.CRUDAction.READ, Optional.empty()); return getValue(getObject(), fieldName, requestScope); } /** * Adds a new element to a collection and tests update permission. * @param collection the collection * @param collectionName the collection name * @param toAdd the to add * @return True if added to collection false otherwise (i.e. element already in collection) */ protected boolean addToCollection(Collection collection, String collectionName, PersistentResource toAdd) { final Collection singleton = Collections.singleton(toAdd.getObject()); final Collection original = copyCollection(collection); checkFieldAwareDeferPermissions( UpdatePermission.class, collectionName, CollectionUtils.union(CollectionUtils.emptyIfNull(collection), singleton), original); if (collection == null) { collection = Collections.singleton(toAdd.getObject()); Object value = getValueUnchecked(collectionName); if (!Objects.equals(value, toAdd.getObject())) { this.setValueChecked(collectionName, collection); return true; } } else { if (!collection.contains(toAdd.getObject())) { collection.add(toAdd.getObject()); triggerUpdate(collectionName, original, collection); return true; } } return false; } /** * Deletes an existing element in a collection and tests update and delete permissions. * @param collection the collection * @param collectionName the collection name * @param toDelete the to delete * @param isInverseCheck Whether or not the deletion is already coming from cleaning up an inverse. * Without this parameter, we could find ourselves in a loop of checks. * TODO: This is a band-aid for a quick fix. This should certainly be refactored. */ protected void delFromCollection( Collection collection, String collectionName, PersistentResource toDelete, boolean isInverseCheck) { final Collection original = copyCollection(collection); checkFieldAwareDeferPermissions( UpdatePermission.class, collectionName, CollectionUtils.disjunction(collection, Collections.singleton(toDelete.getObject())), original ); String inverseField = getInverseRelationField(collectionName); if (!isInverseCheck && !inverseField.isEmpty()) { // Compute the ChangeSpec for the inverse relation and check whether or not we have access // to apply this change to that field. final Object originalValue = toDelete.getValueUnchecked(inverseField); final Collection originalBidirectional; if (originalValue instanceof Collection) { originalBidirectional = copyCollection((Collection) originalValue); } else { originalBidirectional = Collections.singleton(originalValue); } final Collection removedBidrectional = CollectionUtils .disjunction(Collections.singleton(this.getObject()), originalBidirectional); toDelete.checkFieldAwareDeferPermissions( UpdatePermission.class, inverseField, removedBidrectional, originalBidirectional ); } if (collection == null) { return; } collection.remove(toDelete.getObject()); triggerUpdate(collectionName, original, collection); } /** * Invoke the set[fieldName] method on the target object OR set the field with the corresponding name. * @param fieldName the field name to set or invoke equivalent set method * @param value the value to set */ protected void setValue(String fieldName, Object value) { final Object original = getValueUnchecked(fieldName); dictionary.setValue(obj, fieldName, value); triggerUpdate(fieldName, original, value); } /** * Invoke the get[fieldName] method on the target object OR get the field with the corresponding name. * @param target the object to get * @param fieldName the field name to get or invoke equivalent get method * @param requestScope the request scope * @return the value */ public static Object getValue(Object target, String fieldName, RequestScope requestScope) { EntityDictionary dictionary = requestScope.getDictionary(); return dictionary.getValue(target, fieldName, requestScope); } /** * If a bidirectional relationship exists, attempts to delete itself from the inverse * relationship. Given A to B as the relationship, A corresponds to this and B is the inverse. * @param relationName The name of the relationship on this (A) object. * @param inverseEntity The value (B) which has been deleted from this object. */ protected void deleteInverseRelation(String relationName, Object inverseEntity) { String inverseField = getInverseRelationField(relationName); if (!"".equals(inverseField)) { Class<?> inverseType = dictionary.getType(inverseEntity.getClass(), inverseField); String uuid = requestScope.getUUIDFor(inverseEntity); PersistentResource inverseResource = new PersistentResource(inverseEntity, this, uuid, requestScope); Object inverseRelation = inverseResource.getValueUnchecked(inverseField); if (inverseRelation == null) { return; } if (inverseRelation instanceof Collection) { inverseResource.delFromCollection((Collection) inverseRelation, inverseField, this, true); } else if (inverseType.isAssignableFrom(this.getResourceClass())) { inverseResource.nullValue(inverseField, this); } else { throw new InternalServerErrorException("Relationship type mismatch"); } inverseResource.markDirty(); RelationshipType inverseRelationType = inverseResource.getRelationshipType(inverseField); if (inverseRelationType.isToOne()) { //hook for updateToOneRelation transaction.updateToOneRelation(transaction, inverseEntity, inverseField, null, requestScope); } else { //hook for updateToManyRelation assert (inverseRelation instanceof Collection) : inverseField + " not a collection"; transaction.updateToManyRelation(transaction, inverseEntity, inverseField, new LinkedHashSet<>(), Sets.newHashSet(obj), requestScope); } } } private boolean hasInverseRelation(String relationName) { String inverseField = getInverseRelationField(relationName); return StringUtils.isNotEmpty(inverseField); } private String getInverseRelationField(String relationName) { return dictionary.getRelationInverse(obj.getClass(), relationName); } /** * If a bidirectional relationship exists, attempts to add itself to the inverse * relationship. Given A to B as the relationship, A corresponds to this and B is the inverse. * @param relationName The name of the relationship on this (A) object. * @param inverseObj The value (B) which has been added to this object. */ protected void addInverseRelation(String relationName, Object inverseObj) { String inverseName = dictionary.getRelationInverse(obj.getClass(), relationName); if (!"".equals(inverseName)) { Class<?> inverseType = dictionary.getType(inverseObj.getClass(), inverseName); String uuid = requestScope.getUUIDFor(inverseObj); PersistentResource inverseResource = new PersistentResource(inverseObj, this, uuid, requestScope); Object inverseRelation = inverseResource.getValueUnchecked(inverseName); if (Collection.class.isAssignableFrom(inverseType)) { if (inverseRelation != null) { inverseResource.addToCollection((Collection) inverseRelation, inverseName, this); } else { inverseResource.setValueChecked(inverseName, Collections.singleton(this.getObject())); } } else if (inverseType.isAssignableFrom(this.getResourceClass())) { inverseResource.setValueChecked(inverseName, this.getObject()); } else { throw new InternalServerErrorException("Relationship type mismatch"); } inverseResource.markDirty(); RelationshipType inverseRelationType = inverseResource.getRelationshipType(inverseName); if (inverseRelationType.isToOne()) { //hook for updateToOneRelation transaction.updateToOneRelation(transaction, inverseObj, inverseName, obj, requestScope); } else { //hook for updateToManyRelation assert (inverseRelation == null || inverseRelation instanceof Collection) : inverseName + " not a collection"; transaction.updateToManyRelation(transaction, inverseObj, inverseName, Sets.newHashSet(obj), new LinkedHashSet<>(), requestScope); } } } /** * Filter a set of PersistentResources. * Verify fields have ReadPermission on filter join. * * @param permission the permission * @param resources the resources * @return Filtered set of resources */ protected static Set<PersistentResource> filter(Class<? extends Annotation> permission, Optional<FilterExpression> filter, Set<PersistentResource> resources) { Set<PersistentResource> filteredSet = new LinkedHashSet<>(); for (PersistentResource resource : resources) { try { // NOTE: This is for avoiding filtering on _newly created_ objects within this transaction. // Namely-- in a JSONPATCH request or GraphQL request-- we need to read all newly created // resources /regardless/ of whether or not we actually have permission to do so; this is to // retrieve the object id to return to the caller. If no fields on the object are readable by the caller // then they will be filtered out and only the id is returned. Similarly, all future requests to this // object will behave as expected. if (!resource.getRequestScope().getNewResources().contains(resource)) { resource.checkFieldAwarePermissions(permission); // Verify fields have ReadPermission on filter join if (filter.isPresent() && !filter.get().accept(new VerifyFieldAccessFilterExpressionVisitor(resource))) { continue; } } filteredSet.add(resource); } catch (ForbiddenAccessException e) { // Do nothing. Filter from set. } } // keep original SingleElementSet if (resources instanceof SingleElementSet && resources.equals(filteredSet)) { return resources; } return filteredSet; } /** * Filter a set of fields. * * @param fields the fields * @return Filtered set of fields */ protected Set<String> filterFields(Collection<String> fields) { Set<String> filteredSet = new LinkedHashSet<>(); for (String field : fields) { try { if (checkIncludeSparseField(requestScope.getSparseFields(), type, field)) { checkFieldAwareReadPermissions(field); filteredSet.add(field); } } catch (ForbiddenAccessException e) { // Do nothing. Filter from set. } } return filteredSet; } /** * Queue the @*Update triggers iff this is not a newly created object (otherwise we run @*Create) */ private void triggerUpdate(String fieldName, Object original, Object value) { ChangeSpec changeSpec = new ChangeSpec(this, fieldName, original, value); CRUDEvent.CRUDAction action = isNewlyCreated() ? CRUDEvent.CRUDAction.CREATE : CRUDEvent.CRUDAction.UPDATE; requestScope.publishLifecycleEvent(this, fieldName, action, Optional.of(changeSpec)); requestScope.publishLifecycleEvent(this, action); auditField(new ChangeSpec(this, fieldName, original, value)); } private static <A extends Annotation> ExpressionResult checkPermission( Class<A> annotationClass, PersistentResource resource) { return resource.requestScope.getPermissionExecutor().checkPermission(annotationClass, resource); } private <A extends Annotation> ExpressionResult checkFieldAwarePermissions(Class<A> annotationClass) { return requestScope.getPermissionExecutor().checkPermission(annotationClass, this); } private <A extends Annotation> ExpressionResult checkFieldAwareReadPermissions(String fieldName) { return requestScope.getPermissionExecutor() .checkSpecificFieldPermissions(this, null, ReadPermission.class, fieldName); } private <A extends Annotation> ExpressionResult checkFieldAwareDeferPermissions(Class<A> annotationClass, String fieldName, Object modified, Object original) { ChangeSpec changeSpec = (UpdatePermission.class.isAssignableFrom(annotationClass)) ? new ChangeSpec(this, fieldName, original, modified) : null; return requestScope .getPermissionExecutor() .checkSpecificFieldPermissionsDeferred(this, changeSpec, annotationClass, fieldName); } protected static boolean checkIncludeSparseField(Map<String, Set<String>> sparseFields, String type, String fieldName) { if (!sparseFields.isEmpty()) { if (!sparseFields.containsKey(type)) { return false; } if (!sparseFields.get(type).contains(fieldName)) { return false; } } return true; } /** * Audit an action on field. * * @param changeSpec Change spec for audit */ protected void auditField(final ChangeSpec changeSpec) { final String fieldName = changeSpec.getFieldName(); Audit[] annotations = dictionary.getAttributeOrRelationAnnotations(getResourceClass(), Audit.class, fieldName ); if (annotations == null || annotations.length == 0) { // Default to class-level annotation for action auditClass(Audit.Action.UPDATE, changeSpec); return; } for (Audit annotation : annotations) { if (annotation.action().length == 1 && annotation.action()[0] == Audit.Action.UPDATE) { LogMessage message = new LogMessage(annotation, this, Optional.of(changeSpec)); getRequestScope().getAuditLogger().log(message); } else { throw new InvalidSyntaxException("Only Audit.Action.UPDATE is allowed on fields."); } } } /** * Audit an action on an entity. * * @param action the action * @param changeSpec the change that occurred */ protected void auditClass(Audit.Action action, ChangeSpec changeSpec) { Audit[] annotations = getResourceClass().getAnnotationsByType(Audit.class); if (annotations == null) { return; } for (Audit annotation : annotations) { for (Audit.Action auditAction : annotation.action()) { if (auditAction == action) { // compare object reference LogMessage message = new LogMessage(annotation, this, Optional.ofNullable(changeSpec)); getRequestScope().getAuditLogger().log(message); } } } } /** * Shallow copy a collection. * * @param collection Collection to copy * @return New copy of collection */ private Collection copyCollection(final Collection collection) { final ArrayList newCollection = new ArrayList(); if (CollectionUtils.isEmpty(collection)) { return newCollection; } collection.iterator().forEachRemaining(newCollection::add); return newCollection; } /** * Mark this object as dirty. */ private void markDirty() { requestScope.getDirtyResources().add(this); } /** * Assign provided id if id field is not generated. * * @param persistentResource resource * @param id resource id */ private static void assignId(PersistentResource persistentResource, String id) { //If id field is not a `@GeneratedValue` or mapped via a `@MapsId` attribute //then persist the provided id if (!persistentResource.isIdGenerated()) { if (StringUtils.isNotEmpty(id)) { persistentResource.setId(id); } else { //If expecting id to persist and id is not present, throw exception throw new BadRequestException( "No id provided, cannot persist " + persistentResource.getType()); } } } private static <T> T firstOrNullIfEmpty(final Collection<T> coll) { return CollectionUtils.isEmpty(coll) ? null : IterableUtils.first(coll); } }
3e0ffc9851de004a384a7130f7af950e707931b8
3,959
java
Java
app/src/main/java/ss/com/toolkit/view/CusView.java
fjsmf/toolkit
97bdedef36ae9acf6051f41f23bcb3cec4af57eb
[ "Apache-2.0" ]
1
2018-12-27T10:12:41.000Z
2018-12-27T10:12:41.000Z
app/src/main/java/ss/com/toolkit/view/CusView.java
sunmaofei520/toolkit
4895aaf55ee20b6896ff6bff623f646665673874
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ss/com/toolkit/view/CusView.java
sunmaofei520/toolkit
4895aaf55ee20b6896ff6bff623f646665673874
[ "Apache-2.0" ]
null
null
null
35.348214
168
0.652185
6,779
package ss.com.toolkit.view; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class CusView extends View { private Paint mPaint; private Rect mBounds; private Drawable mDrawable; private String mCustomText = "100"; private float mDrawableTextPadding; private float mCusTextSize = 50; private float mDensity; public CusView(Context context) { super(context); init(); } public CusView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public CusView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public CusView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init() { System.out.println("绘图初始化"); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setTextSize(mCusTextSize); mBounds = new Rect(); mDensity = getContext().getResources().getDisplayMetrics().density; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int finalWidth; int finalHeight; mPaint.getTextBounds(mCustomText, 0, mCustomText.length(), mBounds); if (widthMode == MeasureSpec.EXACTLY) { finalWidth = widthSize; } else { if (mDrawable != null) { finalWidth = mDrawable.getIntrinsicWidth() + mBounds.width() + (int) (2 * mDensity) + getPaddingLeft() + getPaddingRight() + (int) mDrawableTextPadding; } else { finalWidth = mBounds.width() + getPaddingLeft() + getPaddingRight() + (int) (5 * mDensity); } } if (heightMode == MeasureSpec.EXACTLY) { finalHeight = heightSize; } else { if (mDrawable != null) { finalHeight = Math.max(mBounds.height(), mDrawable.getIntrinsicHeight()) + getPaddingTop() + getPaddingBottom(); } else { finalHeight = mBounds.height() + (int) (5 * mDensity) + getPaddingTop() + getPaddingBottom(); } } setMeasuredDimension(finalWidth, finalHeight); } @Override protected void onDraw(Canvas canvas) { Rect rect = new Rect(0, 0, mBounds.width(), mBounds.height());//画一个矩形 Paint rectPaint = new Paint(); rectPaint.setColor(Color.BLUE); rectPaint.setStyle(Paint.Style.FILL); canvas.drawRect(rect, rectPaint); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTextSize(50); textPaint.setStyle(Paint.Style.FILL); //该方法即为设置基线上那个点究竟是left,center,还是right 这里我设置为center textPaint.setTextAlign(Paint.Align.CENTER); Paint.FontMetrics fontMetrics = textPaint.getFontMetrics(); float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom int baseLineY = (int) (rect.centerY() - top / 2 - bottom / 2);//基线中间点的y轴计算公式 canvas.drawText("你好世界", rect.centerX(), baseLineY, textPaint); } }
3e0ffcaf430338f7e39ab4397cd42c56f201010c
42
java
Java
src/main/java/MtgEntity/Card.java
M-Kortmann/MtgDataBase
e5269bf8e7c2f08087820cc82ef14ef91f93e845
[ "MIT" ]
null
null
null
src/main/java/MtgEntity/Card.java
M-Kortmann/MtgDataBase
e5269bf8e7c2f08087820cc82ef14ef91f93e845
[ "MIT" ]
null
null
null
src/main/java/MtgEntity/Card.java
M-Kortmann/MtgDataBase
e5269bf8e7c2f08087820cc82ef14ef91f93e845
[ "MIT" ]
null
null
null
8.4
19
0.738095
6,780
package MtgEntity; public class Card { }
3e0ffdeb27c040bcb8fdf5787fca6d9ec800f51d
670
java
Java
Java/SpringMVC/spring-adventure/src/main/java/matheusicaro/com/github/store/controller/ExceptionHandlerController.java
matheusicaro/book-sales-system-java-spring
1435d239435d051b226d85702d83ee66fddaa8f8
[ "MIT" ]
null
null
null
Java/SpringMVC/spring-adventure/src/main/java/matheusicaro/com/github/store/controller/ExceptionHandlerController.java
matheusicaro/book-sales-system-java-spring
1435d239435d051b226d85702d83ee66fddaa8f8
[ "MIT" ]
2
2021-01-20T22:35:53.000Z
2021-12-09T20:07:54.000Z
Java/SpringMVC/spring-adventure/src/main/java/matheusicaro/com/github/store/controller/ExceptionHandlerController.java
matheusicaro/book-sales-system-java-spring
1435d239435d051b226d85702d83ee66fddaa8f8
[ "MIT" ]
null
null
null
33.5
73
0.764179
6,781
package matheusicaro.com.github.store.controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class ExceptionHandlerController { @ExceptionHandler(Exception.class) public ModelAndView answerAnyExceptionGenerica(Exception exception) { System.out.println("Erro genérico acontecendo"); exception.printStackTrace(); ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("exception", exception); return modelAndView; } }
3e0ffee6f1519bbcc75eb184312107ea9e317161
620
java
Java
src/test/java/com/cdr/gen/PhoneNumberTest.java
emcconsulting/TimDataGenerator
dcb0fb1971ac5f723ca09810cd3a1f7852781b87
[ "MIT" ]
30
2016-02-09T21:17:46.000Z
2022-03-18T17:52:17.000Z
src/test/java/com/cdr/gen/PhoneNumberTest.java
emcconsulting/TimDataGenerator
dcb0fb1971ac5f723ca09810cd3a1f7852781b87
[ "MIT" ]
5
2018-01-03T20:14:30.000Z
2020-07-23T13:58:58.000Z
src/test/java/com/cdr/gen/PhoneNumberTest.java
emcconsulting/TimDataGenerator
dcb0fb1971ac5f723ca09810cd3a1f7852781b87
[ "MIT" ]
22
2016-02-09T21:17:54.000Z
2021-03-23T00:36:11.000Z
25.833333
99
0.630645
6,782
package com.cdr.gen; import java.util.Arrays; import java.util.List; import java.util.Map; import junit.framework.TestCase; public class PhoneNumberTest extends TestCase { public PhoneNumberTest(String testName) { super(testName); } public void test() { List<String> types = Arrays.asList("Local", "PRS", "Intl", "Mobile", "National", "Free"); for (Map.Entry<String, List<String>> entry : PhoneNumberGenerator.PHONE_CODES.entrySet()) { System.out.println(entry.getKey()); assertTrue(types.contains(entry.getKey())); } } }
3e100003b918b4f624284803ffa3fd3271611db7
614
java
Java
appcore/src/main/java/com/longngohoang/news/appcore/presentation/viewmodel/DocVM.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
appcore/src/main/java/com/longngohoang/news/appcore/presentation/viewmodel/DocVM.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
appcore/src/main/java/com/longngohoang/news/appcore/presentation/viewmodel/DocVM.java
beyonderVN/NewArtical
ea04c522fcd1cd1cdb48598c64d65429ac1f5fe3
[ "Apache-2.0" ]
null
null
null
16.594595
65
0.625407
6,783
package com.longngohoang.news.appcore.presentation.viewmodel; import com.longngohoang.news.appcore.data.model.Doc; /** * Created by Long on 10/5/2016. */ public class DocVM extends BaseVM { private Doc doc; public DocVM(Doc doc) { this.doc = doc; } public Doc getDoc() { return doc; } public void setMovie(Doc doc) { this.doc = doc; } @Override public int getVMType(NYTimesMViewTypeFactory vmTypeFactory) { return vmTypeFactory.getType(this); } @Override public String toString() { return doc.toString(); } }
3e100116a0e3d5a48e0a52fc9d18dc3e6a003920
1,068
java
Java
DominioLibreria/src/entities/Moneda.java
monotera/Database
ac2d7e3411c9b9f61f28a2827fdf94f3c05bcc38
[ "MIT" ]
2
2020-05-18T04:46:19.000Z
2020-05-18T04:47:33.000Z
DominioLibreria/src/entities/Moneda.java
monotera/Database
ac2d7e3411c9b9f61f28a2827fdf94f3c05bcc38
[ "MIT" ]
null
null
null
DominioLibreria/src/entities/Moneda.java
monotera/Database
ac2d7e3411c9b9f61f28a2827fdf94f3c05bcc38
[ "MIT" ]
1
2021-07-02T05:36:44.000Z
2021-07-02T05:36:44.000Z
21.36
79
0.625468
6,784
/* * 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 entities; import Enums.Denominacion; /** * * @author USER */ public class Moneda { private Denominacion denominacion; private int valor; public Moneda() { } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } public Moneda(Denominacion denominacion) { this.denominacion = denominacion; } public Denominacion getDenominacion() { return denominacion; } public void setDenominacion(Denominacion denominacion) { this.denominacion = denominacion; if(denominacion == Denominacion.QUIENTOS) { setValor(500); }else if(denominacion == Denominacion.MIL) { setValor(1000); } } @Override public String toString(){ return this.denominacion.toString(); } }
3e100164fe137db978e65a35d6ac75b562428180
15,381
java
Java
core/store/dist/src/main/java/org/onosproject/store/topology/impl/DistributedTopologyStore.java
abruno06/onos
cc22546d624e6ee4f83cd12be237939873179ecc
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
core/store/dist/src/main/java/org/onosproject/store/topology/impl/DistributedTopologyStore.java
abruno06/onos
cc22546d624e6ee4f83cd12be237939873179ecc
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
core/store/dist/src/main/java/org/onosproject/store/topology/impl/DistributedTopologyStore.java
abruno06/onos
cc22546d624e6ee4f83cd12be237939873179ecc
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
40.370079
106
0.683766
6,785
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.topology.impl; import org.onlab.graph.GraphPathSearch; import org.onlab.util.KryoNamespace; import org.onosproject.cfg.ComponentConfigService; import org.onosproject.common.DefaultTopology; import org.onosproject.event.Event; import org.onosproject.mastership.MastershipService; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.DisjointPath; import org.onosproject.net.Link; import org.onosproject.net.Path; import org.onosproject.net.device.DeviceService; import org.onosproject.net.provider.ProviderId; import org.onosproject.net.topology.ClusterId; import org.onosproject.net.topology.DefaultGraphDescription; import org.onosproject.net.topology.GeoDistanceLinkWeight; import org.onosproject.net.topology.GraphDescription; import org.onosproject.net.topology.LinkWeigher; import org.onosproject.net.topology.MetricLinkWeight; import org.onosproject.net.topology.PathAdminService; import org.onosproject.net.topology.Topology; import org.onosproject.net.topology.TopologyCluster; import org.onosproject.net.topology.TopologyEdge; import org.onosproject.net.topology.TopologyEvent; import org.onosproject.net.topology.TopologyGraph; import org.onosproject.net.topology.TopologyStore; import org.onosproject.net.topology.TopologyStoreDelegate; import org.onosproject.net.topology.TopologyVertex; import org.onosproject.store.AbstractStore; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.EventuallyConsistentMap; import org.onosproject.store.service.EventuallyConsistentMapEvent; import org.onosproject.store.service.EventuallyConsistentMapListener; import org.onosproject.store.service.LogicalClockService; import org.onosproject.store.service.StorageService; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.slf4j.Logger; import java.util.Collections; import java.util.Dictionary; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static org.onlab.graph.GraphPathSearch.ALL_PATHS; import static org.onlab.util.Tools.get; import static org.onlab.util.Tools.isNullOrEmpty; import static org.onosproject.net.topology.TopologyEvent.Type.TOPOLOGY_CHANGED; import static org.onosproject.store.OsgiPropertyConstants.*; import static org.slf4j.LoggerFactory.getLogger; /** * Manages inventory of topology snapshots using trivial in-memory * structures implementation. * <p> * Note: This component is not distributed per-se. It runs on every * instance and feeds off of other distributed stores. */ @Component( immediate = true, service = { TopologyStore.class, PathAdminService.class }, property = { LINK_WEIGHT_FUNCTION + "=" + LINK_WEIGHT_FUNCTION_DEFAULT, MAX_PATHS + "=" + MAX_PATHS_DEFAULT, } ) public class DistributedTopologyStore extends AbstractStore<TopologyEvent, TopologyStoreDelegate> implements TopologyStore, PathAdminService { private final Logger log = getLogger(getClass()); private static final String FORMAT = "Settings: linkWeightFunction={}"; private volatile DefaultTopology current = new DefaultTopology(ProviderId.NONE, new DefaultGraphDescription(0L, System.currentTimeMillis(), Collections.emptyList(), Collections.emptyList())); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected StorageService storageService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected LogicalClockService clockService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected MastershipService mastershipService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected ComponentConfigService configService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected DeviceService deviceService; private static final String HOP_COUNT = "hopCount"; private static final String LINK_METRIC = "linkMetric"; private static final String GEO_DISTANCE = "geoDistance"; /** Default link-weight function: hopCount, linkMetric, geoDistance. */ private String linkWeightFunction = LINK_WEIGHT_FUNCTION_DEFAULT; /** Default max-paths count. */ private int maxPaths = ALL_PATHS; // Cluster root to broadcast points bindings to allow convergence to // a shared broadcast tree; node that is the master of the cluster root // is the primary. private EventuallyConsistentMap<DeviceId, Set<ConnectPoint>> broadcastPoints; private EventuallyConsistentMapListener<DeviceId, Set<ConnectPoint>> listener = new InternalBroadcastPointListener(); @Activate protected void activate(ComponentContext context) { configService.registerProperties(getClass()); modified(context); KryoNamespace.Builder hostSerializer = KryoNamespace.newBuilder() .register(KryoNamespaces.API); broadcastPoints = storageService.<DeviceId, Set<ConnectPoint>>eventuallyConsistentMapBuilder() .withName("onos-broadcast-trees") .withSerializer(hostSerializer) .withTimestampProvider((k, v) -> clockService.getTimestamp()) .build(); broadcastPoints.addListener(listener); log.info("Started"); } @Deactivate protected void deactivate() { configService.unregisterProperties(getClass(), false); broadcastPoints.removeListener(listener); broadcastPoints.destroy(); log.info("Stopped"); } @Modified protected void modified(ComponentContext context) { Dictionary<?, ?> properties = context.getProperties(); String newLinkWeightFunction = get(properties, LINK_WEIGHT_FUNCTION); if (newLinkWeightFunction != null && !Objects.equals(newLinkWeightFunction, linkWeightFunction)) { linkWeightFunction = newLinkWeightFunction; LinkWeigher weight = linkWeightFunction.equals(LINK_METRIC) ? new MetricLinkWeight() : linkWeightFunction.equals(GEO_DISTANCE) ? new GeoDistanceLinkWeight(deviceService) : null; setDefaultLinkWeigher(weight); } String newMaxPaths = get(properties, MAX_PATHS); if (newMaxPaths != null) { try { setDefaultMaxPaths(Integer.parseInt(newMaxPaths)); } catch (NumberFormatException e) { log.warn("maxPaths must be a number; not {}", newMaxPaths); } } log.info(FORMAT, linkWeightFunction); } @Override public Topology currentTopology() { return current; } @Override public boolean isLatest(Topology topology) { // Topology is current only if it is the same as our current topology return topology == current; } @Override public TopologyGraph getGraph(Topology topology) { return defaultTopology(topology).getGraph(); } @Override public Set<TopologyCluster> getClusters(Topology topology) { return defaultTopology(topology).getClusters(); } @Override public TopologyCluster getCluster(Topology topology, ClusterId clusterId) { return defaultTopology(topology).getCluster(clusterId); } @Override public Set<DeviceId> getClusterDevices(Topology topology, TopologyCluster cluster) { return defaultTopology(topology).getClusterDevices(cluster); } @Override public Set<Link> getClusterLinks(Topology topology, TopologyCluster cluster) { return defaultTopology(topology).getClusterLinks(cluster); } @Override public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst) { return defaultTopology(topology).getPaths(src, dst); } @Override public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher) { return defaultTopology(topology).getPaths(src, dst, weigher); } @Override public Set<Path> getKShortestPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher, int maxPaths) { return defaultTopology(topology).getKShortestPaths(src, dst, weigher, maxPaths); } @Override public Stream<Path> getKShortestPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher) { return defaultTopology(topology).getKShortestPaths(src, dst, weigher); } @Override public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst) { return defaultTopology(topology).getDisjointPaths(src, dst); } @Override public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher) { return defaultTopology(topology).getDisjointPaths(src, dst, weigher); } @Override public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst, Map<Link, Object> riskProfile) { return defaultTopology(topology).getDisjointPaths(src, dst, riskProfile); } @Override public Set<DisjointPath> getDisjointPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeigher weigher, Map<Link, Object> riskProfile) { return defaultTopology(topology).getDisjointPaths(src, dst, weigher, riskProfile); } @Override public boolean isInfrastructure(Topology topology, ConnectPoint connectPoint) { return defaultTopology(topology).isInfrastructure(connectPoint); } @Override public boolean isBroadcastPoint(Topology topology, ConnectPoint connectPoint) { return defaultTopology(topology).isBroadcastPoint(connectPoint); } private boolean isBroadcastPoint(ConnectPoint connectPoint) { // Any non-infrastructure, i.e. edge points are assumed to be OK. if (!current.isInfrastructure(connectPoint)) { return true; } // Find the cluster to which the device belongs. TopologyCluster cluster = current.getCluster(connectPoint.deviceId()); checkArgument(cluster != null, "No cluster found for device %s", connectPoint.deviceId()); // If the broadcast set is null or empty, or if the point explicitly // belongs to it, return true; Set<ConnectPoint> points = broadcastPoints.get(cluster.root().deviceId()); return isNullOrEmpty(points) || points.contains(connectPoint); } @Override public TopologyEvent updateTopology(ProviderId providerId, GraphDescription graphDescription, List<Event> reasons) { // Have the default topology construct self from the description data. DefaultTopology newTopology = new DefaultTopology(providerId, graphDescription, this::isBroadcastPoint); updateBroadcastPoints(newTopology); // Promote the new topology to current and return a ready-to-send event. synchronized (this) { // Make sure that what we're given is indeed newer than what we // already have. if (current != null && newTopology.time() < current.time()) { return null; } current = newTopology; return new TopologyEvent(TOPOLOGY_CHANGED, current, reasons); } } private void updateBroadcastPoints(DefaultTopology topology) { // Remove any broadcast trees rooted by devices for which we are master. Set<DeviceId> toRemove = broadcastPoints.keySet().stream() .filter(mastershipService::isLocalMaster) .collect(Collectors.toSet()); // Update the broadcast trees rooted by devices for which we are master. topology.getClusters().forEach(c -> { toRemove.remove(c.root().deviceId()); if (mastershipService.isLocalMaster(c.root().deviceId())) { broadcastPoints.put(c.root().deviceId(), topology.broadcastPoints(c.id())); } }); toRemove.forEach(broadcastPoints::remove); } // Validates the specified topology and returns it as a default private DefaultTopology defaultTopology(Topology topology) { checkArgument(topology instanceof DefaultTopology, "Topology class %s not supported", topology.getClass()); return (DefaultTopology) topology; } @Override public void setDefaultMaxPaths(int maxPaths) { this.maxPaths = maxPaths; DefaultTopology.setDefaultMaxPaths(maxPaths); } @Override public void setDefaultLinkWeigher(LinkWeigher linkWeigher) { DefaultTopology.setDefaultLinkWeigher(linkWeigher); } @Override public void setDefaultGraphPathSearch(GraphPathSearch<TopologyVertex, TopologyEdge> graphPathSearch) { DefaultTopology.setDefaultGraphPathSearch(graphPathSearch); } private class InternalBroadcastPointListener implements EventuallyConsistentMapListener<DeviceId, Set<ConnectPoint>> { @Override public void event(EventuallyConsistentMapEvent<DeviceId, Set<ConnectPoint>> event) { if (event.type() == EventuallyConsistentMapEvent.Type.PUT) { if (!event.value().isEmpty()) { log.debug("Cluster rooted at {} has {} broadcast-points; #{}", event.key(), event.value().size(), event.value().hashCode()); } } } } }
3e100285d32340ecf05aafbece613b52005a4da9
390
java
Java
casadocodigo/src/main/java/com/casadocodigo/casadocodigo/repository/CategoriaRepository.java
Alexeiabianna/orange-talents-06-template-casa-do-codigo
c34adf3f0d6d9f47e417e0fff9dd4c7730c0c09b
[ "Apache-2.0" ]
null
null
null
casadocodigo/src/main/java/com/casadocodigo/casadocodigo/repository/CategoriaRepository.java
Alexeiabianna/orange-talents-06-template-casa-do-codigo
c34adf3f0d6d9f47e417e0fff9dd4c7730c0c09b
[ "Apache-2.0" ]
null
null
null
casadocodigo/src/main/java/com/casadocodigo/casadocodigo/repository/CategoriaRepository.java
Alexeiabianna/orange-talents-06-template-casa-do-codigo
c34adf3f0d6d9f47e417e0fff9dd4c7730c0c09b
[ "Apache-2.0" ]
null
null
null
26
77
0.823077
6,786
package com.casadocodigo.casadocodigo.repository; import java.util.Optional; import com.casadocodigo.casadocodigo.modelo.Categoria; import org.springframework.data.jpa.repository.JpaRepository; public interface CategoriaRepository extends JpaRepository<Categoria, Long> { Optional<Categoria> findByNomeCategoria(String nomeCategoria); Optional<Categoria> findById(Long id); }
3e1002aa50ee0b149afdb7f69cc8ed197f1283e0
966
java
Java
src/main/scala/org/squeryl/annotations/Transient.java
jmack87/Squeryl
9eec42d9dfb4897d6f5c906b8f00a5064fd1d421
[ "Apache-2.0" ]
245
2015-01-07T01:21:54.000Z
2022-01-30T07:58:02.000Z
src/main/scala/org/squeryl/annotations/Transient.java
jmack87/Squeryl
9eec42d9dfb4897d6f5c906b8f00a5064fd1d421
[ "Apache-2.0" ]
52
2015-02-09T03:33:23.000Z
2021-09-23T12:35:24.000Z
src/main/scala/org/squeryl/annotations/Transient.java
jmack87/Squeryl
9eec42d9dfb4897d6f5c906b8f00a5064fd1d421
[ "Apache-2.0" ]
64
2015-01-28T09:40:38.000Z
2022-01-07T13:19:58.000Z
40.25
81
0.619048
6,787
/******************************************************************************* * Copyright 2010 Maxime Lévesque * * 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.squeryl.annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Transient { }
3e1002ec38b37cd4efd29093f254872969f4440e
644
java
Java
StringProcessing/SeriesOfLetters.java
martinmihov/JavaAdvanced
89c834e02b46c58ead45baed9d0a2b8adfdd424c
[ "MIT" ]
null
null
null
StringProcessing/SeriesOfLetters.java
martinmihov/JavaAdvanced
89c834e02b46c58ead45baed9d0a2b8adfdd424c
[ "MIT" ]
null
null
null
StringProcessing/SeriesOfLetters.java
martinmihov/JavaAdvanced
89c834e02b46c58ead45baed9d0a2b8adfdd424c
[ "MIT" ]
null
null
null
24.769231
63
0.667702
6,788
package StringProcessing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SeriesOfLetters { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); String pattern = "([a-zA-Z ])\\1*"; Pattern regex = Pattern.compile(pattern); Matcher matcher = regex.matcher(input); while (matcher.find()) { System.out.print(matcher.group(1)); } } }
3e100339d6e8992211a3b9f0d7f2ff46adf9347d
81,972
java
Java
gravitee-rest-api-service/src/main/java/io/gravitee/rest/api/service/impl/PageServiceImpl.java
YoranSys/gravitee-management-rest-api
36124ee16323d27a909d9886ea885e824a9fac3f
[ "Apache-2.0" ]
null
null
null
gravitee-rest-api-service/src/main/java/io/gravitee/rest/api/service/impl/PageServiceImpl.java
YoranSys/gravitee-management-rest-api
36124ee16323d27a909d9886ea885e824a9fac3f
[ "Apache-2.0" ]
null
null
null
gravitee-rest-api-service/src/main/java/io/gravitee/rest/api/service/impl/PageServiceImpl.java
YoranSys/gravitee-management-rest-api
36124ee16323d27a909d9886ea885e824a9fac3f
[ "Apache-2.0" ]
null
null
null
45.163636
212
0.620187
6,789
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.rest.api.service.impl; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import io.gravitee.common.http.MediaType; import io.gravitee.fetcher.api.*; import io.gravitee.plugin.core.api.PluginManager; import io.gravitee.plugin.fetcher.FetcherPlugin; import io.gravitee.repository.exceptions.TechnicalException; import io.gravitee.repository.management.api.PageRepository; import io.gravitee.repository.management.api.search.PageCriteria; import io.gravitee.repository.management.model.*; import io.gravitee.rest.api.fetcher.FetcherConfigurationFactory; import io.gravitee.rest.api.model.*; import io.gravitee.rest.api.model.MembershipReferenceType; import io.gravitee.rest.api.model.Visibility; import io.gravitee.rest.api.model.api.ApiEntity; import io.gravitee.rest.api.model.api.ApiEntrypointEntity; import io.gravitee.rest.api.model.descriptor.GraviteeDescriptorEntity; import io.gravitee.rest.api.model.descriptor.GraviteeDescriptorPageEntity; import io.gravitee.rest.api.model.documentation.PageQuery; import io.gravitee.rest.api.model.permissions.ApiPermission; import io.gravitee.rest.api.model.permissions.RolePermissionAction; import io.gravitee.rest.api.service.*; import io.gravitee.rest.api.service.common.GraviteeContext; import io.gravitee.rest.api.service.common.RandomString; import io.gravitee.rest.api.service.exceptions.*; import io.gravitee.rest.api.service.impl.swagger.transformer.SwaggerTransformer; import io.gravitee.rest.api.service.impl.swagger.transformer.entrypoints.EntrypointsOAITransformer; import io.gravitee.rest.api.service.impl.swagger.transformer.entrypoints.EntrypointsSwaggerV2Transformer; import io.gravitee.rest.api.service.impl.swagger.transformer.page.PageConfigurationOAITransformer; import io.gravitee.rest.api.service.impl.swagger.transformer.page.PageConfigurationSwaggerV2Transformer; import io.gravitee.rest.api.service.sanitizer.HtmlSanitizer; import io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils; import io.gravitee.rest.api.service.search.SearchEngineService; import io.gravitee.rest.api.service.spring.ImportConfiguration; import io.gravitee.rest.api.service.swagger.OAIDescriptor; import io.gravitee.rest.api.service.swagger.SwaggerDescriptor; import io.gravitee.rest.api.service.swagger.SwaggerV2Descriptor; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.gravitee.repository.management.model.Audit.AuditProperties.PAGE; import static io.gravitee.repository.management.model.Page.AuditEvent.*; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; import static org.springframework.ui.freemarker.FreeMarkerTemplateUtils.processTemplateIntoString; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author Nicolas GERAUD (nicolas.geraud at graviteesource.com) * @author Guillaume Gillon * @author GraviteeSource Team */ @Component public class PageServiceImpl extends TransactionalService implements PageService, ApplicationContextAware { private static final Gson gson = new Gson(); private static final Logger logger = LoggerFactory.getLogger(PageServiceImpl.class); private static final String SENSITIVE_DATA_REPLACEMENT = "********"; @Value("${documentation.markdown.sanitize:false}") private boolean markdownSanitize; @Autowired private PageRepository pageRepository; @Autowired private ApiService apiService; @Autowired private SwaggerService swaggerService; @Autowired private PluginManager<FetcherPlugin> fetcherPluginManager; @Autowired private FetcherConfigurationFactory fetcherConfigurationFactory; @Autowired private Configuration freemarkerConfiguration; @Autowired private ApplicationContext applicationContext; @Autowired private MembershipService membershipService; @Autowired private RoleService roleService; @Autowired private AuditService auditService; @Autowired private SearchEngineService searchEngineService; @Autowired private MetadataService metadataService; @Autowired private GraviteeDescriptorService graviteeDescriptorService; @Autowired private ImportConfiguration importConfiguration;private enum PageSituation { ROOT, IN_ROOT, IN_FOLDER_IN_ROOT, IN_FOLDER_IN_FOLDER, SYSTEM_FOLDER, IN_SYSTEM_FOLDER, IN_FOLDER_IN_SYSTEM_FOLDER, TRANSLATION; } private PageSituation getPageSituation(String pageId) throws TechnicalException { if (pageId == null) { return PageSituation.ROOT; } else { Optional<Page> optionalPage = pageRepository.findById(pageId); if (optionalPage.isPresent()) { Page page = optionalPage.get(); if (PageType.SYSTEM_FOLDER.name().equalsIgnoreCase(page.getType())) { return PageSituation.SYSTEM_FOLDER; } if (PageType.TRANSLATION.name().equalsIgnoreCase(page.getType())) { return PageSituation.TRANSLATION; } String parentId = page.getParentId(); if (parentId == null) { return PageSituation.IN_ROOT; } Optional<Page> optionalParent = pageRepository.findById(parentId); if (optionalParent.isPresent()) { Page parentPage = optionalParent.get(); if (PageType.SYSTEM_FOLDER.name().equalsIgnoreCase(parentPage.getType())) { return PageSituation.IN_SYSTEM_FOLDER; } if (PageType.FOLDER.name().equalsIgnoreCase(parentPage.getType())) { String grandParentId = parentPage.getParentId(); if (grandParentId == null) { return PageSituation.IN_FOLDER_IN_ROOT; } Optional<Page> optionalGrandParent = pageRepository.findById(grandParentId); if (optionalGrandParent.isPresent()) { Page grandParentPage = optionalGrandParent.get(); if (PageType.SYSTEM_FOLDER.name().equalsIgnoreCase(grandParentPage.getType())) { return PageSituation.IN_FOLDER_IN_SYSTEM_FOLDER; } if (PageType.FOLDER.name().equalsIgnoreCase(grandParentPage.getType())) { return PageSituation.IN_FOLDER_IN_FOLDER; } } } } } logger.debug("Impossible to determine page situation for the page " + pageId); return null; } } @Override public PageEntity findById(String pageId) { return this.findById(pageId, null); } @Override public PageEntity findById(String pageId, String acceptedLocale) { try { logger.debug("Find page by ID: {}", pageId); Optional<Page> page = pageRepository.findById(pageId); if (page.isPresent()) { PageEntity foundPageEntity = convert(page.get()); if (acceptedLocale != null && !acceptedLocale.isEmpty()) { Page translation = getTranslation(foundPageEntity, acceptedLocale); if (translation != null) { String translationName = translation.getName(); if (translationName != null && !translationName.isEmpty()) { foundPageEntity.setName(translationName); } String inheritContent = translation.getConfiguration().get(PageConfigurationKeys.TRANSLATION_INHERIT_CONTENT); if (inheritContent != null && "false".equals(inheritContent)) { foundPageEntity.setContent(translation.getContent()); } } } else { List<PageEntity> translations = convert(getTranslations(foundPageEntity.getId())); if (translations != null && !translations.isEmpty()) { foundPageEntity.setTranslations(translations); } } return foundPageEntity; } throw new PageNotFoundException(pageId); } catch (TechnicalException ex) { logger.error("An error occurs while trying to find a page using its ID {}", pageId, ex); throw new TechnicalManagementException( "An error occurs while trying to find a page using its ID " + pageId, ex); } } @Override public void transformSwagger(PageEntity pageEntity) { String apiId = null; if (pageEntity instanceof ApiPageEntity) { apiId = ((ApiPageEntity) pageEntity).getApi(); } transformSwagger(pageEntity, apiId); } @Override public void transformSwagger(PageEntity pageEntity, String apiId) { // First apply templating if required if (apiId != null) { transformWithTemplate(pageEntity, apiId); } if (markdownSanitize && PageType.MARKDOWN.name().equalsIgnoreCase(pageEntity.getType())) { pageEntity.setContent(HtmlSanitizer.sanitize(pageEntity.getContent())); }else if (PageType.SWAGGER.name().equalsIgnoreCase(pageEntity.getType())) { // If swagger page, let's try to apply transformations SwaggerDescriptor<?> descriptor = swaggerService.parse(pageEntity.getContent()); if (descriptor.getVersion() == SwaggerDescriptor.Version.SWAGGER_V1 || descriptor.getVersion() == SwaggerDescriptor.Version.SWAGGER_V2) { Collection<SwaggerTransformer<SwaggerV2Descriptor>> transformers = new ArrayList<>(); transformers.add(new PageConfigurationSwaggerV2Transformer(pageEntity)); if (apiId != null) { List<ApiEntrypointEntity> entrypoints = apiService.findById(apiId).getEntrypoints(); transformers.add(new EntrypointsSwaggerV2Transformer(pageEntity, entrypoints)); } swaggerService.transform((SwaggerV2Descriptor) descriptor, transformers); } else if (descriptor.getVersion() == SwaggerDescriptor.Version.OAI_V3) { Collection<SwaggerTransformer<OAIDescriptor>> transformers = new ArrayList<>(); transformers.add(new PageConfigurationOAITransformer(pageEntity)); if (apiId != null) { List<ApiEntrypointEntity> entrypoints = apiService.findById(apiId).getEntrypoints(); transformers.add(new EntrypointsOAITransformer(pageEntity, entrypoints)); } swaggerService.transform((OAIDescriptor) descriptor, transformers); } if (pageEntity.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON)) { try { pageEntity.setContent(descriptor.toJson()); } catch (JsonProcessingException e) { logger.error("Unexpected error", e); } } else { try { pageEntity.setContent(descriptor.toYaml()); } catch (JsonProcessingException e) { logger.error("Unexpected error", e); } } } } @Override public List<PageEntity> search(final PageQuery query) { return this.search(query, null, false); } @Override public List<PageEntity> search(final PageQuery query, boolean withTranslations) { return this.search(query, null, withTranslations); } @Override public List<PageEntity> search(final PageQuery query, String acceptedLocale) { return this.search(query, acceptedLocale, false); } private List<PageEntity> search(final PageQuery query, String acceptedLocale, boolean withTranslations) { try { Stream<Page> pagesStream = pageRepository.search(queryToCriteria(query)).stream(); if (!withTranslations) { pagesStream = pagesStream.filter(page -> !PageType.TRANSLATION.name().equals(page.getType())); } List<PageEntity> pages = pagesStream .map(this::convert) .collect(Collectors.toList()); if (acceptedLocale == null || acceptedLocale.isEmpty()) { pages.forEach(p -> { if (!PageType.TRANSLATION.name().equals(p.getType())) { List<PageEntity> translations = convert(getTranslations(p.getId())); if (translations != null && !translations.isEmpty()) { p.setTranslations(translations); } } }); } else { pages.forEach(p -> { if (!PageType.TRANSLATION.name().equals(p.getType())) { Page translation = getTranslation(p, acceptedLocale); if (translation != null) { String translationName = translation.getName(); if (translationName != null && !translationName.isEmpty()) { p.setName(translationName); } String inheritContent = translation.getConfiguration().get(PageConfigurationKeys.TRANSLATION_INHERIT_CONTENT); if (inheritContent != null && "false".equals(inheritContent)) { p.setContent(translation.getContent()); } } } }); } if (query != null && query.getPublished() != null && query.getPublished()) { // remove child of unpublished folders return pages.stream() .filter(page -> { if (page.getParentId() != null) { return this.findById(page.getParentId()).isPublished(); } return true; }) .collect(toList()); } return pages; } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException( "An error occurs while trying to search pages", ex); } } private Page getTranslation(PageEntity pageToTranslate, String acceptedLocale) { if (PageType.LINK.name().equals(pageToTranslate.getType()) && pageToTranslate.getConfiguration() != null && "true".equals(pageToTranslate.getConfiguration().get(PageConfigurationKeys.LINK_INHERIT)) ) { Page relatedTranslation = getTranslation(pageToTranslate.getContent(), acceptedLocale); Page linkTranslation = null; if (relatedTranslation != null) { linkTranslation = new Page(); linkTranslation.setName(relatedTranslation.getName()); linkTranslation.setContent(relatedTranslation.getContent()); linkTranslation.setConfiguration(Collections.emptyMap()); } return linkTranslation; } return getTranslation(pageToTranslate.getId(), acceptedLocale); } private Page getTranslation(String pageId, String acceptedLocale) { try { Optional<Page> optTranslation = this.pageRepository.search(new PageCriteria.Builder().parent(pageId).type(PageType.TRANSLATION.name()).build()) .stream() .filter(t -> acceptedLocale.equals(t.getConfiguration().get(PageConfigurationKeys.TRANSLATION_LANG))) .findFirst(); if (optTranslation.isPresent()) { return optTranslation.get(); } return null; } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException( "An error occurs while trying to search pages", ex); } } @Override public void transformWithTemplate(final PageEntity pageEntity, final String api) { if (pageEntity.getContent() != null) { try { final Template template = new Template(pageEntity.getId(), pageEntity.getContent(), freemarkerConfiguration); final Map<String, Object> model = new HashMap<>(); if (api == null) { final List<MetadataEntity> metadataList = metadataService.findAllDefault(); if (metadataList != null) { final Map<String, String> mapMetadata = new HashMap<>(metadataList.size()); metadataList.forEach(metadata -> mapMetadata.put(metadata.getKey(), metadata.getValue())); model.put("metadata", mapMetadata); } } else { ApiModelEntity apiEntity = apiService.findByIdForTemplates(api, true); model.put("api", apiEntity); } final String content = processTemplateIntoString(template, model); pageEntity.setContent(content); } catch (IOException | TemplateException ex) { logger.error("An error occurs while transforming page content for {}", pageEntity.getId(), ex); } } } @Override public PageEntity createPage(String apiId, NewPageEntity newPageEntity) { return this.createPage(apiId, newPageEntity, GraviteeContext.getCurrentEnvironment()); } private PageEntity createPage(String apiId, NewPageEntity newPageEntity, String environmentId) { try { logger.debug("Create page {} for API {}", newPageEntity, apiId); String id = RandomString.generate(); PageType newPageType = newPageEntity.getType(); if (PageType.TRANSLATION.equals(newPageType)) { checkTranslationConsistency(newPageEntity.getParentId(), newPageEntity.getConfiguration(), true); Optional<Page> optTranslatedPage = this.pageRepository.findById(newPageEntity.getParentId()); if (optTranslatedPage.isPresent()) { newPageEntity.setPublished(optTranslatedPage.get().isPublished()); } } if (PageType.FOLDER.equals(newPageType)) { checkFolderConsistency(newPageEntity); } if (PageType.LINK.equals(newPageType)) { String resourceType = newPageEntity.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE); String content = newPageEntity.getContent(); if (content == null || content.isEmpty()) { throw new PageActionException(PageType.LINK, "be created. It must have a URL, a page Id or a category Id"); } if ("root".equals(content) || PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) || PageConfigurationKeys.LINK_RESOURCE_TYPE_CATEGORY.equals(resourceType)) { newPageEntity.setPublished(true); } else { Optional<Page> optionalRelatedPage = pageRepository.findById(content); if (optionalRelatedPage.isPresent()) { Page relatedPage = optionalRelatedPage.get(); checkLinkRelatedPageType(relatedPage); newPageEntity.setPublished(relatedPage.isPublished()); } } } if (PageType.SWAGGER == newPageType || PageType.MARKDOWN == newPageType) { checkMarkdownOrSwaggerConsistency(newPageEntity, newPageType); } Page page = convert(newPageEntity); if (page.getSource() != null) { fetchPage(page); } page.setId(id); if (StringUtils.isEmpty(apiId)) { page.setReferenceId(environmentId); page.setReferenceType(PageReferenceType.ENVIRONMENT); } else { page.setReferenceId(apiId); page.setReferenceType(PageReferenceType.API); } // Set date fields page.setCreatedAt(new Date()); page.setUpdatedAt(page.getCreatedAt()); Page createdPage = validateContentAndCreate(page); //only one homepage is allowed onlyOneHomepage(page); createAuditLog(apiId, PAGE_CREATED, page.getCreatedAt(), null, page); PageEntity pageEntity = convert(createdPage); // add document in search engine index(pageEntity); return pageEntity; } catch (TechnicalException | FetcherException ex) { logger.error("An error occurs while trying to create {}", newPageEntity, ex); throw new TechnicalManagementException("An error occurs while trying create " + newPageEntity, ex); } } private void checkMarkdownOrSwaggerConsistency(NewPageEntity newPageEntity, PageType newPageType) throws TechnicalException { PageSituation newPageParentSituation = getPageSituation(newPageEntity.getParentId()); if (newPageParentSituation == PageSituation.SYSTEM_FOLDER || newPageParentSituation == PageSituation.IN_SYSTEM_FOLDER) { throw new PageActionException(newPageType, "be created under a system folder"); } } private void checkFolderConsistency(NewPageEntity newPageEntity) throws TechnicalException { if (newPageEntity.getContent() != null && newPageEntity.getContent().length() > 0) { throw new PageFolderActionException("have a content"); } if (newPageEntity.isHomepage()) { throw new PageFolderActionException("be affected to the home page"); } PageSituation newPageParentSituation = getPageSituation(newPageEntity.getParentId()); if (newPageParentSituation == PageSituation.IN_SYSTEM_FOLDER) { throw new PageFolderActionException("be created in a folder of a system folder"); } } private void checkTranslationConsistency(String parentId, Map<String, String> configuration, boolean forCreation) throws TechnicalException { if (parentId == null || parentId.isEmpty()) { throw new PageActionException(PageType.TRANSLATION, "have no parentId"); } if (configuration == null || configuration.get(PageConfigurationKeys.TRANSLATION_LANG) == null || configuration.get(PageConfigurationKeys.TRANSLATION_LANG).isEmpty()) { throw new PageActionException(PageType.TRANSLATION, "have no configured language"); } Optional<Page> optTranslatedPage = this.pageRepository.findById(parentId); if (optTranslatedPage.isPresent()) { Page translatedPage = optTranslatedPage.get(); PageType translatedPageType = PageType.valueOf(translatedPage.getType()); if (PageType.ROOT == translatedPageType || PageType.SYSTEM_FOLDER == translatedPageType || PageType.TRANSLATION == translatedPageType) { throw new PageActionException(PageType.TRANSLATION, "have a parent with type " + translatedPageType.name() + ". Parent " + parentId + " is not one of this type : FOLDER, LINK, MARKDOWN, SWAGGER"); } if (forCreation) { String newTranslationLang = configuration.get(PageConfigurationKeys.TRANSLATION_LANG); Page existingTranslation = getTranslation(parentId, newTranslationLang); if (existingTranslation != null) { throw new PageActionException(PageType.TRANSLATION, "be created. A translation for this language already exist"); } } } else { // TODO: should be reactivated when import/export is fixed //throw new PageActionException(PageType.TRANSLATION, "have an inexisting parent. Parent " + parentId + " not found"); } } private void checkLinkRelatedPageType(Page relatedPage) throws TechnicalException { PageSituation relatedPageSituation = getPageSituation(relatedPage.getId()); if (PageType.LINK.name().equalsIgnoreCase(relatedPage.getType()) || PageType.SYSTEM_FOLDER.name().equalsIgnoreCase(relatedPage.getType()) || (PageType.FOLDER.name().equalsIgnoreCase(relatedPage.getType()) && relatedPageSituation == PageSituation.IN_SYSTEM_FOLDER)) { throw new PageActionException(PageType.LINK, "be related to a Link, a System folder or a folder in a System folder"); } } @Override public PageEntity createPage(NewPageEntity newPageEntity) { return this.createPage(null, newPageEntity); } @Override public PageEntity create(final String apiId, final PageEntity pageEntity) { final NewPageEntity newPageEntity = convert(pageEntity); newPageEntity.setLastContributor(null); return createPage(apiId, newPageEntity); } private void onlyOneHomepage(Page page) throws TechnicalException { if (page.isHomepage()) { Collection<Page> pages = pageRepository.search(new PageCriteria.Builder().referenceId(page.getReferenceId()).referenceType(page.getReferenceType().name()).homepage(true).build()); pages.stream(). filter(i -> !i.getId().equals(page.getId())). forEach(i -> { try { i.setHomepage(false); pageRepository.update(i); } catch (TechnicalException e) { logger.error("An error occurs while trying update homepage attribute from {}", page, e); } }); } } @Override public PageEntity update(String pageId, UpdatePageEntity updatePageEntity) { return this.update(pageId, updatePageEntity, false); } @Override public PageEntity update(String pageId, UpdatePageEntity updatePageEntity, boolean partial) { try { logger.debug("Update Page {}", pageId); Optional<Page> optPageToUpdate = pageRepository.findById(pageId); if (!optPageToUpdate.isPresent()) { throw new PageNotFoundException(pageId); } Page pageToUpdate = optPageToUpdate.get(); Page page = null; String pageType = pageToUpdate.getType(); if (PageType.LINK.name().equalsIgnoreCase(pageType)) { String newResourceRef = updatePageEntity.getContent(); String actualResourceRef = pageToUpdate.getContent(); if (newResourceRef != null && !newResourceRef.equals(actualResourceRef)) { String resourceType = (updatePageEntity.getConfiguration() != null ? updatePageEntity.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE) : pageToUpdate.getConfiguration().get(PageConfigurationKeys.LINK_RESOURCE_TYPE)); if (PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) && (updatePageEntity.getContent() != null && updatePageEntity.getContent().isEmpty())) { throw new PageActionException(PageType.LINK, "be created. An external Link must have a URL"); } if ("root".equals(newResourceRef) || PageConfigurationKeys.LINK_RESOURCE_TYPE_EXTERNAL.equals(resourceType) || PageConfigurationKeys.LINK_RESOURCE_TYPE_CATEGORY.equals(resourceType)) { updatePageEntity.setPublished(true); } else { Optional<Page> optionalRelatedPage = pageRepository.findById(newResourceRef); if (optionalRelatedPage.isPresent()) { Page relatedPage = optionalRelatedPage.get(); checkLinkRelatedPageType(relatedPage); updatePageEntity.setPublished(relatedPage.isPublished()); } } } else if (newResourceRef != null && newResourceRef.equals(actualResourceRef)) { // can not publish or unpublish a Link. LINK publication state is changed when the related page is updated. updatePageEntity.setPublished(pageToUpdate.isPublished()); } } if (PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) { String parentId = (updatePageEntity.getParentId() != null && !updatePageEntity.getParentId().isEmpty()) ? updatePageEntity.getParentId() : pageToUpdate.getParentId(); Map<String, String> configuration = updatePageEntity.getConfiguration() != null ? updatePageEntity.getConfiguration() : pageToUpdate.getConfiguration(); checkTranslationConsistency(parentId, configuration, false); } if (updatePageEntity.getParentId() != null && !updatePageEntity.getParentId().equals(pageToUpdate.getParentId())) { checkUpdatedPageSituation(updatePageEntity, pageType, pageId); if (PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) { Optional<Page> optionalTranslatedPage = pageRepository.findById(updatePageEntity.getParentId()); if (optionalTranslatedPage.isPresent()) { updatePageEntity.setPublished(optionalTranslatedPage.get().isPublished()); } } } if (partial) { page = merge(updatePageEntity, pageToUpdate); } else { page = convert(updatePageEntity); } if (page.getSource() != null) { try { if (pageToUpdate.getSource() != null && pageToUpdate.getSource().getConfiguration() != null) { mergeSensitiveData(this.getFetcher(pageToUpdate.getSource()).getConfiguration(), page); } fetchPage(page); } catch (FetcherException e) { throw onUpdateFail(pageId, e); } } page.setId(pageId); page.setUpdatedAt(new Date()); // Copy fields from existing values page.setCreatedAt(pageToUpdate.getCreatedAt()); page.setType(pageType); page.setReferenceId(pageToUpdate.getReferenceId()); page.setReferenceType(pageToUpdate.getReferenceType()); onlyOneHomepage(page); // if order change, reorder all pages if (page.getOrder() != pageToUpdate.getOrder()) { reorderAndSavePages(page); return null; } else { Page updatedPage = validateContentAndUpdate(page); if (pageToUpdate.isPublished() != page.isPublished() && !PageType.LINK.name().equalsIgnoreCase(pageType) && !PageType.TRANSLATION.name().equalsIgnoreCase(pageType)) { // update all the related links and translations publication status. this.changeRelatedPagesPublicationStatus(pageId, updatePageEntity.isPublished()); } createAuditLog(page.getReferenceId(), PAGE_UPDATED, page.getUpdatedAt(), pageToUpdate, page); PageEntity pageEntity = convert(updatedPage); // update document in search engine if (pageToUpdate.isPublished() && !page.isPublished()) { searchEngineService.delete(convert(pageToUpdate), false); } else { index(pageEntity); } return pageEntity; } } catch (TechnicalException ex) { throw onUpdateFail(pageId, ex); } } private void checkUpdatedPageSituation(UpdatePageEntity updatePageEntity, String pageType, String pageId) throws TechnicalException { PageSituation newParentSituation = getPageSituation(updatePageEntity.getParentId()); switch (pageType) { case "SYSTEM_FOLDER": if (newParentSituation != PageSituation.ROOT) { throw new PageActionException(PageType.SYSTEM_FOLDER, " be moved in this folder"); } break; case "MARKDOWN": if (newParentSituation == PageSituation.SYSTEM_FOLDER || newParentSituation == PageSituation.IN_SYSTEM_FOLDER) { throw new PageActionException(PageType.MARKDOWN, " be moved in a system folder or in a folder of a system folder"); } break; case "SWAGGER": if (newParentSituation == PageSituation.SYSTEM_FOLDER || newParentSituation == PageSituation.IN_SYSTEM_FOLDER) { throw new PageActionException(PageType.SWAGGER, " be moved in a system folder or in a folder of a system folder"); } break; case "FOLDER": PageSituation folderSituation = getPageSituation(pageId); if (folderSituation == PageSituation.IN_SYSTEM_FOLDER && newParentSituation != PageSituation.SYSTEM_FOLDER) { throw new PageActionException(PageType.FOLDER, " be moved anywhere other than in a system folder"); } else if (folderSituation != PageSituation.IN_SYSTEM_FOLDER && newParentSituation == PageSituation.SYSTEM_FOLDER) { throw new PageActionException(PageType.FOLDER, " be moved in a system folder"); } break; case "LINK": if (newParentSituation != PageSituation.SYSTEM_FOLDER && newParentSituation != PageSituation.IN_SYSTEM_FOLDER) { throw new PageActionException(PageType.LINK, " be moved anywhere other than in a system folder or in a folder of a system folder"); } break; case "TRANSLATION": if (newParentSituation == PageSituation.ROOT || newParentSituation == PageSituation.SYSTEM_FOLDER || newParentSituation == PageSituation.TRANSLATION) { throw new PageActionException(PageType.TRANSLATION, "be updated. Parent " + updatePageEntity.getParentId() + " is not one of this type : FOLDER, LINK, MARKDOWN, SWAGGER"); } break; default: break; } } private void changeRelatedPagesPublicationStatus(String pageId, Boolean published) { try { // Update related page's links this.pageRepository.search(new PageCriteria.Builder().type(PageType.LINK.name()).build()).stream() .filter(p -> pageId.equals(p.getContent())) .forEach(p -> { try { // Update link p.setPublished(published); pageRepository.update(p); // Update link's translations changeTranslationPagesPublicationStatus(p.getId(), published); } catch (TechnicalException ex) { throw onUpdateFail(p.getId(), ex); } }); // Update related page's translations changeTranslationPagesPublicationStatus(pageId, published); } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException("An error occurs while trying to search pages", ex); } } private void changeTranslationPagesPublicationStatus(String translatedPageId, Boolean published) { try { this.pageRepository.search(new PageCriteria.Builder().parent(translatedPageId).type(PageType.TRANSLATION.name()).build()).stream() .forEach(p -> { try { p.setPublished(published); pageRepository.update(p); } catch (TechnicalException ex) { throw onUpdateFail(p.getId(), ex); } }); } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException("An error occurs while trying to search pages", ex); } } private void deleteRelatedPages(String pageId) { try { this.pageRepository.search(new PageCriteria.Builder().type("LINK").build()).stream() .filter(p -> pageId.equals(p.getContent())) .forEach(p -> { try { pageRepository.delete(p.getId()); this.deleteRelatedTranslations(p.getId()); } catch (TechnicalException ex) { logger.error("An error occurs while trying to delete Page {}", p.getId(), ex); throw new TechnicalManagementException("An error occurs while trying to delete Page " + p.getId(), ex); } }); this.deleteRelatedTranslations(pageId); } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException("An error occurs while trying to search pages", ex); } } private void deleteRelatedTranslations(String pageId) { try { this.pageRepository.search(new PageCriteria.Builder().parent(pageId).type(PageType.TRANSLATION.name()).build()).stream() .forEach(p -> { try { pageRepository.delete(p.getId()); } catch (TechnicalException ex) { logger.error("An error occurs while trying to delete Page {}", p.getId(), ex); throw new TechnicalManagementException("An error occurs while trying to delete Page " + p.getId(), ex); } }); } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException("An error occurs while trying to search pages", ex); } } private void index(PageEntity pageEntity) { if (pageEntity.isPublished()) { searchEngineService.index(pageEntity, false); } } private void fetchPage(final Page page) throws FetcherException {validateSafeSource(page); Fetcher fetcher = this.getFetcher(page.getSource()); if (fetcher != null) { try { final Resource resource = fetcher.fetch(); page.setContent(getResourceContentAsString(resource)); if (resource.getMetadata() != null) { page.setMetadata(new HashMap<>(resource.getMetadata().size())); for (Map.Entry<String, Object> entry : resource.getMetadata().entrySet()) { if (!(entry.getValue() instanceof Map)) { page.getMetadata().put(entry.getKey(), String.valueOf(entry.getValue())); } } } } catch (Exception e) { logger.error(e.getMessage(), e); throw new FetcherException(e.getMessage(), e); } } } @SuppressWarnings({"Duplicates", "unchecked"}) private Fetcher getFetcher(PageSource ps) throws FetcherException { if (ps.getConfiguration().isEmpty()) { return null; } try { FetcherPlugin fetcherPlugin = fetcherPluginManager.get(ps.getType()); ClassLoader fetcherCL = fetcherPlugin.fetcher().getClassLoader(); Fetcher fetcher; if (fetcherPlugin.configuration().getName().equals(FilepathAwareFetcherConfiguration.class.getName())) { Class<? extends FetcherConfiguration> fetcherConfigurationClass = (Class<? extends FetcherConfiguration>) fetcherCL.loadClass(fetcherPlugin.configuration().getName()); Class<? extends FilesFetcher> fetcherClass = (Class<? extends FilesFetcher>) fetcherCL.loadClass(fetcherPlugin.clazz()); FetcherConfiguration fetcherConfigurationInstance = fetcherConfigurationFactory.create(fetcherConfigurationClass, ps.getConfiguration()); fetcher = fetcherClass.getConstructor(fetcherConfigurationClass).newInstance(fetcherConfigurationInstance); } else { Class<? extends FetcherConfiguration> fetcherConfigurationClass = (Class<? extends FetcherConfiguration>) fetcherCL.loadClass(fetcherPlugin.configuration().getName()); Class<? extends Fetcher> fetcherClass = (Class<? extends Fetcher>) fetcherCL.loadClass(fetcherPlugin.clazz()); FetcherConfiguration fetcherConfigurationInstance = fetcherConfigurationFactory.create(fetcherConfigurationClass, ps.getConfiguration()); fetcher = fetcherClass.getConstructor(fetcherConfigurationClass).newInstance(fetcherConfigurationInstance); } applicationContext.getAutowireCapableBeanFactory().autowireBean(fetcher); return fetcher; } catch (Exception e) { logger.error(e.getMessage(), e); throw new FetcherException(e.getMessage(), e); } } private String getResourceContentAsString(final Resource resource) throws FetcherException { try { StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getContent()))) { String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } } return sb.toString(); } catch (Exception e) { logger.error(e.getMessage(), e); throw new FetcherException(e.getMessage(), e); } } @Override public List<PageEntity> importFiles(ImportPageEntity pageEntity) { return importFiles(null, pageEntity); } @Override public List<PageEntity> importFiles(String apiId, ImportPageEntity pageEntity) { Page page = upsertRootPage(apiId, pageEntity); pageEntity.setSource(convert(page.getSource(), false)); return fetchPages(apiId, pageEntity); } @Override public void fetchAll(PageQuery query, String contributor) { try { pageRepository.search(queryToCriteria(query)) .stream() .filter(pageListItem -> pageListItem.getSource() != null) .forEach(pageListItem -> { if (pageListItem.getType() != null && pageListItem.getType().toString().equals("ROOT")) { final ImportPageEntity pageEntity = new ImportPageEntity(); pageEntity.setType(PageType.valueOf(pageListItem.getType().toString())); pageEntity.setSource(convert(pageListItem.getSource(), false)); pageEntity.setConfiguration(pageListItem.getConfiguration()); pageEntity.setPublished(pageListItem.isPublished()); pageEntity.setExcludedGroups(pageListItem.getExcludedGroups()); pageEntity.setLastContributor(contributor); fetchPages(query.getApi(), pageEntity); } else { fetch(pageListItem.getId(), contributor); } }); } catch (TechnicalException ex) { logger.error("An error occurs while trying to fetch pages", ex); throw new TechnicalManagementException( "An error occurs while trying to fetch pages", ex); } } private List<PageEntity> importDescriptor(final String apiId, final ImportPageEntity descriptorPageEntity, final FilesFetcher fetcher, final GraviteeDescriptorEntity descriptorEntity) { if (descriptorEntity.getDocumentation() == null || descriptorEntity.getDocumentation().getPages() == null || descriptorEntity.getDocumentation().getPages().isEmpty()) { return emptyList(); } Map<String, String> parentsIdByPath = new HashMap<>(); List<PageEntity> createdPages = new ArrayList<>(); int order = 0; for (GraviteeDescriptorPageEntity descriptorPage : descriptorEntity.getDocumentation().getPages()) { NewPageEntity newPage = getPageFromPath(descriptorPage.getSrc()); if (newPage == null) { logger.warn("Unable to find a source file to import. Please fix the descriptor content."); } else { if (descriptorPage.getName() != null && !descriptorPage.getName().isEmpty()) { newPage.setName(descriptorPage.getName()); } newPage.setHomepage(descriptorPage.isHomepage()); newPage.setLastContributor(descriptorPageEntity.getLastContributor()); newPage.setPublished(descriptorPageEntity.isPublished()); newPage.setSource(descriptorPageEntity.getSource()); newPage.setOrder(order++); String parentPath = descriptorPage.getDest() == null || descriptorPage.getDest().isEmpty() ? getParentPathFromFilePath(descriptorPage.getSrc()) : descriptorPage.getDest(); try { createdPages.addAll( upsertPageAndParentFolders( parentPath, newPage, parentsIdByPath, fetcher, apiId, descriptorPage.getSrc())); } catch (TechnicalException ex) { logger.error("An error occurs while trying to import a gravitee descriptor", ex); throw new TechnicalManagementException("An error occurs while trying to import a gravitee descriptor", ex); } } } return createdPages; } private List<PageEntity> importDirectory(String apiId, ImportPageEntity pageEntity, FilesFetcher fetcher) { try { String[] files = fetcher.files(); // if a gravitee descriptor is present, import it. Optional<String> optDescriptor = Arrays.stream(files) .filter(f -> f.endsWith(graviteeDescriptorService.descriptorName())) .findFirst(); if (optDescriptor.isPresent()) { try { ((FilepathAwareFetcherConfiguration) fetcher.getConfiguration()).setFilepath(optDescriptor.get()); final Resource resource = fetcher.fetch(); final GraviteeDescriptorEntity descriptorEntity = graviteeDescriptorService.read(getResourceContentAsString(resource)); return importDescriptor(apiId, pageEntity, fetcher, descriptorEntity); } catch (Exception e) { logger.error(e.getMessage(), e); throw new FetcherException(e.getMessage(), e); } } Map<String, String> parentsIdByPath = new HashMap<>(); List<PageEntity> createdPages = new ArrayList<>(); // for each files returned by the fetcher int order = 0; for (String file : files) { NewPageEntity pageFromPath = getPageFromPath(file); if (pageFromPath != null) { pageFromPath.setLastContributor(pageEntity.getLastContributor()); pageFromPath.setPublished(pageEntity.isPublished()); pageFromPath.setSource(pageEntity.getSource()); pageFromPath.setOrder(order++); try { createdPages.addAll( upsertPageAndParentFolders( getParentPathFromFilePath(file), pageFromPath, parentsIdByPath, fetcher, apiId, file)); } catch (TechnicalException ex) { logger.error("An error occurs while trying to import a directory", ex); throw new TechnicalManagementException("An error occurs while trying to import a directory", ex); } } } return createdPages; } catch (FetcherException ex) { logger.error("An error occurs while trying to import a directory", ex); throw new TechnicalManagementException("An error occurs while trying import a directory", ex); } } private NewPageEntity getPageFromPath(String path) { if (path != null) { String[] extensions = path.split("\\."); if (extensions.length > 0) { PageType supportedPageType = getSupportedPageType(extensions[extensions.length - 1]); // if the file is supported by gravitee if (supportedPageType != null) { String[] pathElements = path.split("/"); if (pathElements.length > 0) { String filename = pathElements[pathElements.length - 1]; NewPageEntity newPage = new NewPageEntity(); newPage.setName(filename.substring(0, filename.lastIndexOf("."))); newPage.setType(supportedPageType); return newPage; } } } } logger.warn("Unable to extract Page informations from :[" + path + "]"); return null; } private String getParentPathFromFilePath(String filePath) { if (filePath != null && !filePath.isEmpty()) { String[] pathElements = filePath.split("/"); if (pathElements.length > 0) { StringJoiner stringJoiner = new StringJoiner("/"); for (int i = 0; i < pathElements.length - 1; i++) { stringJoiner.add(pathElements[i]); } return stringJoiner.toString(); } } return "/"; } private List<PageEntity> upsertPageAndParentFolders( final String parentPath, final NewPageEntity newPageEntity, final Map<String, String> parentsIdByPath, final FilesFetcher fetcher, final String apiId, final String src) throws TechnicalException { ObjectMapper mapper = new ObjectMapper(); String[] pathElements = parentPath.split("/"); String pwd = ""; List<PageEntity> createdPages = new ArrayList<>(); //create each folders before the page itself for (String pathElement : pathElements) { if (!pathElement.isEmpty()) { String futurePwd = pwd + ("/" + pathElement); if (!parentsIdByPath.containsKey(futurePwd)) { String parentId = parentsIdByPath.get(pwd); List<Page> pages = pageRepository.search( new PageCriteria.Builder() .parent(parentId) .referenceId(apiId) .referenceType(PageReferenceType.API.name()) .name(pathElement) .type(PageType.FOLDER.name()) .build()); PageEntity folder; if (pages.isEmpty()) { NewPageEntity newPage = new NewPageEntity(); newPage.setParentId(parentId); newPage.setPublished(newPageEntity.isPublished()); newPage.setLastContributor(newPageEntity.getLastContributor()); newPage.setName(pathElement); newPage.setType(PageType.FOLDER); folder = this.createPage(apiId, newPage); } else { folder = convert(pages.get(0)); } parentsIdByPath.put(futurePwd, folder.getId()); createdPages.add(folder); } pwd = futurePwd; } } // if we have reached the end of path, create or update the page String parentId = parentsIdByPath.get(pwd); List<Page> pages = pageRepository.search( new PageCriteria.Builder() .parent(parentId) .referenceId(apiId) .referenceType(PageReferenceType.API.name()) .name(newPageEntity.getName()) .type(newPageEntity.getType().name()) .build()); if (pages.isEmpty()) { newPageEntity.setParentId(parentId); FilepathAwareFetcherConfiguration configuration = (FilepathAwareFetcherConfiguration) fetcher.getConfiguration(); configuration.setFilepath(src); newPageEntity.getSource().setConfiguration(mapper.valueToTree(configuration)); createdPages.add(this.createPage(apiId, newPageEntity)); } else { Page page = pages.get(0); UpdatePageEntity updatePage = convertToUpdateEntity(page); updatePage.setLastContributor(newPageEntity.getLastContributor()); updatePage.setPublished(newPageEntity.isPublished()); updatePage.setOrder(newPageEntity.getOrder()); updatePage.setHomepage(newPageEntity.isHomepage()); FilepathAwareFetcherConfiguration configuration = (FilepathAwareFetcherConfiguration) fetcher.getConfiguration(); configuration.setFilepath(src); updatePage.setSource(newPageEntity.getSource()); updatePage.getSource().setConfiguration(mapper.valueToTree(configuration)); createdPages.add(this.update(page.getId(), updatePage, false)); } return createdPages; } private Page upsertRootPage(String apiId, ImportPageEntity rootPage) { try { // root page exists ? List<Page> searchResult = pageRepository.search(new PageCriteria.Builder() .referenceId(apiId) .referenceType(PageReferenceType.API.name()) .type(PageType.ROOT.name()) .build()); Page page = convert(rootPage); page.setReferenceId(apiId); if (searchResult.isEmpty()) { page.setId(RandomString.generate()); return validateContentAndCreate(page); } else { page.setId(searchResult.get(0).getId()); mergeSensitiveData(this.getFetcher(searchResult.get(0).getSource()).getConfiguration(), page); return validateContentAndUpdate(page); } } catch (TechnicalException | FetcherException ex) { logger.error("An error occurs while trying to save the configuration", ex); throw new TechnicalManagementException("An error occurs while trying to save the configuration", ex); } } private PageType getSupportedPageType(String extension) { for (PageType pageType : PageType.values()) { if (pageType.extensions().contains(extension.toLowerCase())) { return pageType; } } return null; } private void reorderAndSavePages(final Page pageToReorder) throws TechnicalException { PageCriteria.Builder q = new PageCriteria.Builder().referenceId(pageToReorder.getReferenceId()).referenceType(pageToReorder.getReferenceType().name()); if (pageToReorder.getParentId() == null) { q.rootParent(Boolean.TRUE); } else { q.parent(pageToReorder.getParentId()); } final Collection<Page> pages = pageRepository.search(q.build()); final List<Boolean> increment = asList(true); pages.stream() .sorted(Comparator.comparingInt(Page::getOrder)) .forEachOrdered(page -> { try { if (page.equals(pageToReorder)) { increment.set(0, false); page.setOrder(pageToReorder.getOrder()); } else { final int newOrder; final Boolean isIncrement = increment.get(0); if (page.getOrder() < pageToReorder.getOrder()) { newOrder = page.getOrder() - (isIncrement ? 0 : 1); } else if (page.getOrder() > pageToReorder.getOrder()) { newOrder = page.getOrder() + (isIncrement ? 1 : 0); } else { newOrder = page.getOrder() + (isIncrement ? 1 : -1); } page.setOrder(newOrder); } pageRepository.update(page); } catch (final TechnicalException ex) { throw onUpdateFail(page.getId(), ex); } }); } private TechnicalManagementException onUpdateFail(String pageId, TechnicalException ex) { logger.error("An error occurs while trying to update page {}", pageId, ex); return new TechnicalManagementException("An error occurs while trying to update page " + pageId, ex); } private TechnicalManagementException onUpdateFail(String pageId, FetcherException ex) { logger.error("An error occurs while trying to update page {}", pageId, ex); return new TechnicalManagementException("An error occurs while trying to fetch content. " + ex.getMessage(), ex); } @Override public void delete(String pageId) { try { logger.debug("Delete Page : {}", pageId); Optional<Page> optPage = pageRepository.findById(pageId); if (!optPage.isPresent()) { throw new PageNotFoundException(pageId); } Page page = optPage.get(); // if the folder is not empty, throw exception if (PageType.FOLDER.name().equalsIgnoreCase(page.getType()) && !pageRepository.search(new PageCriteria.Builder() .referenceId(page.getReferenceId()) .referenceType(page.getReferenceType().name()) .parent(page.getId()).build()).isEmpty()) { throw new TechnicalManagementException("Unable to remove the folder. It must be empty before being removed."); } pageRepository.delete(pageId); // delete links and translations related to the page if (!PageType.LINK.name().equalsIgnoreCase(page.getType()) && !PageType.TRANSLATION.name().equalsIgnoreCase(page.getType())) { this.deleteRelatedPages(pageId); } createAuditLog(page.getReferenceId(), PAGE_DELETED, new Date(), page, null); // remove from search engine searchEngineService.delete(convert(page), false); } catch (TechnicalException ex) { logger.error("An error occurs while trying to delete Page {}", pageId, ex); throw new TechnicalManagementException("An error occurs while trying to delete Page " + pageId, ex); } } @Override public int findMaxApiPageOrderByApi(String apiName) { try { logger.debug("Find Max Order Page for api name : {}", apiName); final Integer maxPageOrder = pageRepository.findMaxPageReferenceIdAndReferenceTypeOrder(apiName, PageReferenceType.API); return maxPageOrder == null ? 0 : maxPageOrder; } catch (TechnicalException ex) { logger.error("An error occured when searching max order page for api name [{}]", apiName, ex); throw new TechnicalManagementException("An error occured when searching max order page for api name " + apiName, ex); } } @Override public int findMaxPortalPageOrder() { try { logger.debug("Find Max Order Portal Page"); final Integer maxPageOrder = pageRepository.findMaxPageReferenceIdAndReferenceTypeOrder(GraviteeContext.getCurrentEnvironment(), PageReferenceType.ENVIRONMENT); return maxPageOrder == null ? 0 : maxPageOrder; } catch (TechnicalException ex) { logger.error("An error occured when searching max order portal page", ex); throw new TechnicalManagementException("An error occured when searching max order portal ", ex); } } @Override public boolean isDisplayable(ApiEntity api, boolean pageIsPublished, String username) { boolean isDisplayable = false; if (api.getVisibility() == Visibility.PUBLIC && pageIsPublished) { isDisplayable = true; } else if (username != null) { MemberEntity member = membershipService.getUserMember(MembershipReferenceType.API, api.getId(), username); if (member == null && api.getGroups() != null) { Iterator<String> groupIdIterator = api.getGroups().iterator(); while (!isDisplayable && groupIdIterator.hasNext()) { String groupId = groupIdIterator.next(); member = membershipService.getUserMember(MembershipReferenceType.GROUP, groupId, username); isDisplayable = isDisplayableForMember(member, pageIsPublished); } } else { isDisplayable = isDisplayableForMember(member, pageIsPublished); } } return isDisplayable; } private boolean isDisplayableForMember(MemberEntity member, boolean pageIsPublished) { // if not member => not displayable if (member == null) { return false; } // if member && published page => displayable if (pageIsPublished) { return true; } // only members which could modify a page can see an unpublished page return roleService.hasPermission(member.getPermissions(), ApiPermission.DOCUMENTATION, new RolePermissionAction[]{RolePermissionAction.UPDATE, RolePermissionAction.CREATE, RolePermissionAction.DELETE}); } @Override public PageEntity fetch(String pageId, String contributor) { try { logger.debug("Fetch page {}", pageId); Optional<Page> optPageToUpdate = pageRepository.findById(pageId); if (!optPageToUpdate.isPresent()) { throw new PageNotFoundException(pageId); } Page page = optPageToUpdate.get(); if (page.getSource() == null) { throw new NoFetcherDefinedException(pageId); } try { fetchPage(page); } catch (FetcherException e) { throw onUpdateFail(pageId, e); } page.setUpdatedAt(new Date()); page.setLastContributor(contributor); Page updatedPage = validateContentAndUpdate(page); createAuditLog(page.getReferenceId(), PAGE_UPDATED, page.getUpdatedAt(), page, page); return convert(updatedPage); } catch (TechnicalException ex) { throw onUpdateFail(pageId, ex); } } private List<PageEntity> fetchPages(final String apiId, ImportPageEntity pageEntity) { try { Fetcher _fetcher = this.getFetcher(convert(pageEntity.getSource())); if (_fetcher == null) { return emptyList(); } if (!(_fetcher instanceof FilesFetcher)) { throw new UnsupportedOperationException("The plugin does not support to import a directory."); } FilesFetcher fetcher = (FilesFetcher) _fetcher; return importDirectory(apiId, pageEntity, fetcher); } catch (FetcherException ex) { logger.error("An error occurs while trying to import a directory", ex); throw new TechnicalManagementException("An error occurs while trying import a directory", ex); } } private static Page convert(NewPageEntity newPageEntity) { Page page = new Page(); page.setName(newPageEntity.getName()); final PageType type = newPageEntity.getType(); if (type != null) { page.setType(type.name()); } page.setContent(newPageEntity.getContent()); page.setLastContributor(newPageEntity.getLastContributor()); page.setOrder(newPageEntity.getOrder()); page.setPublished(newPageEntity.isPublished()); page.setHomepage(newPageEntity.isHomepage()); page.setSource(convert(newPageEntity.getSource())); page.setConfiguration(newPageEntity.getConfiguration()); page.setExcludedGroups(newPageEntity.getExcludedGroups()); page.setParentId("".equals(newPageEntity.getParentId()) ? null : newPageEntity.getParentId()); return page; } private NewPageEntity convert(final PageEntity pageEntity) { final NewPageEntity newPageEntity = new NewPageEntity(); newPageEntity.setName(pageEntity.getName()); newPageEntity.setOrder(pageEntity.getOrder()); newPageEntity.setPublished(pageEntity.isPublished()); newPageEntity.setSource(pageEntity.getSource()); newPageEntity.setType(PageType.valueOf(pageEntity.getType())); newPageEntity.setParentId(pageEntity.getParentId()); newPageEntity.setHomepage(pageEntity.isHomepage()); newPageEntity.setContent(pageEntity.getContent()); newPageEntity.setConfiguration(pageEntity.getConfiguration()); newPageEntity.setExcludedGroups(pageEntity.getExcludedGroups()); newPageEntity.setLastContributor(pageEntity.getLastContributor()); return newPageEntity; } private static Page convert(ImportPageEntity importPageEntity) { Page page = new Page(); final PageType type = importPageEntity.getType(); if (type != null) { page.setType(type.name()); } page.setLastContributor(importPageEntity.getLastContributor()); page.setPublished(importPageEntity.isPublished()); page.setSource(convert(importPageEntity.getSource())); page.setConfiguration(importPageEntity.getConfiguration()); page.setExcludedGroups(importPageEntity.getExcludedGroups()); return page; } private List<PageEntity> convert(List<Page> pages) { if (pages == null) { return emptyList(); } return pages.stream().map(this::convert).collect(toList()); } private PageEntity convert(Page page) { PageEntity pageEntity; if (page.getReferenceId() != null && PageReferenceType.API.equals(page.getReferenceType())) { pageEntity = new ApiPageEntity(); ((ApiPageEntity) pageEntity).setApi(page.getReferenceId()); } else { pageEntity = new PageEntity(); } pageEntity.setId(page.getId()); pageEntity.setName(page.getName()); pageEntity.setHomepage(page.isHomepage()); pageEntity.setType(page.getType()); pageEntity.setContent(page.getContent()); if (isJson(page.getContent())) { pageEntity.setContentType(MediaType.APPLICATION_JSON); } else { // Yaml or RAML format ? pageEntity.setContentType("text/yaml"); } pageEntity.setLastContributor(page.getLastContributor()); pageEntity.setLastModificationDate(page.getUpdatedAt()); pageEntity.setOrder(page.getOrder()); pageEntity.setPublished(page.isPublished()); if (page.getSource() != null) { pageEntity.setSource(convert(page.getSource())); } if (page.getConfiguration() != null) { pageEntity.setConfiguration(page.getConfiguration()); } pageEntity.setExcludedGroups(page.getExcludedGroups()); pageEntity.setParentId("".equals(page.getParentId()) ? null : page.getParentId()); pageEntity.setMetadata(page.getMetadata()); return pageEntity; } private List<Page> getTranslations(String pageId) { try { List<Page> searchResult = this.pageRepository .search(new PageCriteria.Builder().parent(pageId).type(PageType.TRANSLATION.name()).build()); searchResult.sort((p1, p2) -> { String lang1 = p1.getConfiguration().get(PageConfigurationKeys.TRANSLATION_LANG); String lang2 = p2.getConfiguration().get(PageConfigurationKeys.TRANSLATION_LANG); return lang1.compareTo(lang2); }); return searchResult; } catch (TechnicalException ex) { logger.error("An error occurs while trying to search pages", ex); throw new TechnicalManagementException( "An error occurs while trying to search pages", ex); } } private static Page merge(UpdatePageEntity updatePageEntity, Page withUpdatePage) { Page page = new Page(); page.setName( updatePageEntity.getName() != null ? updatePageEntity.getName() : withUpdatePage.getName() ); page.setContent( updatePageEntity.getContent() != null ? updatePageEntity.getContent() : withUpdatePage.getContent() ); page.setLastContributor( updatePageEntity.getLastContributor() != null ? updatePageEntity.getLastContributor() : withUpdatePage.getLastContributor() ); page.setOrder( updatePageEntity.getOrder() != null ? updatePageEntity.getOrder() : withUpdatePage.getOrder() ); page.setPublished( updatePageEntity.isPublished() != null ? updatePageEntity.isPublished() : withUpdatePage.isPublished() ); PageSource pageSource = convert(updatePageEntity.getSource()); page.setSource( pageSource != null ? pageSource : withUpdatePage.getSource() ); page.setConfiguration( updatePageEntity.getConfiguration() != null ? updatePageEntity.getConfiguration() : withUpdatePage.getConfiguration() ); page.setHomepage( updatePageEntity.isHomepage() != null ? updatePageEntity.isHomepage() : withUpdatePage.isHomepage() ); page.setExcludedGroups( updatePageEntity.getExcludedGroups() != null ? updatePageEntity.getExcludedGroups() : withUpdatePage.getExcludedGroups() ); page.setParentId( updatePageEntity.getParentId() != null ? updatePageEntity.getParentId().isEmpty() ? null : updatePageEntity.getParentId() : withUpdatePage.getParentId() ); return page; } private static Page convert(UpdatePageEntity updatePageEntity) { Page page = new Page(); page.setName(updatePageEntity.getName()); page.setContent(updatePageEntity.getContent()); page.setLastContributor(updatePageEntity.getLastContributor()); page.setOrder(updatePageEntity.getOrder()); page.setPublished(Boolean.TRUE.equals(updatePageEntity.isPublished())); page.setSource(convert(updatePageEntity.getSource())); page.setConfiguration(updatePageEntity.getConfiguration()); page.setHomepage(Boolean.TRUE.equals(updatePageEntity.isHomepage())); page.setExcludedGroups(updatePageEntity.getExcludedGroups()); page.setParentId("".equals(updatePageEntity.getParentId()) ? null : updatePageEntity.getParentId()); return page; } private UpdatePageEntity convertToUpdateEntity(Page page) { UpdatePageEntity updatePageEntity = new UpdatePageEntity(); updatePageEntity.setName(page.getName()); updatePageEntity.setContent(page.getContent()); updatePageEntity.setLastContributor(page.getLastContributor()); updatePageEntity.setOrder(page.getOrder()); updatePageEntity.setPublished(page.isPublished()); updatePageEntity.setSource(this.convert(page.getSource())); updatePageEntity.setConfiguration(page.getConfiguration()); updatePageEntity.setHomepage(page.isHomepage()); updatePageEntity.setExcludedGroups(page.getExcludedGroups()); updatePageEntity.setParentId("".equals(page.getParentId()) ? null : page.getParentId()); return updatePageEntity; } private static PageSource convert(PageSourceEntity pageSourceEntity) { PageSource source = null; if (pageSourceEntity != null && pageSourceEntity.getType() != null && pageSourceEntity.getConfiguration() != null) { source = new PageSource(); source.setType(pageSourceEntity.getType()); source.setConfiguration(pageSourceEntity.getConfiguration()); } return source; } private PageSourceEntity convert(PageSource pageSource) { return convert(pageSource, true); } private PageSourceEntity convert(PageSource pageSource, boolean removeSensitiveData) { PageSourceEntity entity = null; if (pageSource != null) { entity = new PageSourceEntity(); entity.setType(pageSource.getType()); try { FetcherConfiguration fetcherConfiguration = this.getFetcher(pageSource).getConfiguration(); if (removeSensitiveData) { removeSensitiveData(fetcherConfiguration); } entity.setConfiguration((new ObjectMapper()).valueToTree(fetcherConfiguration)); } catch (FetcherException e) { logger.error(e.getMessage(), e); } } return entity; } private void removeSensitiveData(FetcherConfiguration fetcherConfiguration) { Field[] fields = fetcherConfiguration.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Sensitive.class)) { boolean accessible = field.isAccessible(); field.setAccessible(true); try { field.set(fetcherConfiguration, SENSITIVE_DATA_REPLACEMENT); } catch (IllegalAccessException e) { e.printStackTrace(); } field.setAccessible(accessible); } } } private void mergeSensitiveData(FetcherConfiguration originalFetcherConfiguration, Page page) throws FetcherException { FetcherConfiguration updatedFetcherConfiguration = this.getFetcher(page.getSource()).getConfiguration(); boolean updated = false; Field[] fields = originalFetcherConfiguration.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Sensitive.class)) { boolean accessible = field.isAccessible(); field.setAccessible(true); try { Object updatedValue = field.get(updatedFetcherConfiguration); if (updatedValue.equals(SENSITIVE_DATA_REPLACEMENT)) { updated = true; field.set(updatedFetcherConfiguration, field.get(originalFetcherConfiguration)); } } catch (IllegalAccessException e) { e.printStackTrace(); } field.setAccessible(accessible); } } if (updated) { page.getSource().setConfiguration((new ObjectMapper()).valueToTree(updatedFetcherConfiguration).toString()); } } @SuppressWarnings("squid:S1166") private static boolean isJson(String content) { try { gson.fromJson(content, Object.class); return true; } catch (com.google.gson.JsonSyntaxException ex) { return false; } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } private Page validateContentAndCreate(Page page) throws TechnicalException { validateSafeContent(page); return pageRepository.create(page); } private Page validateContentAndUpdate(Page page) throws TechnicalException { validateSafeContent(page); return pageRepository.update(page); } private void validateSafeContent(Page page) { if (markdownSanitize && PageType.MARKDOWN.name().equals(page.getType())) { HtmlSanitizer.SanitizeInfos sanitizeInfos = HtmlSanitizer.isSafe(page.getContent()); if(!sanitizeInfos.isSafe()) { throw new PageContentUnsafeException(sanitizeInfos.getRejectedMessage()); } } } private void validateSafeSource(Page page) { if (importConfiguration.isAllowImportFromPrivate() || page.getSource() == null || page.getSource().getConfiguration() == null) { return; } PageSource source = page.getSource(); Map<String, String> map; try { map = new ObjectMapper().readValue(source.getConfiguration(), new TypeReference<Map<String, String>>() { }); } catch (IOException e) { throw new InvalidDataException("Source is invalid", e); } Optional<String> urlOpt = map.entrySet().stream().filter(e -> e.getKey().equals("repository") || e.getKey().matches(".*[uU]rl")).map(Map.Entry::getValue).findFirst(); if (!urlOpt.isPresent()) { // There is no source to validate. return; } // Validate the url is allowed. UrlSanitizerUtils.checkAllowed(urlOpt.get(), importConfiguration.getImportWhitelist(), false); }private void createAuditLog(String apiId, Audit.AuditEvent event, Date createdAt, Page oldValue, Page newValue) { String pageId = oldValue != null ? oldValue.getId() : newValue.getId(); if (apiId == null) { auditService.createPortalAuditLog( Collections.singletonMap(PAGE, pageId), event, createdAt, oldValue, newValue ); } else { auditService.createApiAuditLog( apiId, Collections.singletonMap(PAGE, pageId), event, createdAt, oldValue, newValue ); } } private PageCriteria queryToCriteria(PageQuery query) { final PageCriteria.Builder builder = new PageCriteria.Builder(); if (query != null) { builder.homepage(query.getHomepage()); if (query.getApi() != null) { builder.referenceId(query.getApi()); builder.referenceType(PageReferenceType.API.name()); } else { builder.referenceId(GraviteeContext.getCurrentEnvironment()); builder.referenceType(PageReferenceType.ENVIRONMENT.name()); } builder.name(query.getName()); builder.parent(query.getParent()); builder.published(query.getPublished()); if (query.getType() != null) { builder.type(query.getType().name()); } builder.rootParent(query.getRootParent()); } return builder.build(); } @Override public Map<SystemFolderType, String> initialize(String environmentId) { Map<SystemFolderType, String> result = new HashMap<>(); result.put(SystemFolderType.HEADER, createSystemFolder(null, SystemFolderType.HEADER, 1, environmentId).getId()); result.put(SystemFolderType.TOPFOOTER, createSystemFolder(null, SystemFolderType.TOPFOOTER, 2, environmentId).getId()); result.put(SystemFolderType.FOOTER, createSystemFolder(null, SystemFolderType.FOOTER, 3, environmentId).getId()); return result; } @Override public PageEntity createSystemFolder(String apiId, SystemFolderType systemFolderType, int order, String environmentId) { NewPageEntity newSysFolder = new NewPageEntity(); newSysFolder.setName(systemFolderType.folderName()); newSysFolder.setOrder(order); newSysFolder.setPublished(true); newSysFolder.setType(PageType.SYSTEM_FOLDER); return this.createPage(apiId, newSysFolder, environmentId); } }
3e100382246226e8b30b1cc9f980d8c5f9f11193
758
java
Java
SimpleTask/src/main/java/com/demo/SimpleTask/model/Task.java
shindegau95/SimpleTask
b576edb38e49e4a902d4618ad772652e4a0a8574
[ "MIT" ]
null
null
null
SimpleTask/src/main/java/com/demo/SimpleTask/model/Task.java
shindegau95/SimpleTask
b576edb38e49e4a902d4618ad772652e4a0a8574
[ "MIT" ]
5
2021-03-10T19:50:51.000Z
2022-03-02T08:47:48.000Z
SimpleTask/src/main/java/com/demo/SimpleTask/model/Task.java
shindegau95/SimpleTask
b576edb38e49e4a902d4618ad772652e4a0a8574
[ "MIT" ]
null
null
null
19.947368
64
0.659631
6,790
package com.demo.SimpleTask.model; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Data @Entity @Table(name= "task", schema = "task_application") public class Task implements Serializable { @Id @GeneratedValue @Column(name="task_id") private long id; @Column(name="task_description") private String taskDescription; @Column(name = "is_done") private boolean done; public Task() { } public Task(long id, String taskDescription, boolean done) { this.id = id; this.taskDescription = taskDescription; this.done = done; } public Task(String description, boolean done) { this.taskDescription = description; this.done = done; } }
3e1004082efecb85b5da28f48c6c6d9bfa10c1c0
2,128
java
Java
icicle-core/src/test/java/net/iceyleagons/test/icicle/core/bean/unsatisfied/UnsatisfiedDependencyTest.java
Rushmead/Icicle
529e478369d5e51fcc286b73d39c06aa66ac39cc
[ "MIT" ]
null
null
null
icicle-core/src/test/java/net/iceyleagons/test/icicle/core/bean/unsatisfied/UnsatisfiedDependencyTest.java
Rushmead/Icicle
529e478369d5e51fcc286b73d39c06aa66ac39cc
[ "MIT" ]
null
null
null
icicle-core/src/test/java/net/iceyleagons/test/icicle/core/bean/unsatisfied/UnsatisfiedDependencyTest.java
Rushmead/Icicle
529e478369d5e51fcc286b73d39c06aa66ac39cc
[ "MIT" ]
null
null
null
40.150943
141
0.760808
6,791
/* * MIT License * * Copyright (c) 2022 IceyLeagons and Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.iceyleagons.test.icicle.core.bean.unsatisfied; import net.iceyleagons.icicle.core.AbstractIcicleApplication; import net.iceyleagons.icicle.core.Application; import net.iceyleagons.icicle.core.exceptions.UnsatisfiedDependencyException; import net.iceyleagons.icicle.core.utils.ExecutionUtils; import net.iceyleagons.icicle.core.Icicle; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * @author TOTHTOMI * @version 1.0.0 * @since Feb. 01, 2022 */ public class UnsatisfiedDependencyTest { @Test @DisplayName("Circular dependency") public void testCircularDependency() { if(!Icicle.LOADED) Icicle.loadIcicle(); Application app = new AbstractIcicleApplication("net.iceyleagons.test.icicle.core.bean.unsatisfied", ExecutionUtils.debugHandler()) { }; Assertions.assertThrows(UnsatisfiedDependencyException.class, app::start); } }
3e10049e04353b54dfc6022e068ed03a3a5c4059
2,043
java
Java
src/com/facebook/buck/util/Libc.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
src/com/facebook/buck/util/Libc.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
src/com/facebook/buck/util/Libc.java
FightJames/buck
ae2347e05da6f0ef9e0ec21497a654757aca7ad5
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
29.185714
95
0.732256
6,792
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.util; import com.sun.jna.LastErrorException; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; public interface Libc extends Library { Libc INSTANCE = Native.loadLibrary(Platform.C_LIBRARY_NAME, Libc.class); Pointer signal(int signal, Pointer function); int kill(int pid, int sig) throws LastErrorException; interface OpenPtyLibrary extends Library { int openpty( IntByReference master, IntByReference slave, Pointer name, Pointer terp, Pointer winp); } int setsid(); int ioctl(int fd, Pointer request, Object... args); int fcntl(int fd, int cmd, Object... args); int getpid(); int getuid(); final class Constants { public static final int LINUX_TIOCSCTTY = 0x540E; public static final int DARWIN_TIOCSCTTY = 0x20007461; public static int rTIOCSCTTY; public static final int LINUX_FD_CLOEXEC = 0x1; public static final int DARWIN_FD_CLOEXEC = 0x1; public static int rFDCLOEXEC; public static final int LINUX_F_GETFD = 0x1; public static final int DARWIN_F_GETFD = 0x1; public static int rFGETFD; public static final int LINUX_F_SETFD = 0x2; public static final int DARWIN_F_SETFD = 0x2; public static int rFSETFD; public static final int SIGHUP = 1; public static final int SIGINT = 2; } }
3e1005b680651fb5119e7564970043c2394b488a
1,755
java
Java
AlterarUsuario.java
Joaopaulojhon31/mostra
c2c1933e742ba34f13904f122e7e258e5d0f5c0f
[ "Apache-2.0" ]
null
null
null
AlterarUsuario.java
Joaopaulojhon31/mostra
c2c1933e742ba34f13904f122e7e258e5d0f5c0f
[ "Apache-2.0" ]
null
null
null
AlterarUsuario.java
Joaopaulojhon31/mostra
c2c1933e742ba34f13904f122e7e258e5d0f5c0f
[ "Apache-2.0" ]
null
null
null
25.808824
121
0.720228
6,793
package sevlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UsuarioDao; import model.Usuario; @WebServlet("/AlterarUsuario") public class AlterarUsuario extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UsuarioDao userDao = new UsuarioDao(); Usuario user = new Usuario(); String login = request.getParameter("login"); String senha = request.getParameter("senha"); String nivel = request.getParameter("nivel"); String id =request.getParameter("id"); user.setCodAdm(Integer.parseInt(nivel)); user.setLogin(login); user.setSenha(senha); user.setId(Integer.parseInt(id)); try { userDao.Update(user); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } RequestDispatcher rd = request.getRequestDispatcher("alertaUpdateUser.jsp"); rd.forward(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3e1005e482f71a87de120535980dda0256b71ab6
1,671
java
Java
src/test/java/com/example/denaun/aoc2021/day21/Day21Test.java
Denaun/aoc-2021
ffee2fedbf0c7c2264e33a4c82db2baf7455ebf3
[ "MIT" ]
null
null
null
src/test/java/com/example/denaun/aoc2021/day21/Day21Test.java
Denaun/aoc-2021
ffee2fedbf0c7c2264e33a4c82db2baf7455ebf3
[ "MIT" ]
null
null
null
src/test/java/com/example/denaun/aoc2021/day21/Day21Test.java
Denaun/aoc-2021
ffee2fedbf0c7c2264e33a4c82db2baf7455ebf3
[ "MIT" ]
1
2022-01-11T18:29:45.000Z
2022-01-11T18:29:45.000Z
33.42
91
0.681628
6,794
package com.example.denaun.aoc2021.day21; import static com.google.common.truth.Truth.assertThat; import com.example.denaun.aoc2021.AocTestCase; import java.io.IOException; import java.util.Optional; import org.junit.Test; public class Day21Test extends AocTestCase { public Day21Test() throws IOException { super("day21.in"); } private static final GameState EXAMPLE_INPUT = GameState.startingAt(4, 8); @Test public void example1() { var dice = new MultipleDie(new DeterministicDice(), Day21.ROLLS_PER_TURN); var state = EXAMPLE_INPUT.next(dice.getAsInt()); assertThat(state.player1()).isEqualTo(new PlayerState(10, 10)); state = state.next(dice.getAsInt()); assertThat(state.player2()).isEqualTo(new PlayerState(3, 3)); state = state.next(dice.getAsInt()); assertThat(state.player1()).isEqualTo(new PlayerState(4, 14)); state = Day21.playOut(state, dice, Day21.PART1_SCORE); assertThat(state.turns() * Day21.ROLLS_PER_TURN).isEqualTo(993); assertThat(state.loser(Day21.PART1_SCORE)).isEqualTo(Optional.of(state.player2())); assertThat(state.loser(Day21.PART1_SCORE).get().score()).isEqualTo(745); } @Test @Override public void part1() { assertThat(Day21.part1(input)).isEqualTo(913_560); } @Test public void example2() { assertThat(Day21.countWins(EXAMPLE_INPUT, Day21.PART2_SCORE)) .isEqualTo(new Wins(444_356_092_776_315L, 341_960_390_180_808L)); } @Test @Override public void part2() { assertThat(Day21.part2(input)).isEqualTo(110_271_560_863_819L); } }
3e1005ec5a32cc9296261238f78078130c3a567c
14,167
java
Java
hutool-extra/src/main/java/com/xiaoleilu/hutool/extra/servlet/ServletUtil.java
273877189/hutool
3dc3aed5f4420f3828648a77fcbd53884e35a244
[ "Apache-2.0" ]
null
null
null
hutool-extra/src/main/java/com/xiaoleilu/hutool/extra/servlet/ServletUtil.java
273877189/hutool
3dc3aed5f4420f3828648a77fcbd53884e35a244
[ "Apache-2.0" ]
null
null
null
hutool-extra/src/main/java/com/xiaoleilu/hutool/extra/servlet/ServletUtil.java
273877189/hutool
3dc3aed5f4420f3828648a77fcbd53884e35a244
[ "Apache-2.0" ]
null
null
null
28.97137
144
0.646008
6,795
package com.xiaoleilu.hutool.extra.servlet; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.lang.reflect.Type; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xiaoleilu.hutool.bean.BeanUtil; import com.xiaoleilu.hutool.bean.copier.CopyOptions; import com.xiaoleilu.hutool.bean.copier.ValueProvider; import com.xiaoleilu.hutool.exceptions.UtilException; import com.xiaoleilu.hutool.io.IORuntimeException; import com.xiaoleilu.hutool.io.IoUtil; import com.xiaoleilu.hutool.util.ArrayUtil; import com.xiaoleilu.hutool.util.CharsetUtil; import com.xiaoleilu.hutool.util.ReflectUtil; import com.xiaoleilu.hutool.util.StrUtil; /** * Servlet相关工具类封装 * * @author looly * @since 3.2.0 */ public class ServletUtil { public static final String METHOD_DELETE = "DELETE"; public static final String METHOD_HEAD = "HEAD"; public static final String METHOD_GET = "GET"; public static final String METHOD_OPTIONS = "OPTIONS"; public static final String METHOD_POST = "POST"; public static final String METHOD_PUT = "PUT"; public static final String METHOD_TRACE = "TRACE"; // --------------------------------------------------------- getParam start /** * 获得所有请求参数 * * @param request 请求对象{@link ServletRequest} * @return Map */ public static Map<String, String[]> getParams(ServletRequest request) { final Map<String, String[]> map = request.getParameterMap(); return Collections.unmodifiableMap(map); } /** * 获得所有请求参数 * * @param request 请求对象{@link ServletRequest} * @return Map */ public static Map<String, String> getParamMap(ServletRequest request) { Map<String,String> params = new HashMap<String,String>(); for (Map.Entry<String,String[]> entry : getParams(request).entrySet()) { params.put( entry.getKey(), ArrayUtil.join(entry.getValue(), StrUtil.COMMA) ); } return params; } // --------------------------------------------------------- getParam end // --------------------------------------------------------- fillBean start /** * ServletRequest 参数转Bean * * @param <T> Bean类型 * @param request ServletRequest * @param bean Bean * @param copyOptions 注入时的设置 * @return Bean * @since 3.0.4 */ public static <T> T fillBean(final ServletRequest request, T bean, CopyOptions copyOptions) { final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName()); return BeanUtil.fillBean(bean, new ValueProvider<String>() { @Override public Object value(String key, Type valueType) { String value = request.getParameter(key); if (StrUtil.isEmpty(value)) { // 使用类名前缀尝试查找值 value = request.getParameter(beanName + StrUtil.DOT + key); if (StrUtil.isEmpty(value)) { // 此处取得的值为空时跳过,包括null和"" value = null; } } return value; } @Override public boolean containsKey(String key) { // 对于Servlet来说,返回值null意味着无此参数 return null != request.getParameter(key); } }, copyOptions); } /** * ServletRequest 参数转Bean * * @param <T> Bean类型 * @param request {@link ServletRequest} * @param bean Bean * @param isIgnoreError 是否忽略注入错误 * @return Bean */ public static <T> T fillBean(ServletRequest request, T bean, boolean isIgnoreError) { return fillBean(request, bean, CopyOptions.create().setIgnoreError(isIgnoreError)); } /** * ServletRequest 参数转Bean * * @param <T> Bean类型 * @param request ServletRequest * @param beanClass Bean Class * @param isIgnoreError 是否忽略注入错误 * @return Bean */ public static <T> T toBean(ServletRequest request, Class<T> beanClass, boolean isIgnoreError) { return fillBean(request, ReflectUtil.newInstance(beanClass), isIgnoreError); } // --------------------------------------------------------- fillBean end /** * 获取客户端IP<br> * 默认检测的Header:<br> * 1、X-Forwarded-For<br> * 2、X-Real-IP<br> * 3、Proxy-Client-IP<br> * 4、WL-Proxy-Client-IP<br> * otherHeaderNames参数用于自定义检测的Header * * @param request 请求对象{@link HttpServletRequest} * @param otherHeaderNames 其他自定义头文件 * @return IP地址 */ public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) { String[] headers = { "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" }; if (ArrayUtil.isNotEmpty(otherHeaderNames)) { headers = ArrayUtil.addAll(headers, otherHeaderNames); } String ip; for (String header : headers) { ip = request.getHeader(header); if (false == isUnknow(ip)) { return getMultistageReverseProxyIp(ip); } } ip = request.getRemoteAddr(); return getMultistageReverseProxyIp(ip); } // --------------------------------------------------------- Header start /** * 忽略大小写获得请求header中的信息 * * @param request 请求对象{@link HttpServletRequest} * @param nameIgnoreCase 忽略大小写头信息的KEY * @return header值 */ public final static String getHeaderIgnoreCase(HttpServletRequest request, String nameIgnoreCase) { Enumeration<String> names = request.getHeaderNames(); String name = null; while (names.hasMoreElements()) { name = names.nextElement(); if (name != null && name.equalsIgnoreCase(nameIgnoreCase)) { return request.getHeader(name); } } return null; } /** * 获得请求header中的信息 * * @param request 请求对象{@link HttpServletRequest} * @param name 头信息的KEY * @param charset 字符集 * @return header值 */ public final static String getHeader(HttpServletRequest request, String name, String charset) { final String header = request.getHeader(name); if (null != header) { try { return new String(header.getBytes(CharsetUtil.ISO_8859_1), charset); } catch (UnsupportedEncodingException e) { throw new UtilException(StrUtil.format("Error charset {} for http request header.", charset)); } } return null; } /** * 客户浏览器是否为IE * * @param request 请求对象{@link HttpServletRequest} * @return 客户浏览器是否为IE */ public static boolean isIE(HttpServletRequest request) { String userAgent = getHeaderIgnoreCase(request, "User-Agent"); if (StrUtil.isNotBlank(userAgent)) { userAgent = userAgent.toUpperCase(); if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT")) { return true; } } return false; } /** * 是否为GET请求 * * @param request 请求对象{@link HttpServletRequest} * @return 是否为GET请求 */ public static boolean isGetMethod(HttpServletRequest request) { return METHOD_GET.equalsIgnoreCase(request.getMethod()); } /** * 是否为POST请求 * * @param request 请求对象{@link HttpServletRequest} * @return 是否为POST请求 */ public static boolean isPostMethod(HttpServletRequest request) { return METHOD_POST.equalsIgnoreCase(request.getMethod()); } /** * 是否为Multipart类型表单,此类型表单用于文件上传 * * @param request 请求对象{@link HttpServletRequest} * @return 是否为Multipart类型表单,此类型表单用于文件上传 */ public static boolean isMultipart(HttpServletRequest request) { if (false == isPostMethod(request)) { return false; } String contentType = request.getContentType(); if (StrUtil.isBlank(contentType)) { return false; } if (contentType.toLowerCase().startsWith("multipart/")) { return true; } return false; } // --------------------------------------------------------- Header end // --------------------------------------------------------- Cookie start /** * 获得指定的Cookie * * @param httpServletRequest {@link HttpServletRequest} * @param name cookie名 * @return Cookie对象 */ public final static Cookie getCookie(HttpServletRequest httpServletRequest, String name) { final Map<String, Cookie> cookieMap = readCookieMap(httpServletRequest); return cookieMap == null ? null : cookieMap.get(name); } /** * 将cookie封装到Map里面 * * @param httpServletRequest {@link HttpServletRequest} * @return Cookie map */ public final static Map<String, Cookie> readCookieMap(HttpServletRequest httpServletRequest) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = httpServletRequest.getCookies(); if (null == cookies) { return null; } for (Cookie cookie : cookies) { cookieMap.put(cookie.getName().toLowerCase(), cookie); } return cookieMap; } /** * 设定返回给客户端的Cookie * * @param response 响应对象{@link HttpServletResponse} * @param cookie Servlet Cookie对象 */ public final static void addCookie(HttpServletResponse response, Cookie cookie) { response.addCookie(cookie); } /** * 设定返回给客户端的Cookie * * @param response 响应对象{@link HttpServletResponse} * @param name Cookie名 * @param value Cookie值 */ public final static void addCookie(HttpServletResponse response, String name, String value) { response.addCookie(new Cookie(name, value)); } /** * 设定返回给客户端的Cookie * * @param response 响应对象{@link HttpServletResponse} * @param name cookie名 * @param value cookie值 * @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. &gt;0 : Cookie存在的秒数. * @param path Cookie的有效路径 * @param domain the domain name within which this cookie is visible; form is according to RFC 2109 */ public final static void addCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds, String path, String domain) { Cookie cookie = new Cookie(name, value); if (domain != null) { cookie.setDomain(domain); } cookie.setMaxAge(maxAgeInSeconds); cookie.setPath(path); addCookie(response, cookie); } /** * 设定返回给客户端的Cookie<br> * Path: "/"<br> * No Domain * * @param response 响应对象{@link HttpServletResponse} * @param name cookie名 * @param value cookie值 * @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. &gt;0 : Cookie存在的秒数. */ public final static void addCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) { addCookie(response, name, value, maxAgeInSeconds, "/", null); } // --------------------------------------------------------- Cookie end // --------------------------------------------------------- Response start /** * 获得PrintWriter * * @param response 响应对象{@link HttpServletResponse} * @return 获得PrintWriter * @throws IORuntimeException IO异常 */ public static PrintWriter getWriter(HttpServletResponse response) throws IORuntimeException { try { return response.getWriter(); } catch (IOException e) { throw new IORuntimeException(e); } } /** * 返回数据给客户端 * * @param response 响应对象{@link HttpServletResponse} * @param text 返回的内容 * @param contentType 返回的类型 */ public static void write(HttpServletResponse response, String text, String contentType) { response.setContentType(contentType); Writer writer = null; try { writer = response.getWriter(); writer.write(text); writer.flush(); } catch (IOException e) { throw new UtilException(e); } finally { IoUtil.close(writer); } } /** * 返回数据给客户端 * * @param response 响应对象{@link HttpServletResponse} * @param in 需要返回客户端的内容 * @param contentType 返回的类型 */ public static void write(HttpServletResponse response, InputStream in, String contentType) { response.setContentType(contentType); write(response, in); } /** * 返回数据给客户端 * * @param response 响应对象{@link HttpServletResponse} * @param in 需要返回客户端的内容 */ public static void write(HttpServletResponse response, InputStream in) { write(response, in, IoUtil.DEFAULT_BUFFER_SIZE); } /** * 返回数据给客户端 * * @param response 响应对象{@link HttpServletResponse} * @param in 需要返回客户端的内容 * @param bufferSize 缓存大小 */ public static void write(HttpServletResponse response, InputStream in, int bufferSize) { ServletOutputStream out = null; try { out = response.getOutputStream(); IoUtil.copy(in, out, bufferSize); } catch (IOException e) { throw new UtilException(e); } finally { IoUtil.close(out); IoUtil.close(in); } } /** * 设置响应的Header * * @param response 响应对象{@link HttpServletResponse} * @param name 名 * @param value 值,可以是String,Date, int */ public static void setHeader(HttpServletResponse response, String name, Object value) { if (value instanceof String) { response.setHeader(name, (String) value); } else if (Date.class.isAssignableFrom(value.getClass())) { response.setDateHeader(name, ((Date) value).getTime()); } else if (value instanceof Integer || "int".equals(value.getClass().getSimpleName().toLowerCase())) { response.setIntHeader(name, (Integer) value); } else { response.setHeader(name, value.toString()); } } // --------------------------------------------------------- Response end // --------------------------------------------------------- Private methd start /** * 从多级反向代理中获得第一个非unknown IP地址 * * @param ip 获得的IP地址 * @return 第一个非unknown IP地址 */ private static String getMultistageReverseProxyIp(String ip) { // 多级反向代理检测 if (ip != null && ip.indexOf(",") > 0) { final String[] ips = ip.trim().split(","); for (String subIp : ips) { if (false == isUnknow(subIp)) { ip = subIp; break; } } } return ip; } /** * 检测给定字符串是否为未知,多用于检测HTTP请求相关<br> * * @param checkString 被检测的字符串 * @return 是否未知 */ private static boolean isUnknow(String checkString) { return StrUtil.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString); } // --------------------------------------------------------- Private methd end }
3e10068d0e4b0a3eef436ab656877d13e286b35e
1,126
java
Java
src/main/java/net/ncguy/argent/render/sample/light/volumetric/SpotLight.java
ncguy2/Argent
13a5301535b69e3c5ece8fe6962ec470e778d1fd
[ "MIT" ]
1
2016-12-09T19:44:12.000Z
2016-12-09T19:44:12.000Z
src/main/java/net/ncguy/argent/render/sample/light/volumetric/SpotLight.java
ncguy2/Argent
13a5301535b69e3c5ece8fe6962ec470e778d1fd
[ "MIT" ]
null
null
null
src/main/java/net/ncguy/argent/render/sample/light/volumetric/SpotLight.java
ncguy2/Argent
13a5301535b69e3c5ece8fe6962ec470e778d1fd
[ "MIT" ]
null
null
null
25.590909
79
0.672291
6,796
package net.ncguy.argent.render.sample.light.volumetric; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Quaternion; import com.badlogic.gdx.math.Vector3; import net.ncguy.argent.render.WorldRenderer; /** * Created by Guy on 12/07/2016. */ public class SpotLight extends VolumetricLight { public Vector3 direction = new Vector3(1, 0, 0); public SpotLight(WorldRenderer world) { super(world); } public SpotLight(WorldRenderer world, Quaternion lightData) { super(world, lightData); } public SpotLight(WorldRenderer world, float x, float y, float z, float w) { super(world, x, y, z, w); } @Override public void update() { camera().direction.set(direction); super.update(); } @Override public void applyToShader(ShaderProgram program) { final int texNum = 3; fbo().getColorBufferTexture().bind(texNum); program.setUniformi("u_depthMapDir", texNum); program.setUniformMatrix("u_lightTrans", camera().combined); program.setUniformf("u_type", 1); } }
3e1007a55ceca09c707d5543d796bf357608d3c6
5,954
java
Java
src/main/java/com/star/easydoc/service/translator/impl/TencentTranslator.java
shiwenjin/easy_javadoc
bd21c6b831512dd355cb0425b707873613902eb0
[ "Apache-2.0" ]
475
2019-09-01T08:39:52.000Z
2022-03-31T08:36:23.000Z
src/main/java/com/star/easydoc/service/translator/impl/TencentTranslator.java
shaoxiongdu/easy_javadoc
15aaf65f6704d2bb08e2e587dc19457eef85d906
[ "Apache-2.0" ]
49
2019-10-21T07:25:33.000Z
2022-03-30T03:44:27.000Z
src/main/java/com/star/easydoc/service/translator/impl/TencentTranslator.java
shaoxiongdu/easy_javadoc
15aaf65f6704d2bb08e2e587dc19457eef85d906
[ "Apache-2.0" ]
53
2019-09-19T01:41:55.000Z
2022-03-30T05:58:37.000Z
31.502646
132
0.608498
6,797
package com.star.easydoc.service.translator.impl; import java.nio.charset.StandardCharsets; import java.util.Map.Entry; import java.util.Random; import java.util.SortedMap; import java.util.TreeMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; import com.fasterxml.jackson.annotation.JsonProperty; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.star.easydoc.config.EasyJavadocConfigComponent; import com.star.easydoc.model.EasyJavadocConfiguration; import com.star.easydoc.util.HttpUtil; import com.star.easydoc.util.JsonUtil; /** * 腾讯翻译 * * @author wangchao * @date 2020/08/26 */ public class TencentTranslator extends AbstractTranslator { private static final Logger LOGGER = Logger.getInstance(TencentTranslator.class); private EasyJavadocConfiguration config = ServiceManager.getService(EasyJavadocConfigComponent.class).getState(); @Override public String translateEn2Ch(String text) { try { TencentResponse response = get(text, "zh"); return response.getTargetText(); } catch (Exception e) { LOGGER.error("请求腾讯翻译接口异常", e); } return ""; } @Override public String translateCh2En(String text) { try { TencentResponse response = get(text, "en"); return response.getTargetText(); } catch (Exception e) { LOGGER.error("请求腾讯翻译接口异常", e); } return ""; } public TencentResponse get(String text, String target) throws Exception { TencentResponse response = null; for (int i = 0; i < 10; i++) { SortedMap<String, Object> params = new TreeMap<>(); params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE)); params.put("Timestamp", System.currentTimeMillis() / 1000); params.put("Region", "ap-beijing"); params.put("SecretId", config.getSecretId()); params.put("Action", "TextTranslate"); params.put("Version", "2018-03-21"); params.put("SourceText", text); params.put("Source", "auto"); params.put("Target", target); params.put("ProjectId", 0); String str2sign = getStringToSign("GET", "tmt.tencentcloudapi.com", params); String signature = sign(str2sign, config.getSecretKey(), "HmacSHA1"); params.put("Signature", signature); TencentResult result = JsonUtil .fromJson(HttpUtil.get("https://tmt.tencentcloudapi.com", params), TencentResult.class); response = result == null ? null : result.getResponse(); if (response == null || (response.getError() != null && "RequestLimitExceeded".equals(response.getError().getCode()))) { Thread.sleep(500); } else { break; } } return response; } public static String sign(String s, String key, String method) throws Exception { Mac mac = Mac.getInstance(method); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm()); mac.init(secretKeySpec); byte[] hash = mac.doFinal(s.getBytes(StandardCharsets.UTF_8)); return DatatypeConverter.printBase64Binary(hash); } public static String getStringToSign(String method, String endpoint, SortedMap<String, Object> params) { StringBuilder s2s = new StringBuilder(); s2s.append(method).append(endpoint).append("/?"); for (Entry<String, Object> e : params.entrySet()) { s2s.append(e.getKey()).append("=").append(params.get(e.getKey()).toString()).append("&"); } return s2s.substring(0, s2s.length() - 1); } private static class TencentResult { @JsonProperty("Response") private TencentResponse response; public TencentResponse getResponse() { return response; } public void setResponse(TencentResponse response) { this.response = response; } } private static class TencentResponse { @JsonProperty("RequestId") private String requestId; @JsonProperty("Source") private String source; @JsonProperty("Target") private String target; @JsonProperty("TargetText") private String targetText; @JsonProperty("Error") private TencentError error; public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getTargetText() { return targetText; } public void setTargetText(String targetText) { this.targetText = targetText; } public TencentError getError() { return error; } public void setError(TencentError error) { this.error = error; } } private static class TencentError { @JsonProperty("Code") private String code; @JsonProperty("Message") private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } }
3e1007de5b09c984df7673a722ce810b62fcdeee
14,635
java
Java
src/main/java/eu/isas/peptideshaker/scoring/targetdecoy/TargetDecoyMap.java
hbarsnes/peptide-shaker
89178906ce0ec53bdb3e927dc6c70ee46be859c6
[ "Apache-2.0" ]
29
2015-12-08T23:38:07.000Z
2021-12-21T08:41:38.000Z
src/main/java/eu/isas/peptideshaker/scoring/targetdecoy/TargetDecoyMap.java
hbarsnes/peptide-shaker
89178906ce0ec53bdb3e927dc6c70ee46be859c6
[ "Apache-2.0" ]
391
2015-08-27T11:43:58.000Z
2022-02-09T17:23:21.000Z
src/main/java/eu/isas/peptideshaker/scoring/targetdecoy/TargetDecoyMap.java
hbarsnes/peptide-shaker
89178906ce0ec53bdb3e927dc6c70ee46be859c6
[ "Apache-2.0" ]
25
2015-10-07T17:27:29.000Z
2021-12-21T08:41:31.000Z
23.378594
98
0.511309
6,798
package eu.isas.peptideshaker.scoring.targetdecoy; import com.compomics.util.experiment.personalization.ExperimentObject; import com.compomics.util.waiting.WaitingHandler; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; /** * This map contains the information of a target/decoy strategy. * * @author Marc Vaudel */ public class TargetDecoyMap extends ExperimentObject { /** * Serial version UID for post-serialization compatibility. */ static final long serialVersionUID = 7333389442377322662L; /** * The hit map containing the indexed target/decoy points. */ private HashMap<Double, TargetDecoyPoint> hitMap = new HashMap<>(); /** * The scores imported in the map. */ private ArrayList<Double> scores; /** * The number of decoy matches to include in the first bin to set the bin * size nmax. Two means that two consecutive decoys will be used. */ private Integer minDecoysInBin = 2; /** * The bin size, by default the maximal number of target hits comprised * between minDecoysInBin subsequent decoy hits. */ private Integer nmax; /** * The window size for pep estimation. */ private Integer windowSize; /** * The number of target hits found before the first decoy hit. */ private Integer nTargetOnly; /** * The minimal FDR which can be achieved on the dataset. */ private double minFDR = 1.0; /** * The results computed on this map. */ private TargetDecoyResults targetDecoyResults = new TargetDecoyResults(); /** * Constructor. */ public TargetDecoyMap() { } /** * Constructor. * * @param minDecoysInBin the number of decoy matches to include in the first * bin to set the bin size */ public TargetDecoyMap(Integer minDecoysInBin) { this.minDecoysInBin = minDecoysInBin; } /** * Returns the posterior error probability estimated at the given score. * * @param score the given score * @return the estimated posterior error probability */ public double getProbability(double score) { TargetDecoyPoint point = hitMap.get(score); if (point != null) { return point.p; } else if (score >= scores.get(scores.size() - 1)) { return hitMap.get(scores.get(scores.size() - 1)).p; } else { int indexDown = 0; int indexUp = scores.size() - 1; int indexTemp; while (indexUp - indexDown > 1) { indexTemp = (indexUp - indexDown) / 2 + indexDown; if (scores.get(indexTemp) > score) { indexUp = indexTemp; } else { indexDown = indexTemp; } } return (hitMap.get(scores.get(indexUp)).p + hitMap.get(scores.get(indexDown)).p) / 2; } } /** * Returns the number of target hits found at the given score. * * @param score the given score * @return the number of target hits found at the given score */ public int getNTarget(double score) { return hitMap.get(score).nTarget; } /** * Returns the number of decoy hits found at the given score. * * @param score the given score * @return the number of decoy hits found at the given score */ public int getNDecoy(double score) { return hitMap.get(score).nDecoy; } /** * Puts a new point in the target/decoy map at the given score. * * @param score The given score * @param isDecoy boolean indicating whether the hit is decoy */ public void put(double score, boolean isDecoy) { TargetDecoyPoint targetDecoyPoint = hitMap.get(score); if (targetDecoyPoint == null) { targetDecoyPoint = createTargetDecoyPoint(score); } if (isDecoy) { targetDecoyPoint.increaseDecoy(); } else { targetDecoyPoint.increaseTarget(); } } /** * Creates the target decoy point of the map at the given score if no other * thread has done it before. * * @param score the score of interest * * @return the target decoy point of the map at the given score */ public synchronized TargetDecoyPoint createTargetDecoyPoint(double score) { TargetDecoyPoint targetDecoyPoint = hitMap.get(score); if (targetDecoyPoint == null) { targetDecoyPoint = new TargetDecoyPoint(); hitMap.put(score, targetDecoyPoint); } return targetDecoyPoint; } /** * Removes a point in the target/decoy map at the given score. Note: it is * necessary to run cleanUp() afterwards to clean up the map. * * @param score the given score * @param isDecoy boolean indicating whether the hit is decoy */ public void remove(double score, boolean isDecoy) { TargetDecoyPoint targetDecoyPoint = hitMap.get(score); if (!isDecoy) { targetDecoyPoint.decreaseTarget(); } else { targetDecoyPoint.decreaseDecoy(); } } /** * Removes empty points and clears dependent metrics if needed. */ public synchronized void cleanUp() { boolean removed = false; HashSet<Double> currentScores = new HashSet<>(hitMap.keySet()); for (double score : currentScores) { TargetDecoyPoint targetDecoyPoint = hitMap.get(score); if (targetDecoyPoint.nTarget == 0 && targetDecoyPoint.nDecoy == 0) { hitMap.remove(score); removed = true; } } if (removed) { scores = null; nmax = null; windowSize = null; } } /** * Estimates the metrics of the map: Nmax, NtargetOnly, minFDR. Scores of 1 * and above will be skipped for Nmax. */ private void estimateNs() { if (scores == null) { estimateScores(); } boolean onlyTarget = true; nmax = 0; int targetCpt = 0; int decoyCpt = 0; nTargetOnly = 0; int targetCount = 0, decoyCount = 0; for (double score : scores) { TargetDecoyPoint point = hitMap.get(score); if (onlyTarget) { if (point.nDecoy > 0) { nTargetOnly += point.nTarget / 2 + point.nTarget % 2; targetCpt += point.nTarget / 2; onlyTarget = false; decoyCpt += point.nDecoy; } else { nTargetOnly += point.nTarget; } } else if (point.nDecoy > 0) { targetCpt += point.nTarget / 2 + point.nTarget % 2; decoyCpt += point.nDecoy; if (targetCpt > nmax && score < 1.0 && decoyCpt >= minDecoysInBin) { nmax = targetCpt; } targetCpt = point.nTarget / 2; decoyCpt = point.nDecoy; } else { targetCpt += point.nTarget; } targetCount += point.nTarget; decoyCount += point.nDecoy; if (targetCount > 0) { double fdr = ((double) decoyCount) / targetCount; if (fdr < minFDR) { minFDR = fdr; } } } } /** * Estimates the posterior error probabilities in this map. * * @param waitingHandler the handler displaying feedback to the user */ public void estimateProbabilities(WaitingHandler waitingHandler) { if (scores == null) { estimateScores(); } if (nmax == null) { estimateNs(); } if (windowSize == null) { windowSize = nmax; } // estimate p double currentScore = scores.get(0); TargetDecoyPoint tempPoint, previousPoint = hitMap.get(currentScore); double nLimit = 0.5 * windowSize; double nTargetUp = 1.5 * previousPoint.nTarget; double nTargetDown = -0.5 * previousPoint.nTarget; double nDecoy = previousPoint.nDecoy; int iDown = 0; int iUp = 1; boolean oneReached = false; for (int i = 0; i < scores.size(); i++) { currentScore = scores.get(i); TargetDecoyPoint point = hitMap.get(currentScore); if (!oneReached) { double change = 0.5 * (previousPoint.nTarget + point.nTarget); nTargetDown += change; nTargetUp -= change; while (nTargetDown > nLimit) { if (iDown < i) { tempPoint = hitMap.get(scores.get(iDown)); double nTargetDownTemp = nTargetDown - tempPoint.nTarget; if (nTargetDownTemp >= nLimit) { nDecoy -= tempPoint.nDecoy; nTargetDown = nTargetDownTemp; iDown++; } else { break; } } else { break; } } while (nTargetUp < nLimit && iUp < scores.size()) { tempPoint = hitMap.get(scores.get(iUp)); nTargetUp += tempPoint.nTarget; nDecoy += tempPoint.nDecoy; iUp++; } double nTarget = nTargetDown + nTargetUp; point.p = Math.max(Math.min(nDecoy / nTarget, 1), 0); if (point.p >= 0.98) { oneReached = true; } } else { point.p = 1; } previousPoint = point; waitingHandler.increaseSecondaryProgressCounter(); if (waitingHandler.isRunCanceled()) { return; } } } /** * Returns the Nmax metric. * * @return the Nmax metric */ public int getnMax() { if (nmax == null) { estimateNs(); } return nmax; } /** * Returns the minimal FDR which can be achieved in this dataset. * * @return the minimal FDR which can be achieved in this dataset */ public double getMinFdr() { return minFDR; } /** * Returns the minimal detectable PEP variation in percent. * * @return the minimal detectable PEP variation in percent */ public double getResolution() { double pmin = 0; int nMax = getnMax(); if (nMax != 0) { pmin = 100.0 / nMax; } return pmin; } /** * Returns the number of target hits before the first decoy hit. * * @return the number of target hits before the first decoy hit */ public Integer getnTargetOnly() { return nTargetOnly; } /** * Sorts the scores implemented in this map. */ private void estimateScores() { scores = new ArrayList<>(hitMap.keySet()); Collections.sort(scores); } /** * Returns the sorted scores implemented in this map. * * @return the sorted scores implemented in this map. */ public ArrayList<Double> getScores() { if (scores == null) { estimateScores(); } return scores; } /** * Adds all the points from another target/decoy map. * * @param anOtherMap another target/decoy map */ public void addAll(TargetDecoyMap anOtherMap) { for (double score : anOtherMap.getScores()) { for (int i = 0; i < anOtherMap.getNDecoy(score); i++) { put(score, true); } for (int i = 0; i < anOtherMap.getNTarget(score); i++) { put(score, false); } } scores = null; nmax = null; windowSize = null; } /** * Returns a boolean indicating if a suspicious input was detected. * * @param initialFDR the minimal FDR requested for a group * * @return a boolean indicating if a suspicious input was detected */ public boolean suspiciousInput(double initialFDR) { if (nmax == null) { estimateNs(); } if (nmax < 100 || minFDR > initialFDR) { return true; } return false; } /** * Returns the current target decoy results. * * @return the current target decoy results */ public TargetDecoyResults getTargetDecoyResults() { return targetDecoyResults; } /** * Returns the target decoy series. * * @return the target decoy series */ public TargetDecoySeries getTargetDecoySeries() { return new TargetDecoySeries(hitMap); } /** * Returns the window size used for pep estimation. * * @return the window size used for pep estimation */ public int getWindowSize() { if (windowSize == null) { windowSize = getnMax(); } return windowSize; } /** * Sets the window size used for pep estimation. * * @param windowSize the window size used for pep estimation */ public void setWindowSize(int windowSize) { this.windowSize = windowSize; } /** * Returns the size of the map. * * @return the size of the map */ public int getMapSize() { return hitMap.size(); } }
3e10082b719db2c50147648a3f7c385b92492bed
329
java
Java
micro-shop-service/src/main/java/com/abc1236/ms/service/task/TaskLogService.java
tanshion/micro-shop
793252e81e1793c9c6ec3716a1987436feb5d38d
[ "Apache-2.0" ]
1
2021-01-23T03:34:19.000Z
2021-01-23T03:34:19.000Z
micro-shop-service/src/main/java/com/abc1236/ms/service/task/TaskLogService.java
tanshion/micro-shop
793252e81e1793c9c6ec3716a1987436feb5d38d
[ "Apache-2.0" ]
null
null
null
micro-shop-service/src/main/java/com/abc1236/ms/service/task/TaskLogService.java
tanshion/micro-shop
793252e81e1793c9c6ec3716a1987436feb5d38d
[ "Apache-2.0" ]
null
null
null
19.352941
66
0.74772
6,799
package com.abc1236.ms.service.task; import com.abc1236.ms.entity.system.TaskLog; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * 定时任务日志服务类 * * @author tanshion */ public interface TaskLogService { boolean save(TaskLog entity); Page<TaskLog> queryPage(Long taskId, Page<TaskLog> page); }
3e100834d218a87eabd35535ef20d37237016edf
1,375
java
Java
my-spring-beans/src/main/java/util/BeanFactory.java
kihcyaZaynorB/spring-learning
3cbadb921739c3b86274f39b2e7a2def0132b8b4
[ "Apache-2.0" ]
null
null
null
my-spring-beans/src/main/java/util/BeanFactory.java
kihcyaZaynorB/spring-learning
3cbadb921739c3b86274f39b2e7a2def0132b8b4
[ "Apache-2.0" ]
null
null
null
my-spring-beans/src/main/java/util/BeanFactory.java
kihcyaZaynorB/spring-learning
3cbadb921739c3b86274f39b2e7a2def0132b8b4
[ "Apache-2.0" ]
null
null
null
34.375
97
0.681455
6,800
package util; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ConcurrentHashMap; public class BeanFactory { private ConcurrentHashMap<String, BeanDefinition> beanDefinitions; public ConcurrentHashMap<String, BeanDefinition> getBeanDefinitions() { return beanDefinitions; } public void setBeanDefinitions(ConcurrentHashMap<String, BeanDefinition> beanDefinitions) { this.beanDefinitions = beanDefinitions; } public Object getBean(String beanName) { BeanDefinition beanDefinition = beanDefinitions.get(beanName); if (beanDefinition == null) { throw new RuntimeException("no such bean registered"); } Object instance = null; String classPath = beanDefinition.getClazz(); Class clazz = null; try { clazz = Class.forName(classPath); instance = clazz.getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException("class not found"); } catch (NoSuchMethodException e) { throw new RuntimeException("no such constructors"); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("create instance failed"); } return instance; } }
3e10085b945c2f31e231afbd014b397f4c667550
105
java
Java
Lab #3/ProcessorTask.java
doctorblinch/OS_Lab
47cab6b9bda523a4f047575ab3fa5df90580677d
[ "MIT" ]
null
null
null
Lab #3/ProcessorTask.java
doctorblinch/OS_Lab
47cab6b9bda523a4f047575ab3fa5df90580677d
[ "MIT" ]
null
null
null
Lab #3/ProcessorTask.java
doctorblinch/OS_Lab
47cab6b9bda523a4f047575ab3fa5df90580677d
[ "MIT" ]
null
null
null
21
29
0.67619
6,801
public class ProcessorTask { public Task task; public int time; public int queueNumber; }
3e1008b11ad73d208f7c0a26b7835642b704b8d5
1,987
java
Java
src/main/gen/com/justint/usdidea/lang/psi/impl/usdItemImpl.java
justint/usd-idea
3ac7a87661d5920ccd0490e9b35045bb28af27d8
[ "MIT" ]
35
2019-05-28T13:33:57.000Z
2022-03-07T03:38:53.000Z
src/main/gen/com/justint/usdidea/lang/psi/impl/usdItemImpl.java
justint/usd-idea
3ac7a87661d5920ccd0490e9b35045bb28af27d8
[ "MIT" ]
18
2019-06-23T07:08:22.000Z
2021-08-10T14:56:26.000Z
src/main/gen/com/justint/usdidea/lang/psi/impl/usdItemImpl.java
justint/usd-idea
3ac7a87661d5920ccd0490e9b35045bb28af27d8
[ "MIT" ]
1
2021-05-18T15:05:14.000Z
2021-05-18T15:05:14.000Z
22.077778
74
0.742828
6,802
// This is a generated file. Not intended for manual editing. package com.justint.usdidea.lang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.justint.usdidea.lang.psi.USDTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.justint.usdidea.lang.psi.*; public class usdItemImpl extends ASTWrapperPsiElement implements usdItem { public usdItemImpl(@NotNull ASTNode node) { super(node); } public void accept(@NotNull usdVisitor visitor) { visitor.visitItem(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof usdVisitor) accept((usdVisitor)visitor); else super.accept(visitor); } @Override @Nullable public usdArray getArray() { return findChildByClass(usdArray.class); } @Override @Nullable public usdBoolean getBoolean() { return findChildByClass(usdBoolean.class); } @Override @Nullable public usdDict getDict() { return findChildByClass(usdDict.class); } @Override @Nullable public usdInterpolatedArray getInterpolatedArray() { return findChildByClass(usdInterpolatedArray.class); } @Override @Nullable public usdReferenceItem getReferenceItem() { return findChildByClass(usdReferenceItem.class); } @Override @Nullable public usdTimeSample getTimeSample() { return findChildByClass(usdTimeSample.class); } @Override @Nullable public usdVector getVector() { return findChildByClass(usdVector.class); } @Override @Nullable public PsiElement getFloatnumber() { return findChildByType(FLOATNUMBER); } @Override @Nullable public PsiElement getNumber() { return findChildByType(NUMBER); } @Override @Nullable public PsiElement getString() { return findChildByType(STRING); } }
3e1008b9d68f2690d6dac764a88bf9a9cde029a2
1,733
java
Java
Benchmarks_with_Functional_Bugs/Java/Bears-169/src/pinot-common/src/main/java/com/linkedin/pinot/pql/parsers/pql2/ast/GroupByAstNode.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-169/src/pinot-common/src/main/java/com/linkedin/pinot/pql/parsers/pql2/ast/GroupByAstNode.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
null
null
null
Benchmarks_with_Functional_Bugs/Java/Bears-169/src/pinot-common/src/main/java/com/linkedin/pinot/pql/parsers/pql2/ast/GroupByAstNode.java
kupl/starlab-benchmarks
1efc9efffad1b797f6a795da7e032041e230d900
[ "MIT" ]
2
2020-11-26T13:27:14.000Z
2022-03-20T02:12:55.000Z
36.229167
111
0.72973
6,803
/** * Copyright (C) 2014-2016 LinkedIn Corp. (ychag@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.pql.parsers.pql2.ast; import com.linkedin.pinot.common.request.BrokerRequest; import com.linkedin.pinot.common.request.GroupBy; /** * AST node for GROUP BY clauses. */ public class GroupByAstNode extends BaseAstNode { @Override public void updateBrokerRequest(BrokerRequest brokerRequest) { GroupBy groupBy = new GroupBy(); for (AstNode astNode : getChildren()) { if (astNode instanceof IdentifierAstNode) { IdentifierAstNode node = (IdentifierAstNode) astNode; String groupByColumnName = node.getName(); groupBy.addToColumns(groupByColumnName); // List of expression contains columns as well as expressions to maintain ordering of group by columns. groupBy.addToExpressions(groupByColumnName); } else { FunctionCallAstNode functionCallAstNode = (FunctionCallAstNode) astNode; // Remove all white-space until we start compiling expressions on broker side. groupBy.addToExpressions(functionCallAstNode.getExpression()); } } brokerRequest.setGroupBy(groupBy); } }
3e1009ab8230e8178d2e009b9e8904f09eb05c19
571
java
Java
mall-product/src/main/java/com/firenay/mall/product/dao/AttrAttrgroupRelationDao.java
czy1024/luna-mall
7c7eff86b86427b9d750cf630a9822e11236cf2d
[ "Apache-2.0" ]
2
2021-06-08T12:32:56.000Z
2021-06-08T12:33:01.000Z
mall-product/src/main/java/com/firenay/mall/product/dao/AttrAttrgroupRelationDao.java
lunasaw/luna-mall
7c7eff86b86427b9d750cf630a9822e11236cf2d
[ "Apache-2.0" ]
null
null
null
mall-product/src/main/java/com/firenay/mall/product/dao/AttrAttrgroupRelationDao.java
lunasaw/luna-mall
7c7eff86b86427b9d750cf630a9822e11236cf2d
[ "Apache-2.0" ]
null
null
null
25.954545
91
0.796848
6,804
package com.firenay.mall.product.dao; import com.firenay.mall.product.entity.AttrAttrgroupRelationEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 属性&属性分组关联 * * @author firenay * @email dycjh@example.com * @date 2020-05-31 17:06:04 */ @Mapper public interface AttrAttrgroupRelationDao extends BaseMapper<AttrAttrgroupRelationEntity> { void deleteBatchRelation(@Param("entities") List<AttrAttrgroupRelationEntity> entities); }
3e100a991641353099c7825ff609e5d99a8dc0a0
2,017
java
Java
libgpuimage/src/main/java/org/wysaid/nativePort/CGEMultiInputFilterWrapper.java
xuqiqiang/EasyCamera2-GPUImage
546159a2982714de44b5c5d46597d33d1e40f670
[ "Apache-2.0" ]
5
2020-12-16T08:36:52.000Z
2021-08-04T00:59:11.000Z
libgpuimage/src/main/java/org/wysaid/nativePort/CGEMultiInputFilterWrapper.java
xuqiqiang/EasyCamera2-GPUImage
546159a2982714de44b5c5d46597d33d1e40f670
[ "Apache-2.0" ]
null
null
null
libgpuimage/src/main/java/org/wysaid/nativePort/CGEMultiInputFilterWrapper.java
xuqiqiang/EasyCamera2-GPUImage
546159a2982714de44b5c5d46597d33d1e40f670
[ "Apache-2.0" ]
1
2021-06-23T07:03:49.000Z
2021-06-23T07:03:49.000Z
31.515625
143
0.683193
6,805
package org.wysaid.nativePort; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; // A demo for multi input. public class CGEMultiInputFilterWrapper { static { NativeLibraryLoader.load(); } private long mNativeAddress = 0; private CGEMultiInputFilterWrapper() {} static public CGEMultiInputFilterWrapper create(String vsh, String fsh) { CGEMultiInputFilterWrapper wrapper = new CGEMultiInputFilterWrapper(); wrapper.mNativeAddress = wrapper.nativeCreate(vsh, fsh); if(wrapper.mNativeAddress == 0) { wrapper = null; } return wrapper; } // The native filter should not be deleted if passed to an image handler! public void release(boolean deleteFilter) { if(mNativeAddress != 0) { if(deleteFilter) { nativeRelease(mNativeAddress); } mNativeAddress = 0; } } IntBuffer mInputTextureBuffer; public long getNativeAddress() { return mNativeAddress; } public void updateInputTextures(IntBuffer inputTextureBuffer, int count) { nativeUpdateInputTextures(mNativeAddress, inputTextureBuffer, count); } public void updateInputTextures(int[] inputTextures) { if(mInputTextureBuffer == null || mInputTextureBuffer.capacity() < inputTextures.length) { mInputTextureBuffer = ByteBuffer.allocateDirect(inputTextures.length * Integer.BYTES).order(ByteOrder.nativeOrder()).asIntBuffer(); } mInputTextureBuffer.put(inputTextures); mInputTextureBuffer.position(0); nativeUpdateInputTextures(mNativeAddress, mInputTextureBuffer, inputTextures.length); } ///////////////////////////////// protected static native long nativeCreate(String vsh, String fsh); protected static native void nativeRelease(long holder); protected native void nativeUpdateInputTextures(long holder, IntBuffer inputTextureBuffer, int count); }
3e100ab3b37363b6d5c34ae895d2380252b832ef
2,242
java
Java
Skizzle/optifine/VersionCheckThread.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
3
2022-02-28T17:34:51.000Z
2022-03-06T21:55:16.000Z
Skizzle/optifine/VersionCheckThread.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
2
2022-02-25T20:10:14.000Z
2022-03-03T14:25:03.000Z
Skizzle/optifine/VersionCheckThread.java
14ms/Minecraft-Disclosed-Source-Modifications
d3729ab0fb20c36da1732b2070d1cb5d1409ffbc
[ "Unlicense" ]
null
null
null
36.754098
96
0.540589
6,806
/* * Decompiled with CFR 0.150. */ package optifine; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import net.minecraft.client.ClientBrandRetriever; import optifine.Config; public class VersionCheckThread extends Thread { @Override public void run() { HttpURLConnection conn = null; try { Config.dbg("Checking for new version"); URL e = new URL("http://optifine.net/version/1.8/HD_U.txt"); conn = (HttpURLConnection)e.openConnection(); if (Config.getGameSettings().snooperEnabled) { conn.setRequestProperty("OF-MC-Version", "1.8"); conn.setRequestProperty("OF-MC-Brand", ClientBrandRetriever.getClientModName()); conn.setRequestProperty("OF-Edition", "HD_U"); conn.setRequestProperty("OF-Release", "H6"); conn.setRequestProperty("OF-Java-Version", System.getProperty("java.version")); conn.setRequestProperty("OF-CpuCount", "" + Config.getAvailableProcessors()); conn.setRequestProperty("OF-OpenGL-Version", Config.openGlVersion); conn.setRequestProperty("OF-OpenGL-Vendor", Config.openGlVendor); } conn.setDoInput(true); conn.setDoOutput(false); conn.connect(); try { InputStream in = conn.getInputStream(); String verStr = Config.readInputStream(in); in.close(); String[] verLines = Config.tokenize(verStr, "\n\r"); if (verLines.length < 1) { return; } String newVer = verLines[0].trim(); Config.dbg("Version found: " + newVer); if (Config.compareRelease(newVer, "H6") > 0) { Config.setNewRelease(newVer); return; } } finally { if (conn != null) { conn.disconnect(); } } } catch (Exception var11) { Config.dbg(String.valueOf(var11.getClass().getName()) + ": " + var11.getMessage()); } } }
3e100b4ad22a3c43dab0bdf41ad338a0f87e372d
7,303
java
Java
shim-server/src/test/java/org/openmhealth/shim/misfit/mapper/MisfitSleepMeasureDataPointMapperUnitTests.java
harsh90/shimmer-develop
9ddc81dc74f2f19d7ed4cd3e591c15e0911f6c69
[ "Apache-2.0" ]
432
2015-07-12T07:07:08.000Z
2022-03-01T14:48:47.000Z
shim-server/src/test/java/org/openmhealth/shim/misfit/mapper/MisfitSleepMeasureDataPointMapperUnitTests.java
harsh90/shimmer-develop
9ddc81dc74f2f19d7ed4cd3e591c15e0911f6c69
[ "Apache-2.0" ]
93
2015-06-29T21:31:03.000Z
2022-02-25T14:53:07.000Z
shim-server/src/test/java/org/openmhealth/shim/misfit/mapper/MisfitSleepMeasureDataPointMapperUnitTests.java
harsh90/shimmer-develop
9ddc81dc74f2f19d7ed4cd3e591c15e0911f6c69
[ "Apache-2.0" ]
128
2015-09-03T15:45:33.000Z
2021-12-25T13:02:20.000Z
38.640212
108
0.489114
6,807
/* * Copyright 2017 Open mHealth * * 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.openmhealth.shim.misfit.mapper; import com.fasterxml.jackson.databind.JsonNode; import org.openmhealth.schema.domain.omh.DataPoint; import org.openmhealth.schema.domain.omh.SchemaSupport; import org.openmhealth.shim.common.mapper.DataPointMapperUnitTests; import org.openmhealth.shim.common.mapper.JsonNodeMappingException; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.openmhealth.schema.domain.omh.DataPointModality.SENSED; /** * @author Emerson Farrugia */ public abstract class MisfitSleepMeasureDataPointMapperUnitTests<T extends SchemaSupport> extends DataPointMapperUnitTests { protected JsonNode sleepsResponseNode; @BeforeMethod public void initializeResponseNode() throws IOException { sleepsResponseNode = asJsonNode("org/openmhealth/shim/misfit/mapper/misfit-sleeps.json"); } protected abstract MisfitSleepMeasureDataPointMapper<T> getMapper(); @Test(expectedExceptions = JsonNodeMappingException.class) public void asDataPointsShouldThrowExceptionOnEmptySleepDetails() throws IOException { JsonNode node = objectMapper.readTree("{\n" + " \"sleeps\": [\n" + " {\n" + " \"id\": \"54fa13a8440f705a7406845f\",\n" + " \"autoDetected\": false,\n" + " \"startTime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"duration\": 2580,\n" + " \"sleepDetails\": []\n" + " }\n" + " ]\n" + "}"); getMapper().asDataPoints(node); } @Test public void asDataPointsShouldReturnEmptyListIfOnlyAwake() throws IOException { JsonNode node = objectMapper.readTree("{\n" + " \"sleeps\": [\n" + " {\n" + " \"id\": \"54fa13a8440f705a7406845f\",\n" + " \"autoDetected\": false,\n" + " \"startTime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"duration\": 2580,\n" + " \"sleepDetails\": [\n" + " {\n" + " \"datetime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"value\": 1\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"); List<DataPoint<T>> dataPoints = getMapper().asDataPoints(node); assertThat(dataPoints, notNullValue()); assertThat(dataPoints, empty()); } @Test public void asDataPointsShouldReturnCorrectNumberOfDataPoints() { List<DataPoint<T>> dataPoints = getMapper().asDataPoints(sleepsResponseNode); assertThat(dataPoints, notNullValue()); assertThat(dataPoints.size(), equalTo(2)); } @Test public void asDataPointsShouldReturnEmptyListIfEmptyResponse() throws IOException { JsonNode emptyNode = objectMapper.readTree("{\n" + " \"sleeps\": []\n" + "}"); assertThat(getMapper().asDataPoints(emptyNode), empty()); } @Test public void asDataPointsShouldSetModalityToSensedWhenAutoDetectedIsTrue() throws IOException { JsonNode node = objectMapper.readTree("{\n" + " \"sleeps\": [\n" + " {\n" + " \"id\": \"54fa13a8440f705a7406845f\",\n" + " \"autoDetected\": true,\n" + " \"startTime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"duration\": 2580,\n" + " \"sleepDetails\": [\n" + " {\n" + " \"datetime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"value\": 2\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"); List<DataPoint<T>> dataPoints = getMapper().asDataPoints(node); assertThat(dataPoints.get(0).getHeader().getAcquisitionProvenance().getModality(), equalTo(SENSED)); } @Test public void asDataPointsShouldNotSetModalityWhenAutoDetectedIsFalse() throws IOException { JsonNode node = objectMapper.readTree("{\n" + " \"sleeps\": [\n" + " {\n" + " \"id\": \"54fa13a8440f705a7406845f\",\n" + " \"autoDetected\": false,\n" + " \"startTime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"duration\": 2580,\n" + " \"sleepDetails\": [\n" + " {\n" + " \"datetime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"value\": 2\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"); List<DataPoint<T>> dataPoints = getMapper().asDataPoints(node); assertThat(dataPoints.get(0).getHeader().getAcquisitionProvenance().getModality(), nullValue()); } @Test public void asDataPointsShouldNotSetModalityWhenAutoDetectedIsMissing() throws IOException { JsonNode node = objectMapper.readTree("{\n" + " \"sleeps\": [\n" + " {\n" + " \"id\": \"54fa13a8440f705a7406845f\",\n" + " \"startTime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"duration\": 2580,\n" + " \"sleepDetails\": [\n" + " {\n" + " \"datetime\": \"2015-02-24T21:40:59-05:00\",\n" + " \"value\": 2\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + "}"); List<DataPoint<T>> dataPoints = getMapper().asDataPoints(node); assertThat(dataPoints.get(0).getHeader().getAcquisitionProvenance().getModality(), nullValue()); } }
3e100b4cb9a44db2ef2320cb7c2478174c48bee8
2,582
java
Java
src/EpoctiAntiAliaser.java
kokoscript/EpoctiAA
17c8ca51dbef2c799908a616a28e7d80b31fb8b5
[ "MIT" ]
3
2019-02-19T04:18:28.000Z
2022-03-13T00:40:56.000Z
src/EpoctiAntiAliaser.java
sahwar/EpoctiAA
f38540933616c16da1056ab52eb17e66186a878f
[ "MIT" ]
null
null
null
src/EpoctiAntiAliaser.java
sahwar/EpoctiAA
f38540933616c16da1056ab52eb17e66186a878f
[ "MIT" ]
1
2019-02-19T04:18:46.000Z
2019-02-19T04:18:46.000Z
39.723077
159
0.544539
6,808
import java.awt.*; import java.awt.image.BufferedImage; class EpoctiAntiAliaser{ private BufferedImage img; private int chkRgb, r, g, b, a; EpoctiAntiAliaser(int r, int g, int b, int a, BufferedImage img){ this.r = r; this.g = g; this.b = b; this.a = a; chkRgb = new Color(r, g, b, a).getRGB(); this.img = img; } BufferedImage antiAlias(){ // TODO: Make it so that, if a non 0-alpha pixel needs to be edited, do so by adding the checking color on top of the current pixel BufferedImage aaImg = img; for (int y = 0; y < aaImg.getHeight(); y++){ for (int x = 0; x < aaImg.getWidth(); x++){ if (aaImg.getRGB(x, y) != chkRgb){ if (x > 0 && y > 0){ if ((aaImg.getRGB(x, y - 1) == chkRgb) && (aaImg.getRGB(x - 1, y) == chkRgb)){ Color curCol = new Color(aaImg.getRGB(x, y), true); if (curCol.getAlpha() == 0) aaImg.setRGB(x, y, new Color(r, g, b, 74).getRGB()); else aaImg.setRGB(x, y, new Color((int) (curCol.getRed() * .7), (int) (curCol.getGreen() * .7), (int) (curCol.getBlue() * .7), curCol.getAlpha()).getRGB()); } } if (x < aaImg.getWidth() - 1 && y < aaImg.getHeight() - 1){ if ((aaImg.getRGB(x, y + 1) == chkRgb) && (aaImg.getRGB(x + 1, y) == chkRgb)){ Color curCol = new Color(aaImg.getRGB(x, y), true); if (curCol.getAlpha() == 0) aaImg.setRGB(x, y, new Color(r, g, b, 74).getRGB()); else aaImg.setRGB(x, y, new Color((int) (curCol.getRed() * .7), (int) (curCol.getGreen() * .7), (int) (curCol.getBlue() * .7), curCol.getAlpha()).getRGB()); } } if (y > 0 && x < aaImg.getWidth() - 1){ if ((aaImg.getRGB(x, y - 1) == chkRgb) && (aaImg.getRGB(x + 1, y) == chkRgb)){ Color curCol = new Color(aaImg.getRGB(x, y), true); if (curCol.getAlpha() == 0) aaImg.setRGB(x, y, new Color(r, g, b, 74).getRGB()); else aaImg.setRGB(x, y, new Color((int) (curCol.getRed() * .7), (int) (curCol.getGreen() * .7), (int) (curCol.getBlue() * .7), curCol.getAlpha()).getRGB()); } } if (x > 0 && y < aaImg.getHeight() - 1){ if ((aaImg.getRGB(x, y + 1) == chkRgb) && (aaImg.getRGB(x - 1, y) == chkRgb)){ Color curCol = new Color(aaImg.getRGB(x, y), true); if (curCol.getAlpha() == 0) aaImg.setRGB(x, y, new Color(r, g, b, 74).getRGB()); else aaImg.setRGB(x, y, new Color((int) (curCol.getRed() * .7), (int) (curCol.getGreen() * .7), (int) (curCol.getBlue() * .7), curCol.getAlpha()).getRGB()); } } } } } return aaImg; } }
3e100d7151c0f94e558a1e04b877baf8c0e2d6f2
3,271
java
Java
src/java/crc/dps/output/OutputTrace.java
ssavitzky/pia-historical
43b54554f9277c04450a9a1e5ebb97a0925365fb
[ "DOC" ]
null
null
null
src/java/crc/dps/output/OutputTrace.java
ssavitzky/pia-historical
43b54554f9277c04450a9a1e5ebb97a0925365fb
[ "DOC" ]
null
null
null
src/java/crc/dps/output/OutputTrace.java
ssavitzky/pia-historical
43b54554f9277c04450a9a1e5ebb97a0925365fb
[ "DOC" ]
null
null
null
29.486486
79
0.532233
6,809
////// OutputTrace: debugging shim for an Output // $Id$ /***************************************************************************** * The contents of this file are subject to the Ricoh Source Code Public * License Version 1.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.risource.org/RPL * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * This code was initially developed by Ricoh Silicon Valley, Inc. Portions * created by Ricoh Silicon Valley, Inc. are Copyright (C) 1995-1999. All * Rights Reserved. * * Contributor(s): * ***************************************************************************** */ package crc.dps.output; import crc.dom.*; import crc.dps.*; import crc.dps.util.Log; import java.io.PrintStream; /** * A debugging shim for Outputs. All operations are proxied to a * ``real'' target Output, and also logged to a PrintStream. <p> * * @version $Id$ * @author hzdkv@example.com */ public class OutputTrace extends Proxy { /************************************************************************ ** State: ************************************************************************/ protected PrintStream log = System.err; protected static String NL = "\n"; public void setLog(PrintStream s) { log = s; } public void trace(String message) { log.print(message); } public void trace(String message, int indent) { String s = "=>"; for (int i = 0; i < indent; ++i) s += " "; s += message; log.print(s); } public String logNode(Node aNode) { return Log.node(aNode); } public String logString(String s) { return Log.string(s); } /************************************************************************ ** Operations: ************************************************************************/ public void putNode(Node aNode) { trace("put " + logNode(aNode) + NL, depth); if (target != null) target.putNode(aNode); } public void startNode(Node aNode) { trace("start " + logNode(aNode) + NL, depth); depth++; if (target != null) target.startNode(aNode); } public boolean endNode() { depth --; trace("end " + NL, depth); return (target != null)? target.endNode() : depth >= 0;; } public void startElement(Element anElement) { trace("start " + logNode(anElement) + NL, depth); depth++; if (target != null) target.startElement(anElement); } public boolean endElement(boolean optional) { depth --; trace("end(" + (optional? "true" : "false") +")" + NL, depth); return (target != null)? target.endElement(optional) : depth >= 0; } /************************************************************************ ** Construction: ************************************************************************/ public OutputTrace() { } public OutputTrace(Output theTarget) { super(theTarget); } public OutputTrace(Output theTarget, PrintStream theLog) { super(theTarget); log = theLog; } }
3e100e8fdfa2042d882d7de7321a4b11f1962f4b
483
java
Java
IJPDS_Chapter3/src/Pratise310.java
xinlinrong/JAVA_IJPDS
56f95cdce6e75a5d6c4f4e329fbd1b86c98cd6d3
[ "BSD-3-Clause" ]
null
null
null
IJPDS_Chapter3/src/Pratise310.java
xinlinrong/JAVA_IJPDS
56f95cdce6e75a5d6c4f4e329fbd1b86c98cd6d3
[ "BSD-3-Clause" ]
null
null
null
IJPDS_Chapter3/src/Pratise310.java
xinlinrong/JAVA_IJPDS
56f95cdce6e75a5d6c4f4e329fbd1b86c98cd6d3
[ "BSD-3-Clause" ]
null
null
null
34.5
114
0.583851
6,810
public class Pratise310 extends AbstractPratiseImpl { @Override public void run() { int number1 = (int)(Math.random() * 100.0); int number2 = (int)(Math.random() * 100.0); print("What's answer to expression %d - %d", number1, number2); int answer = in.nextInt(); boolean result = (answer == (number1 - number2)); print("Expression %d - %d = %d is %s", number1, number2, (number1 - number2), result ? "right" : "wrong"); } }
3e100fcfcfc39f0416f6cac313b30598c6f7753f
1,859
java
Java
src/main/java/noppes/npcs/roles/RolePostman.java
Goodbird-git/CustomNPC-Plus
12326dabf2d1a2b12a8f73faa8b5a5c5e9a56737
[ "MIT" ]
13
2021-05-17T14:51:43.000Z
2022-03-23T14:14:23.000Z
src/main/java/noppes/npcs/roles/RolePostman.java
Goodbird-git/CustomNPC-Plus
12326dabf2d1a2b12a8f73faa8b5a5c5e9a56737
[ "MIT" ]
13
2021-05-18T01:10:47.000Z
2022-02-27T01:52:06.000Z
src/main/java/noppes/npcs/roles/RolePostman.java
Goodbird-git/CustomNPC-Plus
12326dabf2d1a2b12a8f73faa8b5a5c5e9a56737
[ "MIT" ]
12
2021-04-28T17:41:29.000Z
2022-03-19T14:51:54.000Z
29.983871
122
0.78752
6,811
package noppes.npcs.roles; import java.util.ArrayList; import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentTranslation; import noppes.npcs.CustomNpcs; import noppes.npcs.NoppesUtilServer; import noppes.npcs.NpcMiscInventory; import noppes.npcs.constants.EnumGuiType; import noppes.npcs.controllers.PlayerDataController; import noppes.npcs.entity.EntityNPCInterface; public class RolePostman extends RoleInterface{ public NpcMiscInventory inventory = new NpcMiscInventory(1); private List<EntityPlayer> recentlyChecked = new ArrayList<EntityPlayer>(); private List<EntityPlayer> toCheck; public RolePostman(EntityNPCInterface npc) { super(npc); } public boolean aiShouldExecute() { if(npc.ticksExisted % 20 != 0) return false; toCheck = npc.worldObj.getEntitiesWithinAABB(EntityPlayer.class, npc.boundingBox.expand(10, 10, 10)); toCheck.removeAll(recentlyChecked); List<EntityPlayer> listMax = npc.worldObj.getEntitiesWithinAABB(EntityPlayer.class, npc.boundingBox.expand(20, 20, 20)); recentlyChecked.retainAll(listMax); recentlyChecked.addAll(toCheck); for(EntityPlayer player : toCheck){ if(PlayerDataController.instance.hasMail(player)) player.addChatMessage(new ChatComponentTranslation("You've got mail")); } return false; } @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setTag("PostInv", inventory.getToNBT()); return nbttagcompound; } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { inventory.setFromNBT(nbttagcompound.getCompoundTag("PostInv")); } @Override public void interact(EntityPlayer player) { player.openGui(CustomNpcs.instance, EnumGuiType.PlayerMailman.ordinal(), player.worldObj, 1, 1, 0); } }
3e10105ba601d16f97c0133fe78226dcb33a36e8
1,008
java
Java
src/test/java/ch/heigvd/res/chill/domain/texx94/CoopersTest.java
CosmicElodie/Teaching-HEIGVD-RES-2019-Chill
f2f3b2471004038da410bb3ee1afc8b98cfd309d
[ "MIT" ]
4
2019-02-23T19:26:03.000Z
2019-03-02T12:16:21.000Z
src/test/java/ch/heigvd/res/chill/domain/texx94/CoopersTest.java
CosmicElodie/Teaching-HEIGVD-RES-2019-Chill
f2f3b2471004038da410bb3ee1afc8b98cfd309d
[ "MIT" ]
493
2019-02-15T12:21:20.000Z
2021-09-30T07:34:44.000Z
src/test/java/ch/heigvd/res/chill/domain/texx94/CoopersTest.java
CosmicElodie/Teaching-HEIGVD-RES-2019-Chill
f2f3b2471004038da410bb3ee1afc8b98cfd309d
[ "MIT" ]
108
2019-02-15T12:17:21.000Z
2021-02-26T09:13:28.000Z
31.5
82
0.72619
6,812
package ch.heigvd.res.chill.domain.texx94; import ch.heigvd.res.chill.domain.Bartender; import ch.heigvd.res.chill.protocol.OrderRequest; import ch.heigvd.res.chill.protocol.OrderResponse; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static org.junit.jupiter.api.Assertions.assertEquals; class CoopersTest { @Test void thePriceAndNameForBoxerShouldBeCorrect() { Coopers beer = new Coopers(); assertEquals(beer.getName(), Coopers.NAME); assertEquals(beer.getPrice(), Coopers.PRICE); } @Test void aBartenderShouldAcceptAnOrderForBoxer() { Bartender jane = new Bartender(); String productName = "ch.heigvd.res.chill.domain.texx94.Coopers"; OrderRequest request = new OrderRequest(3, productName); OrderResponse response = jane.order(request); BigDecimal expectedTotalPrice = Coopers.PRICE.multiply(new BigDecimal(3)); assertEquals(expectedTotalPrice, response.getTotalPrice()); } }
3e1010a5859ff7e00ad619987b77bfcaaaddcd22
2,948
java
Java
digital-sign-engine/tianwei-cert-core/src/main/java/com/liumapp/cert/core/user/UserAPIServicePortType.java
SpringForAll/spring-cloud-digital-sign
108c2ba82e2eba740efb5ed8743a4dfb7d3568f6
[ "Apache-2.0" ]
15
2018-02-26T00:58:28.000Z
2022-03-14T02:02:13.000Z
digital-sign-engine/tianwei-cert-core/src/main/java/com/liumapp/cert/core/user/UserAPIServicePortType.java
Gsmall7/spring-cloud-digital-sign
dafc7d3ed0a34add1d8b82d1ae24a058c12ee059
[ "Apache-2.0" ]
null
null
null
digital-sign-engine/tianwei-cert-core/src/main/java/com/liumapp/cert/core/user/UserAPIServicePortType.java
Gsmall7/spring-cloud-digital-sign
dafc7d3ed0a34add1d8b82d1ae24a058c12ee059
[ "Apache-2.0" ]
7
2018-02-26T00:58:29.000Z
2020-03-05T01:27:35.000Z
54.666667
237
0.82893
6,813
package com.liumapp.cert.core.user; import com.liumapp.cert.core.cert.CertInfo; import com.liumapp.cert.core.error.RaServiceUnavailable; import com.liumapp.cert.core.query.QueryCertResult; import com.liumapp.cert.core.cert.CertInfo; import com.liumapp.cert.core.error.RaServiceUnavailable; import com.liumapp.cert.core.query.QueryCertResult; import java.rmi.Remote; import java.rmi.RemoteException; /** * @author liumapp * @file UserAPIServicePortType.java * @email anpch@example.com * @homepage http://www.liumapp.com * @date 3/23/18 */ public interface UserAPIServicePortType extends Remote { public QueryCertResult queryCertByCertId(int certId, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public String downloadCRL(String accountHash) throws RemoteException, RaServiceUnavailable; public void unsuspendCert(String serialNumber, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public void enrollCert(UserInfo userInfo, String certReqBuf, String certReqChallenge, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public QueryCertResult queryCerts(UserInfo userInfo, CertInfo certInfo, int pageIndex, int pageSize, String sqlTemplateFileName, String nextResultTag, String totalTag, String accountHash) throws RemoteException, RaServiceUnavailable; public CertInfo renewCertAA(UserInfo userInfo, CertInfo origin, String accountHash, String aaCheckPoint, String passCode, String json) throws RemoteException, RaServiceUnavailable; public String downloadDeltaCRL(String accountHash) throws RemoteException, RaServiceUnavailable; public String downloadCA(String accountHash) throws RemoteException, RaServiceUnavailable; public String doScript(String scriptName, String jsonMap) throws RemoteException, RaServiceUnavailable; public AccountConfigResult synchroTemplate(String accountHash) throws RemoteException, RaServiceUnavailable; public QueryCertResult queryCertBySerialNumber(String serialNumber, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public CertInfo pickupCert(String certPin, String certReqChallenge, String certReqBuf, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public void revokeCert(String serialNumber, String certReqChallenge, String certRevokeReason, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public void renewCert(UserInfo userInfo, CertInfo origin, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public void suspendCert(String serialNumber, String accountHash, String json) throws RemoteException, RaServiceUnavailable; public CertInfo enrollCertAA(UserInfo userInfo, String certReqBuf, String accountHash, String aaCheckPoint, String passCode, String json) throws RemoteException, RaServiceUnavailable; }
3e101127d2e6aa2184b25c6ffd222dc41dfb1d30
2,188
java
Java
src/main/java/raylras/zen/ast/decl/ParameterDeclaration.java
Raylras/ZenServer
890c7d0cb60f2442b965b9b1b24b63eb465c832e
[ "MIT" ]
2
2021-12-06T12:50:15.000Z
2021-12-06T13:08:40.000Z
src/main/java/raylras/zen/ast/decl/ParameterDeclaration.java
Raylras/ZenServer
890c7d0cb60f2442b965b9b1b24b63eb465c832e
[ "MIT" ]
null
null
null
src/main/java/raylras/zen/ast/decl/ParameterDeclaration.java
Raylras/ZenServer
890c7d0cb60f2442b965b9b1b24b63eb465c832e
[ "MIT" ]
null
null
null
26.361446
126
0.653565
6,814
package raylras.zen.ast.decl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import raylras.zen.ast.*; import raylras.zen.ast.expr.Expression; import raylras.zen.ast.visit.NodeVisitor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; public final class ParameterDeclaration extends BaseNode implements Declaration, Variable, LocatableID { @NotNull private final String name; @Nullable private final TypeDeclaration typeDecl; @Nullable private final Expression defaultValue; private Range idRange; public ParameterDeclaration(@NotNull String name, @Nullable TypeDeclaration typeDecl, @Nullable Expression defaultValue) { this.name = name; this.typeDecl = typeDecl; this.defaultValue = defaultValue; } @NotNull public String getName() { return name; } public Optional<TypeDeclaration> getTypeDecl() { return Optional.ofNullable(typeDecl); } public Optional<Expression> getDefaultValue() { return Optional.ofNullable(defaultValue); } @Override public <T> T accept(NodeVisitor<? extends T> visitor) { return visitor.visit(this); } @Override public List<Node> getChildren() { if (typeDecl == null && defaultValue == null) { return Collections.emptyList(); } List<Node> children = new ArrayList<>(2); if (typeDecl != null) children.add(typeDecl); if (defaultValue != null) children.add(defaultValue); return Collections.unmodifiableList(children); } @Override public Range getIdRange() { return idRange; } public void setIDRange(Range idRange) { this.idRange = idRange; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(name); if (getType() != null) { builder.append(" as ").append(getType()); } if (defaultValue != null) { builder.append(" = ").append(defaultValue); } return builder.toString(); } }
3e10117ad4d7d922b3abe2927f6247c248adc9be
7,983
java
Java
bytekit-core/src/main/java/com/alibaba/bytekit/asm/location/InvokeLocationMatcher.java
hengyunabc/bytekit
a5db9d5682d562946695de6daae0025e9ef11327
[ "Apache-2.0" ]
231
2020-10-21T03:20:24.000Z
2022-03-30T02:20:34.000Z
bytekit-core/src/main/java/com/alibaba/bytekit/asm/location/InvokeLocationMatcher.java
kylixs/bytekit
4013cc3cd5e2f5550058bfe4d89a7334ce363172
[ "Apache-2.0" ]
18
2020-11-17T02:11:28.000Z
2022-03-08T16:56:40.000Z
bytekit-core/src/main/java/com/alibaba/bytekit/asm/location/InvokeLocationMatcher.java
kylixs/bytekit
4013cc3cd5e2f5550058bfe4d89a7334ce363172
[ "Apache-2.0" ]
55
2020-10-28T08:25:34.000Z
2022-03-28T10:38:52.000Z
32.717213
116
0.633847
6,815
package com.alibaba.bytekit.asm.location; import java.util.ArrayList; import java.util.List; import com.alibaba.deps.org.objectweb.asm.Opcodes; import com.alibaba.deps.org.objectweb.asm.Type; import com.alibaba.deps.org.objectweb.asm.tree.AbstractInsnNode; import com.alibaba.deps.org.objectweb.asm.tree.InsnList; import com.alibaba.deps.org.objectweb.asm.tree.JumpInsnNode; import com.alibaba.deps.org.objectweb.asm.tree.LabelNode; import com.alibaba.deps.org.objectweb.asm.tree.MethodInsnNode; import com.alibaba.deps.org.objectweb.asm.tree.MethodNode; import com.alibaba.bytekit.asm.MethodProcessor; import com.alibaba.bytekit.asm.TryCatchBlock; import com.alibaba.bytekit.asm.location.Location.InvokeExceptionExitLocation; import com.alibaba.bytekit.asm.location.Location.InvokeLocation; import com.alibaba.bytekit.asm.location.filter.LocationFilter; import com.alibaba.bytekit.utils.AsmOpUtils; import com.alibaba.bytekit.utils.MatchUtils; /** * * @author hengyunabc * */ public class InvokeLocationMatcher implements LocationMatcher { /** * the name of the method being invoked at the point where the trigger point * should be inserted. maybe null, when null, match all method invoke. */ private String methodName; /** * the name of the type to which the method belongs or null if any type will do */ private String owner; /** * the method signature in externalised form, maybe null. */ private String desc; /** * count identifying which invocation should be taken as the trigger point. if * not specified as a parameter this defaults to the first invocation. */ private int count; /** * flag which is false if the trigger should be inserted before the method * invocation is performed and true if it should be inserted after */ private boolean whenComplete; /** * wildcard matcher to exclude the invoke class, such as java.* to exclude jdk * invoke. */ private List<String> excludes = new ArrayList<String>(); private boolean atInvokeExcpetionExit = false; public InvokeLocationMatcher(String owner, String methodName, String desc, int count, boolean whenComplete, List<String> excludes, boolean atInvokeExcpetionExit) { super(); this.owner = owner; this.methodName = methodName; this.desc = desc; this.count = count; this.whenComplete = whenComplete; this.excludes = excludes; this.atInvokeExcpetionExit = atInvokeExcpetionExit; } public InvokeLocationMatcher(String owner, String methodName, String desc, int count, boolean whenComplete, List<String> excludes) { this(owner, methodName, desc, count, whenComplete, excludes, false); } public InvokeLocationMatcher(String owner, String methodName, String desc, int count, boolean whenComplete) { this(owner, methodName, desc, count, whenComplete, new ArrayList<String>()); } @Override public List<Location> match(MethodProcessor methodProcessor) { if (this.atInvokeExcpetionExit) { return matchForException(methodProcessor); } List<Location> locations = new ArrayList<Location>(); AbstractInsnNode insnNode = methodProcessor.getEnterInsnNode(); LocationFilter locationFilter = methodProcessor.getLocationFilter(); LocationType locationType = whenComplete ? LocationType.INVOKE_COMPLETED : LocationType.INVOKE; int matchedCount = 0; while (insnNode != null) { if (insnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (matchCall(methodInsnNode)) { if(locationFilter.allow(methodInsnNode, locationType, this.whenComplete)) { matchedCount++; if (count <= 0 || count == matchedCount) { InvokeLocation invokeLocation = new InvokeLocation(methodInsnNode, count, whenComplete); locations.add(invokeLocation); } } } } insnNode = insnNode.getNext(); } return locations; } public List<Location> matchForException(MethodProcessor methodProcessor) { List<Location> locations = new ArrayList<Location>(); AbstractInsnNode insnNode = methodProcessor.getEnterInsnNode(); MethodNode methodNode = methodProcessor.getMethodNode(); List<MethodInsnNode> methodInsnNodes = new ArrayList<MethodInsnNode>(); LocationFilter locationFilter = methodProcessor.getLocationFilter(); LocationType locationType = LocationType.INVOKE_EXCEPTION_EXIT; int matchedCount = 0; while (insnNode != null) { if (insnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) insnNode; if (matchCall(methodInsnNode)) { if(locationFilter.allow(methodInsnNode, locationType, this.whenComplete)) { matchedCount++; if (count <= 0 || count == matchedCount) { methodInsnNodes.add(methodInsnNode); } } } } insnNode = insnNode.getNext(); } // insert try/catch for (MethodInsnNode methodInsnNode : methodInsnNodes) { TryCatchBlock tryCatchBlock = new TryCatchBlock(methodNode); InsnList toInsert = new InsnList(); LabelNode gotoDest = new LabelNode(); LabelNode startLabelNode = tryCatchBlock.getStartLabelNode(); LabelNode endLabelNode = tryCatchBlock.getEndLabelNode(); toInsert.add(new JumpInsnNode(Opcodes.GOTO, gotoDest)); toInsert.add(endLabelNode); AsmOpUtils.throwException(toInsert); locations.add(new InvokeExceptionExitLocation(methodInsnNode, endLabelNode)); toInsert.add(gotoDest); methodNode.instructions.insertBefore(methodInsnNode, startLabelNode); methodNode.instructions.insert(methodInsnNode, toInsert); tryCatchBlock.sort(); } return locations; } private boolean matchCall(MethodInsnNode methodInsnNode) { if (methodName != null && !methodName.isEmpty()) { if (!this.methodName.equals(methodInsnNode.name)) { return false; } } if (!excludes.isEmpty()) { String ownerClassName = Type.getObjectType(methodInsnNode.owner).getClassName(); for (String exclude : excludes) { if (MatchUtils.wildcardMatch(ownerClassName, exclude)) { return false; } } } if (this.owner != null && !this.owner.equals(methodInsnNode.owner)) { return false; } if (this.desc != null && !desc.equals(methodInsnNode.desc)) { return false; } return true; } public String getMethodName() { return methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public boolean isWhenComplete() { return whenComplete; } public void setWhenComplete(boolean whenComplete) { this.whenComplete = whenComplete; } }
3e10123061bdc37ef464258d6d92162c5f305401
2,960
java
Java
dhis2-android-app/src/main/java/org/dhis2/mobile/utils/date/DateHolder.java
AusseKalega/DHIS2-OLAPI
69d26f0af518a06a8acd6e6cfc424620b23e98d6
[ "BSD-3-Clause" ]
10
2015-07-22T12:49:35.000Z
2019-11-27T08:20:53.000Z
dhis2-android-app/src/main/java/org/dhis2/mobile/utils/date/DateHolder.java
AusseKalega/DHIS2-OLAPI
69d26f0af518a06a8acd6e6cfc424620b23e98d6
[ "BSD-3-Clause" ]
138
2017-05-05T16:29:39.000Z
2018-10-09T08:11:12.000Z
dhis2-android-app/src/main/java/org/dhis2/mobile/utils/date/DateHolder.java
EyeSeeTea/dhis2-android-datacapture
7f9f30b0f56a21873044284595eae164065b0fa6
[ "BSD-3-Clause" ]
24
2015-04-16T05:50:47.000Z
2019-10-17T07:22:45.000Z
33.258427
104
0.705743
6,816
/* * Copyright (c) 2014, Araz Abishov * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dhis2.mobile.utils.date; import android.os.Parcel; import android.os.Parcelable; public class DateHolder implements Parcelable { public static final String TAG = DateHolder.class.getSimpleName(); private final String date; private final String dateTime; private final String label; public DateHolder(String date, String dateTime, String label) { this.date = date; this.dateTime = dateTime; this.label = label; } private DateHolder(Parcel in) { date = in.readString(); dateTime = in.readString(); label = in.readString(); } public static final Parcelable.Creator<DateHolder> CREATOR = new Parcelable.Creator<DateHolder>() { public DateHolder createFromParcel(Parcel in) { return new DateHolder(in); } public DateHolder[] newArray(int size) { return new DateHolder[size]; } }; @Override public int describeContents() { return TAG.length(); } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(date); parcel.writeString(dateTime); parcel.writeString(label); } public String getLabel() { return label; } public String getDate() { return date; } public String getDateTime() { return dateTime; } }
3e1012844d561267213e15878026ab417843f8fc
15,619
java
Java
src/test/tck/msgflow/callflows/forkedinvite/Shootist.java
dinoop-p/jain-sip
e9772e5e00dbd6cdcc233484988a0ac522d9d012
[ "Apache-2.0" ]
115
2016-01-20T14:33:49.000Z
2022-03-15T09:04:41.000Z
src/test/tck/msgflow/callflows/forkedinvite/Shootist.java
dinoop-p/jain-sip
e9772e5e00dbd6cdcc233484988a0ac522d9d012
[ "Apache-2.0" ]
150
2016-01-15T16:13:53.000Z
2022-03-16T08:11:07.000Z
src/test/tck/msgflow/callflows/forkedinvite/Shootist.java
dinoop-p/jain-sip
e9772e5e00dbd6cdcc233484988a0ac522d9d012
[ "Apache-2.0" ]
121
2016-01-13T23:19:35.000Z
2022-03-31T09:31:14.000Z
37.099762
100
0.600038
6,817
package test.tck.msgflow.callflows.forkedinvite; import java.util.ArrayList; import java.util.HashSet; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogState; import javax.sip.DialogTerminatedEvent; import javax.sip.IOExceptionEvent; import javax.sip.ListeningPoint; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.ServerTransaction; import javax.sip.SipListener; import javax.sip.SipProvider; import javax.sip.TransactionTerminatedEvent; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import test.tck.TestHarness; import test.tck.msgflow.callflows.ProtocolObjects; import test.tck.msgflow.callflows.TestAssertion; /** * This class is a UAC template. Shootist is the guy that shoots and shootme is * the guy that gets shot. * * @author M. Ranganathan */ public class Shootist implements SipListener { private ContactHeader contactHeader; private ClientTransaction inviteTid; private SipProvider sipProvider; private String host = "127.0.0.1"; private int port; private String peerHost = "127.0.0.1"; private int peerPort; private ListeningPoint listeningPoint; private static String unexpectedException = "Unexpected exception "; private static Logger logger = Logger.getLogger(Shootist.class); private ProtocolObjects protocolObjects; private Dialog originalDialog; private HashSet forkedDialogs; private Dialog ackedDialog; private Shootist() { this.forkedDialogs = new HashSet(); } public Shootist(int myPort, int proxyPort, ProtocolObjects protocolObjects) { this(); this.protocolObjects = protocolObjects; this.port = myPort; this.peerPort = proxyPort; protocolObjects.logLevel = 32; // JvB } public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); logger.info("\n\nRequest " + request.getMethod() + " received at " + protocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the UAC so the only request we get is the BYE. if (request.getMethod().equals(Request.BYE)) processBye(request, serverTransactionId); else TestHarness.fail("Unexpected request ! : " + request); } public void processBye(Request request, ServerTransaction serverTransactionId) { try { logger.info("shootist: got a bye ."); if (serverTransactionId == null) { logger.info("shootist: null TID."); return; } Dialog dialog = serverTransactionId.getDialog(); logger.info("Dialog State = " + dialog.getState()); Response response = protocolObjects.messageFactory.createResponse( 200, request); serverTransactionId.sendResponse(response); logger.info("shootist: Sending OK."); logger.info("Dialog State = " + dialog.getState()); } catch (Exception ex) { ex.printStackTrace(); junit.framework.TestCase.fail("Exit JVM"); } } public synchronized void processResponse(ResponseEvent responseReceivedEvent) { logger.info("Got a response"); Response response = (Response) responseReceivedEvent.getResponse(); ClientTransaction tid = responseReceivedEvent.getClientTransaction(); CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME); logger.info("Response received : Status Code = " + response.getStatusCode() + " " + cseq); logger.info("Response = " + response + " class=" + response.getClass() ); Dialog dialog = responseReceivedEvent.getDialog(); TestHarness.assertNotNull( dialog ); if (tid != null) logger.info("transaction state is " + tid.getState()); else logger.info("transaction = " + tid); logger.info("Dialog = " + dialog); logger.info("SHOOTIST: Dialog state is " + dialog.getState()); try { if (response.getStatusCode() == Response.OK) { if (cseq.getMethod().equals(Request.INVITE)) { /* * Can get a late arriving response. */ // TestHarness.assertEquals( DialogState.CONFIRMED, dialog.getState()); Request ackRequest = dialog.createAck(cseq .getSeqNumber()); TestHarness.assertNotNull( ackRequest.getHeader( MaxForwardsHeader.NAME ) ); // Proxy will fork. I will accept the second dialog // but not the first. this.forkedDialogs.add(dialog); logger.info("Sending ACK"); dialog.sendAck(ackRequest); if ( dialog.getState() == DialogState.TERMINATED ) { return; } if ( forkedDialogs.size() == 2 ) { TestHarness.assertTrue( "Dialog state should be CONFIRMED", dialog .getState() == DialogState.CONFIRMED); this.ackedDialog = dialog; // TestHarness.assertNotNull( "JvB: Need CT to find original dialog", tid ); } else { // Kill the first dialog by sending a bye. SipProvider sipProvider = (SipProvider) responseReceivedEvent .getSource(); Request byeRequest = dialog.createRequest(Request.BYE); ClientTransaction ct = sipProvider .getNewClientTransaction(byeRequest); dialog.sendRequest(ct); } } else { logger.info("Response method = " + cseq.getMethod()); } } else if ( response.getStatusCode() == Response.RINGING ) { //TestHarness.assertEquals( DialogState.EARLY, dialog.getState() ); } } catch (Throwable ex) { ex.printStackTrace(); // junit.framework.TestCase.fail("Exit JVM"); } } public SipProvider createSipProvider() { try { listeningPoint = protocolObjects.sipStack.createListeningPoint( host, port, protocolObjects.transport); logger.info("listening point = " + host + " port = " + port); logger.info("listening point = " + listeningPoint); sipProvider = protocolObjects.sipStack .createSipProvider(listeningPoint); return sipProvider; } catch (Exception ex) { logger.error(unexpectedException, ex); TestHarness.fail(unexpectedException); return null; } } public TestAssertion getAssertion() { return new TestAssertion() { @Override public boolean assertCondition() { return (forkedDialogs.size() == 2) && forkedDialogs.contains(originalDialog); } }; } public void checkState() { TestHarness.assertEquals("Should see two distinct dialogs", 2,this.forkedDialogs.size()); TestHarness.assertTrue( "Should see the original (default) dialog in the forked set", this.forkedDialogs.contains(this.originalDialog)); // cleanup forkedDialogs.clear(); } public void processTimeout(javax.sip.TimeoutEvent timeoutEvent) { logger.info("Transaction Time out"); } public void sendInvite() { try { String fromName = "BigGuy"; String fromSipAddress = "here.com"; String fromDisplayName = "The Master Blaster"; String toSipAddress = "there.com"; String toUser = "LittleGuy"; String toDisplayName = "The Little Blister"; // create >From Header SipURI fromAddress = protocolObjects.addressFactory.createSipURI( fromName, fromSipAddress); Address fromNameAddress = protocolObjects.addressFactory .createAddress(fromAddress); fromNameAddress.setDisplayName(fromDisplayName); FromHeader fromHeader = protocolObjects.headerFactory .createFromHeader(fromNameAddress, "12345"); // create To Header SipURI toAddress = protocolObjects.addressFactory.createSipURI( toUser, toSipAddress); Address toNameAddress = protocolObjects.addressFactory .createAddress(toAddress); toNameAddress.setDisplayName(toDisplayName); ToHeader toHeader = protocolObjects.headerFactory.createToHeader( toNameAddress, null); // create Request URI String peerHostPort = peerHost + ":" + peerPort; SipURI requestURI = protocolObjects.addressFactory.createSipURI( toUser, peerHostPort); // Create ViaHeaders ArrayList viaHeaders = new ArrayList(); ViaHeader viaHeader = protocolObjects.headerFactory .createViaHeader(host, sipProvider.getListeningPoint( protocolObjects.transport).getPort(), protocolObjects.transport, null); // add via headers viaHeaders.add(viaHeader); SipURI sipuri = protocolObjects.addressFactory.createSipURI(null, host); sipuri.setPort(peerPort); sipuri.setLrParam(); RouteHeader routeHeader = protocolObjects.headerFactory .createRouteHeader(protocolObjects.addressFactory .createAddress(sipuri)); // Create ContentTypeHeader ContentTypeHeader contentTypeHeader = protocolObjects.headerFactory .createContentTypeHeader("application", "sdp"); // Create a new CallId header CallIdHeader callIdHeader = sipProvider.getNewCallId(); // JvB: Make sure that the implementation matches the messagefactory callIdHeader = protocolObjects.headerFactory .createCallIdHeader(callIdHeader.getCallId()); // Create a new Cseq header CSeqHeader cSeqHeader = protocolObjects.headerFactory .createCSeqHeader(1L, Request.INVITE); // Create a new MaxForwardsHeader MaxForwardsHeader maxForwards = protocolObjects.headerFactory .createMaxForwardsHeader(70); // Create the request. Request request = protocolObjects.messageFactory.createRequest( requestURI, Request.INVITE, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards); // Create contact headers SipURI contactUrl = protocolObjects.addressFactory.createSipURI( fromName, host); contactUrl.setPort(listeningPoint.getPort()); // Create the contact name address. SipURI contactURI = protocolObjects.addressFactory.createSipURI( fromName, host); contactURI.setPort(sipProvider.getListeningPoint( protocolObjects.transport).getPort()); contactURI.setTransportParam(protocolObjects.transport); Address contactAddress = protocolObjects.addressFactory .createAddress(contactURI); // Add the contact address. contactAddress.setDisplayName(fromName); contactHeader = protocolObjects.headerFactory .createContactHeader(contactAddress); request.addHeader(contactHeader); // Dont use the Outbound Proxy. Use Lr instead. request.setHeader(routeHeader); // Add the extension header. Header extensionHeader = protocolObjects.headerFactory .createHeader("My-Header", "my header value"); request.addHeader(extensionHeader); String sdpData = "v=0\r\n" + "o=4855 13760799956958020 13760799956958020" + " IN IP4 129.6.55.78\r\n" + "s=mysession session\r\n" + "p=+46 8 52018010\r\n" + "c=IN IP4 129.6.55.78\r\n" + "t=0 0\r\n" + "m=audio 6022 RTP/AVP 0 4 18\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:4 G723/8000\r\n" + "a=rtpmap:18 G729A/8000\r\n" + "a=ptime:20\r\n"; byte[] contents = sdpData.getBytes(); request.setContent(contents, contentTypeHeader); extensionHeader = protocolObjects.headerFactory.createHeader( "My-Other-Header", "my new header value "); request.addHeader(extensionHeader); Header callInfoHeader = protocolObjects.headerFactory.createHeader( "Call-Info", "<http://www.antd.nist.gov>"); request.addHeader(callInfoHeader); // Create the client transaction. inviteTid = sipProvider.getNewClientTransaction(request); Dialog dialog = inviteTid.getDialog(); TestHarness.assertTrue("Initial dialog state should be null", dialog.getState() == null); // send the request out. inviteTid.sendRequest(); this.originalDialog = dialog; // This is not a valid test. There is a race condition in this test // the response may have already come in and reset the state of the tx // to proceeding. // TestHarness.assertSame( // "Initial transaction state should be CALLING", inviteTid // .getState(), TransactionState.CALLING); } catch (Exception ex) { logger.error(unexpectedException, ex); TestHarness.fail(unexpectedException); } } public void processIOException(IOExceptionEvent exceptionEvent) { logger.info("IOException happened for " + exceptionEvent.getHost() + " port = " + exceptionEvent.getPort()); } public void processTransactionTerminated( TransactionTerminatedEvent transactionTerminatedEvent) { logger.info("Transaction terminated event recieved"); } public void processDialogTerminated( DialogTerminatedEvent dialogTerminatedEvent) { logger.info("dialogTerminatedEvent"); } }
3e10130afbcd63313a00b619f491a54ac161afcc
516
java
Java
src/com/eyelinecom/whoisd/sads2/ccc/api/UserApi.java
kirikprotocol/Chat-call-centre
773491f4617091b4b7c7bce7830b95bf58cd495c
[ "Apache-2.0" ]
null
null
null
src/com/eyelinecom/whoisd/sads2/ccc/api/UserApi.java
kirikprotocol/Chat-call-centre
773491f4617091b4b7c7bce7830b95bf58cd495c
[ "Apache-2.0" ]
null
null
null
src/com/eyelinecom/whoisd/sads2/ccc/api/UserApi.java
kirikprotocol/Chat-call-centre
773491f4617091b4b7c7bce7830b95bf58cd495c
[ "Apache-2.0" ]
null
null
null
25.8
64
0.751938
6,818
package com.eyelinecom.whoisd.sads2.ccc.api; import com.eyelinecom.whoisd.sads2.ccc.model.Operator; import com.eyelinecom.whoisd.sads2.ccc.model.User; /** * Created with IntelliJ IDEA. * User: gev * Date: 17.11.16 * Time: 17:19 * To change this template use File | Settings | File Templates. */ public interface UserApi { User getUser(String subscriber); Operator getAssignedOperator(User user); void sendMessageToOperator(String message, User user); void setUserName(User user, String userName); }
3e1014d571b99e851c33f308496382d7c0e89bac
1,547
java
Java
mantis-test/src/test/java/ru/stqa/pft/github/mantis/appmanager/MailHelper.java
yutta13/java_36
696068cbb731b2a75e08397842a2827e660e8cd5
[ "Apache-2.0" ]
null
null
null
mantis-test/src/test/java/ru/stqa/pft/github/mantis/appmanager/MailHelper.java
yutta13/java_36
696068cbb731b2a75e08397842a2827e660e8cd5
[ "Apache-2.0" ]
null
null
null
mantis-test/src/test/java/ru/stqa/pft/github/mantis/appmanager/MailHelper.java
yutta13/java_36
696068cbb731b2a75e08397842a2827e660e8cd5
[ "Apache-2.0" ]
null
null
null
24.951613
104
0.676794
6,819
package ru.stqa.pft.github.mantis.appmanager; import ru.stqa.pft.github.mantis.model.MailMessage; import org.subethamail.wiser.Wiser; import org.subethamail.wiser.WiserMessage; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; /** * Created by uttabondarenko on 20.02.17. */ public class MailHelper { private ApplicationManager app; private final Wiser wiser; public MailHelper(ApplicationManager app) { this.app = app; wiser = new Wiser(); } public List<MailMessage> waitForMail(int count, long timeout) throws MessagingException, IOException { long start = System.currentTimeMillis(); while (System.currentTimeMillis() < start + timeout) { if (wiser.getMessages().size() >= count) { return wiser.getMessages().stream().map((m) -> toModelMail(m)).collect(Collectors.toList()); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } throw new Error("No mail :("); } public static MailMessage toModelMail(WiserMessage m) { try { MimeMessage mm = m.getMimeMessage(); return new MailMessage(mm.getAllRecipients()[0].toString(), (String) mm.getContent()); } catch (MessagingException | IOException e) { e.printStackTrace(); return null; } } public void start() { wiser.setPort(2223); wiser.start(); } public void stop() { wiser.stop(); } }
3e10163da940a20ea400a12ee6bf2e98eac7afc5
2,153
java
Java
luffy-jtl/src/main/java/org/noear/localjt/widget/JsDialog.java
noear/luffy
35b779bc040e8fd96a283b14679c396920d7ecc5
[ "MIT" ]
6
2021-05-14T08:58:55.000Z
2021-09-13T08:40:59.000Z
luffy-jtl/src/main/java/org/noear/localjt/widget/JsDialog.java
noear/luffy
35b779bc040e8fd96a283b14679c396920d7ecc5
[ "MIT" ]
null
null
null
luffy-jtl/src/main/java/org/noear/localjt/widget/JsDialog.java
noear/luffy
35b779bc040e8fd96a283b14679c396920d7ecc5
[ "MIT" ]
4
2021-05-17T01:26:27.000Z
2021-07-01T10:11:02.000Z
28.328947
78
0.650255
6,820
package org.noear.localjt.widget; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.web.PromptData; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.util.Optional; public class JsDialog { public static void alert(String content) { Alert dialog = new Alert(Alert.AlertType.NONE); dialog.initStyle(StageStyle.UTILITY); dialog.setTitle("提示"); dialog.setHeaderText(null); dialog.setContentText(content); ButtonType okBtn = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE); dialog.getButtonTypes().setAll(okBtn); dialog.showAndWait(); dialog.hide(); } public static boolean confirm(String content) { Alert dialog = new Alert(Alert.AlertType.NONE); dialog.initStyle(StageStyle.UTILITY); dialog.setTitle("确认"); dialog.setHeaderText(null); dialog.setContentText(content); ButtonType okBtn = new ButtonType("确定", ButtonBar.ButtonData.YES); ButtonType cancelBtn = new ButtonType("取消", ButtonBar.ButtonData.NO); dialog.getButtonTypes().setAll(cancelBtn, okBtn); Optional<ButtonType> rst = dialog.showAndWait(); dialog.hide(); return (rst.get() == okBtn); } public static String prompt(PromptData pd) { TextInputDialogX dialog = new TextInputDialogX(pd.getDefaultValue()); dialog.initStyle(StageStyle.UTILITY); dialog.setTitle("输入框"); dialog.setWidth(371); dialog.setContentText(pd.getMessage()); // Traditional way to get the response value. Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { return result.get(); } else { return ""; } } public static WebEngine popup(){ Stage stage = new Stage(StageStyle.UTILITY); WebView popupView = new WebView(); stage.setScene(new Scene(popupView)); stage.show(); return popupView.getEngine(); } }
3e10169f529be6ac1633aeac2704b8e800fc2168
2,059
java
Java
module_news/src/main/java/com/fly/news/util/UserUtils.java
zouyu0008/spring-cloud-flycloud
d5507da91c146661ffdd395d3d15d25ad351a5a2
[ "Apache-2.0" ]
1,228
2019-08-01T01:47:07.000Z
2022-03-26T16:00:04.000Z
module_news/src/main/java/com/fly/news/util/UserUtils.java
liusg110/spring-cloud-flycloud
6cafd8835b24cada6917f40d14e25aeff2a2f9d0
[ "Apache-2.0" ]
5
2019-09-19T09:07:20.000Z
2022-02-20T16:03:37.000Z
module_news/src/main/java/com/fly/news/util/UserUtils.java
liusg110/spring-cloud-flycloud
6cafd8835b24cada6917f40d14e25aeff2a2f9d0
[ "Apache-2.0" ]
398
2019-08-01T12:12:11.000Z
2022-03-11T10:30:50.000Z
23.666667
118
0.61389
6,821
package com.fly.news.util; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import java.util.List; /** * Description: <><br> * Author:    mxdl<br> * Date:     2019/2/19<br> * Version:   V1.0.0<br> * Update:     <br> */ public class UserUtils { private static final String AUTHORIZATION = "authorization"; /** * 获取当前请求的token * * @return */ public static String getCurrentToken() { return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION); } /** * 获取当前请求的用户Id * * @return */ public static String getCurrentPrinciple() { return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } /** * 判读当前token用户是否为接口所需的参数username * * @param username * @return */ public static boolean isMyself(String username) { return username.equals(getCurrentPrinciple()); } /** * 获取当前请求Authentication * * @return */ public static Authentication getCurrentAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 获取当前请求的权限信息 * * @return */ public static List<SimpleGrantedAuthority> getCurrentAuthorities() { return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); } /** * @param role * @return */ public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; } }
3e101848935aac1417a02247a7fe38d15f79c8fa
2,875
java
Java
api-model/src/main/java/io/enmasse/admin/model/v1/AddressPlan.java
myeung18/enmasse
10ea3d391fe67c74dc02dedf873de65616746d48
[ "Apache-2.0" ]
1
2020-07-09T12:07:51.000Z
2020-07-09T12:07:51.000Z
api-model/src/main/java/io/enmasse/admin/model/v1/AddressPlan.java
obabec/enmasse
1479dd4cc47ff6c3a5ed60060a2109239c182e1d
[ "Apache-2.0" ]
1
2019-11-27T14:38:41.000Z
2019-11-27T14:45:31.000Z
api-model/src/main/java/io/enmasse/admin/model/v1/AddressPlan.java
obabec/enmasse
1479dd4cc47ff6c3a5ed60060a2109239c182e1d
[ "Apache-2.0" ]
null
null
null
26.378378
137
0.64515
6,822
/* * Copyright 2018, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.admin.model.v1; import com.fasterxml.jackson.annotation.JsonIgnore; import io.enmasse.address.model.MessageTtl; import io.enmasse.common.model.DefaultCustomResource; import io.fabric8.kubernetes.api.model.Doneable; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import io.sundr.builder.annotations.Inline; import java.util.Map; import java.util.Objects; @Buildable( editableEnabled = false, generateBuilderPackage = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs= nnheo@example.com)}, inline = @Inline(type = Doneable.class, prefix = "Doneable", value = "done") ) @DefaultCustomResource @SuppressWarnings("serial") public class AddressPlan extends AbstractHasMetadataWithAdditionalProperties<AddressPlan> implements io.enmasse.admin.model.AddressPlan { public static final String KIND = "AddressPlan"; private AddressPlanSpec spec; private AddressPlanStatus status; public AddressPlan() { super(KIND, AdminCrd.API_VERSION_V1BETA2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AddressPlan that = (AddressPlan) o; return Objects.equals(getMetadata(), that.getMetadata()) && Objects.equals(spec, that.spec); } @Override public int hashCode() { return Objects.hash(getMetadata(), spec); } @Override public String toString() { return "AddressPlan{" + "metadata='" + getMetadata() + '\'' + ", spec ='" + spec + '\'' + '}'; } public void setSpec(AddressPlanSpec spec) { this.spec = spec; } public AddressPlanSpec getSpec() { return spec; } @Override @JsonIgnore public String getShortDescription() { return spec.getShortDescription(); } @Override @JsonIgnore public String getAddressType() { return spec.getAddressType(); } @Override @JsonIgnore public Map<String, Double> getResources() { return spec.getResources(); } @Override @JsonIgnore public int getPartitions() { if (spec.getPartitions() != null) { return spec.getPartitions(); } else { return 1; } } @Override @JsonIgnore public MessageTtl getTtl() { return spec == null ? null : spec.getMessageTtl(); } public AddressPlanStatus getStatus() { return status; } public void setStatus(AddressPlanStatus status) { this.status = status; } }
3e101913fc9f5c9c254e65443158cfa687803f02
827
java
Java
gx/gx-core/src/main/java/io/graphenee/core/model/BeanResolver.java
MuhammadHamzaABCD/graphenee
98f14c930f90621a904449a222d5a142fac8550b
[ "Apache-2.0" ]
12
2018-05-21T04:08:27.000Z
2021-11-29T10:55:27.000Z
gx/gx-core/src/main/java/io/graphenee/core/model/BeanResolver.java
MuhammadHamzaABCD/graphenee
98f14c930f90621a904449a222d5a142fac8550b
[ "Apache-2.0" ]
29
2018-05-10T09:41:19.000Z
2022-02-22T04:41:31.000Z
gx/gx-core/src/main/java/io/graphenee/core/model/BeanResolver.java
MuhammadHamzaABCD/graphenee
98f14c930f90621a904449a222d5a142fac8550b
[ "Apache-2.0" ]
27
2018-05-10T10:04:19.000Z
2022-03-29T09:34:32.000Z
39.380952
81
0.598549
6,823
/******************************************************************************* * Copyright (c) 2016, 2018 Farrukh Ijaz * * 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 io.graphenee.core.model; public class BeanResolver { }
3e10194db38798ac7c38193a177d7a5f61aba812
891
java
Java
src/jeu/computer/MainTestComputer.java
hanzopgp/TetrisRevisitedGame
d283f64eba1a68144369c30dda196f99b6a74fd9
[ "MIT" ]
2
2020-11-23T16:45:00.000Z
2020-12-01T18:51:08.000Z
src/jeu/computer/MainTestComputer.java
hanzopgp/TetrisRevisitedGame
d283f64eba1a68144369c30dda196f99b6a74fd9
[ "MIT" ]
null
null
null
src/jeu/computer/MainTestComputer.java
hanzopgp/TetrisRevisitedGame
d283f64eba1a68144369c30dda196f99b6a74fd9
[ "MIT" ]
null
null
null
27.84375
116
0.602694
6,824
package jeu.computer; import jeu.Main; import jeu.factory.Piece; import jeu.model.Board; public class MainTestComputer { /** * Main de la classe permettant de tester les methodes lies a l'implementation de l'IA Tetris * @param args parametre du main */ public static void main(String[] args){ // System.out.println("TEST VALID MOVES"); // Board board = new Board(10, 10, null); // board.fillBoardRandomly(2); // System.out.println("BOARD DE BASE : "); // System.out.println(board); // for(Piece p : board.getListPiece()){ // System.out.println("PIECE : " + p.getFilling() + ", nbvalidmoves : " + board.getValidMoves(p).size()); // } System.out.println("TEST SOLVER"); Solver solver = new Solver(); solver.boardGenerator(10, 10, 7); //8 8 6 solver.execSolve(0); } }
3e101acdce54222a58212735991840b17cc9a140
474
java
Java
src/main/java/io/github/astrapi69/crypt/info/jpa/repository/ResourcesRepository.java
astrapi69/crypt-info
2780e86a5fc60dcb66ba42bc5e9f3b819fc040ae
[ "MIT" ]
null
null
null
src/main/java/io/github/astrapi69/crypt/info/jpa/repository/ResourcesRepository.java
astrapi69/crypt-info
2780e86a5fc60dcb66ba42bc5e9f3b819fc040ae
[ "MIT" ]
null
null
null
src/main/java/io/github/astrapi69/crypt/info/jpa/repository/ResourcesRepository.java
astrapi69/crypt-info
2780e86a5fc60dcb66ba42bc5e9f3b819fc040ae
[ "MIT" ]
null
null
null
29.625
75
0.833333
6,825
package io.github.astrapi69.crypt.info.jpa.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import io.github.astrapi69.crypt.info.jpa.entity.Resources; import java.util.List; import java.util.UUID; @Repository public interface ResourcesRepository extends JpaRepository<Resources, UUID> { List<Resources> findByDescription(String description); List<Resources> findByFilename(String filename); }
3e101c2ca745d88a466f03772f2e080040caf8ab
7,130
java
Java
src/test/java/seedu/meeting/logic/commands/LeaveCommandTest.java
betakuwe/main
787928fc90262fb2e1c3c8c664917f619cb16526
[ "MIT" ]
null
null
null
src/test/java/seedu/meeting/logic/commands/LeaveCommandTest.java
betakuwe/main
787928fc90262fb2e1c3c8c664917f619cb16526
[ "MIT" ]
203
2018-09-04T17:40:40.000Z
2018-11-12T15:55:32.000Z
src/test/java/seedu/meeting/logic/commands/LeaveCommandTest.java
betakuwe/main
787928fc90262fb2e1c3c8c664917f619cb16526
[ "MIT" ]
6
2018-09-04T14:33:10.000Z
2018-10-28T22:00:31.000Z
34.95098
115
0.686957
6,826
package seedu.meeting.logic.commands; import static java.util.Objects.requireNonNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.meeting.commons.core.Messages.MESSAGE_GROUP_NOT_FOUND; import static seedu.meeting.commons.core.Messages.MESSAGE_PERSON_NOT_FOUND; import static seedu.meeting.commons.util.CollectionUtil.requireAllNonNull; import static seedu.meeting.testutil.TypicalGroups.GROUP_2101; import static seedu.meeting.testutil.TypicalPersons.ALICE; import static seedu.meeting.testutil.TypicalPersons.BENSON; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import seedu.meeting.logic.CommandHistory; import seedu.meeting.logic.commands.exceptions.CommandException; import seedu.meeting.model.MeetingBook; import seedu.meeting.model.ReadOnlyMeetingBook; import seedu.meeting.model.group.Group; import seedu.meeting.model.person.Name; import seedu.meeting.model.person.Person; import seedu.meeting.model.shared.Title; import seedu.meeting.testutil.GroupBuilder; import seedu.meeting.testutil.ModelStub; import seedu.meeting.testutil.PersonBuilder; import seedu.meeting.testutil.TypicalGroups; import seedu.meeting.testutil.TypicalPersons; public class LeaveCommandTest { private static final CommandHistory EMPTY_COMMAND_HISTORY = new CommandHistory(); @Rule public ExpectedException thrown = ExpectedException.none(); private CommandHistory commandHistory = new CommandHistory(); @Test public void constructor_nullGroup_throwsNullPointerException() { thrown.expect(NullPointerException.class); Person person = new PersonBuilder().build(); new LeaveCommand(person, null); } @Test public void constructor_nullPerson_throwsNullPointerException() { thrown.expect(NullPointerException.class); Group group = new GroupBuilder().build(); new LeaveCommand(null, group); } @Test public void execute_acceptedByModel_leaveSuccessful() throws Exception { ModelStubAcceptingPersonLeft modelStub = new ModelStubAcceptingPersonLeft(); Group validGroup = GROUP_2101.copy(); Person validPerson = BENSON.copy(); validGroup.addMember(validPerson); modelStub.updatePerson(BENSON, validPerson); modelStub.updateGroup(GROUP_2101, validGroup); CommandResult commandResult = new LeaveCommand(validPerson, validGroup).execute(modelStub, commandHistory); assertEquals(String.format(LeaveCommand.MESSAGE_LEAVE_SUCCESS, validPerson.getName().fullName, validGroup.getTitle().fullTitle), commandResult.feedbackToUser); assertEquals(EMPTY_COMMAND_HISTORY, commandHistory); } @Test public void execute_groupNotFound_throwsCommandException() throws Exception { Person validPerson = ALICE.copy(); Group invalidGroup = new GroupBuilder().withTitle("Mystery").build(); LeaveCommand leaveCommand = new LeaveCommand(validPerson, invalidGroup); ModelStubAcceptingPersonLeft modelStub = new ModelStubAcceptingPersonLeft(); thrown.expect(CommandException.class); thrown.expectMessage(MESSAGE_GROUP_NOT_FOUND); leaveCommand.execute(modelStub, commandHistory); } @Test public void execute_personNotFound_throwsCommandException() throws Exception { Person invalidPerson = new PersonBuilder().withName("Derek").build(); Group validGroup = GROUP_2101.copy(); LeaveCommand leaveCommand = new LeaveCommand(invalidPerson, validGroup); ModelStubAcceptingPersonLeft modelStub = new ModelStubAcceptingPersonLeft(); thrown.expect(CommandException.class); thrown.expectMessage(MESSAGE_PERSON_NOT_FOUND); leaveCommand.execute(modelStub, commandHistory); } @Test public void equals() { Group network = new GroupBuilder().withTitle("CS2105").build(); Person hardy = new PersonBuilder().withName("hardy").build(); Group software = new GroupBuilder().withTitle("CS2103").build(); Person derek = new PersonBuilder().withName("derek").build(); LeaveCommand leaveCommand1 = new LeaveCommand(hardy, network); LeaveCommand leaveCommand2 = new LeaveCommand(derek, software); // same object -> returns true assertTrue(leaveCommand1.equals(leaveCommand1)); // same values -> returns true LeaveCommand leaveCommand1Copy = new LeaveCommand(hardy, network); assertTrue(leaveCommand1Copy.equals(leaveCommand1)); // different types -> returns false assertFalse(leaveCommand1.equals(2)); // null -> returns false assertFalse(leaveCommand1.equals(null)); // different person -> returns false assertFalse(leaveCommand1.equals(leaveCommand2)); } /** * A Model stub that always accept the group being removed. */ private class ModelStubAcceptingPersonLeft extends ModelStub { private List<Group> groupsJoined = new ArrayList<>(TypicalGroups.getTypicalGroups()); private List<Person> personList = new ArrayList<>(TypicalPersons.getTypicalPersons()); @Override public void updatePerson(Person target, Person editedPerson) { requireAllNonNull(target, editedPerson); personList.remove(target); personList.add(editedPerson); } @Override public void updateGroup(Group target, Group editedGroup) { requireAllNonNull(target, editedGroup); groupsJoined.remove(target); groupsJoined.add(editedGroup); } @Override public void leaveGroup(Person person, Group group) { requireAllNonNull(person, group); Person personCopy = person.copy(); Group groupCopy = group.copy(); group.removeMember(person); updatePerson(personCopy, person); updateGroup(groupCopy, group); } @Override public Group getGroupByTitle(Title title) { requireNonNull(title); for (Group group : groupsJoined) { Title groupTitle = group.getTitle(); if (groupTitle.equals(title)) { return group.copy(); } } return null; } @Override public Person getPersonByName(Name name) { requireNonNull(name); for (Person person : personList) { Name personName = person.getName(); if (personName.equals(name)) { return person.copy(); } } return null; } @Override public void commitMeetingBook() { // called by {@code AddCommand#execute()} } @Override public ReadOnlyMeetingBook getMeetingBook() { return new MeetingBook(); } } }
3e101c2cbd3378839ddea0de53ccd604ca06d78c
721
java
Java
src/main/java/com/niraj/model/user.java
Niraj-Ranjan/CRUD-Application-using-Servlet-And-JSP
f0d6eef3fd4666c724204a59be0e3d4c8121a1cc
[ "Apache-2.0" ]
null
null
null
src/main/java/com/niraj/model/user.java
Niraj-Ranjan/CRUD-Application-using-Servlet-And-JSP
f0d6eef3fd4666c724204a59be0e3d4c8121a1cc
[ "Apache-2.0" ]
null
null
null
src/main/java/com/niraj/model/user.java
Niraj-Ranjan/CRUD-Application-using-Servlet-And-JSP
f0d6eef3fd4666c724204a59be0e3d4c8121a1cc
[ "Apache-2.0" ]
null
null
null
17.585366
101
0.654646
6,827
package com.niraj.model; public class user { private int id; private String fname; private String uname; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "user [id=" + id + ", fname=" + fname + ", uname=" + uname + ", password=" + password + "]"; } }
3e101cd94c3341367ae324a93a97e7e965e09b54
1,946
java
Java
src/StatsView.java
JohnBrodie/visual-kanban
95f189ab8a38d916af6e752d561c50f9db035e5e
[ "MIT" ]
null
null
null
src/StatsView.java
JohnBrodie/visual-kanban
95f189ab8a38d916af6e752d561c50f9db035e5e
[ "MIT" ]
null
null
null
src/StatsView.java
JohnBrodie/visual-kanban
95f189ab8a38d916af6e752d561c50f9db035e5e
[ "MIT" ]
null
null
null
25.272727
71
0.737924
6,828
/* * John Brodie * anpch@example.com * CS338:GUI, Assignment 3 */ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.io.Serializable; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import org.jfree.chart.ChartPanel; public class StatsView extends JFrame implements Serializable { private static final long serialVersionUID = -9197648191136657682L; public StatsController controller; JPanel centerPanel = new JPanel(); /* Title Panel */ JPanel titlePanel = new JPanel(); JButton refreshButton = new JButton("Refresh"); private String[] chartOptions = {"Card Types", "Card Priorities"}; JComboBox selectBox = new JComboBox(chartOptions); /* Type Panel */ ChartPanel typeChartPanel; /* Priority Panel */ ChartPanel prioChartPanel; public StatsView(StatsController controller) { this.controller = controller; this.setLayout(new BorderLayout()); titlePanel.setLayout(new BoxLayout(titlePanel, BoxLayout.LINE_AXIS)); this.setTitle("Visual KanBan Stats Version 1.0"); /* public domain icon from http://bit.ly/NRxwCf */ this.setIconImage(Toolkit.getDefaultToolkit() .getImage("k.png")); } public void CreateGUI() { centerPanel.setPreferredSize(new Dimension(800, 450)); /* Title Panel */ titlePanel.add(refreshButton); titlePanel.add(Box.createHorizontalGlue()); titlePanel.add(new JLabel("Chart Type: ")); titlePanel.add(selectBox); this.add(titlePanel, BorderLayout.NORTH); /* Type Panel */ typeChartPanel = new ChartPanel(controller.createTypeChart()); centerPanel.add(typeChartPanel); this.add(centerPanel, BorderLayout.CENTER); /* Priority Panel */ prioChartPanel = new ChartPanel(controller.createPrioChart()); pack(); } protected void update() { } }
3e101cf18319a0c8fe5ff65b7a10dd531eab7d1b
61
java
Java
sodo-goods/src/main/java/cool/sodo/goods/common/Constants.java
Irvingsoft/sodo-platform
77dadb96b9709e5385258ef09eeed598cea5c670
[ "MulanPSL-1.0" ]
3
2022-01-28T10:26:40.000Z
2022-01-28T14:20:26.000Z
sodo-goods/src/main/java/cool/sodo/goods/common/Constants.java
Irvingsoft/sodo-platform
77dadb96b9709e5385258ef09eeed598cea5c670
[ "MulanPSL-1.0" ]
null
null
null
sodo-goods/src/main/java/cool/sodo/goods/common/Constants.java
Irvingsoft/sodo-platform
77dadb96b9709e5385258ef09eeed598cea5c670
[ "MulanPSL-1.0" ]
null
null
null
10.166667
31
0.754098
6,829
package cool.sodo.goods.common; public class Constants { }