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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9241a194a1ac02ad1b58c3c110a3998a8a4ebeb5
| 1,943 |
java
|
Java
|
game_part/src/main/java/com/game/part/io/SyncIoOperProc.java
|
cietwwl/xgame-code_server
|
2fc08d9207223a60069d7c50332e09064cd1e8e0
|
[
"Apache-2.0"
] | 12 |
2015-07-04T07:39:09.000Z
|
2020-12-26T12:23:18.000Z
|
game_part/src/main/java/com/game/part/io/SyncIoOperProc.java
|
cietwwl/xgame-code_server
|
2fc08d9207223a60069d7c50332e09064cd1e8e0
|
[
"Apache-2.0"
] | 1 |
2021-06-23T20:39:28.000Z
|
2021-06-23T20:39:28.000Z
|
game_part/src/main/java/com/game/part/io/SyncIoOperProc.java
|
hjj2017/xgame-code_server
|
2fc08d9207223a60069d7c50332e09064cd1e8e0
|
[
"Apache-2.0"
] | 5 |
2016-11-30T08:19:07.000Z
|
2020-08-16T07:07:51.000Z
| 18.864078 | 59 | 0.454967 | 1,001,974 |
package com.game.part.io;
/**
* 同步的 IO 工作过程
*
* @author haijiang
*
*/
class SyncIoOperProc implements IIoOperProc<IIoOper> {
/** 单例对象 */
static final SyncIoOperProc OBJ = new SyncIoOperProc();
/**
* 类默认构造器
*
*/
private SyncIoOperProc() {
}
@Override
public void execute(IIoOper oper) {
if (oper == null) {
return;
}
// 将异步操作包装成一个有状态的对象,
// 然后带入 invokeDoInit, invokeDoIo 函数中!
this.nextStep(new StatefulIoOper(oper));
}
/**
* 调用异步操作对象的 doInit 函数
*
* @param oper
*/
private void invokeDoInit(StatefulIoOper oper) {
if (oper == null) {
return;
}
try {
// 执行初始化操作并进入下一步!
oper.doInit();
this.nextStep(oper);
} catch (Exception ex) {
// 记录错误日志
IoOperLog.LOG.error(ex.getMessage(), ex);
}
}
/**
* 调用异步操作对象的 doIo 函数
*
* @param oper
*/
private void invokeDoIo(StatefulIoOper oper) {
if (oper == null) {
return;
}
try {
// 执行 IO 操作
oper.doIo();
} catch (Exception ex) {
// 记录错误日志
IoOperLog.LOG.error(ex.getMessage(), ex);
}
}
/**
* 执行下异步操作
*
* @param oper
*/
private void nextStep(StatefulIoOper oper) {
if (oper == null) {
return;
}
// 获取当前工作状态
IoOperStateEnum currState = oper.getCurrState();
if (currState == null) {
this.invokeDoInit(oper);
return;
}
switch (oper.getCurrState()) {
case exit:
case ioFinishOk:
return;
case initOk:
// 执行异步过程
this.invokeDoIo(oper);
return;
default:
return;
}
}
}
|
9241a1990d15472f0daf95401a7e0fc54095fe47
| 2,011 |
java
|
Java
|
currency-conversion/src/main/java/com/ubaid/ms/currencyconversion/service/RequestServiceImpl.java
|
JongbaekKIm/pratice_MSA_K8S_Keycloak
|
7eeb2899ce0852d05592215997973c81f0a2e833
|
[
"MIT"
] | 19 |
2020-10-04T16:50:44.000Z
|
2022-03-31T05:27:40.000Z
|
currency-conversion/src/main/java/com/ubaid/ms/currencyconversion/service/RequestServiceImpl.java
|
JongbaekKIm/pratice_MSA_K8S_Keycloak
|
7eeb2899ce0852d05592215997973c81f0a2e833
|
[
"MIT"
] | 197 |
2020-10-02T17:56:18.000Z
|
2022-03-27T16:54:52.000Z
|
currency-conversion/src/main/java/com/ubaid/ms/currencyconversion/service/RequestServiceImpl.java
|
JongbaekKIm/pratice_MSA_K8S_Keycloak
|
7eeb2899ce0852d05592215997973c81f0a2e833
|
[
"MIT"
] | 4 |
2022-01-17T20:57:56.000Z
|
2022-02-13T14:18:44.000Z
| 35.280702 | 86 | 0.652412 | 1,001,975 |
package com.ubaid.ms.currencyconversion.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static com.ubaid.ms.common.util.Constants.UNKNOWN;
@Service
@RequiredArgsConstructor
@Slf4j
public class RequestServiceImpl implements RequestService {
private static final String LOCALHOST_IPV4 = "127.0.0.1";
private static final String LOCALHOST_IPV6 = "0:0:0:0:0:0:0:1";
private final HttpServletRequest request;
@Override
public String getClientIP() {
log.debug("Getting Client IP Address");
String ipAddress = request.getHeader("X-Forwarded-For");
if(StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if(StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if(StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if(LOCALHOST_IPV4.equals(ipAddress) || LOCALHOST_IPV6.equals(ipAddress)) {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
ipAddress = inetAddress.getHostAddress();
} catch (UnknownHostException e) {
log.error("Unknown Exception while getting Client IP address", e);
}
}
}
if(!StringUtils.isEmpty(ipAddress)
&& ipAddress.length() > 15
&& ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
log.debug("Client IP address: {}", ipAddress);
return ipAddress;
}
}
|
9241a1d060c6c404fd067bd5013921b39f84cc81
| 2,956 |
java
|
Java
|
src/main/java/com/adamk33n3r/runelite/watchdog/FlashOverlay.java
|
adamk33n3r/RuneLiteNarration
|
594e11e0347ce3932c2816c6605ddd01d24f3401
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/com/adamk33n3r/runelite/watchdog/FlashOverlay.java
|
adamk33n3r/RuneLiteNarration
|
594e11e0347ce3932c2816c6605ddd01d24f3401
|
[
"BSD-2-Clause"
] | null | null | null |
src/main/java/com/adamk33n3r/runelite/watchdog/FlashOverlay.java
|
adamk33n3r/RuneLiteNarration
|
594e11e0347ce3932c2816c6605ddd01d24f3401
|
[
"BSD-2-Clause"
] | null | null | null | 36.04878 | 127 | 0.644114 | 1,001,976 |
package com.adamk33n3r.runelite.watchdog;
import com.adamk33n3r.runelite.watchdog.notifications.ScreenFlash;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.client.config.FlashNotification;
import net.runelite.client.ui.ClientUI;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayLayer;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import javax.inject.Inject;
import java.awt.*;
import java.time.Instant;
import static net.runelite.api.widgets.WidgetID.*;
@Slf4j
public class FlashOverlay extends Overlay {
@Inject
private Client client;
@Inject
private ClientUI clientUI;
private Instant flashStart;
private long mouseLastPressedMillis;
private ScreenFlash screenFlash;
public FlashOverlay() {
this.setPosition(OverlayPosition.DYNAMIC);
this.setLayer(OverlayLayer.ALWAYS_ON_TOP);
}
public void flash(ScreenFlash screenFlash) {
this.screenFlash = screenFlash;
this.flashStart = Instant.now();
this.mouseLastPressedMillis = client.getMouseLastPressedMillis();
}
@Override
public Dimension render(Graphics2D graphics) {
// Copied from Notifier
if (this.flashStart == null) {
return null;
}
if (Instant.now().minusMillis(2000).isAfter(this.flashStart)) {
switch (this.screenFlash.flashNotification)
{
case FLASH_TWO_SECONDS:
case SOLID_TWO_SECONDS:
flashStart = null;
return null;
case SOLID_UNTIL_CANCELLED:
case FLASH_UNTIL_CANCELLED:
// Any interaction with the client since the notification started will cancel it after the minimum duration
if ((client.getMouseIdleTicks() < 2000 / Constants.CLIENT_TICK_LENGTH
|| client.getKeyboardIdleTicks() < 2000 / Constants.CLIENT_TICK_LENGTH
|| client.getMouseLastPressedMillis() > mouseLastPressedMillis) && clientUI.isFocused())
{
flashStart = null;
return null;
}
break;
}
}
// Me: This can be weird depending on which game cycle the flash is fired
if (client.getGameCycle() % 40 >= 20
// For solid colour, fall through every time.
&& (this.screenFlash.flashNotification == FlashNotification.FLASH_TWO_SECONDS
|| this.screenFlash.flashNotification == FlashNotification.FLASH_UNTIL_CANCELLED))
{
return null;
}
graphics.setColor(this.screenFlash.color);
graphics.fill(new Rectangle(this.client.getCanvas().getSize()));
return null;
}
}
|
9241a2d18fa0e569e96e2bb2e9d8aa23e2334ff9
| 1,172 |
java
|
Java
|
src/main/java/frc/robot/constants/AutoConstants.java
|
Arctos6135/frc-2022-updated
|
ef370c36789c2671a6562be1c76996db923b28ae
|
[
"BSD-3-Clause"
] | 2 |
2022-03-10T16:23:04.000Z
|
2022-03-10T16:23:07.000Z
|
src/main/java/frc/robot/constants/AutoConstants.java
|
Arctos6135/frc-2022-updated
|
ef370c36789c2671a6562be1c76996db923b28ae
|
[
"BSD-3-Clause"
] | 1 |
2022-02-23T03:52:23.000Z
|
2022-02-23T03:52:23.000Z
|
src/main/java/frc/robot/constants/AutoConstants.java
|
Arctos6135/frc-2022-updated
|
ef370c36789c2671a6562be1c76996db923b28ae
|
[
"BSD-3-Clause"
] | null | null | null | 36.625 | 74 | 0.75256 | 1,001,977 |
package frc.robot.constants;
import edu.wpi.first.math.kinematics.DifferentialDriveKinematics;
public class AutoConstants {
public static final double ksVolts = 0;
public static final double kvVoltSecondsPerMeter = 0;
public static final double kaVoltSecondsSquaredPerMeter = 0.0;
public static final double kPDriveVel = 0;
public static final double kDDriveVel = 0;
public static final double maxVoltage = 10;
// Horizontal distance between wheels
public static final double kTrackWidthMeters = 0;
public static final DifferentialDriveKinematics kDriveKinematics =
new DifferentialDriveKinematics(kTrackWidthMeters);
public static final double kMaxSpeedMetersPerSecond = 0;
public static final double kMaxAccelerationMetersPerSecondSquared = 0;
public static final double kRamseteB = 2;
public static final double kRamseteZeta = 0.7;
public static final double AUTO_MECANUM_SPEED = 0.5;
public static final double AUTO_INTAKE_ROLLER_SPEED = 0.75;
public static final double AUTO_ROLL_SPEED = 0.5;
public static final double THREE_BALL_AUTO_ROLL_SPEED = 1.00;
}
|
9241a2ed7637aab9bafffb519716a99b889becfb
| 2,108 |
java
|
Java
|
com/planet_ink/coffee_mud/Items/Basic/Asteroid.java
|
count-infinity/CoffeeMud
|
df458b8721af831f53d7f3275ab32c8c378c2241
|
[
"Apache-2.0"
] | 149 |
2015-01-11T12:55:39.000Z
|
2022-03-03T16:14:48.000Z
|
com/planet_ink/coffee_mud/Items/Basic/Asteroid.java
|
count-infinity/CoffeeMud
|
df458b8721af831f53d7f3275ab32c8c378c2241
|
[
"Apache-2.0"
] | 42 |
2015-02-08T03:44:01.000Z
|
2022-02-10T08:52:43.000Z
|
com/planet_ink/coffee_mud/Items/Basic/Asteroid.java
|
count-infinity/CoffeeMud
|
df458b8721af831f53d7f3275ab32c8c378c2241
|
[
"Apache-2.0"
] | 104 |
2015-01-21T20:20:55.000Z
|
2022-03-24T05:01:20.000Z
| 38.327273 | 150 | 0.756167 | 1,001,978 |
package com.planet_ink.coffee_mud.Items.Basic;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2014-2021 Bo Zimmerman
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.
*/
public class Asteroid extends GenSpaceBody
{
@Override
public String ID()
{
return "Asteroid";
}
public Asteroid()
{
super();
setName("an asteroid");
setDisplayText("an asteroid is here");
setDescription("it`s a big rock");
coordinates=new long[]{Math.round(Long.MAX_VALUE*Math.random()),Math.round(Long.MAX_VALUE*Math.random()),Math.round(Long.MAX_VALUE*Math.random())};
final Random random=new Random(System.currentTimeMillis());
radius=(5*SpaceObject.Distance.Kilometer.dm) + (random.nextLong() % (4*SpaceObject.Distance.Kilometer.dm));
recoverPhyStats();
}
}
|
9241a511be883195ef15aa6330279f150e4ecc09
| 57,190 |
java
|
Java
|
src/common/com/intellij/plugins/haxe/haxelib/HaxelibProjectUpdater.java
|
demurgos/intellij-haxe
|
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
|
[
"Apache-2.0"
] | 124 |
2017-01-04T14:02:38.000Z
|
2022-03-01T01:42:07.000Z
|
src/common/com/intellij/plugins/haxe/haxelib/HaxelibProjectUpdater.java
|
demurgos/intellij-haxe
|
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
|
[
"Apache-2.0"
] | 455 |
2017-01-10T03:44:40.000Z
|
2022-02-01T16:13:54.000Z
|
src/common/com/intellij/plugins/haxe/haxelib/HaxelibProjectUpdater.java
|
demurgos/intellij-haxe
|
f6d85d14a77c35f5b16b6cd2fcd53a97d00f2478
|
[
"Apache-2.0"
] | 59 |
2017-01-20T07:46:49.000Z
|
2022-03-26T13:15:50.000Z
| 35.923367 | 143 | 0.65132 | 1,001,979 |
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2014 AS3Boyan
* Copyright 2014-2014 Elias Ku
* Copyright 2017-2018 Eric Bishton
*
* 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.intellij.plugins.haxe.haxelib;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.progress.PerformInBackgroundOption;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.*;
import com.intellij.plugins.haxe.build.IdeaTarget;
import com.intellij.plugins.haxe.build.MethodWrapper;
import com.intellij.plugins.haxe.config.HaxeConfiguration;
import com.intellij.plugins.haxe.config.sdk.HaxeSdkType;
import com.intellij.plugins.haxe.hxml.HXMLFileType;
import com.intellij.plugins.haxe.hxml.model.HXMLProjectModel;
import com.intellij.plugins.haxe.ide.module.HaxeModuleSettings;
import com.intellij.plugins.haxe.ide.module.HaxeModuleType;
import com.intellij.plugins.haxe.nmml.NMMLFileType;
import com.intellij.plugins.haxe.util.HaxeDebugTimeLog;
import com.intellij.plugins.haxe.util.HaxeDebugUtil;
import com.intellij.plugins.haxe.util.HaxeFileUtil;
import com.intellij.plugins.haxe.util.Lambda;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlFile;
import org.apache.log4j.Level;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.LocalFileFinder;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Manages Haxe library class paths across projects.
*
* This class is intended to keep the class paths up to date as the projects
* and module settings change. It encapsulates reading classpaths from the
* various types of Haxe project definitions (OpenFL, NME, etc.) and adding
* them to module settings so that the paths available at runtime are also
* available when writing the code.
*
*
* Implementation Note: We might need to track each module separately, in a
* list attached to the project. We'd need that in case we can update the
* project fast enough that all of the modules haven't been opened yet.
* However, this is unlikely, since the first project update run takes place
* after the project has finished initializing, and the open notifications
* come during initialization.
*
*/
public class HaxelibProjectUpdater {
static Logger LOG = Logger.getInstance("#com.intellij.plugins.haxe.haxelib.HaxelibManager");
{
LOG.setLevel(Level.DEBUG);
}
/**
* Set this to run in the foreground for speed testing.
* It overrides myRunInForeground. The UI is blocked with no updates.
*/
private static final boolean myTestInForeground = false;
/**
* Set this true to put up a modal dialog and run in the foreground thread
* (locking up the UI.)
* Set it false to run in a background thread. Progress is updated in the
* status bar and the UI is usable.
*/
private static final boolean myRunInForeground = false;
public static final HaxelibProjectUpdater INSTANCE = new HaxelibProjectUpdater();
private ProjectUpdateQueue myQueue = null;
private ProjectMap myProjects = null;
private HaxelibProjectUpdater() {
myQueue = new ProjectUpdateQueue();
myProjects = new ProjectMap();
}
@NotNull
static HaxelibProjectUpdater getInstance() {
return INSTANCE;
}
/**
* Adds a new project to the manager. This is normally called in response to a
* ModuleComponent.openProject() notification. Multiple modules referencing
* the same project cause a counter to be incremented.
*
* @param project that is being opened.
*/
public void openProject(@NotNull Project project) {
ProjectTracker tracker = myProjects.add(project);
tracker.setDirty(true);
myQueue.add(tracker);
}
/**
* Close and possibly remove a project, if the reference count has been exhausted.
*
* @param project to close
* @return whether the close has been delayed because an update is in process.
*/
public boolean closeProject(Project project) {
boolean delayed = false;
boolean removed = false;
ProjectTracker tracker = myProjects.get(project);
removed = myProjects.remove(project);
if (removed) {
myQueue.remove(tracker);
if (tracker.equals(myQueue.getUpdatingProject())) {
delayed = true;
}
}
return delayed;
}
/**
* Retrieve the HaxelibLibraryCacheManager for a given module/project.
* <p>
* Convenience function that doesn't quite match the purpose of this class,
* but we haven't made the CacheManager a singleton -- and we really can't
* unless we move the notion of a project into it.
*
* @param module that we need the HaxelibLibraryCacheManager for.
* @return the appropriate HaxelibLibraryCacheManager.
*/
@Nullable
public HaxelibLibraryCacheManager getLibraryCacheManager(@NotNull Module module) {
return getLibraryCacheManager(module.getProject());
}
/**
* Retrieve the HaxelibLibraryCacheManager for a given module/project.
* <p>
* Convenience function that doesn't quite match the purpose of this class,
* but we haven't made the CacheManager a singleton -- and we really can't
* unless we move the notion of a project into it.
*
* @param project that we need the HaxelibLibraryCacheManager for.
* @return the appropriate HaxelibLibraryCacheManager.
*/
@Nullable
public HaxelibLibraryCacheManager getLibraryCacheManager(@NotNull Project project) {
ProjectTracker tracker = myProjects.get(project);
return null == tracker ? null : tracker.getSdkManager();
}
/**
* Retrieve the library cache for a given module.
* <p>
* Convenience function that doesn't quite match the purpose of this class,
* but we haven't made the CacheManager a singleton -- and we really can't
* unless we move the notion of a project into it.
*
* @param module
* @return the HaxelibLibraryCache for the module, if found; null, otherwise.
*/
@Nullable
public static HaxelibLibraryCache getLibraryCache(@NotNull Module module) {
HaxelibLibraryCacheManager mgr = HaxelibProjectUpdater.getInstance().getLibraryCacheManager(module);
return mgr != null ? mgr.getLibraryManager(module) : null;
}
/**
* Retrieve the library cache for a given module.
* <p>
* Convenience function that doesn't quite match the purpose of this class,
* but we haven't made the CacheManager a singleton -- and we really can't
* unless we move the notion of a project into it.
*
* @param project
* @return the HaxelibLibraryCache for the project, if found; null, otherwise.
*/
@Nullable
public static HaxelibLibraryCache getLibraryCache(@NotNull Project project) {
HaxelibLibraryCacheManager mgr = HaxelibProjectUpdater.getInstance().getLibraryCacheManager(project);
Sdk projectSdk = HaxelibSdkUtils.lookupSdk(project);
return (mgr != null && projectSdk != null) ? mgr.getLibraryCache(projectSdk) : null;
}
/**
* Resolve the classpath/library entries for a module. Determines which
* libraries to add and remove from the module. Only libraries that have
* previously been added may be removed, if they have become redundant
* or otherwise specified.
*
* @param tracker for the project being updated.
* @param module being updated.
* @param externalLibs potential new libraries that must be available
* to the module when this routine finishes. These are
* typically specified in the Haxe project files. (e.g. -lib)
*/
private void resolveModuleLibraries(ProjectTracker tracker, Module module, HaxeLibraryList externalLibs) {
HaxeLibraryList toAdd;
HaxeLibraryList toRemove;
toAdd = new HaxeLibraryList(module);
toRemove = new HaxeLibraryList(module);
Sdk moduleSdk = ModuleRootManager.getInstance(module).getSdk();
if (null == moduleSdk) {
LOG.debug("No SDK for module " + module.getName() + ". Not syncing haxelibs.");
return; // Nothing to do if there is no SDK.
}
syncLibraryLists(moduleSdk,
HaxelibUtil.getModuleLibraries(module),
externalLibs,
/*modifies*/ toAdd,
/*modifies*/ toRemove);
updateModule(tracker, module, toRemove, toAdd);
}
/**
* Find an IDEA library matching a HaxeLibraryReference.
*
* @param iter the table iterator.
* @param ref the library to look for.
* @return the Library, if found; null, otherwise.
*/
@Nullable
private Library lookupLibrary(@NotNull Iterator<Library> iter, @NotNull HaxeLibraryReference ref) {
Library found = null;
while (null == found && iter.hasNext()) {
Library toTest = iter.next();
if (ref.matchesIdeaLib(toTest)) {
found = toTest;
}
}
return found;
}
/**
* Find an IDEA library in a project's LibraryTable matching a HaxeLibraryReference.
*
* @param table - the LibraryTable to look in.
* @param ref - the library to find.
* @return the Library, if found; null, otherwise.
*/
@Nullable
private Library lookupProjectLibrary(@NotNull LibraryTable table, @NotNull HaxeLibraryReference ref) {
return lookupLibrary(table.getLibraryIterator(), ref);
}
/**
* Find an IDEA library in a module's LibraryTable (actually, its ModifiableModel)
* matching a HaxeLibraryReference.
*
* @param table - the LibraryTable to look in.
* @param ref - the library to find.
* @return the Library, if found; null, otherwise.
*/
@Nullable
private Library lookupModelLibrary(@NotNull LibraryTable.ModifiableModel table, @NotNull HaxeLibraryReference ref) {
return lookupLibrary(table.getLibraryIterator(), ref);
}
/**
* Remove libraries from a library table.
*
* @param toRemove - The list of libraries to remove.
* @param libraryTableModel - The (modifiable model of the) table to remove them from.
* @param timeLog - Debugging time log.
*/
private void removeLibraries(@NotNull final HaxeLibraryList toRemove,
@NotNull final LibraryTable.ModifiableModel libraryTableModel,
@NotNull final HaxeDebugTimeLog timeLog) {
timeLog.stamp("Removing libraries.");
toRemove.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
Library library = lookupModelLibrary(libraryTableModel, entry);
if (null != library) {
// Why use this?: ModuleHelper.removeDependency(rootManager, library);
libraryTableModel.removeLibrary(library);
timeLog.stamp("Removed library " + library.getName());
}
else {
LOG.warn(
"Internal inconsistency: library to remove was not found: " +
entry.getName());
}
return true;
}
});
}
/**
* Add libraries to a library table.
*
* @param toAdd - List of libraries to add.
* @param projectLibraries - libraries that can be referenced instead of created.
* @param projectTable - the library table that projectLibraries belong to.
* @param moduleModel - the module we are adding libraries to
* @param libraryTableModel - the library table for that module
* @param timeLog - Debugging info and timer.
*/
private void addLibraries(@NotNull final HaxeLibraryList toAdd,
@NotNull final HaxeLibraryList projectLibraries,
@NotNull final LibraryTable projectTable,
@NotNull final ModifiableRootModel moduleModel,
@NotNull final LibraryTable.ModifiableModel libraryTableModel,
@NotNull final HaxeDebugTimeLog timeLog) {
timeLog.stamp("Locating libraries and adding dependencies.");
toAdd.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
Library moduleLibrary = lookupModelLibrary(libraryTableModel, entry);
// If the lib is in the project list, then we just add a reference to it.
if (projectLibraries.contains(entry)) {
if (null != moduleLibrary) {
LOG.warn("Internal inconsistency: attempting to add library that is already in the module.");
} else {
Library projectLibrary = lookupProjectLibrary(projectTable, entry);
if (null == projectLibrary) {
// EMB: Not writing recovery code because this really shouldn't happen.
LOG.warn("Internal inconsistency: Could not find project library when it should exist.");
} else {
LibraryOrderEntry libraryOrderEntry = moduleModel.addLibraryEntry(projectLibrary);
libraryOrderEntry.setExported(false);
libraryOrderEntry.setScope(DependencyScope.PROVIDED);
timeLog.stamp("Added module-level reference to project lib " + projectLibrary.getName());
}
}
}
else { // Not in the project, so add it to the module.
if (moduleLibrary == null) {
Library.ModifiableModel libraryModelToDispose = null;
try {
final Library newLibrary = libraryTableModel.createLibrary(entry.getPresentableName());
moduleLibrary = newLibrary;
final Library.ModifiableModel libraryModifiableModel = newLibrary.getModifiableModel();
libraryModelToDispose = libraryModifiableModel;
HaxeLibrary entryLibrary = entry.getLibrary();
HaxeClasspath classpath = entryLibrary != null ? entryLibrary.getClasspathEntries() : null;
if (null != classpath) {
classpath.iterate(new HaxeClasspath.Lambda() {
@Override
public boolean processEntry(HaxeClasspathEntry cp) {
String url = HaxeFileUtil.fixUrl(cp.getUrl());
VirtualFile directory = VirtualFileManager.getInstance().findFileByUrl(url);
if (null == directory) {
timeLog.stamp("Skipping classpath for " + newLibrary.getName() + ", no directory entry for " + url);
}
else {
libraryModifiableModel.addRoot(directory, OrderRootType.CLASSES);
libraryModifiableModel.addRoot(directory, OrderRootType.SOURCES);
}
return true;
}
});
}
LibraryOrderEntry libraryOrderEntry = moduleModel.findLibraryOrderEntry(newLibrary);
libraryOrderEntry.setExported(false);
libraryOrderEntry.setScope(DependencyScope.PROVIDED);
libraryModifiableModel.commit();
libraryModelToDispose = null; // So we don't dispose of it now that we've committed.
timeLog.stamp("Added library " + newLibrary.getName());
}
finally {
if (null != libraryModelToDispose) {
timeLog.stamp("Failure to create library " + moduleLibrary.getName());
Disposer.dispose(libraryModelToDispose);
}
}
}
else {
LOG.warn("Internal inconsistency: library to add was already in the module's library table.");
}
}
return true;
}
});
}
/**
* Ensure that all entries in the given list are managed.
*
* @param list - List of entries to check.
* @param msg - Message to display on failure.
*/
private void assertEntriesAreManaged(HaxeLibraryList list, final String msg) {
if (null != list) {
list.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
LOG.assertTrue(entry.isManaged(), msg);
return true;
}
});
}
}
/**
* Workhorse routine for resolveModuleLibraries. This does the actual
* update of the module. It will block until all of the running events
* on the AWT thread have completed, and then this will run on that thread.
*
* @param module to update.
* @param toRemove libraries that need to be removed from the module.
* @param toAdd libraries that need to be added to the module.
*/
private void updateModule(final ProjectTracker tracker,
final Module module,
final HaxeLibraryList toRemove,
final HaxeLibraryList toAdd) {
if ((null == toRemove || toRemove.isEmpty()) && (null == toAdd || toAdd.isEmpty())) {
return;
}
// Some internal error checking.
assertEntriesAreManaged(toRemove, "Attempting to automatically remove a library that was not marked as managed.");
assertEntriesAreManaged(toAdd, "Attempting to automatically add a library that is not marked as managed.");
final HaxeDebugTimeLog timeLog = new HaxeDebugTimeLog("Write action:");
timeLog.stamp("Queueing write action...");
doWriteAction(new Runnable() {
@Override
public void run() {
timeLog.stamp("<-- Time elapsed waiting for write access on the AWT thread.");
timeLog.stamp("Begin: Updating module libraries for " + module.getName());
// Figure out the list of project libraries that we should reference, if we can.
HaxeLibraryList projectLibraries = ModuleRootManager.getInstance(module).isSdkInherited()
? getProjectLibraryList(tracker)
: new HaxeLibraryList(module);
final LibraryTable projectTable = ProjectLibraryTable.getInstance(tracker.getProject());
timeLog.stamp("<-- Time elapsed retrieving project libraries.");
ModifiableRootModel moduleRootModel = null;
LibraryTable.ModifiableModel libraryTableModel = null;
try {
moduleRootModel = ModuleRootManager.getInstance(module).getModifiableModel();
libraryTableModel = moduleRootModel.getModuleLibraryTable().getModifiableModel();
// Remove unused packed "haxelib|<lib_name>" libraries from the module and project library.
if (null != toRemove) {
removeLibraries(toRemove, libraryTableModel, timeLog);
}
// Add new dependencies to modules.
if (null != toAdd) {
addLibraries(toAdd, projectLibraries, projectTable, moduleRootModel, libraryTableModel, timeLog);
}
timeLog.stamp("Committing changes to module libraries");
libraryTableModel.commit();
libraryTableModel = null;
moduleRootModel.commit();
moduleRootModel = null;
}
finally {
if (null != moduleRootModel || null != libraryTableModel)
timeLog.stamp("Failure to update module libraries");
if (null != libraryTableModel)
if (IdeaTarget.IS_VERSION_15_COMPATIBLE) {
// libraryTableModel.dispose() in IDEA 15+; not a disposable in earlier versions.
new MethodWrapper<Void>(libraryTableModel.getClass(), "dispose").invoke(libraryTableModel);
}
if (null != moduleRootModel)
moduleRootModel.dispose();
}
timeLog.stamp("Finished: Updating module libraries");
}
});
timeLog.print();
}
/**
* The guts of syncModuleClasspaths, separated so that it can be run as
* either a foreground or background task.
*
* @param tracker for the project being updated.
* @param module being updated.
* @param timeLog where to log timing results
*/
private void syncOneModule(@NotNull final ProjectTracker tracker, @NotNull Module module, @NotNull HaxeDebugTimeLog timeLog) {
Project project = tracker.getProject();
HaxeLibraryList haxelibExternalItems = new HaxeLibraryList(module);
HaxelibLibraryCache libManager = tracker.getSdkManager().getLibraryManager(module);
HaxeModuleSettings settings = HaxeModuleSettings.getInstance(module);
// If the module says not to keep libs synched, then don't.
if (!settings.isKeepSynchronizedWithProjectFile()) {
timeLog.stamp("Module " + module.getName() + " is set to not synchronize dependencies.");
return;
}
switch (settings.getBuildConfiguration()) {
case NMML:
timeLog.stamp("Start loading haxelibs from NMML file.");
HaxeLibrary nme = libManager.getLibrary("nme", HaxelibSemVer.ANY_VERSION);
if (null != nme) {
haxelibExternalItems.add(nme.createReference(HaxelibSemVer.ANY_VERSION));
}
else {
// TODO: Figure out how to communicate this to the user.
LOG.warn("Required library 'nme' is not known to haxelib.");
}
// TODO: Pull libs off of the command line, too.
String nmmlPath = settings.getNmmlPath();
if (nmmlPath != null && !nmmlPath.isEmpty()) {
VirtualFile file = LocalFileFinder.findFile(nmmlPath);
if (file != null && file.getFileType().equals(NMMLFileType.INSTANCE)) {
VirtualFileManager.getInstance().syncRefresh();
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (psiFile != null && psiFile instanceof XmlFile) {
haxelibExternalItems.addAll(HaxelibUtil.getHaxelibsFromXmlFile((XmlFile)psiFile, libManager));
}
}
}
timeLog.stamp("Finished loading haxelibs from NMML file.");
// TODO: Load classpaths from the NMML file, CL, and ensure that they are included in the module sources.
break;
case OPENFL:
timeLog.stamp("Start loading haxelibs from openFL configuration file.");
HaxeLibrary openfl = libManager.getLibrary("openfl", HaxelibSemVer.ANY_VERSION);
if (null != openfl) {
haxelibExternalItems.add(openfl.createReference(HaxelibSemVer.ANY_VERSION)); // No specific version.
}
else {
// TODO: Figure out how to report this to the user.
LOG.warn("Required library 'openfl' is not known to haxelib.");
}
// TODO: Pull libs off of the command line, too.
String openFLXmlPath = settings.getOpenFLPath();
if (openFLXmlPath != null && !openFLXmlPath.isEmpty()) {
VirtualFile file = LocalFileFinder.findFile(openFLXmlPath);
if (file != null && file.getFileType().equals(XmlFileType.INSTANCE)) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (psiFile != null && psiFile instanceof XmlFile) {
haxelibExternalItems.addAll(HaxelibUtil.getHaxelibsFromXmlFile((XmlFile)psiFile, libManager));
}
}
}
else {
// XXX: EMB - Not sure of the validity of using this path if xml lib isn't specified.
String projectBasePath = project.getBasePath();
if (null == projectBasePath) {
projectBasePath = "";
}
File dir = new File(projectBasePath);
List<String> projectClasspaths =
HaxelibClasspathUtils.getProjectDisplayInformation(project, dir, "openfl",
HaxelibSdkUtils.lookupSdk(module));
for (String classpath : projectClasspaths) {
VirtualFile file = LocalFileFinder.findFile(classpath);
if (file != null) {
HaxeLibrary lib = libManager.getLibraryByPath(file.getPath());
if (null != lib) {
haxelibExternalItems.add(lib.createReference());
}
else {
// TODO: Figure out how to communicate this to the user.
LOG.warn("Library referenced by openFL configuration is not known to haxelib " + classpath);
}
}
}
}
haxelibExternalItems.debugDump("haxelibExternalItems for module " + module.getName());
timeLog.stamp("Finished loading haxelibs from openfl file.");
// TODO: Add classpaths from the xml file and the CL to the module sources.
break;
case HXML:
timeLog.stamp("Start loading haxelibs from HXML file.");
String hxmlPath = settings.getHxmlPath();
// TODO: Walk the command line looking for libs, too.
if (hxmlPath != null && !hxmlPath.isEmpty()) {
VirtualFile file = LocalFileFinder.findFile(hxmlPath);
if (file != null && file.getFileType().equals(HXMLFileType.INSTANCE)) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (psiFile != null) {
HXMLProjectModel hxml = new HXMLProjectModel(psiFile);
// TODO: Needs to walk all of the children and load referenced .hxml files in place. Should probably be added to the model.
List<String> libs = hxml.getLibraries();
if (libs != null) {
for (String lib : libs) {
HaxeLibraryReference reference = HaxeLibraryReference.create(module, lib);
if (null != reference.getLibrary()) {
haxelibExternalItems.add(reference);
}
else {
LOG.warn("Library referenced by HXML configuration is not known to haxelib.");
}
}
}
}
}
}
timeLog.stamp("Finish loading haxelibs from HXML file.");
// TODO: Add classpaths from the HXML file and CL to module sources
break;
case CUSTOM:
timeLog.stamp("Start loading haxelibs from properties.");
// TODO: Grab the command line?? Run it through the algorithm for USE_HXML.
timeLog.stamp("Finish loading haxelibs from properties.");
break;
default:
throw new HaxeDebugUtil.InvalidCaseException(settings.getBuildConfiguration());
}
// We can't just remove all of the project classpaths from the module's
// library list here because we need to remove any managed classpaths that
// are no longer valid in the modules. We can't do that if we don't have
// the list of valid ones. :/
timeLog.stamp("Adding libraries to module.");
resolveModuleLibraries(tracker, module, haxelibExternalItems);
timeLog.stamp("Finished adding libraries to module.");
}
private void syncModuleClasspaths(final ProjectTracker tracker) {
final HaxeDebugTimeLog timeLog = HaxeDebugTimeLog.startNew("syncModuleClasspaths");
final Project project = tracker.getProject();
//LOG.debug("Scanning project " + project.getName());
timeLog.stamp("Scanning project " + project.getName());
Collection<Module> modules = ModuleUtil.getModulesOfType(project, HaxeModuleType.getInstance());
int i = 0;
final int count = modules.size();
for (final Module module : modules) {
final int num = ++i;
//LOG.debug("Scanning module " + (++i) + " of " + count + ": " + module.getName());
timeLog.stamp("\nScanning module " + (num) + " of " + count + ": " + module.getName());
if (myTestInForeground) {
syncOneModule(tracker, module, timeLog);
}
else {
// Running inside of a read action lets the UI run, and messes with the timing.
doReadAction(new Runnable() {
@Override
public void run() {
syncOneModule(tracker, module, timeLog);
}
});
}
}
timeLog.stamp("Completed.");
timeLog.print();
}
private void synchronizeClasspaths(@NotNull ProjectTracker tracker) {
//
// Either of these commented-out sections will cause indexing to not be attempted
// while the haxelibs are synchronizing. However, they also hide the fact that
// haxelibs are updating by not allowing the haxelib progress dialog to start.
// Instead, it looks like indexing restarts over and over and over (which it
// kinda does).
//
//DumbServiceImpl dumbService = DumbServiceImpl.getInstance(tracker.getProject());
//dumbService.queueTask(new DumbModeTask() {
// @Override
// public void performInDumbMode(@NotNull ProgressIndicator indicator) {
// syncProjectClasspath(tracker);
// syncModuleClasspaths(tracker);
// }
//});
//TransactionGuard tg = TransactionGuard.getInstance();
//tg.submitTransactionAndWait(new Runnable() {
// @Override
// public void run() {
// syncProjectClasspath(tracker);
// syncModuleClasspaths(tracker);
// }
//});
syncProjectClasspath(tracker);
syncModuleClasspaths(tracker);
}
/**
* Retrieves the project's libraries, either from the cache if available,
* or from the project's library table.
*
* @param tracker for the project being updated.
* @return a HaxeClasspath representing the libraries specified at the project level.
*/
@NotNull
private HaxeLibraryList getProjectLibraryList(@NotNull ProjectTracker tracker) {
ProjectLibraryCache cache = tracker.getCache();
HaxeLibraryList projectLibraries;
HaxeConfiguration buildConfig = HaxeConfiguration.CUSTOM; // Only properties available.
if (cache.isListSetFor(buildConfig)) {
projectLibraries = cache.getListFor(buildConfig);
}
else {
projectLibraries = HaxelibUtil.getProjectLibraries(tracker.getProject(), false, false);
cache.setListFor(buildConfig, projectLibraries);
}
return projectLibraries;
}
/**
* Collect all dependencies for libraries in list.
*
* @param list of libraries to collect dependencies for.
* @return a list of libraries that list depends upon. May include entries
* from list itself, if there are cross-dependencies.
*/
@NotNull
private HaxeLibraryList collectDependencies(@NotNull HaxeLibraryList list) {
final HaxeLibraryList dependencies = new HaxeLibraryList(list.getOwner());
list.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
if (entry.isAvailable()) {
dependencies.addAll(entry.getLibrary().collectDependents());
}
return true;
}
});
return dependencies;
}
/**
* Mark all entries in a list as managed...
*
* @param list
*/
@NotNull
private void markAsManaged(@NotNull HaxeLibraryList list) {
list.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
entry.markAsManagedEntry();
return true;
}
});
}
/**
* Find libraries with roots that exist in the classpath.
*
* @param libs libs to match to classpaths.
* @param classpath classpath to match.
* @return a list of libraries whose directory entries match entries from the classpath.
*/
@NotNull
private HaxeLibraryList findLibsMatchingClasspath(@NotNull final HaxeLibraryList libs, @NotNull final HaxeClasspath classpath) {
final HaxeLibraryList matchingLibs = new HaxeLibraryList(libs.getOwner());
libs.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
HaxeLibrary lib = entry.getLibrary();
if (null != lib && classpath.contains(lib.getLibraryRoot()))
matchingLibs.add(entry);
return true;
}
});
return matchingLibs;
}
/**
* Synchronize library lists to figure out which dependencies need to be added or removed.
*
* @param currentList the list of libraries currently defined in the module/project/sdk.
* @param externallyRequired the list of libraries required by project settings. (e.g. openfl, nme)
* @param newLibrariesToAdd the resultant list of libraries to add to currentList
* @param oldLibrariesToRemove the resultant list of libraries to remove from currentList.
*/
@NotNull
private void syncLibraryLists(@NotNull Sdk sdk,
@NotNull HaxeLibraryList currentList,
@NotNull HaxeLibraryList externallyRequired,
/*modifies*/ @NotNull HaxeLibraryList newLibrariesToAdd,
/*modifies*/ @NotNull HaxeLibraryList oldLibrariesToRemove) {
final HaxeLibraryList currentManagedEntries = new HaxeLibraryList(sdk);
final HaxeLibraryList currentUnmanagedEntries = new HaxeLibraryList(sdk);
currentList.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
if (entry.isManaged()) { // (e.g. starts with "haxelib|"
currentManagedEntries.add(entry);
} else {
currentUnmanagedEntries.add(entry);
}
return true;
}
});
HaxeLibraryList dependencies = new HaxeLibraryList(collectDependencies(externallyRequired));
dependencies.addAll(collectDependencies(currentUnmanagedEntries));
// We want to remove all managed entries that we don't need any more.
HaxeLibraryList toRemove = currentManagedEntries;
// We want to add all externally required entries
HaxeLibraryList toAdd = new HaxeLibraryList(sdk);
toAdd.addAll(externallyRequired);
toAdd.addAll(dependencies);
toAdd.removeAll(currentUnmanagedEntries);
// At this point, we could remove libs that exist via alternative names (find by classpath).
// However, they can't be used with the compiler anyway, so the better part of valor
// is to include them by the name that haxelib knows, even if it technically duplicates
// the entry.
markAsManaged(toAdd);
// Anything that is in both lists, we don't want to touch.
newLibrariesToAdd.addAll(toAdd);
newLibrariesToAdd.removeAll(toRemove);
oldLibrariesToRemove.addAll(toRemove);
oldLibrariesToRemove.removeAll(toAdd);
}
/**
* Removes old unneeded libraries and adds new dependencies to the project classpath.
* Queues an update to the Project.
*
* @param tracker for the project being updated.
*/
@NotNull
private void syncProjectClasspath(@NotNull ProjectTracker tracker) {
Sdk sdk = HaxelibSdkUtils.lookupSdk(tracker.getProject());
boolean isHaxeSDK = sdk.getSdkType().equals(HaxeSdkType.getInstance());
if (!isHaxeSDK) {
return;
}
HaxeDebugTimeLog timeLog = new HaxeDebugTimeLog("syncProjectClasspath");
timeLog.stamp("Start synchronizing project " + tracker.getProject().getName());
HaxeLibraryList toAdd = new HaxeLibraryList(sdk);
HaxeLibraryList toRemove = new HaxeLibraryList(sdk);
syncLibraryLists(sdk,
HaxelibUtil.getProjectLibraries(tracker.getProject(),false, false),
new HaxeLibraryList(sdk),
/*modifies*/ toAdd,
/*modifies*/ toRemove );
if (!toAdd.isEmpty() && !toRemove.isEmpty()) {
timeLog.stamp("Add/Remove calculations finished. Queuing write task.");
updateProject(tracker, toRemove, toAdd);
}
timeLog.stamp("Finished synchronizing.");
timeLog.print();
// And update the cache.
tracker.getCache().setPropertiesList(HaxelibUtil.getProjectLibraries(tracker.getProject(), false, false));
}
/**
* Workhorse routine for syncProjectClasspath. This does the actual update of the
* project. It will block until all of the running events on the AWT thread have
* completed, and then this will run on that thread.
*
* @param tracker for the project to update.
* @param toRemove libraries that need to be removed from the project.
* @param toAdd libraries that need to be added to the project.
*/
private void updateProject(@NotNull final ProjectTracker tracker,
final @Nullable HaxeLibraryList toRemove,
final @Nullable HaxeLibraryList toAdd) {
if (null == toRemove && null == toAdd) {
return;
}
if (null != toRemove) {
toRemove.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
LOG.assertTrue(entry.isManaged(), "Attempting to automatically remove a library that was not marked as managed.");
return true;
}
});
}
if (null != toAdd) {
toAdd.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
LOG.assertTrue(entry.isManaged(), "Attempting to automatically add a library that is not marked as managed.");
return true;
}
});
}
doWriteAction(new Runnable() {
@Override
public void run() {
final HaxeDebugTimeLog timeLog = new HaxeDebugTimeLog("Write action:");
timeLog.stamp("Begin: Updating project libraries");
LibraryTable projectTable = ProjectLibraryTable.getInstance(tracker.getProject());
final LibraryTable.ModifiableModel projectModifiableModel = projectTable.getModifiableModel();
// Remove unused packed "haxelib|<lib_name>" libraries from the module and project library.
if (null != toRemove) {
timeLog.stamp("Removing unneeded haxelib libraries.");
toRemove.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference entry) {
Library library = projectModifiableModel.getLibraryByName(
entry.getName());
LOG.assertTrue(null != library, "Library " + entry.getName() + " was not found in the project and will not be removed.");
if (null != library) {
projectModifiableModel.removeLibrary(library);
timeLog.stamp("Removed library " + entry.getName());
}
else {
timeLog.stamp(
"Library to remove was not found: " + entry.getName());
}
return true;
}
});
}
// Add new dependencies to modules.
if (null != toAdd) {
timeLog.stamp("Adding haxelib dependencies.");
toAdd.iterate(new HaxeLibraryList.Lambda() {
@Override
public boolean processEntry(HaxeLibraryReference newItem) {
Library libraryByName = projectModifiableModel.getLibraryByName(newItem.getName());
if (libraryByName == null) {
assert newItem.isAvailable(); // Should have been removed if unavailable.
libraryByName = projectModifiableModel.createLibrary(newItem.getName()); // TODO: Presentable Name??
Library.ModifiableModel libraryModifiableModel = libraryByName.getModifiableModel();
libraryModifiableModel.addRoot(newItem.getLibrary().getSourceRoot().getUrl(), OrderRootType.CLASSES);
libraryModifiableModel.addRoot(newItem.getLibrary().getSourceRoot().getUrl(), OrderRootType.SOURCES);
libraryModifiableModel.commit();
timeLog.stamp("Added library " + libraryByName.getName());
}
return true;
}
});
}
timeLog.stamp("Committing project changes.");
projectModifiableModel.commit();
timeLog.stamp("Finished: Updating project Libraries");
timeLog.print();
}
});
}
/**
* Cause a synchronous write action to be run on the AWT thread.
*
* @param action action to run.
*/
private static void doWriteAction(final Runnable action) {
final Application application = ApplicationManager.getApplication();
application.invokeAndWait(new Runnable() {
@Override
public void run() {
application.runWriteAction(action);
}
}, application.getDefaultModalityState());
}
/**
* Cause a synchronous read action to be run. Blocks if a write action is
* currently running in the AWT thread. Also blocks write actions from
* occuring while this is being run. So don't let tasks take too long, or
* the UI gets choppy.
*
* @param action action to run.
*/
private static void doReadAction(final Runnable action) {
final Application application = ApplicationManager.getApplication();
application.invokeAndWait(new Runnable() {
@Override
public void run() {
application.runReadAction(action);
}
}, application.getDefaultModalityState());
}
/**
* Cache for project library lists.
*/
final private class ProjectLibraryCache {
private Sdk sdk;
private HaxeLibraryList nmmlList;
private HaxeLibraryList openFLList;
private HaxeLibraryList hxmlList;
private HaxeLibraryList propertiesList;
private boolean nmmlIsSet;
private boolean openFLIsSet;
private boolean hxmlIsSet;
private boolean propertiesIsSet;
public ProjectLibraryCache(@NotNull Sdk sdk) {
this.sdk = sdk;
clear();
}
public void clear() {
setNmmlList(new HaxeLibraryList(sdk));
setOpenFLList(new HaxeLibraryList(sdk));
setHxmlList(new HaxeLibraryList(sdk));
setPropertiesList(new HaxeLibraryList(sdk));
// Reset the 'set' bits.
nmmlIsSet = openFLIsSet = hxmlIsSet = propertiesIsSet = false;
}
public boolean isListSetFor(HaxeConfiguration buildConfig) {
switch(buildConfig) {
case NMML:
return nmmlIsSet;
case OPENFL:
return openFLIsSet;
case HXML:
return hxmlIsSet;
case CUSTOM:
return propertiesIsSet;
}
return false;
}
@NotNull
public HaxeLibraryList getListFor(HaxeConfiguration buildConfig) {
switch(buildConfig) {
case NMML:
return getNmmlList();
case OPENFL:
return getOpenFLList();
case HXML:
return getHxmlList();
case CUSTOM:
return getPropertiesList();
}
return new HaxeLibraryList(sdk);
}
public void setListFor(HaxeConfiguration buildConfig, HaxeLibraryList list) {
switch(buildConfig) {
case NMML:
setNmmlList(list);
case OPENFL:
setOpenFLList(list);
case HXML:
setHxmlList(list);
case CUSTOM:
setPropertiesList(list);
}
}
@NotNull
public HaxeLibraryList getNmmlList() {
return nmmlList != null ? nmmlList : new HaxeLibraryList(sdk);
}
@NotNull
public HaxeLibraryList getOpenFLList() {
return openFLList != null ? openFLList : new HaxeLibraryList(sdk);
}
@NotNull
public HaxeLibraryList getHxmlList() {
return hxmlList != null ? hxmlList : new HaxeLibraryList(sdk);
}
@NotNull
public HaxeLibraryList getPropertiesList() {
return propertiesList != null ? propertiesList : new HaxeLibraryList(sdk);
}
public void setNmmlList(HaxeLibraryList nmmlList) {
this.nmmlList = nmmlList;
nmmlIsSet = true;
}
public void setOpenFLList(HaxeLibraryList openFLList) {
this.openFLList = openFLList;
openFLIsSet = true;
}
public void setHxmlList(HaxeLibraryList hxmlList) {
this.hxmlList = hxmlList;
hxmlIsSet = true;
}
public void setPropertiesList(HaxeLibraryList propertiesList) {
this.propertiesList = propertiesList;
propertiesIsSet = true;
}
}
/**
* Tracks the state of a project for updating class paths.
*/
public final class ProjectTracker {
final Project myProject;
boolean myIsDirty;
boolean myIsUpdating;
ProjectLibraryCache myCache;
HaxelibLibraryCacheManager mySdkManager;
// TODO: Determine if we need to track whether the project is still open.
/**
* Typically, a project gets open and closed events for all of the modules it
* contains. We don't want to destroy or de-queue ProjectTrackers until all
* of the modules have been destroyed.
*/
int myReferenceCount;
public ProjectTracker(Project project) {
myProject = project;
myIsDirty = true;
myIsUpdating = false;
myReferenceCount = 0;
myCache = new ProjectLibraryCache(HaxelibSdkUtils.lookupSdk(project));
mySdkManager = new HaxelibLibraryCacheManager();
}
/**
* Get the settings cache.
*/
@NotNull
public ProjectLibraryCache getCache() {
return myCache;
}
/**
* Get the library classpath cache.
*/
@NotNull
public HaxelibLibraryCacheManager getSdkManager() {
return mySdkManager;
}
/**
* Tell whether this project is dirty (needs updating).
*
* @return true if the project needs updating.
*/
public boolean isDirty() {
boolean ret = false;
synchronized (this) {
ret = myIsDirty;
}
return ret;
}
/**
* Set/clear the dirty state. Marking the project dirty clears the cache.
*
* @param newState the new state to set.
* @return the state prior to setting it.
*/
public boolean setDirty(boolean newState) {
boolean ret = false;
synchronized (this) {
ret = myIsDirty;
myIsDirty = newState;
if (myIsDirty) {
// XXX: May need something more sophisicated than just clearing it.
// It could be that a module is getting changed, but not
// the project. In that case, we would want to detect whether
// the project settings really changed, and act accordingly.
myCache.clear();
}
}
return ret;
}
/**
* Tell whether this project is currently updating.
*
* @return true if the project is currently running an update.
*/
public boolean isUpdating() {
boolean ret = false;
synchronized(this) {
ret = myIsUpdating;
}
return ret;
}
/**
* Set/clear the 'updating' state.
*
* @param newState the new state to set.
* @return the state prior to setting it.
*/
public boolean setUpdating(boolean newState) {
boolean ret = false;
synchronized(this) {
ret = myIsUpdating;
myIsUpdating = newState;
}
return ret;
}
/**
* Increase the reference count.
*/
public void addReference() {
synchronized(this) {
myReferenceCount++;
}
}
/**
* Decrease the reference count.
*
* @return the number of references still attached to the object.
*/
public int removeReference() {
int refs;
synchronized(this) {
refs = --myReferenceCount;
}
// XXX: Maybe we don't need an assertion for this.
LOG.assertTrue(refs >= 0);
return refs;
}
/**
* Get the project we are tracking. Note that the project may
* not still be open at the moment that this is retrieved.
*/
@NotNull
public Project getProject() {
return myProject;
}
@NotNull
public String toString() {
return "ProjectTracker:" + myProject.getName();
}
public boolean equalsName(@Nullable ProjectTracker tracker) {
if (null == tracker) {
return false;
}
return myProject.getName().equals(tracker.getProject().getName());
}
} // end class ProjectTracker
/**
* Tracks all of the projects that are currently open. (As opposed to those
* that are bing queued for update, which the ProjectUpdateQueue does.)
* ProjectTrackers are shared between this map and the queue.
*/
public final class ProjectMap {
// Hashtable is already synchronized, so we don't have to manage that ourselves.
final Hashtable<String, ProjectTracker> myMap;
public ProjectMap() {
myMap = new Hashtable<String, ProjectTracker>();
}
/**
* Adds a new project to the map, if it doesn't exist there already.
*
* @param project An open project to be tracked.
*
* @return a new ProjectTracker for the project added, or the existing
* ProjectTracker for an existing project.
*/
@NotNull
public ProjectTracker add(@NotNull Project project) {
ProjectTracker tracker;
synchronized (this) {
tracker = myMap.get(project.getName());
if (null == tracker) {
tracker = new ProjectTracker(project);
myMap.put(project.getName(), tracker);
}
tracker.addReference();
}
return tracker;
}
public boolean remove(@NotNull Project project) {
boolean removed = false;
synchronized(this) {
ProjectTracker tracker = myMap.get(project.getName());
if (null != tracker) {
int refs = tracker.removeReference();
if (refs == 0) {
removed = null != myMap.remove(project.getName());
}
}
}
return removed;
}
@Nullable
public ProjectTracker get(@NotNull Project project) {
ProjectTracker tracker;
synchronized(this) {
tracker = myMap.get(project.getName());
}
return tracker;
}
public boolean iterate(@NotNull Lambda<ProjectTracker> lambda) {
synchronized(this) {
for(ProjectTracker tracker : myMap.values()) {
if (!lambda.process(tracker)) {
return false;
}
}
}
return true;
}
}
/**
* A FIFO queue for projects that need updating. Projects are tracked
* through the ProjectTracker class. When a project placed is in this queue,
* it is marked dirty. When the project is being updated, it's marked
* as updating. The currently updating project can be retrieved with
* getUpdatingProject().
*/
final class ProjectUpdateQueue {
final Object updateSyncToken;
ConcurrentLinkedQueue<ProjectTracker> queue;
ProjectTracker updatingProject = null;
public ProjectUpdateQueue() {
queue = new ConcurrentLinkedQueue<ProjectTracker>();
updateSyncToken = new Object();
updatingProject = null;
}
/**
* Determine whether there are any projects awaiting updating.
*
* The queue may be empty even though a project is currently updating.
*
* @return whether there are any projects waiting to be updated.
*/
public boolean isEmpty() {
return queue.isEmpty();
}
/**
* Adds a new project to the update queue. If the project already
* exists in the queue (as described by equals()) then it will not
* be added.
*
* @param tracker for the project that needs to be updated.
* @return true if the project was added to the update queue.
*/
public boolean add(@NotNull ProjectTracker tracker) {
boolean ret = false;
// XXX: Something seems wrong about skipping the currently updating project.
// What if a project change happens while the project is already running?
// Should we cancel and restart instead? And, if so, should we have a
// short delay to ensure that all identical messages are already queued?
if (!tracker.equalsName(getUpdatingProject())) {
if (queue.isEmpty() || !queue.contains(tracker)) {
ret = queue.add(tracker);
if (null == getUpdatingProject()) {
queueNextProject();
}
}
}
return ret;
}
/**
* Remove a project from the update queue.
*
* Projects that are currently updating are not canceled or removed, but will
* be as soon as they are finished.
*
* @param tracker project to remove
* @return true if the project was removed; false otherwise, or if it wasn't queued.
*/
public boolean remove(@NotNull ProjectTracker tracker) {
boolean removed = false;
synchronized(updateSyncToken) {
if (queue.remove(tracker)) {
tracker.setUpdating(false);
// We haven't changed anything, so it's still dirty.
removed = true;
}
}
return removed;
}
/**
* @return the project currently being updated, if any.
*/
@Nullable
public ProjectTracker getUpdatingProject() {
ProjectTracker tracker;
synchronized (updateSyncToken) {
tracker = updatingProject;
}
return tracker;
}
/**
* Puts the next project on the event queue.
*/
private void queueNextProject() {
synchronized (updateSyncToken) {
LOG.assertTrue(null == updatingProject);
// Get the next project from the queue. We're done if there's
// nothing left.
updatingProject = queue.poll(); // null if empty.
if (updatingProject == null) return;
LOG.assertTrue(updatingProject.isDirty());
LOG.assertTrue(!updatingProject.isUpdating());
updatingProject.setUpdating(true);
}
// Waiting for runWhenProjectIsInitialized() ensures that the project is
// fully loaded and accessible. Otherwise, we crash. ;)
StartupManager.getInstance(updatingProject.getProject()).runWhenProjectIsInitialized(new Runnable() {
public void run() {
LOG.debug("Starting haxelib library sync...");
runUpdate();
}
});
}
/**
* Runs the update, either in the foreground or background, depending upon
* the state of the myTestInForeground debug flag.
*/
private void runUpdate() {
final ProjectTracker tracker = getUpdatingProject();
final Project project = tracker == null ? null : tracker.getProject();
if (myTestInForeground) {
doUpdateWork();
} else if (myRunInForeground) {
// TODO: Put this string in a resource bundle.
ProgressManager.getInstance().run(new Task.Modal(project, "Synchronizing with haxelib libraries...", false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
indicator.setIndeterminate(true);
indicator.startNonCancelableSection();
doUpdateWork();
indicator.finishNonCancelableSection();
}
});
} else {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ProgressManager.getInstance().run(
// TODO: Put this string in a resource bundle.
new Task.Backgroundable(project, "Synchronizing with haxelib libraries...", false, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
doUpdateWork();
}
});
}
});
}
}
/**
* The basic bit of work that an update does.
*/
private void doUpdateWork() {
LOG.debug("Loading referenced libraries...");
ProjectTracker tracker = getUpdatingProject();
if (null == tracker) {
LOG.warn("Attempt to load libraries, but no project queued for updating.");
return;
}
synchronizeClasspaths(tracker);
finishUpdate(tracker);
}
/**
* Cleanup and queue the next in line, if any.
*
* @param up - the project that is finishing its update run.
*/
private void finishUpdate(ProjectTracker up) {
synchronized (updateSyncToken) {
LOG.assertTrue(null != updatingProject);
LOG.assertTrue(up.equals(updatingProject));
updatingProject.setUpdating(false);
updatingProject.setDirty(false);
updatingProject = null;
}
queueNextProject();
}
} // end class projectUpdateQueue
}
|
9241a5ff8c8b16b9cbcadb45f45fc63353482af4
| 1,713 |
java
|
Java
|
core/src/main/java/org/apache/calcite/sql/SqlSecondaryIndex.java
|
ArthurInTheShell/calcite
|
d2300090cad2990d6b3b5de59d3222a7fe7ee718
|
[
"Apache-2.0"
] | 1 |
2020-06-19T20:36:23.000Z
|
2020-06-19T20:36:23.000Z
|
core/src/main/java/org/apache/calcite/sql/SqlSecondaryIndex.java
|
ArthurInTheShell/calcite
|
d2300090cad2990d6b3b5de59d3222a7fe7ee718
|
[
"Apache-2.0"
] | 27 |
2020-05-29T17:50:29.000Z
|
2020-08-24T17:03:32.000Z
|
core/src/main/java/org/apache/calcite/sql/SqlSecondaryIndex.java
|
ArthurInTheShell/calcite
|
d2300090cad2990d6b3b5de59d3222a7fe7ee718
|
[
"Apache-2.0"
] | 9 |
2020-05-26T19:31:03.000Z
|
2020-06-18T19:21:03.000Z
| 34.959184 | 80 | 0.701109 | 1,001,980 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.calcite.sql;
import org.apache.calcite.sql.parser.SqlParserPos;
/**
* A {@code SqlSecondaryIndex} is a class that can be used to create a
* non-primary index, which is used by the SQL CREATE TABLE function.
*/
public class SqlSecondaryIndex extends SqlIndex {
public SqlSecondaryIndex(SqlParserPos pos, SqlNodeList columns,
SqlIdentifier name, boolean isUnique) {
super(pos, columns, name, isUnique);
}
@Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
if (isUnique) {
writer.keyword("UNIQUE");
}
writer.keyword("INDEX");
if (name != null) {
name.unparse(writer, leftPrec, rightPrec);
}
if (columns != null) {
SqlWriter.Frame frame = writer.startList("(", ")");
for (SqlNode c : columns) {
writer.sep(",");
c.unparse(writer, 0, 0);
}
writer.endList(frame);
}
}
}
|
9241a6f00d05e8f25a572fb73b4e8ad382fee8e1
| 1,553 |
java
|
Java
|
calimocho-tab/src/main/java/org/hupo/psi/calimocho/tab/io/formatter/XrefFieldFormatter.java
|
vibbits/psimi
|
9baca51cd699a69b3a61533093919ccd614b42b4
|
[
"CC-BY-4.0"
] | 4 |
2015-07-25T10:56:52.000Z
|
2022-02-04T12:51:56.000Z
|
calimocho-tab/src/main/java/org/hupo/psi/calimocho/tab/io/formatter/XrefFieldFormatter.java
|
vibbits/psimi
|
9baca51cd699a69b3a61533093919ccd614b42b4
|
[
"CC-BY-4.0"
] | 12 |
2015-12-17T14:52:54.000Z
|
2021-12-16T16:50:06.000Z
|
calimocho-tab/src/main/java/org/hupo/psi/calimocho/tab/io/formatter/XrefFieldFormatter.java
|
vibbits/psimi
|
9baca51cd699a69b3a61533093919ccd614b42b4
|
[
"CC-BY-4.0"
] | 4 |
2015-06-17T10:40:07.000Z
|
2021-12-14T13:04:36.000Z
| 33.042553 | 133 | 0.650354 | 1,001,981 |
package org.hupo.psi.calimocho.tab.io.formatter;
import org.hupo.psi.calimocho.tab.io.FieldFormatter;
import org.hupo.psi.calimocho.io.IllegalFieldException;
import org.hupo.psi.calimocho.key.CalimochoKeys;
import org.hupo.psi.calimocho.model.Field;
import org.hupo.psi.calimocho.model.Row;
import org.hupo.psi.calimocho.tab.util.MitabEscapeUtils;
/**
* TODO document this !
*
* @author Bruno Aranda ([email protected])
* @version $Id$
* @since 1.0
*/
public class XrefFieldFormatter implements FieldFormatter {
public String format( Field field ) throws IllegalFieldException {
StringBuilder sb = new StringBuilder();
final String db = field.get( CalimochoKeys.DB );
final String value = field.get( CalimochoKeys.VALUE );
if(db == null){
throw new IllegalFieldException( "Missing database in field: " + field.toString() );
}
if(value == null){
throw new IllegalFieldException( "Missing value in field: " + field.toString() );
}
sb.append( MitabEscapeUtils.escapeFieldElement( db ) ).append( ':' ).append( MitabEscapeUtils.escapeFieldElement( value ) );
final String text = field.get( CalimochoKeys.TEXT );
if(text != null){
sb.append('(').append( MitabEscapeUtils.escapeFieldElement( text )).append( ')' );
}
return sb.toString();
}
public String format( Field field, Row row ) throws IllegalFieldException {
return format(field);
}
}
|
9241a7ecfb935ca63f7d107a577419dda2501b25
| 1,809 |
java
|
Java
|
common-lib/src/main/java/com/codekutter/common/model/NullOrEmpty.java
|
krmahadevan/codekutter
|
0715300a7c953d4c02bb386d58a2fcc9789d6508
|
[
"Apache-2.0"
] | 3 |
2019-11-30T06:41:44.000Z
|
2021-01-13T04:17:29.000Z
|
common-lib/src/main/java/com/codekutter/common/model/NullOrEmpty.java
|
krmahadevan/codekutter
|
0715300a7c953d4c02bb386d58a2fcc9789d6508
|
[
"Apache-2.0"
] | 27 |
2019-11-30T06:35:17.000Z
|
2021-02-02T18:11:29.000Z
|
common-lib/src/main/java/com/codekutter/common/model/NullOrEmpty.java
|
krmahadevan/codekutter
|
0715300a7c953d4c02bb386d58a2fcc9789d6508
|
[
"Apache-2.0"
] | 2 |
2021-06-05T15:08:53.000Z
|
2021-06-05T15:10:21.000Z
| 35.470588 | 135 | 0.687673 | 1,001,982 |
/*
* Copyright (2020) Subhabrata Ghosh (subho dot ghosh at outlook dot 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.codekutter.common.model;
import java.util.Collection;
/**
* Check for NULL/Empty values.
* <p>
* Empty values will be checked for String/Collections.
*/
public class NullOrEmpty implements IValidationConstraint {
public static final String DEFAULT = NullOrEmpty.class.getCanonicalName();
/**
* Validate the input value.
*
* @param property - Property being validated.
* @param type - Type of object being validated.
* @param value - Input value.
* @throws ValidationException - Exception will be thrown on validation failure.
*/
@Override
public void validate(String property, Class<?> type, Object value) throws ValidationException {
ValidationException.checkNotNull(type.getCanonicalName(), value);
if (value instanceof String) {
ValidationException.checkNotEmpty(property, (String) value);
}
if (value instanceof Collection) {
if (((Collection) value).isEmpty()) {
throw new ValidationException(String.format("Empty collection: {property=%s[%s]}", type.getCanonicalName(), property));
}
}
}
}
|
9241a802aa7a354be0c509a3d7d9b99eb2fabf25
| 5,223 |
java
|
Java
|
src/main/java/com/spingular/cms/service/CommentQueryService.java
|
Tonterias/SpingularJhipsterV7
|
c17f299bf03b5d60775e432155c9be864d41b708
|
[
"Apache-2.0"
] | 6 |
2020-12-31T09:53:18.000Z
|
2021-09-10T08:39:38.000Z
|
src/main/java/com/spingular/cms/service/CommentQueryService.java
|
Tonterias/SpingularJhipsterV7
|
c17f299bf03b5d60775e432155c9be864d41b708
|
[
"Apache-2.0"
] | 2 |
2021-06-19T12:23:58.000Z
|
2021-06-23T09:30:50.000Z
|
src/main/java/com/spingular/cms/service/CommentQueryService.java
|
Tonterias/SpingularJhipsterV7
|
c17f299bf03b5d60775e432155c9be864d41b708
|
[
"Apache-2.0"
] | 2 |
2021-06-23T08:59:31.000Z
|
2021-06-24T11:46:05.000Z
| 45.815789 | 136 | 0.691557 | 1,001,983 |
package com.spingular.cms.service;
import com.spingular.cms.domain.*; // for static metamodels
import com.spingular.cms.domain.Comment;
import com.spingular.cms.repository.CommentRepository;
import com.spingular.cms.service.criteria.CommentCriteria;
import com.spingular.cms.service.dto.CommentDTO;
import com.spingular.cms.service.mapper.CommentMapper;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.jhipster.service.QueryService;
/**
* Service for executing complex queries for {@link Comment} entities in the database.
* The main input is a {@link CommentCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link CommentDTO} or a {@link Page} of {@link CommentDTO} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class CommentQueryService extends QueryService<Comment> {
private final Logger log = LoggerFactory.getLogger(CommentQueryService.class);
private final CommentRepository commentRepository;
private final CommentMapper commentMapper;
public CommentQueryService(CommentRepository commentRepository, CommentMapper commentMapper) {
this.commentRepository = commentRepository;
this.commentMapper = commentMapper;
}
/**
* Return a {@link List} of {@link CommentDTO} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<CommentDTO> findByCriteria(CommentCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Comment> specification = createSpecification(criteria);
return commentMapper.toDto(commentRepository.findAll(specification));
}
/**
* Return a {@link Page} of {@link CommentDTO} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<CommentDTO> findByCriteria(CommentCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Comment> specification = createSpecification(criteria);
return commentRepository.findAll(specification, page).map(commentMapper::toDto);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(CommentCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Comment> specification = createSpecification(criteria);
return commentRepository.count(specification);
}
/**
* Function to convert {@link CommentCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<Comment> createSpecification(CommentCriteria criteria) {
Specification<Comment> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), Comment_.id));
}
if (criteria.getCreationDate() != null) {
specification = specification.and(buildRangeSpecification(criteria.getCreationDate(), Comment_.creationDate));
}
if (criteria.getCommentText() != null) {
specification = specification.and(buildStringSpecification(criteria.getCommentText(), Comment_.commentText));
}
if (criteria.getIsOffensive() != null) {
specification = specification.and(buildSpecification(criteria.getIsOffensive(), Comment_.isOffensive));
}
if (criteria.getAppuserId() != null) {
specification =
specification.and(
buildSpecification(criteria.getAppuserId(), root -> root.join(Comment_.appuser, JoinType.LEFT).get(Appuser_.id))
);
}
if (criteria.getPostId() != null) {
specification =
specification.and(
buildSpecification(criteria.getPostId(), root -> root.join(Comment_.post, JoinType.LEFT).get(Post_.id))
);
}
}
return specification;
}
}
|
9241a8c8eb06417e6697edf77d9df510ce1f0b29
| 7,745 |
java
|
Java
|
cruncher-war/src/test/java/org/surfnet/cruncher/resource/CruncherResourceTest.java
|
OpenConext-Attic/OpenConext-cruncher
|
a6509aeda6ba3c6982a0c71291296467ee1cd0ad
|
[
"Apache-2.0"
] | null | null | null |
cruncher-war/src/test/java/org/surfnet/cruncher/resource/CruncherResourceTest.java
|
OpenConext-Attic/OpenConext-cruncher
|
a6509aeda6ba3c6982a0c71291296467ee1cd0ad
|
[
"Apache-2.0"
] | null | null | null |
cruncher-war/src/test/java/org/surfnet/cruncher/resource/CruncherResourceTest.java
|
OpenConext-Attic/OpenConext-cruncher
|
a6509aeda6ba3c6982a0c71291296467ee1cd0ad
|
[
"Apache-2.0"
] | null | null | null | 34.887387 | 127 | 0.714009 | 1,001,984 |
/*
* Copyright 2013 SURFnet bv, The Netherlands
*
* 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.surfnet.cruncher.resource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import junit.framework.Assert;
import org.joda.time.LocalDate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.surfnet.cruncher.message.Aggregator;
import org.surfnet.cruncher.model.LoginData;
import org.surfnet.cruncher.model.SpStatistic;
import org.surfnet.cruncher.model.VersStatistic;
import org.surfnet.cruncher.unittest.config.SpringConfigurationForTest;
@SuppressWarnings("unchecked")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfigurationForTest.class)
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class CruncherResourceTest {
@Inject
private CruncherResource cruncherResource;
@Inject
private Aggregator aggregator;
@Inject
private JdbcTemplate cruncherJdbcTemplate;
@Test
public void getLogins() {
LocalDate start = new LocalDate(2013, 1, 1);
LocalDate end = new LocalDate(2013, 1, 12);
Response response = cruncherResource.getLoginsPerInterval(start.toDate().getTime(), end.toDate().getTime(), "idp1", "sp1");
List<LoginData> result = (List<LoginData>) response.getEntity();
assertNotNull(result);
assertEquals(1, result.size());
LoginData data = result.get(0);
checkSp1Entry(data);
}
@Test
public void getMultipleLogins() {
LocalDate start = new LocalDate(2013, 1, 1);
LocalDate end = new LocalDate(2013, 1, 12);
Response response = cruncherResource.getLoginsPerInterval(start.toDate().getTime(), end.toDate().getTime(), "idp1", null);
List<LoginData> result = (List<LoginData>) response.getEntity();
assertNotNull(result);
assertEquals(2, result.size());
LoginData first = result.get(0);
LoginData second = result.get(1);
if (first.getSpEntityId().equals("sp1")) {
checkSp1Entry(first);
} else {
checkSp1Entry(second);
}
}
private void checkSp1Entry(LoginData data) {
assertEquals("idp1", data.getIdpEntityId());
assertEquals("idp1_name", data.getIdpname());
assertEquals("sp1", data.getSpEntityId());
assertEquals("sp1_name", data.getSpName());
assertEquals(240, data.getTotal());
assertEquals(12, data.getData().size());
assertEquals(20, (int) data.getData().get(0));
assertEquals(20, (int) data.getData().get(6));
assertEquals(20, (int) data.getData().get(11));
}
@Test
public void testIllegalArguments() {
cruncherResource.getLoginsPerInterval(0L, 0L, null, null).getEntity();
try {
cruncherResource.getLoginsPerInterval(null, null, null, null).getEntity();
fail("illegal start and end date may not be null");
} catch (IllegalArgumentException e) {
//expected
}
}
@Test
public void testResponseWithZeros() {
LocalDate start = new LocalDate(2013, 1, 10);
LocalDate end = new LocalDate(2013, 1, 20);
Response response = cruncherResource.getLoginsPerInterval(start.toDate().getTime(), end.toDate().getTime(), "idp1", "sp1");
List<LoginData> result = (List<LoginData>) response.getEntity();
assertNotNull(result);
assertEquals(1, result.size());
LoginData loginData = result.get(0);
assertEquals(11, loginData.getData().size());
assertEquals(20, (int) loginData.getData().get(2));
assertEquals(0, (int) loginData.getData().get(3));
assertEquals(0, (int) loginData.getData().get(4));
assertEquals(0, (int) loginData.getData().get(10));
}
@Test
public void getActiveServices() {
aggregator.run();
Response response = cruncherResource.getRecentLoginsForUser("idp2:user_1", "idp2");
List<SpStatistic> result = (List<SpStatistic>) response.getEntity();
assertNotNull(result);
assertEquals(2, result.size());
SpStatistic currentStat = result.get(0);
if (currentStat.getSpEntityId().equals("sp2")) {
checkStatistics(result.get(0));
} else {
checkStatistics(result.get(1));
}
}
@Test
public void testDifferentResultsForSameSpWhenRetrievedWithExplcitSpParameterAndNot() throws IOException {
LocalDate start = new LocalDate(1999, 1, 10);
LocalDate end = new LocalDate(2999, 1, 20);
Response response = cruncherResource.getLoginsPerInterval(start.toDate().getTime(),
end.toDate().getTime(), null, null);
List<LoginData> loginData = (List<LoginData>) response.getEntity();
Set<String> idps = uniqueIdps(loginData);
for (String idp : idps) {
List<LoginData> sPsPerIdp = sPsPerIdp(idp, loginData);
for (LoginData data : sPsPerIdp) {
assertLoginStats(data, idp, start, end);
}
}
}
private List<LoginData> sPsPerIdp(String iDP, List<LoginData> loginData) {
List<LoginData> result = new ArrayList<LoginData>();
for (LoginData data : loginData) {
if (data.getIdpEntityId().equals(iDP)) {
result.add(data);
}
}
return result;
}
private Set<String> uniqueIdps(List<LoginData> loginData) {
Set<String> idps = new HashSet<String>();
for (LoginData data : loginData) {
idps.add(data.getIdpEntityId());
}
return idps;
}
private void assertLoginStats(LoginData loginData, String idp, LocalDate start, LocalDate end) throws IOException {
String spId = loginData.getSpEntityId();
Response response = cruncherResource.getLoginsPerInterval(start.toDate().getTime(),
end.toDate().getTime(), idp, spId);
List<LoginData> result = (List<LoginData>) response.getEntity();
Assert.assertEquals(1, result.size());
LoginData oneSp = result.get(0);
assertEquals(oneSp.getData().size(), loginData.getData().size());
assertEquals(oneSp.getTotal(), loginData.getTotal());
}
private void checkStatistics(SpStatistic spStatistic) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date entryDate = null;
try {
entryDate = sdf.parse("2012-03-19 11:48:42");
} catch (ParseException e) {
e.printStackTrace();
}
assertEquals(entryDate.getTime(), spStatistic.getEntryTime());
}
@Test
public void testVersStatistics() {
Response result = cruncherResource.getVersStatistics(1, 2013, "sp2");
assertNotNull(result);
VersStatistic stats = (VersStatistic) result.getEntity();
assertNotNull(stats);
assertEquals(120, stats.getTotalLogins());
assertEquals(new Long(120), stats.getInstitutionLogins().get("mock-institution-id"));
}
}
|
9241a92ee52b24ca686c523a00cb8249fc1a6bda
| 1,629 |
java
|
Java
|
Java/808.java
|
vindhya2g/LeetCode
|
73790d44605fbd51e8f7e804b9808e364fcfc680
|
[
"MIT"
] | 854 |
2018-11-09T08:06:16.000Z
|
2022-03-31T06:05:53.000Z
|
Java/808.java
|
vindhya2g/LeetCode
|
73790d44605fbd51e8f7e804b9808e364fcfc680
|
[
"MIT"
] | 29 |
2019-06-02T05:02:25.000Z
|
2021-11-15T04:09:37.000Z
|
Java/808.java
|
vindhya2g/LeetCode
|
73790d44605fbd51e8f7e804b9808e364fcfc680
|
[
"MIT"
] | 347 |
2018-12-23T01:57:37.000Z
|
2022-03-12T14:51:21.000Z
| 28.086207 | 98 | 0.508287 | 1,001,985 |
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public double soupServings(int N) {
if (N > 4800) {
return 1;
}
int servings = N % 25 == 0 ? N/25 : N/25+1;
return helper(servings, servings, new double[servings+1][servings+1]);
}
private double helper(int a, int b, double[][] memo) {
if (a <= 0 && b <= 0) {
return 0.5;
}
if (a <= 0) {
return 1;
}
if (b <= 0) {
return 0;
}
if (memo[a][b] > 0) {
return memo[a][b];
}
double p = 0;
for (int i=1; i<=4; i++) {
p += 0.25 * helper(a-i, b-(4-i), memo);
}
memo[a][b] = p;
return p;
}
}
__________________________________________________________________________________________________
sample 32228 kb submission
class Solution {
static double[][] memo = new double[200][200];
public double soupServings(int N) {
return N >= 4800 ? 1.0 : f((N + 24) / 25, (N + 24) / 25);
}
public double f(int a, int b) {
if (a <= 0 && b <= 0) return 0.5;
if (a <= 0) return 1;
if (b <= 0) return 0;
if (memo[a][b] > 0) return memo[a][b];
memo[a][b] = 0.25 * (f(a - 4, b) + f(a - 3, b - 1) + f(a - 2, b - 2) + f(a - 1, b - 3));
return memo[a][b];
}
}
__________________________________________________________________________________________________
|
9241aa26a56cf8b164e847c1235fca8d717aa1b7
| 15,985 |
java
|
Java
|
enhanced/archive/classlib/java6/modules/x-net/src/test/api/java/org/apache/harmony/xnet/tests/javax/net/ssl/SSLEngineTest.java
|
qinFamily/freeVM
|
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
|
[
"Apache-2.0"
] | 5 |
2017-03-08T20:32:39.000Z
|
2021-07-10T10:12:38.000Z
|
enhanced/archive/classlib/java6/modules/x-net/src/test/api/java/org/apache/harmony/xnet/tests/javax/net/ssl/SSLEngineTest.java
|
qinFamily/freeVM
|
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
|
[
"Apache-2.0"
] | null | null | null |
enhanced/archive/classlib/java6/modules/x-net/src/test/api/java/org/apache/harmony/xnet/tests/javax/net/ssl/SSLEngineTest.java
|
qinFamily/freeVM
|
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
|
[
"Apache-2.0"
] | 4 |
2015-07-07T07:06:59.000Z
|
2018-06-19T22:38:04.000Z
| 30.859073 | 107 | 0.624148 | 1,001,986 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.xnet.tests.javax.net.ssl;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLEngineResult;
import junit.framework.TestCase;
/**
* Tests for SSLEngine class
*
*/
public class SSLEngineTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(SSLEngineTest.class);
}
/**
* Test for <code>SSLEngine()</code> constructor Assertion: creates
* SSLEngine object with null host and -1 port
*/
public void test01() {
SSLEngine e = new mySSLEngine();
assertNull(e.getPeerHost());
assertEquals(e.getPeerPort(), -1);
String[] suites = { "a", "b", "c" };
e.setEnabledCipherSuites(suites);
assertEquals(e.getEnabledCipherSuites().length, suites.length);
}
/**
* Test for <code>SSLEngine(String host, int port)</code> constructor
*/
public void test02() throws SSLException {
int port = 1010;
SSLEngine e = new mySSLEngine(null, port);
assertNull(e.getPeerHost());
assertEquals(e.getPeerPort(), port);
try {
e.beginHandshake();
} catch (SSLException ex) {
}
}
/**
* Test for <code>SSLEngine(String host, int port)</code> constructor
*/
public void test03() {
String host = "new host";
int port = 8080;
SSLEngine e = new mySSLEngine(host, port);
assertEquals(e.getPeerHost(), host);
assertEquals(e.getPeerPort(), port);
String[] suites = { "a", "b", "c" };
e.setEnabledCipherSuites(suites);
assertEquals(e.getEnabledCipherSuites().length, suites.length);
e.setUseClientMode(true);
assertTrue(e.getUseClientMode());
}
/**
* Test for <code>wrap(ByteBuffer src, ByteBuffer dst)</code> method
* Assertions:
* throws IllegalArgumentException when src or dst is null
* throws ReadOnlyBufferException when dst is ReadOnly byte buffer
*
* Check that implementation behavior follows RI:
* jdk 1.5 does not throw IllegalArgumentException when parameters are null
* and does not throw ReadOnlyBufferException if dst is read only byte buffer
*/
public void testWrap01() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bbN = null;
ByteBuffer bb = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine(host, port);
e.wrap(bbN, bb);
e.wrap(bb, bbN);
ByteBuffer roBb = bb.asReadOnlyBuffer();
assertTrue("Not read only byte buffer", roBb.isReadOnly());
e.wrap(bb, roBb);
}
/**
* Test for <code>wrap(ByteBuffer[] srcs, ByteBuffer dst)</code> method
*
* Assertions: throws IllegalArgumentException when srcs or dst is null or
* srcs contains null byte buffer; throws ReadOnlyBufferException when dst
* is read only byte buffer
*
* Check that implementation behavior follows RI:
* jdk 1.5 does not throw IllegalArgumentException when dst is null or
* if srcs contains null elements It does not throw ReadOnlyBufferException
* for read only dst
*/
public void testWrap02() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer[] bbNA = null;
ByteBuffer[] bbA = { null, ByteBuffer.allocate(10), null };
ByteBuffer bb = ByteBuffer.allocate(10);
ByteBuffer bbN = null;
SSLEngine e = new mySSLEngine(host, port);
try {
e.wrap(bbNA, bb);
fail("IllegalArgumentException must be thrown for null srcs byte buffer array");
} catch (IllegalArgumentException ex) {
}
e.wrap(bbA, bb);
e.wrap(bbA, bbN);
ByteBuffer roBb = bb.asReadOnlyBuffer();
bbA[0] = ByteBuffer.allocate(100);
bbA[2] = ByteBuffer.allocate(20);
assertTrue("Not read only byte buffer", roBb.isReadOnly());
e.wrap(bbA, roBb);
}
/**
* Test for <code>wrap(ByteBuffer src, ByteBuffer dst)</code> and
* <code>wrap(ByteBuffer[] srcs, ByteBuffer dst)</code> methods
*
* Assertion: these methods throw SSLException
*/
public void testWrap03() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bbs = ByteBuffer.allocate(100);
ByteBuffer bbd = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine1(host, port);
try {
e.wrap(bbs, bbd);
fail("SSLException must be thrown");
} catch (SSLException ex) {
}
SSLEngineResult res = e.wrap(bbd, bbs);
assertEquals(res.bytesConsumed(), 10);
assertEquals(res.bytesProduced(), 20);
try {
e.wrap(new ByteBuffer[] { bbs }, bbd);
fail("SSLException must be thrown");
} catch (SSLException ex) {
}
res = e.wrap(new ByteBuffer[] { bbd }, bbs);
assertEquals(res.bytesConsumed(), 10);
assertEquals(res.bytesProduced(), 20);
}
/**
* Test for <code>wrap(ByteBuffer src, ByteBuffer dst)</code> method
*
* Assertion: encodes a buffer data into network data.
*
*/
public void testWrap04() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bb = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine(host, port);
SSLEngineResult res = e.wrap(bb, ByteBuffer.allocate(10));
assertEquals(res.bytesConsumed(), 10);
assertEquals(res.bytesProduced(), 20);
}
/**
* Test for <code>wrap(ByteBuffer[] srcs, ByteBuffer dst)</code> method
*
* Assertion: encodes datas from buffers into network data.
*/
public void testWrap05() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bb = ByteBuffer.allocate(10);
ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
SSLEngine e = new mySSLEngine(host, port);
SSLEngineResult res = e.wrap(bbA, bb);
assertEquals(res.bytesConsumed(), 10);
assertEquals(res.bytesProduced(), 20);
}
/**
* Test for <code>unwrap(ByteBuffer src, ByteBuffer dst)</code> method
*
* Assertions:
* throws IllegalArgumentException when src or dst is null
* throws ReadOnlyBufferException when dst is read only byte buffer
*
* Check that implementation behavior follows RI:
* jdk 1.5 does not throw IllegalArgumentException when parameters are null
* and does not throw ReadOnlyBufferException if dst is read only byte buffer
*/
public void testUnwrap01() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bbN = null;
ByteBuffer bb = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine(host, port);
e.unwrap(bbN, bb);
e.unwrap(bb, bbN);
ByteBuffer roBb = bb.asReadOnlyBuffer();
assertTrue("Not read only byte buffer", roBb.isReadOnly());
e.unwrap(bb, roBb);
}
/**
* Test for <code>unwrap(ByteBuffer src, ByteBuffer[] dsts)</code> method
*
* Assertions: throws IllegalArgumentException if parameters are null or
* when dsts contains null elements throws ReadOnlyBufferException when dsts
* contains read only elements
*
* Check that implementation behavior follows RI:
* jdk 1.5 does not throw IllegalArgumentException when src is null or
* if dsts contains null elements It does not throw ReadOnlyBufferException
* when dsts contains read only elements
*/
public void testUnwrap02() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer[] bbNA = null;
ByteBuffer[] bbA = { null, ByteBuffer.allocate(10), null };
ByteBuffer bb = ByteBuffer.allocate(10);
ByteBuffer bbN = null;
SSLEngine e = new mySSLEngine(host, port);
try {
e.unwrap(bb, bbNA);
fail("IllegalArgumentException must be thrown for null dsts byte buffer array");
} catch (IllegalArgumentException ex) {
}
e.unwrap(bb, bbA);
e.unwrap(bbN, bbA);
ByteBuffer bb1 = ByteBuffer.allocate(100);
ByteBuffer roBb = bb1.asReadOnlyBuffer();
bbA[0] = bb1;
bbA[2] = roBb;
assertTrue("Not read only byte buffer", bbA[2].isReadOnly());
e.unwrap(bb, bbA);
}
/**
* Test for <code>unwrap(ByteBuffersrc, ByteBuffer dst)</code> and
* <code>unwrap(ByteBuffer src, ByteBuffer[] dsts)</code> methods
*
* Assertion: these methods throw SSLException
*/
public void testUnwrap03() throws SSLException {
ByteBuffer bbs = ByteBuffer.allocate(100);
ByteBuffer bbd = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine1();
try {
e.unwrap(bbs, bbd);
fail("SSLException must be thrown");
} catch (SSLException ex) {
}
SSLEngineResult res = e.unwrap(bbd, bbs);
assertEquals(res.bytesConsumed(), 1);
assertEquals(res.bytesProduced(), 2);
try {
e.unwrap(bbs, new ByteBuffer[] { bbd });
fail("SSLException must be thrown");
} catch (SSLException ex) {
}
res = e.unwrap(bbd, new ByteBuffer[] { bbs });
assertEquals(res.bytesConsumed(), 1);
assertEquals(res.bytesProduced(), 2);
}
/**
* Test for <code>unwrap(ByteBuffer src, ByteBuffer dst)</code> method
*
* Assertion: decodes network data into a data buffer.
*/
public void testUnwrap04() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer bb = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine(host, port);
SSLEngineResult res = e.unwrap(bb, ByteBuffer.allocate(10));
assertEquals(res.bytesConsumed(), 1);
assertEquals(res.bytesProduced(), 2);
}
/**
* Test for <code>unwrap(ByteBuffer src, ByteBuffer[] dsts)</code> method
*
* Assertion:
* decode network data into data buffers.
*/
public void testUnwrap05() throws SSLException {
String host = "new host";
int port = 8080;
ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
ByteBuffer bb = ByteBuffer.allocate(10);
SSLEngine e = new mySSLEngine(host, port);
SSLEngineResult res = e.unwrap(bb, bbA);
assertEquals(res.bytesConsumed(), 1);
assertEquals(res.bytesProduced(), 2);
}
}
/*
* Additional class for verification SSLEngine constructors
*/
class mySSLEngine extends SSLEngine {
private boolean useClientMode;
private boolean needClientAuth;
private boolean enableSessionCreation;
private boolean wantClientAuth;
private String[] enabledProtocols;
private String[] enabledCipherSuites;
public mySSLEngine() {
super();
}
protected mySSLEngine(String host, int port) {
super(host, port);
}
public void beginHandshake() throws SSLException {
String host = super.getPeerHost();
if ((host == null) || (host.length() == 0)) {
throw new SSLException("");
}
}
public void closeInbound() throws SSLException {
}
public void closeOutbound() {
}
public Runnable getDelegatedTask() {
return null;
}
public String[] getEnabledCipherSuites() {
return enabledCipherSuites;
}
public String[] getEnabledProtocols() {
return enabledProtocols;
}
public boolean getEnableSessionCreation() {
return enableSessionCreation;
}
public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
return SSLEngineResult.HandshakeStatus.FINISHED;
}
public boolean getNeedClientAuth() {
return needClientAuth;
}
public SSLSession getSession() {
return null;
}
public String[] getSupportedCipherSuites() {
return new String[0];
}
public String[] getSupportedProtocols() {
return new String[0];
}
public boolean getUseClientMode() {
return useClientMode;
}
public boolean getWantClientAuth() {
return wantClientAuth;
}
public boolean isInboundDone() {
return false;
}
public boolean isOutboundDone() {
return false;
}
public void setEnabledCipherSuites(String[] suites) {
enabledCipherSuites = suites;
}
public void setEnabledProtocols(String[] protocols) {
enabledProtocols = protocols;
}
public void setEnableSessionCreation(boolean flag) {
enableSessionCreation = flag;
}
public void setNeedClientAuth(boolean need) {
needClientAuth = need;
}
public void setUseClientMode(boolean mode) {
useClientMode = mode;
}
public void setWantClientAuth(boolean want) {
wantClientAuth = want;
}
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts,
int offset, int length) throws SSLException {
return new SSLEngineResult(SSLEngineResult.Status.OK,
SSLEngineResult.HandshakeStatus.FINISHED, 1, 2);
}
public SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length,
ByteBuffer dst) throws SSLException {
return new SSLEngineResult(SSLEngineResult.Status.OK,
SSLEngineResult.HandshakeStatus.FINISHED, 10, 20);
}
}
class mySSLEngine1 extends mySSLEngine {
public mySSLEngine1() {
}
public mySSLEngine1(String host, int port) {
super(host, port);
}
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst)
throws SSLException {
if (src.limit() > dst.limit()) {
throw new SSLException("incorrect limits");
}
return super.unwrap(src, dst);
}
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts)
throws SSLException {
if (src.limit() > dsts[0].limit()) {
throw new SSLException("incorrect limits");
}
return super.unwrap(src, dsts);
}
public SSLEngineResult wrap(ByteBuffer[] srcs, ByteBuffer dst)
throws SSLException {
if (srcs[0].limit() > dst.limit()) {
throw new SSLException("incorrect limits");
}
return super.wrap(srcs, dst);
}
public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst)
throws SSLException {
if (src.limit() > dst.limit()) {
throw new SSLException("incorrect limits");
}
return super.wrap(src, dst);
}
}
|
9241aa35767eca9c8ccd9cb31efa045040902fd6
| 4,237 |
java
|
Java
|
hbl/src/main/java/com/inadco/hbl/model/SimpleCube.java
|
bikash/HBase-Lattice
|
b90f1a3caa0f3ea244613a4adc27a57dc73445b4
|
[
"Apache-2.0"
] | 1 |
2015-11-08T05:21:45.000Z
|
2015-11-08T05:21:45.000Z
|
hbl/src/main/java/com/inadco/hbl/model/SimpleCube.java
|
bikash/HBase-Lattice
|
b90f1a3caa0f3ea244613a4adc27a57dc73445b4
|
[
"Apache-2.0"
] | null | null | null |
hbl/src/main/java/com/inadco/hbl/model/SimpleCube.java
|
bikash/HBase-Lattice
|
b90f1a3caa0f3ea244613a4adc27a57dc73445b4
|
[
"Apache-2.0"
] | null | null | null | 30.702899 | 105 | 0.62143 | 1,001,987 |
/*
*
* Copyright © 2010, 2011 Inadco, 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.inadco.hbl.model;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.Validate;
import com.inadco.hbl.api.AggregateFunction;
import com.inadco.hbl.api.Cube;
import com.inadco.hbl.api.Cuboid;
import com.inadco.hbl.api.Dimension;
import com.inadco.hbl.api.Measure;
/**
* Simple cube model implementation.
*
* @author dmitriy
*
*/
public class SimpleCube implements Cube {
protected String name;
protected Map<String, Dimension> dimensions = new HashMap<String, Dimension>();
protected Map<String, Dimension> readonlyDims = Collections.unmodifiableMap(dimensions);
// mapped by "cuboid path" which is
// the combination of dimensions in the composite hbase key
// specified by name.
protected Map<List<String>, Cuboid> cuboids = new HashMap<List<String>, Cuboid>();
protected Map<String, Measure> measures = new HashMap<String, Measure>();
protected Map<String, Measure> readonlyMeasures = Collections.unmodifiableMap(measures);
protected SimpleAggregateFunctionRegistry afr;
protected long ms;
/**
* constructor
*
* @param name
* cube name
* @param dimensions
* list (set) of dimensions
* @param cuboids
* sequence of cuboids. Order important.
* @param measures
* list (set) of measures
*/
public SimpleCube(String name, Dimension[] dimensions, Cuboid[] cuboids, Measure[] measures) {
super();
this.name = name;
for (Dimension dim : dimensions)
this.dimensions.put(dim.getName(), dim);
for (Cuboid c : cuboids) {
this.cuboids.put(c.getCuboidPath(), c);
c.setTablePrefix(name + "_");
if (c instanceof SimpleCuboid)
((SimpleCuboid) c).setParentCube(this);
}
for (Measure m : measures)
this.measures.put(m.getName(), m);
this.afr = new SimpleAggregateFunctionRegistry();
ms = System.currentTimeMillis();
}
public SimpleCube(String name,
Dimension[] dimensions,
Cuboid[] cuboids,
Measure[] measures,
AggregateFunction[] customFunctions) {
this(name, dimensions, cuboids, measures);
for (AggregateFunction cf : customFunctions)
afr.addFunction(cf);
}
public String getName() {
return name;
}
@Override
public Collection<? extends Cuboid> getCuboids() {
return Collections.unmodifiableCollection(cuboids.values());
}
@Override
public Cuboid findCuboidForPath(List<String> path) {
Validate.notNull(path);
return cuboids.get(path);
}
@Override
public Cuboid findClosestSupercube(Set<String> dimensions) {
// reserved
throw new UnsupportedOperationException();
}
@Override
public Map<String, ? extends Measure> getMeasures() {
return readonlyMeasures;
}
@Override
public Map<String, ? extends Dimension> getDimensions() {
return readonlyDims;
}
@Override
public SimpleAggregateFunctionRegistry getAggregateFunctionRegistry() {
return afr;
}
public long getTimestamp() {
return ms;
}
}
|
9241ab696c6a80f65bb7967a9bc2a5fea47b4d86
| 210 |
java
|
Java
|
master_worker/deployment/digigob/digigob/commons-project/ccomplejos/ccomplejos-base-core/src/main/java/com/egoveris/ccomplejos/base/repository/ViewResumenImpoRepository.java
|
GrupoWeb/k8s_srv_mineco
|
8be27c3d88d52a155a7a577a9a98af8baa68e89d
|
[
"MIT"
] | null | null | null |
master_worker/deployment/digigob/digigob/commons-project/ccomplejos/ccomplejos-base-core/src/main/java/com/egoveris/ccomplejos/base/repository/ViewResumenImpoRepository.java
|
GrupoWeb/k8s_srv_mineco
|
8be27c3d88d52a155a7a577a9a98af8baa68e89d
|
[
"MIT"
] | null | null | null |
master_worker/deployment/digigob/digigob/commons-project/ccomplejos/ccomplejos-base-core/src/main/java/com/egoveris/ccomplejos/base/repository/ViewResumenImpoRepository.java
|
GrupoWeb/k8s_srv_mineco
|
8be27c3d88d52a155a7a577a9a98af8baa68e89d
|
[
"MIT"
] | null | null | null | 26.25 | 96 | 0.866667 | 1,001,988 |
package com.egoveris.ccomplejos.base.repository;
import com.egoveris.ccomplejos.base.model.ViewResumenImpo;
public interface ViewResumenImpoRepository extends AbstractCComplejoRepository<ViewResumenImpo>{
}
|
9241ab8a29f355ac622b723c1b5b16bbd26873e1
| 28,758 |
java
|
Java
|
kernel/kernel-impl/src/test/java/org/sakaiproject/tool/impl/MySessionTest.java
|
txstate-etc/tracs
|
461c2e8ebface6f2801859ff9610682e3f048cec
|
[
"ECL-2.0"
] | 13 |
2016-05-25T16:12:49.000Z
|
2021-04-09T01:49:24.000Z
|
kernel/kernel-impl/src/test/java/org/sakaiproject/tool/impl/MySessionTest.java
|
txstate-etc/tracs
|
461c2e8ebface6f2801859ff9610682e3f048cec
|
[
"ECL-2.0"
] | 265 |
2015-10-19T02:40:55.000Z
|
2022-03-28T07:24:49.000Z
|
kernel/kernel-impl/src/test/java/org/sakaiproject/tool/impl/MySessionTest.java
|
txstate-etc/tracs
|
461c2e8ebface6f2801859ff9610682e3f048cec
|
[
"ECL-2.0"
] | 7 |
2016-02-08T11:41:40.000Z
|
2021-06-08T18:18:02.000Z
| 41.263989 | 165 | 0.782136 | 1,001,989 |
package org.sakaiproject.tool.impl;
import org.apache.commons.lang.mutable.MutableLong;
import org.jmock.Expectations;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.thread_local.api.ThreadLocalManager;
import org.sakaiproject.tool.api.*;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.util.*;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
/**
* Verifies behavior of {@link MySession}, which
* is the standard implementation of {@link Session}.
*
* <p>Tests are not comprehensive. Where an implementation is simple
* field access, the corresponding test has typically been skipped.</p>
*
* <p>Read on for more design notes.</p>
*
* <p>Theoretically, this guards against regressions in this module.
* In reality, though, this test will eventually fail as-is b/c it
* actually does test <code>MySession</code> as a unit as opposed to,
* for example, relying on factory methods like
* {@link SessionComponent#startSession()}. Thus, were
* <code>MySession</code> refactored to a top-level class, which we
* expect, this test will need to be modified accordingly. So we were
* forced to choose between "pure" unit tests, which break
* (paradoxically) if the relationship between <code>MySession</code>
* and <code>SessionComponent</code> changes, and black box-ish tests
* which intentionally obscure the division of responsibilities between
* <code>MySession</code> and <code>SessionComponent</code>.</p>
*
* <p>We decided to pursue "pure" unit tests in combination with a small
* quantity of black box-ish tests in {@link SessionComponentRegressionTest}
* to guard against complete failure. For example, see
* {@link SessionComponentRegressionTest#testGetSessionReturnsNullIfSessionExpired()},
* which implicitly tests callbacks to <code>SessionComponent</code>
* from {@link Session#invalidate()}. We felt this was the correct
* decision because testing the behavior of factory methods should be a
* separate concern from testing the behavior of the created object
* itself. Such a design improves the overall quality of the code base
* while still satisfying our original goal of supporting anticipated
* modifications to both {@link SessionComponent} and its internal
* implementations of the Sessions domain.</p>
*
*
* @author [email protected]
*
*/
public class MySessionTest extends BaseSessionComponentTest {
public void testCreatedInExpectedState() throws Exception {
final String sessionId = "SESSION_ID";
doTestCreatedInExpectedState(sessionId, new Callable<MySession>() {
public MySession call() throws Exception {
return createSession(sessionId);
}
});
}
public void testCreatedInExpectedStateWithClientSpecifiedId()
throws Exception {
final String sessionId = "SESSION_ID";
doTestCreatedInExpectedState(sessionId, new Callable<MySession>() {
public MySession call() throws Exception {
return createSessionWithClientSpecifiedId(sessionId);
}
});
}
protected void doTestCreatedInExpectedState(String sessionId,
Callable<MySession> factoryCallback) throws Exception {
MySession session = factoryCallback.call();
assertEquals(sessionId, session.getId());
assertTrue(session.getCreationTime() > 0);
assertEquals(session.getCreationTime(), session.getLastAccessedTime());
assertEquals(sessionComponent.m_defaultInactiveInterval, session
.getMaxInactiveInterval());
assertNull(session.getUserId());
assertNull(session.getUserEid());
assertFalse(session.getAttributeNames().hasMoreElements());
}
/**
* {@link MySession#invalidate()} should behave like
* {@link MySession#clear()} but with extra logic for unsetting itself as
* the "current" session.
*
* @see #doTestSessionClear(org.sakaiproject.tool.impl.MySessionTest.MyTestableSession,
* Runnable)
*/
public void testInvalidateClearsSessionAndUnsetsItselfAsCurrent() {
allowToolCheck("simple.unit.test");
allowPlacementCheck("sakai-context-1");
final MyTestableSession session = createSession();
doTestSessionClear(session, new Runnable() {
public void run() {
expectGetAndUnsetCurrentSession(session);
session.invalidate();
}
});
}
/**
* Exactly the same as {@link #testInvalidateClearsSessionAndUnsetsItselfAsCurrent()}
* except that the session's currentness should not be affected.
*
* @see #doTestSessionClear(org.sakaiproject.tool.impl.MySessionTest.MyTestableSession, Runnable)
*/
public void testClearUnbindsAttributes() {
allowToolCheck("simple.unit.test");
allowPlacementCheck("sakai-context-1");
final MyTestableSession session = createSession();
doTestSessionClear(session, new Runnable() {
public void run() {
session.clear();
}
});
}
protected void doTestSessionClear(final MyTestableSession session, Runnable codeExerciseCallback) {
ContextSession contextSession = getContextSession(session, "CONTEXT_SESSION_ID");
ToolSession toolSession = getToolSession(session, "PLACEMENT_ID");
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
setNewListeningAttribValue(contextSession, "CONTEXT_SESSION_ATTRIB_KEY");
setNewListeningAttribValue(toolSession, "TOOL_SESSION_ATTRIB_KEY");
codeExerciseCallback.run();
assertHasNoAttributes(session);
assertHasNoAttributes(toolSession);
assertHasNoAttributes(contextSession);
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue);
}}, session.unbindInvokedWith);
// Oddly, we can still use the session as a factory even after its been
// invalidated. Were this to change, we'd need to devise a more clever
// mechanism for detecting cascaded context/tool session invalidation.
assertNotSame(contextSession, session.getContextSession(contextSession.getContextId()));
assertNotSame(toolSession, session.getToolSession(toolSession.getPlacementId()));
}
/**
* Hard to believe this is the correct behavior, but this is what
* the "legacy" implementation does. The {@link Session}'s own attributes
* are selectively filtered, retaining only those named by the specified
* <code>Collection</code>, but all child {@link ToolSession} and
* {@link ContextSession} attributes are wiped away by virtue of a call to
* {@link Session#clear()}.
*/
public void testClearExceptFiltersSessionAttribsButClearsAllToolAndContextSessionAttribs() {
MyTestableSession session = createSession();
ContextSession contextSession = getContextSession(session, "CONTEXT_SESSION_ID");
allowToolCheck("simple.unit.test");
allowPlacementCheck("PLACEMENT_ID");
ToolSession toolSession = getToolSession(session, "PLACEMENT_ID");
final String sessionAttribKey1 = "SESSION_ATTRIB_KEY_1";
final String sessionAttribKey2 = "SESSION_ATTRIB_KEY_2";
final ListeningAttribValue sessionAttribValue1 =
setNewListeningAttribValue(session, sessionAttribKey1);
final ListeningAttribValue sessionAttribValue2 =
setNewListeningAttribValue(session, sessionAttribKey2);
setNewListeningAttribValue(contextSession, "CONTEXT_SESSION_ATTRIB_KEY");
setNewListeningAttribValue(toolSession, "TOOL_SESSION_ATTRIB_KEY");
session.clearExcept(new HashSet<String>() {{ add(sessionAttribKey1); }});
assertEquals(sessionAttribValue1, session.getAttribute(sessionAttribKey1));
assertNull(session.getAttribute(sessionAttribKey2));
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey2, sessionAttribValue2);
}}, session.unbindInvokedWith);
assertHasNoAttributes(toolSession);
assertHasNoAttributes(contextSession);
}
public void testRemoveAttributeReleasesAttributeAndFiresUnbind() {
MyTestableSession session = createSession();
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
session.removeAttribute(sessionAttribKey);
assertNull(session.getAttribute(sessionAttribKey));
assertHasNoAttributes(session);
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue);
}}, session.unbindInvokedWith);
}
public void testSetAndRemoveAttributeDoNotUpdateLastAccessedTime()
throws InterruptedException {
MyTestableSession session = createSession();
long origLastAccessed = session.getLastAccessedTime();
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
Thread.sleep(2); // we might execute too quickly to affect lastAccessedTime
session.removeAttribute(sessionAttribKey);
assertEquals(origLastAccessed, session.getLastAccessedTime());
}
public void testSettingNullAttributeValueReleasesAttributeAndFiresUnbind() {
MyTestableSession session = createSession();
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
session.setAttribute(sessionAttribKey, null);
assertNull(session.getAttribute(sessionAttribKey));
assertHasNoAttributes(session);
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue);
}}, session.unbindInvokedWith);
}
public void testSetAttributeCachesAttributeAndFiresBind() {
MyTestableSession session = createSession();
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
assertEquals(sessionAttribValue, session.getAttribute(sessionAttribKey));
assertEquals(sessionAttribKey, session.getAttributeNames().nextElement());
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue);
}}, session.bindInvokedWith);
}
public void testSetAttributeOverwritesExistingAttributeAndFiresBindAndUnbind() {
MyTestableSession session = createSession();
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue1 =
setNewListeningAttribValue(session, sessionAttribKey);
final ListeningAttribValue sessionAttribValue2 =
setNewListeningAttribValue(session, sessionAttribKey);
assertEquals(sessionAttribValue2, session.getAttribute(sessionAttribKey));
assertEquals(sessionAttribKey, session.getAttributeNames().nextElement());
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue1);
}}, session.unbindInvokedWith);
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue2);
}}, session.bindInvokedWith);
}
public void testLazilyCreatesToolSessionInExpectedState() {
MySession session = createSession();
session.setUserEid("USER_EID");
session.setUserId("USER_ID");
String toolSessionId = "TOOL_SESSION_ID";
String placementId = "TOOL_PLACEMENT_ID";
allowToolCheck("sakai.tool.id");
allowPlacementCheck(placementId);
ToolSession toolSession = getToolSession(session, placementId, toolSessionId);
assertEquals(toolSessionId, toolSession.getId());
assertEquals(placementId, toolSession.getPlacementId());
assertTrue(toolSession.getCreationTime() > 0);
assertTrue(toolSession.getLastAccessedTime() >= toolSession.getCreationTime());
assertEquals(session.getUserEid(), toolSession.getUserEid());
assertEquals(session.getUserId(), toolSession.getUserId());
assertHasNoAttributes(toolSession);
}
public void testLazilyCreatesContextSessionInExpectedState() {
MySession session = createSession();
session.setUserEid("USER_EID");
session.setUserId("USER_ID");
String contextSessionId = "CONTEXT_SESSION_ID";
String contextId = "CONTEXT_ID";
ContextSession contextSession = getContextSession(session, contextId, contextSessionId);
assertEquals(contextSessionId, contextSession.getId());
assertEquals(contextId, contextSession.getContextId());
assertTrue(contextSession.getCreationTime() > 0);
assertTrue(contextSession.getLastAccessedTime() >= contextSession.getCreationTime());
assertEquals(session.getUserEid(), contextSession.getUserEid());
assertEquals(session.getUserId(), contextSession.getUserId());
assertHasNoAttributes(contextSession);
}
// note this is part of the protected API
public void testIsInactive() throws InterruptedException {
//return ((m_inactiveInterval > 0) && (System.currentTimeMillis() > (m_accessed + (m_inactiveInterval * 1000))));
MySession session = createSession();
int inactivityThreshold = 1;
session.setMaxInactiveInterval(1);
session.setActive();
Thread.sleep(inactivityThreshold * 2000);
assertTrue(session.isInactive());
}
public void testNeverInactiveIfMaxInactiveIntervalLteZero() {
MySession session = createSession();
session.setMaxInactiveInterval(0);
assertFalse(session.isInactive());
session.setMaxInactiveInterval(-1);
assertFalse(session.isInactive());
}
public void testSetActiveDoesNotUpdateTimeExpirationSuggestion() {
// inactivity in seconds
int inactivityThreshold = 30;
// original expirationTimeSuggestion value gets set to current time + MaxInActive
MySession session = createSessionSetMaxInActive(inactivityThreshold);
long originalValue = session.expirationTimeSuggestion.longValue();
// setActive should force expirationTimeSuggestion value to be updated
// if the difference between currentTime and expiry time is smaller then inactive period/2
session.setActive();
long newValue = session.expirationTimeSuggestion.longValue();
// make sure the expiry value was not updated (because we let no time expire)
// by asserting the original and new value are the same
assertEquals(originalValue, newValue);
}
public void testSetActiveUpdatesTimeExpirationSuggestion() {
// inactivity in seconds
int inactivityThreshold = 30;
// original expirationTimeSuggestion value gets set to current time + MaxInActive
// Simulate some time has past since the session was last accessed by setting the accessed time
long pastTime = now() - ((inactivityThreshold*1000)+5000);
MySession session = createSessionSetMaxInActiveAndAccessTime(inactivityThreshold,pastTime);
long originalValue = session.expirationTimeSuggestion.longValue();
// setActive should force expirationTimeSuggestion value to be updated
// if the difference between currentTime and expiry time is smaller then inactive period/2
session.setActive();
long newValue = session.expirationTimeSuggestion.longValue();
// make sure the expiry value was not updated (because we let no time expire)
// by asserting the original and new value are the same
assertNotSame(Long.valueOf(originalValue), Long.valueOf(newValue));
}
public MySession createSessionSetMaxInActive(int maxInactive) {
MySession session = createSession();
session.setMaxInactiveInterval(maxInactive);
return session;
}
public MySession createSessionSetMaxInActiveAndAccessTime(int maxInactive, long accessedTime) {
MySession session = createSessionSetMaxInActive(maxInactive);
session.m_accessed = accessedTime;
return session;
}
public long now() {
return System.currentTimeMillis();
}
public void testEqualsMatchesAnySessionImplementorHavingSameId() {
// attributes added in for a little noise, to be "extra sure" we only care about IDs.
final MySession session1 = createSession();
setNewListeningAttribValue(session1, "SESSION_ATTRIB_KEY_1");
MySession session2 = createSession(session1.getId());
setNewListeningAttribValue(session2, "SESSION_ATTRIB_KEY_2");
assertEquals(session1, session2);
// now lets see if it cares about a sibling implementation
final Session session3 = mock(Session.class);
checking(new Expectations(){{
one(session3).getId();
will(returnValue(session1.getId()));
}});
assertEquals(session1, session3);
}
public void testUnbindNotifiesValueIfIsSessionBindingListener() {
MySession session = createSession();
ListeningAttribValue attribValue = new ListeningAttribValue();
session.unBind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.sessionValueUnboundInvokedWith.size());
SessionBindingEvent event = attribValue.sessionValueUnboundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
}
public void testUnbindNotifiesValueIfIsHttpSessionBindingListener() {
MySession session = createSession();
ListeningAttribValue attribValue = new ListeningAttribValue();
session.unBind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.httpSessionValueUnboundInvokedWith.size());
HttpSessionBindingEvent event = attribValue.httpSessionValueUnboundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
}
public void testBindNotifiesValueIfIsSessionBindingListener() {
MySession session = createSession();
ListeningAttribValue attribValue = new ListeningAttribValue();
session.bind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.sessionValueBoundInvokedWith.size());
SessionBindingEvent event = attribValue.sessionValueBoundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
}
public void testBindNotifiesValueIfIsHttpSessionBindingListener() {
MySession session = createSession();
ListeningAttribValue attribValue = new ListeningAttribValue();
session.bind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.httpSessionValueBoundInvokedWith.size());
HttpSessionBindingEvent event = attribValue.httpSessionValueBoundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
}
public void testNonPortableAttributesStoreAndRetrieve() {
MySession session = createSession();
String value = "VALUE";
System.setProperty("sakai.cluster.terracotta","true");
session.setAttribute("SESSION_KEY", value);
System.setProperty("sakai.cluster.terracotta","false");
session.setAttribute("SESSION_KEY_2", value);
assertEquals(value,session.getAttribute("SESSION_KEY"));
assertEquals(value,session.getAttribute("SESSION_KEY_2"));
}
public void testNonPortableBindNotifiesValueIfIsSessionBindingListener() {
MySession session = createSession();
System.setProperty("sakai.cluster.terracotta","true");
ListeningAttribValue attribValue = new ListeningAttribValue();
session.bind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.sessionValueBoundInvokedWith.size());
SessionBindingEvent event = attribValue.sessionValueBoundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
System.setProperty("sakai.cluster.terracotta","false");
}
public void testNonPortableUnbindNotifiesValueIfIsSessionBindingListener() {
MySession session = createSession();
System.setProperty("sakai.cluster.terracotta","true");
ListeningAttribValue attribValue = new ListeningAttribValue();
session.unBind("SESSION_KEY", attribValue);
assertEquals(1, attribValue.sessionValueUnboundInvokedWith.size());
SessionBindingEvent event = attribValue.sessionValueUnboundInvokedWith.get(0);
assertEventState(event, "SESSION_KEY", session, attribValue);
System.setProperty("sakai.cluster.terracotta","false");
}
public void testNonPortableRemoveAttributeReleasesAttributeAndFiresUnbind() {
System.setProperty("sakai.cluster.terracotta","true");
MyTestableSession session = createSession();
allowToolCheck("simple.unit.test");
final String sessionAttribKey = "SESSION_ATTRIB_KEY";
final ListeningAttribValue sessionAttribValue =
setNewListeningAttribValue(session, sessionAttribKey);
session.removeAttribute(sessionAttribKey);
assertNull(session.getAttribute(sessionAttribKey));
assertHasNoAttributes(session);
assertEquals(new HashMap<String,Object>() {{
put(sessionAttribKey, sessionAttribValue);
}}, session.unbindInvokedWith);
System.setProperty("sakai.cluster.terracotta","false");
}
public void testNonPortableClearUnbindsAttributes() {
final MyTestableSession session = createSession();
System.setProperty("sakai.cluster.terracotta","true");
allowToolCheck("simple.unit.test");
allowPlacementCheck("sakai-context-1");
doTestSessionClear(session, new Runnable() {
public void run() {
session.clear();
}
});
System.setProperty("sakai.cluster.terracotta","false");
}
protected void assertEventState(SessionBindingEvent event, String name,
MySession session, Object value) {
assertEquals(name, event.getName());
assertEquals(session, event.getSession());
assertEquals(value, event.getValue());
}
protected void assertEventState(HttpSessionBindingEvent event, String name,
MySession session, Object value) {
assertEquals(name, event.getName());
assertEquals(session, event.getSession());
assertEquals(value, event.getValue());
}
protected ContextSession getContextSession(MySession session,
String contextId) {
allowCreateUuidRequest();
return session.getContextSession(contextId);
}
protected ContextSession getContextSession(MySession session,
String contextId, String contextSessionId) {
expectCreateUuidRequest(contextSessionId); // mtd signature implies we must _expect_ the IdManager call
return session.getContextSession(contextId);
}
protected ToolSession getToolSession(MySession session,
String placementId) {
allowCreateUuidRequest();
return session.getToolSession(placementId);
}
protected ToolSession getToolSession(MySession session,
String placementId, String toolSessionId) {
expectCreateUuidRequest(toolSessionId); // mtd signature implies we must _expect_ the IdManager call
return session.getToolSession(placementId);
}
protected MyTestableSession createSession() {
String uuid = nextUuid();
return new MyTestableSession(sessionComponent,uuid,threadLocalManager,idManager,sessionListener,new MyNonPortableSession());
}
protected MyTestableSession createSession(String sessionId) {
return new MyTestableSession(sessionComponent,sessionId,threadLocalManager,idManager,sessionListener,new MyNonPortableSession());
}
/**
* Like {@link #createSession(String)} but assigns the given ID
* directly, rather than allowing the created session to
* retrieve an ID from the <code>IdManager</code>. This allows
* us to test a different constructor than does
* {@link #createSession(String)}.
*
* @param sessionId
* @return
*/
protected MyTestableSession createSessionWithClientSpecifiedId(String sessionId) {
return new MyTestableSession(sessionComponent, sessionId, threadLocalManager, idManager, sessionListener, new MyNonPortableSession());
}
protected ListeningAttribValue setNewListeningAttribValue(
ToolSession toolSession, String key) {
ListeningAttribValue value = new ListeningAttribValue();
toolSession.setAttribute(key, value);
return value;
}
protected ListeningAttribValue setNewListeningAttribValue(
ContextSession contextSession, String key) {
ListeningAttribValue value = new ListeningAttribValue();
contextSession.setAttribute(key, value);
return value;
}
protected ListeningAttribValue setNewListeningAttribValue(MySession session,
String key) {
ListeningAttribValue value = new ListeningAttribValue();
session.setAttribute(key, value);
return value;
}
protected void assertHasNoAttributes(ContextSession contextSession) {
assertFalse(contextSession.getAttributeNames().hasMoreElements());
}
protected void assertHasNoAttributes(ToolSession toolSession) {
assertFalse(toolSession.getAttributeNames().hasMoreElements());
}
protected void assertHasNoAttributes(MySession session) {
assertFalse(session.getAttributeNames().hasMoreElements());
}
/**
* Verifies that multiple {@link MySession#invalidate()} calls can proceed
* concurrently without error and with the session properly invalidated
* after all threads return. This turns out to be quite difficult to test
* reliably, even with knowledge of the implementation. In fact, you can't get
* the following test to fail, even if you remove all explicit concurrency
* precautions in <code>MySession.invalidate()</code>. It will fail, though,
* if sleep times are injected after taking a local copies of the attribute
* map, though. So, at best this test will catch truly gross errors, but
* for the most part is dead-weight.
*/
public void testConcurrentInvalidation() {
final MyTestableSession session = createSession();
Collection<ListeningAttribValue> attribValues =
new ArrayList<ListeningAttribValue>();
attribValues.add(setNewListeningAttribValue(session, "SESSION_ATTRIB_KEY_1"));
attribValues.add(setNewListeningAttribValue(session, "SESSION_ATTRIB_KEY_2"));
attribValues.add(setNewListeningAttribValue(session, "SESSION_ATTRIB_KEY_3"));
attribValues.add(setNewListeningAttribValue(session, "SESSION_ATTRIB_KEY_4"));
attribValues.add(setNewListeningAttribValue(session, "SESSION_ATTRIB_KEY_5"));
final Set<Throwable> failures = Collections.synchronizedSet(new HashSet<Throwable>());
final int workersCnt = 5;
final CyclicBarrier invalidateBarrier = new CyclicBarrier(workersCnt);
final CyclicBarrier testExitBarrier = new CyclicBarrier(workersCnt + 1);
class Worker extends Thread {
public void run() {
try {
invalidateBarrier.await(10, TimeUnit.SECONDS);
session.invalidate();
} catch ( Throwable t ) {
failures.add(t);
} finally {
try {
testExitBarrier.await();
} catch ( Throwable t ) {}
}
}
}
allowGetAndUnsetCurrentSession(session);
Worker[] workers = new Worker[workersCnt];
for ( int p = 0; p < workersCnt; p++) {
workers[p] = new Worker();
workers[p].start();
}
try {
testExitBarrier.await();
} catch ( InterruptedException e ) {
} catch ( BrokenBarrierException e ) {}
assertEquals(Collections.synchronizedSet(new HashSet<Throwable>()), failures);
for ( ListeningAttribValue attribValue : attribValues ) {
assertEquals(1, attribValue.httpSessionValueUnboundInvokedWith.size());
assertEquals(1, attribValue.sessionValueUnboundInvokedWith.size());
}
}
private static class MyTestableSession extends MySession {
private Map<String,Object> unbindInvokedWith = new HashMap<String,Object>();
private Map<String,Object> bindInvokedWith = new HashMap<String,Object>();
public MyTestableSession(SessionComponent outer, String sessionId, ThreadLocalManager threadLocalManager,
IdManager idManager, SessionAttributeListener sessionListener, NonPortableSession nps) {
super(outer, sessionId, threadLocalManager, idManager, outer, sessionListener, outer.getInactiveInterval(),nps,new MutableLong(System.currentTimeMillis()), null);
}
@Override
protected void unBind(String name, Object value) {
unbindInvokedWith.put(name, value);
super.unBind(name, value);
}
@Override
protected void bind(String name, Object value) {
bindInvokedWith.put(name, value);
super.bind(name, value);
}
}
private static class ListeningAttribValue implements SessionBindingListener, HttpSessionBindingListener {
private List<SessionBindingEvent> sessionValueBoundInvokedWith =
Collections.synchronizedList(new ArrayList<SessionBindingEvent>());
private List<SessionBindingEvent> sessionValueUnboundInvokedWith =
Collections.synchronizedList(new ArrayList<SessionBindingEvent>());
private List<HttpSessionBindingEvent> httpSessionValueBoundInvokedWith =
Collections.synchronizedList(new ArrayList<HttpSessionBindingEvent>());
private List<HttpSessionBindingEvent> httpSessionValueUnboundInvokedWith =
Collections.synchronizedList(new ArrayList<HttpSessionBindingEvent>());
public void valueBound(SessionBindingEvent event) {
this.sessionValueBoundInvokedWith.add(event);
}
public void valueUnbound(SessionBindingEvent event) {
this.sessionValueUnboundInvokedWith.add(event);
}
public void valueBound(HttpSessionBindingEvent event) {
this.httpSessionValueBoundInvokedWith.add(event);
}
public void valueUnbound(HttpSessionBindingEvent event) {
this.httpSessionValueUnboundInvokedWith.add(event);
}
}
/* Questioning the cost/benefit ration of the following:
public void testConcurrentInvalidationAndSetAttribute() {
fail("implement me");
}
public void testConcurrentClear() {
fail("implement me");
}
public void testConcurrentSetAttributeAndGetAttributeNames() {
fail("implement me");
}
public void testConcurrentClearExcept() {
fail("implement me");
}
*/
}
|
9241abfbf8bd4ef499a799f00c30223451a40e4d
| 2,763 |
java
|
Java
|
android application/app/src/main/java/com/slensky/focussis/parser/CalendarEventParser.java
|
emnaayedi/Smart-School-Library
|
9cac5f3b9f97936c1d2dd85815acfa3502b378fb
|
[
"MIT"
] | null | null | null |
android application/app/src/main/java/com/slensky/focussis/parser/CalendarEventParser.java
|
emnaayedi/Smart-School-Library
|
9cac5f3b9f97936c1d2dd85815acfa3502b378fb
|
[
"MIT"
] | null | null | null |
android application/app/src/main/java/com/slensky/focussis/parser/CalendarEventParser.java
|
emnaayedi/Smart-School-Library
|
9cac5f3b9f97936c1d2dd85815acfa3502b378fb
|
[
"MIT"
] | null | null | null | 41.863636 | 258 | 0.65219 | 1,001,990 |
package com.slensky.focussis.parser;
import com.slensky.focussis.data.CalendarEvent;
import com.slensky.focussis.data.CalendarEventDetails;
import com.slensky.focussis.util.DateUtil;
import org.joda.time.DateTime;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
* Created by slensky on 3/18/18.
*/
public class CalendarEventParser extends FocusPageParser {
private static final String TAG = "CalendarEventParser";
private String id;
private CalendarEvent.EventType type;
@Override
public CalendarEventDetails parse(String html) {
Document calendarEvent = Jsoup.parse(html);
Elements tr = calendarEvent.selectFirst("div.scroll_contents").getElementsByTag("tr");
// if the event exists
if (!tr.get(0).getElementsByTag("td").get(1).text().replace('\u00A0', ' ').equals("-")) {
String dateStr = tr.get(0).getElementsByTag("td").get(1).text();
DateTime date = new DateTime(DateUtil.nattyDateParser.parse(dateStr).get(0).getDates().get(0));
String title = tr.get(1).getElementsByTag("td").get(1).text();
int start = type.equals(CalendarEvent.EventType.ASSIGNMENT) ? 5 : 2;
String school = tr.get(start).getElementsByTag("td").get(1).text().replace('\u00A0', ' ').trim();
String notes = tr.get(start + 1).getElementsByTag("td").get(1).text().replace('\u00A0', ' ').trim();
if (notes.trim().equals("-")) {
notes = null;
}
// legacy code to detect if event is assignment
// if (tr.get(2).getElementsByTag("td").get(0).text().equals("Teacher")) {
if (type.equals(CalendarEvent.EventType.ASSIGNMENT)) {
String courseName = tr.get(3).getElementsByTag("td").get(1).text();
String courseInformationStr = tr.get(4).getElementsByTag("td").get(1).text();
HyphenatedCourseInformation courseInformation = parseHyphenatedCourseInformation(courseInformationStr, false, true, true);
return new CalendarEventDetails(date, id, school, title, type, notes, courseInformation.getMeetingDays(), courseName, courseInformation.getPeriod(), courseInformation.getSection(), courseInformation.getTeacher(), courseInformation.getTerm());
}
// event is occasion
return new CalendarEventDetails(date, id, school, title, type, notes, null, null, null, null, null, null);
}
throw new FocusParseException("Calendar event could not be found " + tr.get(0).text());
}
public void setId(String id) {
this.id = id;
}
public void setType(CalendarEvent.EventType type) {
this.type = type;
}
}
|
9241acee6ffeea170862625177713c9ad34063fc
| 2,986 |
java
|
Java
|
ZimbraServer/src/java/com/zimbra/cs/service/account/CreateDistributionList.java
|
fciubotaru/z-pec
|
82335600341c6fb1bb8a471fd751243a90bc4d57
|
[
"MIT"
] | 5 |
2019-03-26T07:51:56.000Z
|
2021-08-30T07:26:05.000Z
|
ZimbraServer/src/java/com/zimbra/cs/service/account/CreateDistributionList.java
|
fciubotaru/z-pec
|
82335600341c6fb1bb8a471fd751243a90bc4d57
|
[
"MIT"
] | 1 |
2015-08-18T19:03:32.000Z
|
2015-08-18T19:03:32.000Z
|
ZimbraServer/src/java/com/zimbra/cs/service/account/CreateDistributionList.java
|
fciubotaru/z-pec
|
82335600341c6fb1bb8a471fd751243a90bc4d57
|
[
"MIT"
] | 13 |
2015-03-11T00:26:35.000Z
|
2020-07-26T16:25:18.000Z
| 40.90411 | 112 | 0.718687 | 1,001,991 |
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2005, 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.service.account;
import java.util.Map;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AccountConstants;
import com.zimbra.common.soap.Element;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.AccessManager;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Group;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.ldap.entry.LdapDistributionList;
import com.zimbra.cs.account.ldap.entry.LdapDynamicGroup;
import com.zimbra.soap.ZimbraSoapContext;
public class CreateDistributionList extends AccountDocumentHandler {
public Element handle(Element request, Map<String, Object> context)
throws ServiceException {
ZimbraSoapContext zsc = getZimbraSoapContext(context);
Provisioning prov = Provisioning.getInstance();
Account acct = getAuthenticatedAccount(zsc);
String name = request.getAttribute(AccountConstants.E_NAME).toLowerCase();
if (!AccessManager.getInstance().canCreateGroup(acct, name)) {
throw ServiceException.PERM_DENIED("you do not have sufficient rights to create distribution list");
}
Map<String, Object> attrs = AccountService.getKeyValuePairs(
request, AccountConstants.E_A, AccountConstants.A_N);
boolean dynamic = request.getAttributeBool(AccountConstants.A_DYNAMIC, true);
// creator of the group will automatically become the first owner of the group
Account creator = getAuthenticatedAccount(zsc);
Group group = prov.createDelegatedGroup(name, attrs, dynamic, creator);
ZimbraLog.security.info(ZimbraLog.encodeAttrs(
new String[] { "cmd", "CreateDistributionList", "name", name }, attrs));
Element response = zsc.createElement(AccountConstants.CREATE_DISTRIBUTION_LIST_RESPONSE);
Element eDL = response.addElement(AccountConstants.E_DL);
eDL.addAttribute(AccountConstants.A_NAME, group.getName());
if (group.isDynamic()) {
eDL.addAttribute(AccountConstants.A_REF, ((LdapDynamicGroup) group).getDN());
} else {
eDL.addAttribute(AccountConstants.A_REF, ((LdapDistributionList) group).getDN());
}
eDL.addAttribute(AccountConstants.A_ID, group.getId());
GetDistributionList.encodeAttrs(group, eDL, null);
return response;
}
}
|
9241ad19a7f83e381fbaa2b456cdd234191ec12e
| 144 |
java
|
Java
|
com.servlets.project1.prashanth/src/com/servlets/project1/prashanth/EmployeeBean.java
|
thesonofgod/javawithshan
|
7102494fdb78f31ac6eaa09c6b477929b9332713
|
[
"Unlicense"
] | null | null | null |
com.servlets.project1.prashanth/src/com/servlets/project1/prashanth/EmployeeBean.java
|
thesonofgod/javawithshan
|
7102494fdb78f31ac6eaa09c6b477929b9332713
|
[
"Unlicense"
] | null | null | null |
com.servlets.project1.prashanth/src/com/servlets/project1/prashanth/EmployeeBean.java
|
thesonofgod/javawithshan
|
7102494fdb78f31ac6eaa09c6b477929b9332713
|
[
"Unlicense"
] | null | null | null | 14.4 | 41 | 0.75 | 1,001,992 |
package com.servlets.project1.prashanth;
public class EmployeeBean {
public EmployeeBean() {
// TODO Auto-generated constructor stub
}
}
|
9241ada313615b911804d878db6a6dc02ba4346d
| 317 |
java
|
Java
|
note/src/main/java/com/designpattern/observer/pushmodel/T.java
|
CodingSoldier/java-learn
|
c480f0c26c95b65f49c082e0ffeb10706bd366b1
|
[
"Apache-2.0"
] | 23 |
2018-02-11T13:28:42.000Z
|
2021-12-24T05:53:13.000Z
|
note/src/main/java/com/designpattern/observer/pushmodel/T.java
|
CodingSoldier/java-learn
|
c480f0c26c95b65f49c082e0ffeb10706bd366b1
|
[
"Apache-2.0"
] | 5 |
2019-12-23T01:51:45.000Z
|
2021-11-30T15:12:08.000Z
|
note/src/main/java/com/designpattern/observer/pushmodel/T.java
|
CodingSoldier/java-learn
|
c480f0c26c95b65f49c082e0ffeb10706bd366b1
|
[
"Apache-2.0"
] | 17 |
2018-02-11T13:28:03.000Z
|
2022-01-24T20:30:02.000Z
| 22.642857 | 56 | 0.671924 | 1,001,993 |
package com.designpattern.observer.pushmodel;
import org.junit.Test;
public class T {
@Test
public void t(){
ConcreteSubject subject = new ConcreteSubject();
Observer observer = new ConcreteObserver();
subject.attach(observer);
subject.change("subject的change方法执行了");
}
}
|
9241ae6ce319555bf3c4d5567668b2e7f9790de8
| 27,386 |
java
|
Java
|
modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/models/Domain.java
|
bd2019us/airavata
|
658385197c476d41b3982683636349db0924701e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/models/Domain.java
|
bd2019us/airavata
|
658385197c476d41b3982683636349db0924701e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
modules/sharing-registry/sharing-registry-stubs/src/main/java/org/apache/airavata/sharing/registry/models/Domain.java
|
bd2019us/airavata
|
658385197c476d41b3982683636349db0924701e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 32.294811 | 186 | 0.667677 | 1,001,994 |
/**
*
* 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.
*/
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.airavata.sharing.registry.models;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
/**
* <p>Domain is the entity that enables multi-tenency in this componenet. Every tenant will be
* operating separately it's own silo which is identified by the domain id. In the current implementation domain id
* will be same as the domain name</p>
* <li>domainId : Will be generated by the server based on the domain name</li>
* <li><b>name</b> : A single word name that identifies the domain e.g seagrid, ultrascan</li>
* <li>description : A short description for the domain</li>
* <li>createdTime : Will be set by the system</li>
* <li>updatedTime : Will be set by the system</li>
*
*/
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
public class Domain implements org.apache.thrift.TBase<Domain, Domain._Fields>, java.io.Serializable, Cloneable, Comparable<Domain> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("Domain");
private static final org.apache.thrift.protocol.TField DOMAIN_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("domainId", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField CREATED_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("createdTime", org.apache.thrift.protocol.TType.I64, (short)4);
private static final org.apache.thrift.protocol.TField UPDATED_TIME_FIELD_DESC = new org.apache.thrift.protocol.TField("updatedTime", org.apache.thrift.protocol.TType.I64, (short)5);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new DomainStandardSchemeFactory());
schemes.put(TupleScheme.class, new DomainTupleSchemeFactory());
}
public String domainId; // optional
public String name; // optional
public String description; // optional
public long createdTime; // optional
public long updatedTime; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
DOMAIN_ID((short)1, "domainId"),
NAME((short)2, "name"),
DESCRIPTION((short)3, "description"),
CREATED_TIME((short)4, "createdTime"),
UPDATED_TIME((short)5, "updatedTime");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // DOMAIN_ID
return DOMAIN_ID;
case 2: // NAME
return NAME;
case 3: // DESCRIPTION
return DESCRIPTION;
case 4: // CREATED_TIME
return CREATED_TIME;
case 5: // UPDATED_TIME
return UPDATED_TIME;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __CREATEDTIME_ISSET_ID = 0;
private static final int __UPDATEDTIME_ISSET_ID = 1;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.DOMAIN_ID,_Fields.NAME,_Fields.DESCRIPTION,_Fields.CREATED_TIME,_Fields.UPDATED_TIME};
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.DOMAIN_ID, new org.apache.thrift.meta_data.FieldMetaData("domainId", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.CREATED_TIME, new org.apache.thrift.meta_data.FieldMetaData("createdTime", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.UPDATED_TIME, new org.apache.thrift.meta_data.FieldMetaData("updatedTime", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(Domain.class, metaDataMap);
}
public Domain() {
this.domainId = "DO_NOT_SET_AT_CLIENTS_ID";
}
/**
* Performs a deep copy on <i>other</i>.
*/
public Domain(Domain other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetDomainId()) {
this.domainId = other.domainId;
}
if (other.isSetName()) {
this.name = other.name;
}
if (other.isSetDescription()) {
this.description = other.description;
}
this.createdTime = other.createdTime;
this.updatedTime = other.updatedTime;
}
public Domain deepCopy() {
return new Domain(this);
}
@Override
public void clear() {
this.domainId = "DO_NOT_SET_AT_CLIENTS_ID";
this.name = null;
this.description = null;
setCreatedTimeIsSet(false);
this.createdTime = 0;
setUpdatedTimeIsSet(false);
this.updatedTime = 0;
}
public String getDomainId() {
return this.domainId;
}
public Domain setDomainId(String domainId) {
this.domainId = domainId;
return this;
}
public void unsetDomainId() {
this.domainId = null;
}
/** Returns true if field domainId is set (has been assigned a value) and false otherwise */
public boolean isSetDomainId() {
return this.domainId != null;
}
public void setDomainIdIsSet(boolean value) {
if (!value) {
this.domainId = null;
}
}
public String getName() {
return this.name;
}
public Domain setName(String name) {
this.name = name;
return this;
}
public void unsetName() {
this.name = null;
}
/** Returns true if field name is set (has been assigned a value) and false otherwise */
public boolean isSetName() {
return this.name != null;
}
public void setNameIsSet(boolean value) {
if (!value) {
this.name = null;
}
}
public String getDescription() {
return this.description;
}
public Domain setDescription(String description) {
this.description = description;
return this;
}
public void unsetDescription() {
this.description = null;
}
/** Returns true if field description is set (has been assigned a value) and false otherwise */
public boolean isSetDescription() {
return this.description != null;
}
public void setDescriptionIsSet(boolean value) {
if (!value) {
this.description = null;
}
}
public long getCreatedTime() {
return this.createdTime;
}
public Domain setCreatedTime(long createdTime) {
this.createdTime = createdTime;
setCreatedTimeIsSet(true);
return this;
}
public void unsetCreatedTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __CREATEDTIME_ISSET_ID);
}
/** Returns true if field createdTime is set (has been assigned a value) and false otherwise */
public boolean isSetCreatedTime() {
return EncodingUtils.testBit(__isset_bitfield, __CREATEDTIME_ISSET_ID);
}
public void setCreatedTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __CREATEDTIME_ISSET_ID, value);
}
public long getUpdatedTime() {
return this.updatedTime;
}
public Domain setUpdatedTime(long updatedTime) {
this.updatedTime = updatedTime;
setUpdatedTimeIsSet(true);
return this;
}
public void unsetUpdatedTime() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __UPDATEDTIME_ISSET_ID);
}
/** Returns true if field updatedTime is set (has been assigned a value) and false otherwise */
public boolean isSetUpdatedTime() {
return EncodingUtils.testBit(__isset_bitfield, __UPDATEDTIME_ISSET_ID);
}
public void setUpdatedTimeIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __UPDATEDTIME_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case DOMAIN_ID:
if (value == null) {
unsetDomainId();
} else {
setDomainId((String)value);
}
break;
case NAME:
if (value == null) {
unsetName();
} else {
setName((String)value);
}
break;
case DESCRIPTION:
if (value == null) {
unsetDescription();
} else {
setDescription((String)value);
}
break;
case CREATED_TIME:
if (value == null) {
unsetCreatedTime();
} else {
setCreatedTime((Long)value);
}
break;
case UPDATED_TIME:
if (value == null) {
unsetUpdatedTime();
} else {
setUpdatedTime((Long)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case DOMAIN_ID:
return getDomainId();
case NAME:
return getName();
case DESCRIPTION:
return getDescription();
case CREATED_TIME:
return getCreatedTime();
case UPDATED_TIME:
return getUpdatedTime();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case DOMAIN_ID:
return isSetDomainId();
case NAME:
return isSetName();
case DESCRIPTION:
return isSetDescription();
case CREATED_TIME:
return isSetCreatedTime();
case UPDATED_TIME:
return isSetUpdatedTime();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof Domain)
return this.equals((Domain)that);
return false;
}
public boolean equals(Domain that) {
if (that == null)
return false;
boolean this_present_domainId = true && this.isSetDomainId();
boolean that_present_domainId = true && that.isSetDomainId();
if (this_present_domainId || that_present_domainId) {
if (!(this_present_domainId && that_present_domainId))
return false;
if (!this.domainId.equals(that.domainId))
return false;
}
boolean this_present_name = true && this.isSetName();
boolean that_present_name = true && that.isSetName();
if (this_present_name || that_present_name) {
if (!(this_present_name && that_present_name))
return false;
if (!this.name.equals(that.name))
return false;
}
boolean this_present_description = true && this.isSetDescription();
boolean that_present_description = true && that.isSetDescription();
if (this_present_description || that_present_description) {
if (!(this_present_description && that_present_description))
return false;
if (!this.description.equals(that.description))
return false;
}
boolean this_present_createdTime = true && this.isSetCreatedTime();
boolean that_present_createdTime = true && that.isSetCreatedTime();
if (this_present_createdTime || that_present_createdTime) {
if (!(this_present_createdTime && that_present_createdTime))
return false;
if (this.createdTime != that.createdTime)
return false;
}
boolean this_present_updatedTime = true && this.isSetUpdatedTime();
boolean that_present_updatedTime = true && that.isSetUpdatedTime();
if (this_present_updatedTime || that_present_updatedTime) {
if (!(this_present_updatedTime && that_present_updatedTime))
return false;
if (this.updatedTime != that.updatedTime)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_domainId = true && (isSetDomainId());
list.add(present_domainId);
if (present_domainId)
list.add(domainId);
boolean present_name = true && (isSetName());
list.add(present_name);
if (present_name)
list.add(name);
boolean present_description = true && (isSetDescription());
list.add(present_description);
if (present_description)
list.add(description);
boolean present_createdTime = true && (isSetCreatedTime());
list.add(present_createdTime);
if (present_createdTime)
list.add(createdTime);
boolean present_updatedTime = true && (isSetUpdatedTime());
list.add(present_updatedTime);
if (present_updatedTime)
list.add(updatedTime);
return list.hashCode();
}
@Override
public int compareTo(Domain other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetDomainId()).compareTo(other.isSetDomainId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDomainId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.domainId, other.domainId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDescription()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetCreatedTime()).compareTo(other.isSetCreatedTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCreatedTime()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.createdTime, other.createdTime);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetUpdatedTime()).compareTo(other.isSetUpdatedTime());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetUpdatedTime()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.updatedTime, other.updatedTime);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Domain(");
boolean first = true;
if (isSetDomainId()) {
sb.append("domainId:");
if (this.domainId == null) {
sb.append("null");
} else {
sb.append(this.domainId);
}
first = false;
}
if (isSetName()) {
if (!first) sb.append(", ");
sb.append("name:");
if (this.name == null) {
sb.append("null");
} else {
sb.append(this.name);
}
first = false;
}
if (isSetDescription()) {
if (!first) sb.append(", ");
sb.append("description:");
if (this.description == null) {
sb.append("null");
} else {
sb.append(this.description);
}
first = false;
}
if (isSetCreatedTime()) {
if (!first) sb.append(", ");
sb.append("createdTime:");
sb.append(this.createdTime);
first = false;
}
if (isSetUpdatedTime()) {
if (!first) sb.append(", ");
sb.append("updatedTime:");
sb.append(this.updatedTime);
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class DomainStandardSchemeFactory implements SchemeFactory {
public DomainStandardScheme getScheme() {
return new DomainStandardScheme();
}
}
private static class DomainStandardScheme extends StandardScheme<Domain> {
public void read(org.apache.thrift.protocol.TProtocol iprot, Domain struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // DOMAIN_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.domainId = iprot.readString();
struct.setDomainIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // DESCRIPTION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // CREATED_TIME
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.createdTime = iprot.readI64();
struct.setCreatedTimeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // UPDATED_TIME
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.updatedTime = iprot.readI64();
struct.setUpdatedTimeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, Domain struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.domainId != null) {
if (struct.isSetDomainId()) {
oprot.writeFieldBegin(DOMAIN_ID_FIELD_DESC);
oprot.writeString(struct.domainId);
oprot.writeFieldEnd();
}
}
if (struct.name != null) {
if (struct.isSetName()) {
oprot.writeFieldBegin(NAME_FIELD_DESC);
oprot.writeString(struct.name);
oprot.writeFieldEnd();
}
}
if (struct.description != null) {
if (struct.isSetDescription()) {
oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
oprot.writeString(struct.description);
oprot.writeFieldEnd();
}
}
if (struct.isSetCreatedTime()) {
oprot.writeFieldBegin(CREATED_TIME_FIELD_DESC);
oprot.writeI64(struct.createdTime);
oprot.writeFieldEnd();
}
if (struct.isSetUpdatedTime()) {
oprot.writeFieldBegin(UPDATED_TIME_FIELD_DESC);
oprot.writeI64(struct.updatedTime);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class DomainTupleSchemeFactory implements SchemeFactory {
public DomainTupleScheme getScheme() {
return new DomainTupleScheme();
}
}
private static class DomainTupleScheme extends TupleScheme<Domain> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, Domain struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetDomainId()) {
optionals.set(0);
}
if (struct.isSetName()) {
optionals.set(1);
}
if (struct.isSetDescription()) {
optionals.set(2);
}
if (struct.isSetCreatedTime()) {
optionals.set(3);
}
if (struct.isSetUpdatedTime()) {
optionals.set(4);
}
oprot.writeBitSet(optionals, 5);
if (struct.isSetDomainId()) {
oprot.writeString(struct.domainId);
}
if (struct.isSetName()) {
oprot.writeString(struct.name);
}
if (struct.isSetDescription()) {
oprot.writeString(struct.description);
}
if (struct.isSetCreatedTime()) {
oprot.writeI64(struct.createdTime);
}
if (struct.isSetUpdatedTime()) {
oprot.writeI64(struct.updatedTime);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, Domain struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(5);
if (incoming.get(0)) {
struct.domainId = iprot.readString();
struct.setDomainIdIsSet(true);
}
if (incoming.get(1)) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
}
if (incoming.get(2)) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
}
if (incoming.get(3)) {
struct.createdTime = iprot.readI64();
struct.setCreatedTimeIsSet(true);
}
if (incoming.get(4)) {
struct.updatedTime = iprot.readI64();
struct.setUpdatedTimeIsSet(true);
}
}
}
}
|
9241aee65d210427f5ecd0a5af26fb71bd0ad0e4
| 4,156 |
java
|
Java
|
aerospike-batch-updater/src/test/java/nosql/batch/update/aerospike/basic/BasicRecoveryTest.java
|
Playtika/nosql-batch-updater
|
bb1bc5276a8309372fd5ea55996e6c039d263855
|
[
"Apache-2.0"
] | 1 |
2021-11-24T23:09:09.000Z
|
2021-11-24T23:09:09.000Z
|
aerospike-batch-updater/src/test/java/nosql/batch/update/aerospike/basic/BasicRecoveryTest.java
|
Playtika/nosql-batch-updater
|
bb1bc5276a8309372fd5ea55996e6c039d263855
|
[
"Apache-2.0"
] | null | null | null |
aerospike-batch-updater/src/test/java/nosql/batch/update/aerospike/basic/BasicRecoveryTest.java
|
Playtika/nosql-batch-updater
|
bb1bc5276a8309372fd5ea55996e6c039d263855
|
[
"Apache-2.0"
] | 1 |
2022-02-04T11:21:10.000Z
|
2022-02-04T11:21:10.000Z
| 39.580952 | 117 | 0.76179 | 1,001,995 |
package nosql.batch.update.aerospike.basic;
import com.aerospike.client.AerospikeClient;
import com.aerospike.client.Key;
import com.aerospike.client.Value;
import com.aerospike.client.async.NioEventLoops;
import nosql.batch.update.BatchOperations;
import nosql.batch.update.BatchUpdater;
import nosql.batch.update.RecoveryTest;
import nosql.batch.update.aerospike.basic.lock.AerospikeBasicBatchLocks;
import nosql.batch.update.aerospike.lock.AerospikeLock;
import nosql.batch.update.util.FixedClock;
import nosql.batch.update.wal.CompletionStatistic;
import nosql.batch.update.wal.ExclusiveLocker;
import nosql.batch.update.wal.WriteAheadLogCompleter;
import org.testcontainers.containers.GenericContainer;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import static nosql.batch.update.aerospike.AerospikeTestUtils.AEROSPIKE_PROPERTIES;
import static nosql.batch.update.aerospike.AerospikeTestUtils.deleteAllRecords;
import static nosql.batch.update.aerospike.AerospikeTestUtils.getAerospikeClient;
import static nosql.batch.update.aerospike.AerospikeTestUtils.getAerospikeContainer;
import static nosql.batch.update.aerospike.basic.BasicConsistencyTest.getValue;
import static nosql.batch.update.aerospike.basic.BasicConsistencyTest.incrementBoth;
import static nosql.batch.update.aerospike.basic.util.BasicHangingOperationsUtil.hangingOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Duration.ONE_SECOND;
public class BasicRecoveryTest extends RecoveryTest {
static final GenericContainer aerospike = getAerospikeContainer();
static final NioEventLoops eventLoops = new NioEventLoops();
static final AerospikeClient client = getAerospikeClient(aerospike, eventLoops);
static final FixedClock clock = new FixedClock();
static BatchOperations<AerospikeBasicBatchLocks, List<Record>, AerospikeLock, Value> operations
= hangingOperations(client, Executors.newCachedThreadPool(), clock,
hangsAcquire, hangsUpdate, hangsRelease, hangsDeleteBatchInWal);
static BatchUpdater<AerospikeBasicBatchLocks, List<Record>, AerospikeLock, Value> updater
= new BatchUpdater<>(operations);
public static final Duration STALE_BATCHES_THRESHOLD = Duration.ofSeconds(1);
static WriteAheadLogCompleter<AerospikeBasicBatchLocks, List<Record>, AerospikeLock, Value> walCompleter
= new WriteAheadLogCompleter<>(
operations, STALE_BATCHES_THRESHOLD,
new DummyExclusiveLocker(),
Executors.newScheduledThreadPool(1));
static String setName = String.valueOf(BasicRecoveryTest.class.hashCode());
static AtomicInteger keyCounter = new AtomicInteger();
private final Key key1 = new Key(AEROSPIKE_PROPERTIES.getNamespace(), setName, keyCounter.incrementAndGet());
private final Key key2 = new Key(AEROSPIKE_PROPERTIES.getNamespace(), setName, keyCounter.incrementAndGet());
@Override
protected void runUpdate() {
for(int i = 0; i < 10; i++){
incrementBoth(key1, key2, updater, client);
}
}
@Override
protected CompletionStatistic runCompleter(){
clock.setTime(STALE_BATCHES_THRESHOLD.toMillis() + 1);
return walCompleter.completeHangedTransactions();
}
@Override
protected void checkForConsistency() {
assertThat(getValue(key1, client)).isEqualTo(getValue(key2, client));
await().timeout(ONE_SECOND).untilAsserted(() ->
assertThat(operations.getWriteAheadLogManager().getStaleBatches(STALE_BATCHES_THRESHOLD)).isEmpty());
}
@Override
protected void cleanUp() throws InterruptedException {
deleteAllRecords(aerospike);
clock.setTime(0);
}
static class DummyExclusiveLocker implements ExclusiveLocker{
@Override
public boolean acquire() {
return true;
}
@Override
public void release() {}
@Override
public void shutdown() {}
}
}
|
9241afb8febf3720564acf67f0d38320543f3b79
| 1,368 |
java
|
Java
|
src/main/java/com/dualion/meetup/service/dto/PadreDTO.java
|
Dualion/meetup-ng-table
|
2b65e9f1208a1085d3dc3f6610a526829ec69e8d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/dualion/meetup/service/dto/PadreDTO.java
|
Dualion/meetup-ng-table
|
2b65e9f1208a1085d3dc3f6610a526829ec69e8d
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/dualion/meetup/service/dto/PadreDTO.java
|
Dualion/meetup-ng-table
|
2b65e9f1208a1085d3dc3f6610a526829ec69e8d
|
[
"Apache-2.0"
] | null | null | null | 18.739726 | 61 | 0.544591 | 1,001,996 |
package com.dualion.meetup.service.dto;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A DTO for the Padre entity.
*/
public class PadreDTO implements Serializable {
private Long id;
private String nombre;
private String apellidos;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PadreDTO padreDTO = (PadreDTO) o;
if ( ! Objects.equals(id, padreDTO.id)) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "PadreDTO{" +
"id=" + id +
", nombre='" + nombre + "'" +
", apellidos='" + apellidos + "'" +
'}';
}
}
|
9241b0176541ef60e6f179f444ccfe9ef6c60673
| 1,797 |
java
|
Java
|
confirmation/src/main/java/com/reservation/confirmation/domain/ReservationEvent.java
|
Artemas-Muzanenhamo/party-reservation
|
6b9720a54ddce0a36bfb00ba613bab72b7de7039
|
[
"MIT"
] | 2 |
2021-11-27T10:03:22.000Z
|
2022-03-20T07:47:00.000Z
|
confirmation/src/main/java/com/reservation/confirmation/domain/ReservationEvent.java
|
Artemas-Muzanenhamo/party-reservation
|
6b9720a54ddce0a36bfb00ba613bab72b7de7039
|
[
"MIT"
] | null | null | null |
confirmation/src/main/java/com/reservation/confirmation/domain/ReservationEvent.java
|
Artemas-Muzanenhamo/party-reservation
|
6b9720a54ddce0a36bfb00ba613bab72b7de7039
|
[
"MIT"
] | null | null | null | 26.426471 | 110 | 0.56483 | 1,001,997 |
package com.reservation.confirmation.domain;
import java.util.Objects;
public class ReservationEvent {
private String secret;
private String name;
private String surname;
private Boolean hasPlusOne;
private Integer plusOne;
public ReservationEvent(String secret, String name, String surname, Boolean hasPlusOne, Integer plusOne) {
this.secret = secret;
this.name = name;
this.surname = surname;
this.hasPlusOne = hasPlusOne;
this.plusOne = plusOne;
}
public String getSecret() {
return secret;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public Boolean getHasPlusOne() {
return hasPlusOne;
}
public Integer getPlusOne() {
return plusOne;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReservationEvent that = (ReservationEvent) o;
return Objects.equals(secret, that.secret) &&
Objects.equals(name, that.name) &&
Objects.equals(surname, that.surname) &&
Objects.equals(hasPlusOne, that.hasPlusOne) &&
Objects.equals(plusOne, that.plusOne);
}
@Override
public int hashCode() {
return Objects.hash(secret, name, surname, hasPlusOne, plusOne);
}
@Override
public String toString() {
return "ReservationEvent{" +
"secret='" + secret + '\'' +
", name='" + name + '\'' +
", surname='" + surname + '\'' +
", hasPlusOne=" + hasPlusOne +
", plusOne=" + plusOne +
'}';
}
}
|
9241b0d0ad9c74c09b04594d58cce74a9fb2b52f
| 2,097 |
java
|
Java
|
sdk/storage/azure-storage-internal-avro/src/main/java/com/azure/storage/internal/avro/implementation/schema/complex/AvroEnumSchema.java
|
yiliuTo/azure-sdk-for-java
|
4536b6e99ded1b2b77f79bc2c31f42566c97b704
|
[
"MIT"
] | 1,350 |
2015-01-17T05:22:05.000Z
|
2022-03-29T21:00:37.000Z
|
sdk/storage/azure-storage-internal-avro/src/main/java/com/azure/storage/internal/avro/implementation/schema/complex/AvroEnumSchema.java
|
yiliuTo/azure-sdk-for-java
|
4536b6e99ded1b2b77f79bc2c31f42566c97b704
|
[
"MIT"
] | 16,834 |
2015-01-07T02:19:09.000Z
|
2022-03-31T23:29:10.000Z
|
sdk/storage/azure-storage-internal-avro/src/main/java/com/azure/storage/internal/avro/implementation/schema/complex/AvroEnumSchema.java
|
yiliuTo/azure-sdk-for-java
|
4536b6e99ded1b2b77f79bc2c31f42566c97b704
|
[
"MIT"
] | 1,586 |
2015-01-02T01:50:28.000Z
|
2022-03-31T11:25:34.000Z
| 31.772727 | 106 | 0.678112 | 1,001,999 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.internal.avro.implementation.schema.complex;
import com.azure.core.util.logging.ClientLogger;
import com.azure.storage.internal.avro.implementation.AvroParserState;
import com.azure.storage.internal.avro.implementation.schema.AvroCompositeSchema;
import com.azure.storage.internal.avro.implementation.schema.primitive.AvroIntegerSchema;
import java.util.List;
import java.util.function.Consumer;
/**
* An enum is encoded by a int, representing the zero-based position of the symbol in the schema.
*
* Add an IntegerSchema and convert the result into the Enum by indexing the values.
*
* Integer
*/
public class AvroEnumSchema extends AvroCompositeSchema {
private final ClientLogger logger = new ClientLogger(AvroEnumSchema.class);
private final List<String> values;
/**
* Constructs a new AvroEnumSchema.
*
* @param symbols The enum symbols.
* @param state The state of the parser.
* @param onResult The result handler.
*/
public AvroEnumSchema(List<String> symbols, AvroParserState state, Consumer<Object> onResult) {
super(state, onResult);
this.values = symbols;
}
@Override
public void pushToStack() {
this.state.pushToStack(this);
/* Read the index, call onIndex. */
AvroIntegerSchema indexSchema = new AvroIntegerSchema(
this.state,
this::onIndex
);
indexSchema.pushToStack();
}
/**
* Index handler.
*
* @param index The index.
*/
private void onIndex(Object index) {
checkType("index", index, Integer.class);
Integer i = (Integer) index;
if (i < 0 || i >= this.values.size()) {
throw logger.logExceptionAsError(new IllegalArgumentException("Invalid index to parse enum"));
}
/* Using the zero-based index, get the appropriate symbol, then we're done. */
this.result = this.values.get(i);
this.done = true;
}
}
|
9241b0dfaa7aafcb7097daa053943a6d6bd73ca8
| 2,441 |
java
|
Java
|
repository/src/test/java/org/polyforms/repository/jpa/executor/LoadTest.java
|
AutoscanForJava/org.polyforms-polyforms
|
2438166289895f8882bfc518e733815e927914cd
|
[
"Apache-2.0"
] | null | null | null |
repository/src/test/java/org/polyforms/repository/jpa/executor/LoadTest.java
|
AutoscanForJava/org.polyforms-polyforms
|
2438166289895f8882bfc518e733815e927914cd
|
[
"Apache-2.0"
] | null | null | null |
repository/src/test/java/org/polyforms/repository/jpa/executor/LoadTest.java
|
AutoscanForJava/org.polyforms-polyforms
|
2438166289895f8882bfc518e733815e927914cd
|
[
"Apache-2.0"
] | 2 |
2022-02-10T17:40:47.000Z
|
2022-02-11T18:09:44.000Z
| 36.984848 | 121 | 0.727571 | 1,002,000 |
package org.polyforms.repository.jpa.executor;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.polyforms.repository.spi.EntityClassResolver;
import org.polyforms.repository.spi.Executor;
import org.springframework.test.util.ReflectionTestUtils;
public class LoadTest {
private final Object repository = new Object();
private EntityManager entityManager;
private EntityClassResolver entityClassResolver;
private Executor executor;
@Before
public void setUp() {
entityClassResolver = EasyMock.createMock(EntityClassResolver.class);
executor = new Load(entityClassResolver);
entityManager = EasyMock.createMock(EntityManager.class);
ReflectionTestUtils.setField(executor, "entityManager", entityManager);
}
@Test
public void load() throws NoSuchMethodException {
final Object mockEntity = new Object();
entityClassResolver.resolve(Object.class);
EasyMock.expectLastCall().andReturn(Object.class);
entityManager.find(Object.class, 1L);
EasyMock.expectLastCall().andReturn(mockEntity);
EasyMock.replay(entityClassResolver, entityManager);
Assert.assertEquals(mockEntity,
executor.execute(repository, Repository.class.getMethod("load", new Class<?>[] { Object.class }), 1L));
EasyMock.verify(entityClassResolver, entityManager);
}
@Test(expected = EntityNotFoundException.class)
public void entityNotFound() throws NoSuchMethodException {
entityClassResolver.resolve(Object.class);
EasyMock.expectLastCall().andReturn(Object.class);
entityManager.find(Object.class, 1L);
EasyMock.expectLastCall().andReturn(null);
EasyMock.replay(entityClassResolver, entityManager);
executor.execute(repository, Repository.class.getMethod("load", new Class<?>[] { Object.class }), 1L);
EasyMock.verify(entityClassResolver, entityManager);
}
@Test(expected = IllegalArgumentException.class)
public void loadWithoutArguments() throws NoSuchMethodException {
executor.execute(repository, Repository.class.getMethod("load", new Class<?>[] { Object.class }), new Object[0]);
}
private static interface Repository {
Object load(Object id);
}
}
|
9241b1f3f984a77fb16e9eab470b506c4534cc8b
| 764 |
java
|
Java
|
springboot-lab/07-mars-designpattern/src/main/java/mars/gupao/adapter/demo/passport/Member.java
|
marswang2020/springboot-lab
|
47e48b5c33b86b45ac23d4fc37ce7dc7b2bab224
|
[
"MIT"
] | null | null | null |
springboot-lab/07-mars-designpattern/src/main/java/mars/gupao/adapter/demo/passport/Member.java
|
marswang2020/springboot-lab
|
47e48b5c33b86b45ac23d4fc37ce7dc7b2bab224
|
[
"MIT"
] | null | null | null |
springboot-lab/07-mars-designpattern/src/main/java/mars/gupao/adapter/demo/passport/Member.java
|
marswang2020/springboot-lab
|
47e48b5c33b86b45ac23d4fc37ce7dc7b2bab224
|
[
"MIT"
] | null | null | null | 16.977778 | 46 | 0.592932 | 1,002,001 |
package mars.gupao.adapter.demo.passport;
/**
* Created by Tom.
*/
public class Member {
private String username;
private String password;
private String mid;
private String info;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
|
9241b1f820411d2b09ef274f19ba39e469f9afb7
| 3,538 |
java
|
Java
|
atlasdb-tests-shared/src/test/java/com/palantir/atlasdb/schema/stream/generated/StreamTestWithHashMetadataCleanupTask.java
|
ferozco/atlasdb
|
c343649c9027936043b3f0d0c92e2852cd2a18b4
|
[
"Apache-2.0"
] | null | null | null |
atlasdb-tests-shared/src/test/java/com/palantir/atlasdb/schema/stream/generated/StreamTestWithHashMetadataCleanupTask.java
|
ferozco/atlasdb
|
c343649c9027936043b3f0d0c92e2852cd2a18b4
|
[
"Apache-2.0"
] | null | null | null |
atlasdb-tests-shared/src/test/java/com/palantir/atlasdb/schema/stream/generated/StreamTestWithHashMetadataCleanupTask.java
|
ferozco/atlasdb
|
c343649c9027936043b3f0d0c92e2852cd2a18b4
|
[
"Apache-2.0"
] | null | null | null | 58.966667 | 185 | 0.767665 | 1,002,002 |
package com.palantir.atlasdb.schema.stream.generated;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.collect.Sets;
import com.palantir.atlasdb.cleaner.api.OnCleanupTask;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.keyvalue.api.BatchColumnRangeSelection;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.keyvalue.api.Namespace;
import com.palantir.atlasdb.protos.generated.StreamPersistence.Status;
import com.palantir.atlasdb.protos.generated.StreamPersistence.StreamMetadata;
import com.palantir.atlasdb.table.description.ValueType;
import com.palantir.atlasdb.transaction.api.Transaction;
import com.palantir.common.streams.KeyedStream;
public class StreamTestWithHashMetadataCleanupTask implements OnCleanupTask {
private final StreamTestTableFactory tables;
public StreamTestWithHashMetadataCleanupTask(Namespace namespace) {
tables = StreamTestTableFactory.of(namespace);
}
@Override
public boolean cellsCleanedUp(Transaction t, Set<Cell> cells) {
StreamTestWithHashStreamMetadataTable metaTable = tables.getStreamTestWithHashStreamMetadataTable(t);
Set<StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow> rows = Sets.newHashSetWithExpectedSize(cells.size());
for (Cell cell : cells) {
rows.add(StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow.BYTES_HYDRATOR.hydrateFromBytes(cell.getRowName()));
}
StreamTestWithHashStreamIdxTable indexTable = tables.getStreamTestWithHashStreamIdxTable(t);
Set<StreamTestWithHashStreamIdxTable.StreamTestWithHashStreamIdxRow> indexRows = rows.stream()
.map(StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow::getId)
.map(StreamTestWithHashStreamIdxTable.StreamTestWithHashStreamIdxRow::of)
.collect(Collectors.toSet());
Map<StreamTestWithHashStreamIdxTable.StreamTestWithHashStreamIdxRow, Iterator<StreamTestWithHashStreamIdxTable.StreamTestWithHashStreamIdxColumnValue>> referenceIteratorByStream
= indexTable.getRowsColumnRangeIterator(indexRows,
BatchColumnRangeSelection.create(PtBytes.EMPTY_BYTE_ARRAY, PtBytes.EMPTY_BYTE_ARRAY, 1));
Set<StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow> streamsWithNoReferences
= KeyedStream.stream(referenceIteratorByStream)
.filter(valueIterator -> !valueIterator.hasNext())
.keys() // (authorized)
.map(StreamTestWithHashStreamIdxTable.StreamTestWithHashStreamIdxRow::getId)
.map(StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow::of)
.collect(Collectors.toSet());
Map<StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow, StreamMetadata> currentMetadata = metaTable.getMetadatas(rows);
Set<Long> toDelete = Sets.newHashSet();
for (Map.Entry<StreamTestWithHashStreamMetadataTable.StreamTestWithHashStreamMetadataRow, StreamMetadata> e : currentMetadata.entrySet()) {
if (e.getValue().getStatus() != Status.STORED || streamsWithNoReferences.contains(e.getKey())) {
toDelete.add(e.getKey().getId());
}
}
StreamTestWithHashStreamStore.of(tables).deleteStreams(t, toDelete);
return false;
}
}
|
9241b2c5552a2672300a70e670c04de7b8ffb8f3
| 1,152 |
java
|
Java
|
src/java/edu/stanford/math/plex4/homology/filtration/IdentityConverter.java
|
ChristianKKelley/javaplex
|
b80ae1f59ed8d7b99e1f20838c280191c4009a53
|
[
"BSD-3-Clause"
] | 188 |
2015-02-05T14:47:44.000Z
|
2022-02-22T11:12:59.000Z
|
src/java/edu/stanford/math/plex4/homology/filtration/IdentityConverter.java
|
sangmanjung/javaplex
|
05a288a4a99f27242d8f4b24e98d4cce749fb71a
|
[
"BSD-3-Clause"
] | 28 |
2015-02-20T07:36:24.000Z
|
2021-05-11T14:22:42.000Z
|
src/java/edu/stanford/math/plex4/homology/filtration/IdentityConverter.java
|
sangmanjung/javaplex
|
05a288a4a99f27242d8f4b24e98d4cce749fb71a
|
[
"BSD-3-Clause"
] | 67 |
2015-01-05T02:39:06.000Z
|
2021-10-01T13:37:08.000Z
| 21.735849 | 96 | 0.743056 | 1,002,003 |
package edu.stanford.math.plex4.homology.filtration;
/**
* This class defines a filtration value conversion which simply defines the filtration
* value to be equal to the filtration index. (i.e. f_i = i)
*
* @author Andrew Tausz
*
*/
public class IdentityConverter extends FiltrationConverter {
/**
* This is the single instance of the class
*/
private static IdentityConverter instance = new IdentityConverter();
/**
* Private constructor to prevent instantiation.
*/
private IdentityConverter(){}
/**
* This returns the single instance of the class.
*
* @return the single instance of the class
*/
public static IdentityConverter getInstance() {
return instance;
}
@Override
public int getFiltrationIndex(double filtrationValue) {
return (int) filtrationValue;
}
@Override
public double getFiltrationValue(int filtrationIndex) {
return filtrationIndex;
}
@Override
public double computeInducedFiltrationValue(double filtrationValue1, double filtrationValue2) {
return Math.max(filtrationValue1, filtrationValue2);
}
@Override
public double getInitialFiltrationValue() {
return 0;
}
}
|
9241b38a611fb968d0f1f446556fb8690dbe1e2d
| 11,903 |
java
|
Java
|
reset-pass/account-validator-tool/src/java/org/sakaiproject/accountvalidator/tool/producers/PasswordResetProducer.java
|
danadel/sakai
|
68947659150056932d0896237eaeb0ed38c3fc7f
|
[
"ECL-2.0"
] | 13 |
2016-05-25T16:12:49.000Z
|
2021-04-09T01:49:24.000Z
|
reset-pass/account-validator-tool/src/java/org/sakaiproject/accountvalidator/tool/producers/PasswordResetProducer.java
|
danadel/sakai
|
68947659150056932d0896237eaeb0ed38c3fc7f
|
[
"ECL-2.0"
] | 265 |
2015-10-19T02:40:55.000Z
|
2022-03-28T07:24:49.000Z
|
reset-pass/account-validator-tool/src/java/org/sakaiproject/accountvalidator/tool/producers/PasswordResetProducer.java
|
danadel/sakai
|
68947659150056932d0896237eaeb0ed38c3fc7f
|
[
"ECL-2.0"
] | 7 |
2016-02-08T11:41:40.000Z
|
2021-06-08T18:18:02.000Z
| 36.087879 | 174 | 0.73096 | 1,002,004 |
/**
* $Id: MainProducer.java 105078 2012-02-24 23:00:38Z [email protected] $
* $URL: https://source.sakaiproject.org/svn/reset-pass/trunk/account-validator-tool/src/java/org/sakaiproject/accountvalidator/tool/producers/MainProducer.java $
* DeveloperHelperService.java - entity-broker - Apr 13, 2008 5:42:38 PM - azeckoski
**************************************************************************
* Copyright (c) 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.accountvalidator.tool.producers;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;
import org.sakaiproject.accountvalidator.model.ValidationAccount;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserNotDefinedException;
import uk.org.ponder.localeutil.LocaleGetter;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.rsf.components.*;
import uk.org.ponder.rsf.flow.ActionResultInterceptor;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import java.util.Locale;
/**
* Produces passwordReset.html - builds a form containing nothing more than the a password and confirm password field
* @author bbailla2
*/
public class PasswordResetProducer extends BaseValidationProducer implements ViewComponentProducer, ActionResultInterceptor {
private static Log log = LogFactory.getLog(PasswordResetProducer.class);
public static final String VIEW_ID = "passwordReset";
private static final String MAX_PASSWORD_RESET_MINUTES = "accountValidator.maxPasswordResetMinutes";
private static LocaleGetter localeGetter;
public void setLocaleGetter(LocaleGetter localeGetter)
{
this.localeGetter = localeGetter;
}
private Locale getLocale()
{
return localeGetter.get();
}
public String getViewID() {
return VIEW_ID;
}
public void init()
{
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker)
{
Object[] args = new Object[]{serverConfigurationService.getString("ui.service", "Sakai")};
UIMessage.make(tofill, "welcome1", "validate.welcome1.reset", args);
ValidationAccount va = getValidationAccount(viewparams, tml);
if (va == null)
{
//handled by getValidationAccount
return;
}
else if (!va.getAccountStatus().equals(ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET))
{
//this is not a password reset
args = new Object[] {va.getValidationToken()};
//no such validation of the required account status
tml.addMessage(new TargettedMessage("msg.noSuchValidation", args, TargettedMessage.SEVERITY_ERROR));
return;
}
else if (ValidationAccount.STATUS_CONFIRMED.equals(va.getStatus()))
{
args = new Object[] {va.getValidationToken()};
tml.addMessage(new TargettedMessage("msg.alreadyValidated", args, TargettedMessage.SEVERITY_ERROR));
addResetPassLink(tofill, va);
return;
}
else if (ValidationAccount.STATUS_EXPIRED.equals(va.getStatus()))
{
/*
* If accountValidator.maxPasswordResetMinutes is configured,
* we give them an approrpiate message, otherwise we give them the default
*/
TargettedMessage message = getExpirationMessage();
if (message == null)
{
//give them the default
args = new Object[]{ va.getValidationToken() };
tml.addMessage(new TargettedMessage("msg.expiredValidation", args, TargettedMessage.SEVERITY_ERROR));
addResetPassLink(tofill, va);
}
else
{
tml.addMessage(message);
}
return;
}
else if (sendLegacyLinksEnabled())
{
redirectToLegacyLink(tofill, va);
return;
}
else
{
/*
* Password resets should go quickly. If it takes longer than accountValidator.maxPasswordResetMinutes,
* it could be an intruder who stumbled on an old validation token.
*/
//Only do this check if accountValidator.maxPasswordResetMinutes is configured correctly
String strMinutes = serverConfigurationService.getString(MAX_PASSWORD_RESET_MINUTES);
if (strMinutes != null && !"".equals(strMinutes))
{
if (va.getAccountStatus() != null)
{
try
{
//get the time limit and convert to millis
long maxMillis = Long.parseLong(strMinutes);
maxMillis*=60*1000;
//the time when the validation token was sent to the email server
long sentTime = va.getValidationSent().getTime();
if (System.currentTimeMillis() - sentTime > maxMillis)
{
//it's been too long, so invalide the token and stop the user
va.setStatus(ValidationAccount.STATUS_EXPIRED);
//get a nice expiration meesage
TargettedMessage expirationMessage = getExpirationMessage();
if (expirationMessage == null)
{
//should never happen
args = new Object[]{ va.getValidationToken() };
tml.addMessage(new TargettedMessage("msg.expiredValidation", args, TargettedMessage.SEVERITY_ERROR));
return;
}
tml.addMessage(expirationMessage);
addResetPassLink(tofill, va);
return;
}
}
catch (NumberFormatException nfe)
{
log.error("accountValidator.maxPasswordResetMinutes is not configured correctly");
}
}
}
}
User u = null;
try
{
u = userDirectoryService.getUser(EntityReference.getIdFromRef(va.getUserId()));
}
catch (UserNotDefinedException e)
{
}
if (u == null)
{
log.error("user ID does not exist for ValidationAccount with tokenId: " + va.getValidationToken());
tml.addMessage(new TargettedMessage("validate.userNotDefined", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
return;
}
String resetMinutes = serverConfigurationService.getString(MAX_PASSWORD_RESET_MINUTES);
if (resetMinutes != null && !"".equals(resetMinutes))
{
try
{
int minutes = Integer.parseInt(resetMinutes);
UIMessage.make(tofill, "welcome2", "validate.expirationtime", new Object[]{getFormattedMinutes(minutes)});
}
catch (NumberFormatException nfe)
{
log.error("accountValidator.maxPasswordResetMinutes is not configured correctly");
}
}
//the form
UIForm detailsForm = UIForm.make(tofill, "setDetailsForm");
UICommand.make(detailsForm, "addDetailsSub", UIMessage.make("submit.new.reset"), "accountValidationLocator.validateAccount");
String otp = "accountValidationLocator." + va.getId();
UIMessage.make(detailsForm, "username.new", "username.new.reset", args);
UIOutput.make(detailsForm, "eid", u.getDisplayId());
boolean passwordPolicyEnabled = (userDirectoryService.getPasswordPolicy() != null);
String passwordPolicyEnabledJavaScript = "VALIDATOR.isPasswordPolicyEnabled = " + Boolean.toString(passwordPolicyEnabled) + ";";
UIVerbatim.make(tofill, "passwordPolicyEnabled", passwordPolicyEnabledJavaScript);
UIBranchContainer row1 = UIBranchContainer.make(detailsForm, "passrow1:");
UIInput.make(row1, "password1", otp + ".password");
UIBranchContainer row2 = UIBranchContainer.make(detailsForm, "passrow2:");
UIInput.make(row2, "password2", otp + ".password2");
detailsForm.parameters.add(new UIELBinding(otp + ".userId", va.getUserId()));
}
/**
* Converts some number of minutes into a presentable String'
* ie for English:
* 122 minutes -> 2 hours 2 minutes
* 121 minutes -> 2 hours 1 minute
* 120 minutes -> 2 hours
* 62 minutes -> 1 hour 2 minutes
* 61 minutes -> 1 hour 1 minute
* 60 minutes -> 1 hour
* 2 minutes -> 2 minutes
* 1 minutes -> 1 minute
* 0 minutes -> 0 minutes
* Works with other languages too.
* @param totalMinutes some number of minutes
* @return a presentable String representation of totalMinutes
*/
public String getFormattedMinutes(int totalMinutes)
{
// Create a joda time period (takes milliseconds)
Period period = new Period(totalMinutes*60*1000);
// format the period for the locale
/*
* Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish.
* To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
* (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
*/
PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
return periodFormatter.print(period);
}
/**
* Adds a link to the page for the user to request another validation token
* @param tofill the parent of the link
*/
private void addResetPassLink(UIContainer toFill, ValidationAccount va)
{
if (toFill == null || va == null)
{
// enforce method contract
throw new IllegalArgumentException("null passed to addResetPassLink()");
}
//the url to reset-pass - assume it's on the gateway. Otherwise, we don't render a link and we log a warning
String url = null;
try
{
//get the link target
url = developerHelperService.getToolViewURL("sakai.resetpass", null, null, developerHelperService.getStartingLocationReference());
}
catch (IllegalArgumentException e)
{
log.warn("Couldn't create a link to reset-pass; no instance of reset-pass found on the gateway");
}
if (url != null)
{
//add the container
UIBranchContainer requestAnotherContainer = UIBranchContainer.make(toFill, "requestAnotherContainer:");
//add a label
UIMessage.make(requestAnotherContainer, "request.another.label", "validate.requestanother.label");
//add the link to reset-pass
String requestAnother = null;
if (ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET == va.getAccountStatus())
{
requestAnother = messageLocator.getMessage("validate.requestanother.reset");
}
else
{
requestAnother = messageLocator.getMessage("validate.requestanother");
}
UILink.make(requestAnotherContainer, "request.another", requestAnother, url);
}
//else - there is no reset pass instance on the gateway, but the user sees an appropriate message regardless (handled by a targetted message)
}
/**
* When a user's validation token expires (by accountValidator.maxPasswordResetMinutes elapsing)
* this returns an appropriate TargettedMessage
* @return an approrpiate TargettedMessage when a validaiton token has expired,
* null if accountValidator.maxPasswordResetMinutes isn't configured correctly
*/
private TargettedMessage getExpirationMessage()
{
//get the time limit (iff possible)
String strMinutes = serverConfigurationService.getString(MAX_PASSWORD_RESET_MINUTES);
if (strMinutes != null && !"".equals(strMinutes))
{
try
{
int totalMinutes = Integer.parseInt(strMinutes);
//get a formatted string representation of the time limit, and create the return value
String formattedTime = getFormattedMinutes(totalMinutes);
Object [] args = new Object[]{ formattedTime };
return new TargettedMessage("msg.expiredValidationRealTime", args, TargettedMessage.SEVERITY_ERROR);
}
catch (NumberFormatException e)
{
log.warn("accountValidator.maxPasswordResetMinutes is not configured properly");
}
}
return null;
}
}
|
9241b3b3f14a1c33e278aebf0fa6269d239dcebb
| 393 |
java
|
Java
|
Product/src/main/java/com/newhopemail/product/dao/SkuSaleAttrValueDao.java
|
Mrzaotian/NewHopeMail
|
a0c92a3530c4bf167b9058a4d11ae32af13a2221
|
[
"Apache-2.0"
] | null | null | null |
Product/src/main/java/com/newhopemail/product/dao/SkuSaleAttrValueDao.java
|
Mrzaotian/NewHopeMail
|
a0c92a3530c4bf167b9058a4d11ae32af13a2221
|
[
"Apache-2.0"
] | null | null | null |
Product/src/main/java/com/newhopemail/product/dao/SkuSaleAttrValueDao.java
|
Mrzaotian/NewHopeMail
|
a0c92a3530c4bf167b9058a4d11ae32af13a2221
|
[
"Apache-2.0"
] | null | null | null | 22 | 81 | 0.777778 | 1,002,005 |
package com.newhopemail.product.dao;
import com.newhopemail.product.entity.SkuSaleAttrValueEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* sku销售属性&值
*
* @author zao
* @email [email protected]
* @date 2021-04-26 01:58:32
*/
@Mapper
public interface SkuSaleAttrValueDao extends BaseMapper<SkuSaleAttrValueEntity> {
}
|
9241b4ba836b686c1ce7f77352d2b76cc5e1de95
| 11,091 |
java
|
Java
|
src/main/java/org/akomantoso/schema/v3/csd06/ListItems.java
|
lewismc/akomantoso-lib
|
438f7b8956cbcab29788128c3b7b807dacb92f01
|
[
"Apache-2.0"
] | 2 |
2020-03-25T02:30:20.000Z
|
2020-06-23T13:20:48.000Z
|
src/main/java/org/akomantoso/schema/v3/csd06/ListItems.java
|
lewismc/akomantoso-lib
|
438f7b8956cbcab29788128c3b7b807dacb92f01
|
[
"Apache-2.0"
] | 11 |
2015-01-07T15:58:37.000Z
|
2017-07-04T16:27:22.000Z
|
src/main/java/org/akomantoso/schema/v3/csd06/ListItems.java
|
lewismc/akomantoso-lib
|
438f7b8956cbcab29788128c3b7b807dacb92f01
|
[
"Apache-2.0"
] | 1 |
2016-09-04T11:57:20.000Z
|
2016-09-04T11:57:20.000Z
| 24.867713 | 189 | 0.567397 | 1,002,006 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.05 at 10:55:21 PM EAT
//
package org.akomantoso.schema.v3.csd06;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><type xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD06" xmlns:xsd="http://www.w3.org/2001/XMLSchema">Complex</type>
* </pre>
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><name xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD06" xmlns:xsd="http://www.w3.org/2001/XMLSchema">listItems</name>
* </pre>
*
* <pre>
* <?xml version="1.0" encoding="UTF-8"?><comment xmlns="http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD06" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
* the complex type listItems specifies the content model of elements ul and ol, and specifies just a sequence of list items (elements li).</comment>
* </pre>
*
*
* <p>Java class for listItems complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="listItems">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD06}li" maxOccurs="unbounded"/>
* </sequence>
* <attGroup ref="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD06}corereq"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listItems", propOrder = {
"li"
})
public class ListItems {
@XmlElement(required = true)
protected List<Li> li;
@XmlAttribute(name = "alternativeTo")
@XmlSchemaType(name = "anyURI")
protected String alternativeTo;
@XmlAttribute(name = "refersTo")
protected List<String> refersTo;
@XmlAttribute(name = "currentId", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String currentId;
@XmlAttribute(name = "originalId")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String originalId;
@XmlAttribute(name = "GUID")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String guid;
@XmlAttribute(name = "status")
protected StatusType status;
@XmlAttribute(name = "period")
@XmlSchemaType(name = "anyURI")
protected String period;
@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
protected String lang;
@XmlAttribute(name = "space", namespace = "http://www.w3.org/XML/1998/namespace")
protected String space;
@XmlAttribute(name = "class")
protected String clazz;
@XmlAttribute(name = "style")
protected String style;
@XmlAttribute(name = "title")
protected String titleAttr;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the li property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the li property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLi().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Li }
*
*
*/
public List<Li> getLi() {
if (li == null) {
li = new ArrayList<Li>();
}
return this.li;
}
/**
* Gets the value of the alternativeTo property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlternativeTo() {
return alternativeTo;
}
/**
* Sets the value of the alternativeTo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlternativeTo(String value) {
this.alternativeTo = value;
}
/**
* Gets the value of the refersTo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the refersTo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRefersTo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getRefersTo() {
if (refersTo == null) {
refersTo = new ArrayList<String>();
}
return this.refersTo;
}
/**
* Gets the value of the currentId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCurrentId() {
return currentId;
}
/**
* Sets the value of the currentId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCurrentId(String value) {
this.currentId = value;
}
/**
* Gets the value of the originalId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOriginalId() {
return originalId;
}
/**
* Sets the value of the originalId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOriginalId(String value) {
this.originalId = value;
}
/**
* Gets the value of the guid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGUID() {
return guid;
}
/**
* Sets the value of the guid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGUID(String value) {
this.guid = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link StatusType }
*
*/
public StatusType getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link StatusType }
*
*/
public void setStatus(StatusType value) {
this.status = value;
}
/**
* Gets the value of the period property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPeriod() {
return period;
}
/**
* Sets the value of the period property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPeriod(String value) {
this.period = value;
}
/**
* Gets the value of the lang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLang() {
return lang;
}
/**
* Sets the value of the lang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLang(String value) {
this.lang = value;
}
/**
* Gets the value of the space property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpace() {
return space;
}
/**
* Sets the value of the space property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpace(String value) {
this.space = value;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the titleAttr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitleAttr() {
return titleAttr;
}
/**
* Sets the value of the titleAttr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitleAttr(String value) {
this.titleAttr = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
|
9241b4e1437edc66c536136d2d96ebee31bd15e3
| 668 |
java
|
Java
|
src/main/java/com/utag/phase1/service/UserService.java
|
Autumn-NJU/PhaseI
|
7d704bceec70279800b0fe9cdb1f5f836a8dfdd6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/utag/phase1/service/UserService.java
|
Autumn-NJU/PhaseI
|
7d704bceec70279800b0fe9cdb1f5f836a8dfdd6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/utag/phase1/service/UserService.java
|
Autumn-NJU/PhaseI
|
7d704bceec70279800b0fe9cdb1f5f836a8dfdd6
|
[
"Apache-2.0"
] | null | null | null | 18.555556 | 89 | 0.643713 | 1,002,007 |
package com.utag.phase1.service;
import com.utag.phase1.domain.User;
import com.utag.phase1.util.Response;
import java.io.IOException;
public interface UserService {
/**
*
* @return
*/
public Response<Boolean> saveUser(String user, String password) throws IOException;
/**
*
* @return
*/
public Response<Boolean> deleteUser(String user) throws IOException;
/**
*
* @return
*/
public Response<Boolean> updateUser(String user, String password) throws IOException;
/**
*
* @return
*/
public Response<Boolean> canLogin(String user, String password) throws IOException;
}
|
9241b61f62122b525ee690564a2f5c0ffa2d641f
| 389 |
java
|
Java
|
server-core/src/main/java/io/onedev/server/entitymanager/PullRequestQuerySettingManager.java
|
simgagne/onedev
|
fd974b295c8c00fbc1be3729830a8d1277cf55e5
|
[
"MIT"
] | 1 |
2020-12-07T02:47:58.000Z
|
2020-12-07T02:47:58.000Z
|
server-core/src/main/java/io/onedev/server/entitymanager/PullRequestQuerySettingManager.java
|
hslooooooool/onedev
|
5621ed17eb8209442967bfb36f70a299bdbe9cfc
|
[
"MIT"
] | 2 |
2021-02-21T18:41:18.000Z
|
2021-02-21T22:20:07.000Z
|
server-core/src/main/java/io/onedev/server/entitymanager/PullRequestQuerySettingManager.java
|
hslooooooool/onedev
|
5621ed17eb8209442967bfb36f70a299bdbe9cfc
|
[
"MIT"
] | 1 |
2021-04-18T22:18:30.000Z
|
2021-04-18T22:18:30.000Z
| 29.923077 | 96 | 0.840617 | 1,002,008 |
package io.onedev.server.entitymanager;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequestQuerySetting;
import io.onedev.server.model.User;
import io.onedev.server.persistence.dao.EntityManager;
public interface PullRequestQuerySettingManager extends EntityManager<PullRequestQuerySetting> {
PullRequestQuerySetting find(Project project, User user);
}
|
9241b63c7e8b98b005c6ae0bd23d0f928b8b98d5
| 18,203 |
java
|
Java
|
sdk/src/main/java/com/jq/chatsdk/activities/ChatSDKBaseActivity.java
|
daleside710/fitlab
|
18e67fc716df521895d9cc36eb93a6f1f3d0b161
|
[
"MIT"
] | null | null | null |
sdk/src/main/java/com/jq/chatsdk/activities/ChatSDKBaseActivity.java
|
daleside710/fitlab
|
18e67fc716df521895d9cc36eb93a6f1f3d0b161
|
[
"MIT"
] | null | null | null |
sdk/src/main/java/com/jq/chatsdk/activities/ChatSDKBaseActivity.java
|
daleside710/fitlab
|
18e67fc716df521895d9cc36eb93a6f1f3d0b161
|
[
"MIT"
] | null | null | null | 36.997967 | 157 | 0.620887 | 1,002,009 |
/*
* Created by Itzik Braun on 12/3/2015.
* Copyright (c) 2015 deluge. All rights reserved.
*
* Last Modification at: 3/12/15 4:32 PM
*/
package com.jq.chatsdk.activities;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.jq.chatsdk.R;
import com.jq.chatsdk.Utils.Debug;
import com.jq.chatsdk.Utils.DialogUtils;
import com.jq.chatsdk.Utils.helper.ChatSDKUiHelper;
import com.jq.chatsdk.dao.BThread;
import com.jq.chatsdk.dao.BUser;
import com.jq.chatsdk.network.AbstractNetworkAdapter;
import com.jq.chatsdk.network.BFacebookManager;
import com.jq.chatsdk.network.BNetworkManager;
import com.jq.chatsdk.object.BError;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.github.johnpersano.supertoasts.SuperCardToast;
import com.github.johnpersano.supertoasts.SuperToast;
import org.apache.commons.lang3.StringUtils;
import org.jdeferred.DoneCallback;
import org.jdeferred.FailCallback;
import org.jdeferred.Promise;
import java.util.concurrent.Callable;
import timber.log.Timber;
/**
* Created by braunster on 18/06/14.
*/
public class ChatSDKBaseActivity extends ChatSDKMBaseActivity implements ChatSDKBaseActivityInterface {
private static final String TAG = ChatSDKBaseActivity.class.getSimpleName();
private static final boolean DEBUG = Debug.BaseActivity;
public static final String FROM_LOGIN = "From_Login";
private UiLifecycleHelper uiHelper;
private ProgressDialog progressDialog;
/** If true the app will check if the user is online each time the activity is resumed.
* When the app is on the background the Android system can kill the app.
* When the app is killed the firebase api will set the user online status to false.
* Also all the listeners attached to the user, threads, friends etc.. are gone so each time the activity is resumed we will
* check to see if the user is online and if not start the auth process for registering to all events.*/
private boolean checkOnlineOnResumed = false;
/** If true the activity will implement facebook SDK components like sessionChangeState and the facebook UI helper.
* This is good for caching a press on the logout button in the main activity or in any activity that will implement the facebook login button.*/
protected boolean integratedWithFacebook = false;
/** A flag indicates that the activity in opened from the login activity so we wont do auth check when the activity will get to the onResume state.*/
boolean fromLoginActivity = false;
protected ChatSDKUiHelper chatSDKUiHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
chatSDKUiHelper = ChatSDKUiHelper.getInstance().get(this);
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
{
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
}
if (getIntent() != null && getIntent().getExtras() != null)
{
if (DEBUG) Timber.d("From login");
fromLoginActivity = getIntent().getExtras().getBoolean(FROM_LOGIN, false);
// So we wont encounter this flag again.
getIntent().removeExtra(FROM_LOGIN);
} else fromLoginActivity = false;
if (savedInstanceState != null)
fromLoginActivity = savedInstanceState.getBoolean(FROM_LOGIN, false);
// Setting the default task description.
setTaskDescription(getTaskDescriptionBitmap(), getTaskDescriptionLabel(), getTaskDescriptionColor());
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
/**
* @return the bitmap that will be used for the screen overview also called the recents apps.
**/
protected Bitmap getTaskDescriptionBitmap(){
return BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
protected int getTaskDescriptionColor(){
TypedValue typedValue = new TypedValue();
Resources.Theme theme = getTheme();
theme.resolveAttribute(R.attr.colorPrimary, typedValue, true);
return typedValue.data;
}
protected String getTaskDescriptionLabel(){
return (String) getTitle();
}
protected void setTaskDescription(Bitmap bm, String label, int color){
// Color the app topbar label and icon in the overview screen
//http://www.bignerdranch.com/blog/polishing-your-Android-overview-screen-entry/
// Placed in the post create so it would be called after the action bar is initialized and we have a title.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager.TaskDescription td = new ActivityManager.TaskDescription(label, bm, color);
setTaskDescription(td);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null && intent.getExtras() != null)
{
if (DEBUG) Timber.d("From login");
fromLoginActivity = intent.getExtras().getBoolean(FROM_LOGIN, false);
// So we wont encounter this flag again.
intent.removeExtra(FROM_LOGIN);
}
}
@Override
protected void onPause() {
super.onPause();
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
uiHelper.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (DEBUG) Timber.v("onResumed, From login: %s, Check online: %s", fromLoginActivity, checkOnlineOnResumed);
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
uiHelper.onResume();
if (checkOnlineOnResumed && !fromLoginActivity)
{
if(DEBUG) Timber.d("Check online on resumed");
getWindow().getDecorView().post(new Runnable() {
@Override
public void run() {
getNetworkAdapter().isOnline()
.done(new DoneCallback<Boolean>() {
@Override
public void onDone(Boolean online) {
if (online == null) return;
if(DEBUG) Timber.d("Check done, ", online);
if (!online)
{
authenticate().done(new DoneCallback<BUser>() {
@Override
public void onDone(BUser bUser) {
if (DEBUG) Timber.d("Authenticated!");
onAuthenticated();
}
}).fail(new FailCallback<BError>() {
@Override
public void onFail(BError bError) {
if (DEBUG) Timber.d("Authenticated Failed!");
onAuthenticationFailed();
}
});
}
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
if (DEBUG) Timber.e("Check online failed!, Error message: %s", error.message);
onAuthenticationFailed();
}
});
}
});
}
fromLoginActivity = false;
}
@Override
protected void onStart() {
super.onStart();
getNetworkAdapter().setUserOnline();
}
@Override
protected void onStop() {
super.onStop();
getNetworkAdapter().setUserOffline();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
uiHelper.onDestroy();
dismissProgDialog();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled()) uiHelper.onSaveInstanceState(outState);
outState.putBoolean(FROM_LOGIN, fromLoginActivity);
}
/** Set up the ui so every view and nested view that is not EditText will listen to touch event and dismiss the keyboard if touched.
* http://stackoverflow.com/questions/4165414/how-to-hide-soft-keyboard-on-android-after-clicking-outside-edittext*/
public void setupTouchUIToDismissKeyboard(View view) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(ChatSDKBaseActivity.this);
return false;
}
});
}
public void setupTouchUIToDismissKeyboard(View view, final Integer... exceptIDs) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(ChatSDKBaseActivity.this);
return false;
}
}, exceptIDs);
}
public void setupTouchUIToDismissKeyboard(View view, View.OnTouchListener onTouchListener, final Integer... exceptIDs) {
ChatSDKUiHelper.setupTouchUIToDismissKeyboard(view, onTouchListener, exceptIDs);
}
/** Hide the Soft Keyboard.*/
public static void hideSoftKeyboard(Activity activity) {
ChatSDKUiHelper.hideSoftKeyboard(activity);
}
/** Show a SuperToast with the given text. */
protected void showToast(String text){
if (chatSDKUiHelper==null || StringUtils.isEmpty(text))
return;
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}
protected void showAlertToast(String text){
showToast(text);
}
/** Authenticates the current user.*/
public Promise<BUser, BError, Void> authenticate(){
return getNetworkAdapter().checkUserAuthenticated();
}
/** Create a thread for given users and name, When thread and all users are all pushed to the server the chat activity for this thread will be open.*/
protected void createAndOpenThreadWithUsers(String name, BUser...users){
getNetworkAdapter().createThreadWithUsers(name, users)
.done(new DoneCallback<BThread>() {
@Override
public void onDone(final BThread thread) {
dismissProgDialog();
if (thread == null) {
if (DEBUG) Timber.e("thread added is null");
return;
}
if (isOnMainThread()) {
startChatActivityForID(thread.getId());
} else ChatSDKBaseActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
startChatActivityForID(thread.getId());
}
});
}
})
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError error) {
if (isOnMainThread())
showAlertToast(getString(R.string.create_thread_with_users_fail_toast));
else ChatSDKBaseActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
showAlertToast(getString(R.string.create_thread_with_users_fail_toast));
}
});
}
});
}
/** Start the chat activity for the given thread id.
* @param id is the long value of local db id.*/
public void startChatActivityForID(long id){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startChatActivityForID(id);
}
public void startLoginActivity(boolean loggedOut){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startLoginActivity(loggedOut);
}
public void startMainActivity(){
if (chatSDKUiHelper != null)
chatSDKUiHelper.startMainActivity();
}
public void startSearchActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startSearchActivity();
}
public void startPickFriendsActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startPickFriendsActivity();
}
public void startShareWithFriendsActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startShareWithFriendsActivity();
}
public void startShareLocationActivityActivity() {
if (chatSDKUiHelper != null)
chatSDKUiHelper.startShareLocationActivityActivity();
}
protected void showProgDialog(String message){
if (progressDialog == null)
progressDialog = new ProgressDialog(this);
if (!progressDialog.isShowing())
{
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(message);
progressDialog.show();
}
}
protected void showOrUpdateProgDialog(String message){
if (progressDialog == null)
progressDialog = new ProgressDialog(this);
if (!progressDialog.isShowing())
{
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(message);
progressDialog.show();
} else progressDialog.setMessage(message);
}
protected void dismissProgDialog(){
// For handling orientation changed.
try {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
} catch (Exception e) {
}
}
protected void showAlertDialog(String title, String alert, String p, String n, final Callable neg, final Callable pos){
DialogUtils.showAlertDialog(this, title, alert, p, n, neg, pos);
}
protected void onSessionStateChange(Session session, final SessionState state, Exception exception){
BFacebookManager.onSessionStateChange(session, state, exception)
.fail(new FailCallback<BError>() {
@Override
public void onFail(BError bError) {
if (DEBUG) Timber.e("onDoneWithError. Error: %s", bError.message);
// Facebook session is closed so we need to disconnect from firebase.
getNetworkAdapter().logout();
startLoginActivity(true);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(DEBUG) Timber.v("onActivityResult");
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
uiHelper.onActivityResult(requestCode, resultCode, data);
}
// Facebook Login stuff.
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (integratedWithFacebook && getNetworkAdapter().facebookEnabled())
onSessionStateChange(session, state, exception);
}
};
/** When enabled the app will check the user online ref to see if he is not offline each time that the activity is resumed.
* This method is good for times that the app is in the background and killed by the android system and we need to listen to all the user details again.
* i.e Authenticate again.*/
public void enableCheckOnlineOnResumed(boolean checkOnlineOnResumed) {
this.checkOnlineOnResumed = checkOnlineOnResumed;
}
public void enableFacebookIntegration(boolean integratedWithFacebook) {
this.integratedWithFacebook = integratedWithFacebook;
}
@Override
public void onAuthenticated() {
}
@Override
public void onAuthenticationFailed() {
startLoginActivity(true);
}
protected boolean isOnMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
return false;
}
return true;
}
@Override
public AbstractNetworkAdapter getNetworkAdapter() {
return BNetworkManager.sharedManager().getNetworkAdapter();
}
public void setChatSDKUiHelper(ChatSDKUiHelper chatSDKUiHelper) {
this.chatSDKUiHelper = chatSDKUiHelper;
}
}
interface ChatSDKBaseActivityInterface extends ChatSDKUiHelper.ChatSDKUiHelperInterface {
/** This method is called after the activity authenticated the user. When the activity is resumed the activity
* checks if the user is authenticated(optional {@link ChatSDKBaseActivity#checkOnlineOnResumed}),
* If the user was re - authenticated when it was resumed this method will be called. */
public void onAuthenticated();
public void onAuthenticationFailed();
public AbstractNetworkAdapter getNetworkAdapter();
}
|
9241b65891aa60b70bc9d0c3a4a5e54bfb2406b9
| 501 |
java
|
Java
|
osgp/platform/osgp-domain-distributionautomation/src/main/java/org/opensmartgridplatform/domain/da/valueobjects/GetDeviceModelRequest.java
|
ekmixon/open-smart-grid-platform
|
ca095718390ce8b33db399722e86fc43f252057a
|
[
"Apache-2.0"
] | 77 |
2018-10-25T12:05:06.000Z
|
2022-02-03T12:49:56.000Z
|
osgp/platform/osgp-domain-distributionautomation/src/main/java/org/opensmartgridplatform/domain/da/valueobjects/GetDeviceModelRequest.java
|
OSGP/open-smart-grid-platform
|
f431e30820fe79dbde7da963f51b087a8a0c91d0
|
[
"Apache-2.0"
] | 526 |
2018-10-24T15:58:01.000Z
|
2022-03-31T20:06:59.000Z
|
osgp/platform/osgp-domain-distributionautomation/src/main/java/org/opensmartgridplatform/domain/da/valueobjects/GetDeviceModelRequest.java
|
ekmixon/open-smart-grid-platform
|
ca095718390ce8b33db399722e86fc43f252057a
|
[
"Apache-2.0"
] | 30 |
2018-12-27T07:11:35.000Z
|
2021-09-09T06:57:44.000Z
| 31.3125 | 92 | 0.770459 | 1,002,010 |
/*
* Copyright 2017 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.domain.da.valueobjects;
import java.io.Serializable;
public class GetDeviceModelRequest implements Serializable {
private static final long serialVersionUID = 4776483459295843436L;
}
|
9241b70e130b9220459e7c592f4316be17d19f1f
| 36,323 |
java
|
Java
|
chpl/chpl-service/src/test/java/gov/healthit/chpl/upload/listing/validation/reviewer/TestParticipantReviewerTest.java
|
athomas-git/chpl-api
|
7b1b61c20bef3e5b1c2ca542472934471b40ca68
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
chpl/chpl-service/src/test/java/gov/healthit/chpl/upload/listing/validation/reviewer/TestParticipantReviewerTest.java
|
athomas-git/chpl-api
|
7b1b61c20bef3e5b1c2ca542472934471b40ca68
|
[
"BSD-2-Clause-FreeBSD"
] | 2 |
2016-02-11T12:55:32.000Z
|
2021-01-05T17:18:38.000Z
|
chpl/chpl-service/src/test/java/gov/healthit/chpl/upload/listing/validation/reviewer/TestParticipantReviewerTest.java
|
kekey1/chpl-api
|
0cb921bad1a38ec0678773e89171fb5288154392
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null | 53.259531 | 187 | 0.677009 | 1,002,011 |
package gov.healthit.chpl.upload.listing.validation.reviewer;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import gov.healthit.chpl.domain.CertifiedProductSearchDetails;
import gov.healthit.chpl.domain.CertifiedProductSed;
import gov.healthit.chpl.domain.TestParticipant;
import gov.healthit.chpl.domain.TestTask;
import gov.healthit.chpl.util.ErrorMessageUtil;
public class TestParticipantReviewerTest {
private static final String TEST_PARTICIPANT_FIELD_ROUNDED = "A non-integer numeric number was found in Test Participant \"%s\" \"%s\" \"%s\". The number has been rounded to \"%s\".";
private ErrorMessageUtil errorMessageUtil;
private TestParticipantReviewer reviewer;
@Before
@SuppressWarnings("checkstyle:magicnumber")
public void setup() {
errorMessageUtil = Mockito.mock(ErrorMessageUtil.class);
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.roundedParticipantNumber"), ArgumentMatchers.anyString(),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(TEST_PARTICIPANT_FIELD_ROUNDED, i.getArgument(1), i.getArgument(2), i.getArgument(3), i.getArgument(4)));
reviewer = new TestParticipantReviewer(errorMessageUtil);
}
@Test
public void review_nullTestTasksNoCertificationResults_noError() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
listing.getSed().setTestTasks(null);
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_emptyTestTasksNoCertificationResults_noError() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_nullTestParticipantsNoCertificationResults_noError() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(null);
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_emptyTestParticipantsNoCertificationResults_noError() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_NullUniqueID_hasError() {
String errMsg = "A test participant is missing its unique ID.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingTestParticipantUniqueId")))
.thenReturn(errMsg);
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(buildValidTestParticipant(null)).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(errMsg));
}
@Test
public void review_EmptyUniqueID_hasError() {
String errMsg = "A test participant is missing its unique ID.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingTestParticipantUniqueId")))
.thenReturn(errMsg);
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder()
.build())
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(buildValidTestParticipant("")).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(errMsg));
}
@Test
public void review_NullAgeRangeId_NullAgeRangeStr_hasError() {
String errMsg = "Age range is required for participant %s but was not found.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantAgeRange"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder()
.build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.ageRange(null)
.ageRangeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullAgeRangeId_EmptyAgeRangeStr_hasError() {
String errMsg = "Age range is required for participant %s but was not found.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantAgeRange"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.ageRange("")
.ageRangeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullAgeRangeId_InvalidAgeRangeStr_hasError() {
String errMsg = "Age range %s for participant %s is an invalid value.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.invalidParticipantAgeRange"),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), i.getArgument(2)));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.ageRange("notanagerange")
.ageRangeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "notanagerange", "TP1")));
}
@Test
public void review_NullEducationLevelId_NullEducationLevelStr_hasError() {
String errMsg = "Education level is required for participant %s but was not found.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantEducationLevel"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.educationTypeName(null)
.educationTypeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullEducationLevelId_EmptyEducationLevelStr_hasError() {
String errMsg = "Education level is required for participant %s but was not found.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantEducationLevel"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.educationTypeName("")
.educationTypeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullEducationLevelId_InvalidEducationLevelStr_hasError() {
String errMsg = "Education level %s for participant %s is an invalid value.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.invalidParticipantEducationLevel"),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), i.getArgument(2)));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.educationTypeName("notaneducation")
.educationTypeId(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "notaneducation", "TP1")));
}
@Test
public void review_NullGender_hasError() {
String errMsg = "Gender is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantGender"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.gender(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
System.out.println(listing.getErrorMessages().iterator().next());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_EmptyGender_hasError() {
String errMsg = "Gender is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantGender"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.gender("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_NullOccupation_hasError() {
String errMsg = "Occupation is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantOccupation"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.occupation(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_EmptyOccupation_hasError() {
String errMsg = "Occupation is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantOccupation"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.occupation("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_NullAssistiveTechnologyNeeds_hasError() {
String errMsg = "Assistive Technology Needs are required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantAssistiveTechnologyNeeds"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.assistiveTechnologyNeeds(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_EmptyAssistiveTechnologyNeeds_hasError() {
String errMsg = "Assistive Technology Needs are required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantAssistiveTechnologyNeeds"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.assistiveTechnologyNeeds("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1")));
}
@Test
public void review_NullProfessionalExperienceMonths_NullProfessionalExperienceMonthsStr_hasError() {
String errMsg = "Professional Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantProfessionalExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.professionalExperienceMonths(null)
.professionalExperienceMonthsStr(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullProfessionalExperienceMonths_EmptyProfessionalExperienceMonthsStr_hasError() {
String errMsg = "Professional Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantProfessionalExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.professionalExperienceMonths(null)
.professionalExperienceMonthsStr("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullProfessionalExperienceMonths_NaNProfessionalExperienceMonthsStr_hasError() {
String errMsg = "Professional Experience (in months) has an invalid value '%s' for participant %s. The field must be a whole number.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.invalidParticipantProfessionalExperienceMonths"),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), i.getArgument(2)));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.professionalExperienceMonths(null)
.professionalExperienceMonthsStr("K")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "K", "TP1")));
}
@Test
public void review_RoundedProfessionalExperieneMonths_NaNProfessionalExperienceMonthsStr_hasWarning() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.professionalExperienceMonths(1)
.professionalExperienceMonthsStr("1.2")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(1, listing.getWarningMessages().size());
assertTrue(listing.getWarningMessages().contains(String.format(TEST_PARTICIPANT_FIELD_ROUNDED, "TP1", "Professional Experience Months", "1.2", "1")));
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_NullProductExperienceMonths_NullProductExperienceMonthsStr_hasError() {
String errMsg = "Product Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantProductExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.productExperienceMonths(null)
.productExperienceMonthsStr(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullProductExperienceMonths_EmptyProductExperienceMonthsStr_hasError() {
String errMsg = "Product Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantProductExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.productExperienceMonths(null)
.productExperienceMonthsStr("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullProductExperienceMonths_NaNProductExperienceMonthsStr_hasError() {
String errMsg = "Product Experience (in months) has an invalid value '%s' for participant %s. The field must be a whole number.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.invalidParticipantProductExperienceMonths"),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), i.getArgument(2)));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.productExperienceMonths(null)
.productExperienceMonthsStr("K")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "K", "TP1")));
}
@Test
public void review_RoundedProductExperieneMonths_NaNProductExperienceMonthsStr_hasWarning() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.productExperienceMonths(1)
.productExperienceMonthsStr("1.2")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(1, listing.getWarningMessages().size());
assertTrue(listing.getWarningMessages().contains(String.format(TEST_PARTICIPANT_FIELD_ROUNDED, "TP1", "Product Experience Months", "1.2", "1")));
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_NullComputerExperienceMonths_NullComputerExperienceMonthsStr_hasError() {
String errMsg = "Computer Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantComputerExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.computerExperienceMonths(null)
.computerExperienceMonthsStr(null)
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullComputerExperienceMonths_EmptyComputerExperienceMonthsStr_hasError() {
String errMsg = "Computer Experience (in months) is required for participant %s.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.missingParticipantComputerExperienceMonths"),
ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), ""));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.computerExperienceMonths(null)
.computerExperienceMonthsStr("")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "TP1", "")));
}
@Test
public void review_NullComputerExperienceMonths_NaNComputerExperienceMonthsStr_hasError() {
String errMsg = "Computer Experience (in months) has an invalid value '%s' for participant %s. The field must be a whole number.";
Mockito.when(errorMessageUtil.getMessage(ArgumentMatchers.eq("listing.criteria.invalidParticipantComputerExperienceMonths"),
ArgumentMatchers.anyString(), ArgumentMatchers.anyString()))
.thenAnswer(i -> String.format(errMsg, i.getArgument(1), i.getArgument(2)));
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.computerExperienceMonths(null)
.computerExperienceMonthsStr("K")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(1, listing.getErrorMessages().size());
assertTrue(listing.getErrorMessages().contains(String.format(errMsg, "K", "TP1")));
}
@Test
public void review_RoundedComputerExperieneMonths_NaNComputerExperienceMonthsStr_hasWarning() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
TestParticipant testParticipant = buildValidTestParticipant("TP1").toBuilder()
.computerExperienceMonths(1)
.computerExperienceMonthsStr("1.2")
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(Stream.of(testParticipant).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(1, listing.getWarningMessages().size());
assertTrue(listing.getWarningMessages().contains(String.format(TEST_PARTICIPANT_FIELD_ROUNDED, "TP1", "Computer Experience Months", "1.2", "1")));
assertEquals(0, listing.getErrorMessages().size());
}
@Test
public void review_testParticipantsValid_noError() {
CertifiedProductSearchDetails listing = CertifiedProductSearchDetails.builder()
.sed(CertifiedProductSed.builder().build())
.build();
listing.getSed().getTestTasks().add(TestTask.builder().build());
listing.getSed().getTestTasks().get(0).setTestParticipants(
Stream.of(buildValidTestParticipant("TP1"), buildValidTestParticipant("TP2")).collect(Collectors.toSet()));
reviewer.review(listing);
assertEquals(0, listing.getWarningMessages().size());
assertEquals(0, listing.getErrorMessages().size());
}
private TestParticipant buildValidTestParticipant(String uniqueId) {
return buildTestParticipant(uniqueId);
}
private TestParticipant buildTestParticipant(String uniqueId) {
return TestParticipant.builder()
.uniqueId(uniqueId)
.ageRange("10-20")
.ageRangeId(1L)
.assistiveTechnologyNeeds("some needs")
.computerExperienceMonths(24)
.computerExperienceMonthsStr("24")
.educationTypeId(2L)
.educationTypeName("Bachelor's Degree")
.gender("F")
.occupation("Teacher")
.productExperienceMonths(5)
.productExperienceMonthsStr("5")
.professionalExperienceMonths(10)
.professionalExperienceMonthsStr("10")
.build();
}
}
|
9241b9937d92fca32079eab053ad7f83e68ae3a8
| 2,639 |
java
|
Java
|
src/main/java/ru/fsrar/wegais/productref/ObjectFactory.java
|
ytimesru/kkm-pc-client
|
899a6f00b2067a5d0823fd3d468be693af1dbdba
|
[
"MIT"
] | null | null | null |
src/main/java/ru/fsrar/wegais/productref/ObjectFactory.java
|
ytimesru/kkm-pc-client
|
899a6f00b2067a5d0823fd3d468be693af1dbdba
|
[
"MIT"
] | null | null | null |
src/main/java/ru/fsrar/wegais/productref/ObjectFactory.java
|
ytimesru/kkm-pc-client
|
899a6f00b2067a5d0823fd3d468be693af1dbdba
|
[
"MIT"
] | null | null | null | 25.375 | 140 | 0.64911 | 1,002,012 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.06.05 at 08:50:12 PM SAMT
//
package ru.fsrar.wegais.productref;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the ru.fsrar.wegais.productref package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: ru.fsrar.wegais.productref
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link MarkInfoType }
*
*/
public MarkInfoType createMarkInfoType() {
return new MarkInfoType();
}
/**
* Create an instance of {@link MarkInfoType.Ranges }
*
*/
public MarkInfoType.Ranges createMarkInfoTypeRanges() {
return new MarkInfoType.Ranges();
}
/**
* Create an instance of {@link ProductsType }
*
*/
public ProductsType createProductsType() {
return new ProductsType();
}
/**
* Create an instance of {@link ProductInfo }
*
*/
public ProductInfo createProductInfo() {
return new ProductInfo();
}
/**
* Create an instance of {@link InformBTypeItem }
*
*/
public InformBTypeItem createInformBTypeItem() {
return new InformBTypeItem();
}
/**
* Create an instance of {@link InformAType }
*
*/
public InformAType createInformAType() {
return new InformAType();
}
/**
* Create an instance of {@link InformBType }
*
*/
public InformBType createInformBType() {
return new InformBType();
}
/**
* Create an instance of {@link MarkInfoType.Ranges.Range }
*
*/
public MarkInfoType.Ranges.Range createMarkInfoTypeRangesRange() {
return new MarkInfoType.Ranges.Range();
}
}
|
9241ba23274bfcc37aa5a928af76e1ea74563c50
| 2,780 |
java
|
Java
|
core/src/main/java/org/apache/accumulo/core/client/admin/DelegationTokenConfig.java
|
mware-solutions/accumulo
|
14dd12c3a97f44cd6c0273552ce8bc3b5439cd20
|
[
"Apache-2.0"
] | 870 |
2015-01-02T21:22:16.000Z
|
2022-03-26T13:30:52.000Z
|
core/src/main/java/org/apache/accumulo/core/client/admin/DelegationTokenConfig.java
|
mware-solutions/accumulo
|
14dd12c3a97f44cd6c0273552ce8bc3b5439cd20
|
[
"Apache-2.0"
] | 1,941 |
2015-01-12T02:02:45.000Z
|
2022-03-31T19:18:54.000Z
|
core/src/main/java/org/apache/accumulo/core/client/admin/DelegationTokenConfig.java
|
mware-solutions/accumulo
|
14dd12c3a97f44cd6c0273552ce8bc3b5439cd20
|
[
"Apache-2.0"
] | 417 |
2015-01-12T01:40:57.000Z
|
2022-03-25T17:58:13.000Z
| 31.954023 | 99 | 0.719784 | 1,002,013 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.client.admin;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.TimeUnit;
/**
* Configuration options for obtaining a delegation token created by
* {@link SecurityOperations#getDelegationToken(DelegationTokenConfig)}
*
* @since 1.7.0
*/
public class DelegationTokenConfig {
private long lifetime = 0;
/**
* Requests a specific lifetime for the token that is different than the default system lifetime.
* The lifetime must not exceed the secret key lifetime configured on the servers.
*
* @param lifetime
* Token lifetime
* @param unit
* Unit of time for the lifetime
* @return this
*/
public DelegationTokenConfig setTokenLifetime(long lifetime, TimeUnit unit) {
checkArgument(lifetime >= 0, "Lifetime must be non-negative");
requireNonNull(unit, "TimeUnit was null");
this.lifetime = TimeUnit.MILLISECONDS.convert(lifetime, unit);
return this;
}
/**
* The current token lifetime. A value of zero corresponds to using the system configured
* lifetime.
*
* @param unit
* The unit of time the lifetime should be returned in
* @return Token lifetime in requested unit of time
*/
public long getTokenLifetime(TimeUnit unit) {
requireNonNull(unit);
return unit.convert(lifetime, TimeUnit.MILLISECONDS);
}
@Override
public boolean equals(Object o) {
if (o instanceof DelegationTokenConfig) {
DelegationTokenConfig other = (DelegationTokenConfig) o;
return lifetime == other.lifetime;
}
return false;
}
@Override
public int hashCode() {
return Long.valueOf(lifetime).hashCode();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(32);
sb.append("DelegationTokenConfig[lifetime=").append(lifetime).append("ms]");
return sb.toString();
}
}
|
9241bb02862e08c95bb6da6a720dee018cd1ac4f
| 95 |
java
|
Java
|
bin/graphics/ui/IPositioner.java
|
FIREdog5/Hughs-Hubble-Emergence
|
2ef3581529a69e693f2ff3427cadec03cd507de2
|
[
"MIT"
] | null | null | null |
bin/graphics/ui/IPositioner.java
|
FIREdog5/Hughs-Hubble-Emergence
|
2ef3581529a69e693f2ff3427cadec03cd507de2
|
[
"MIT"
] | 6 |
2021-11-28T19:09:43.000Z
|
2021-12-01T04:51:01.000Z
|
bin/graphics/ui/IPositioner.java
|
FIREdog5/Hughs-Hubble-Emergence
|
2ef3581529a69e693f2ff3427cadec03cd507de2
|
[
"MIT"
] | null | null | null | 15.833333 | 35 | 0.778947 | 1,002,014 |
package bin.graphics.ui;
public interface IPositioner {
public UIElement getRealParent();
}
|
9241bb325608b60970f8cf5bada6050bc532a555
| 562 |
java
|
Java
|
src/main/java/com/YTrollman/UniversalGrid/registry/ModItems.java
|
starforcraft/Universal-Grid
|
a77457c12b1d714990b6036876b717fb1d657132
|
[
"MIT"
] | 3 |
2021-10-19T15:00:41.000Z
|
2022-01-09T04:05:37.000Z
|
src/main/java/com/YTrollman/UniversalGrid/registry/ModItems.java
|
starforcraft/Universal-Grid
|
a77457c12b1d714990b6036876b717fb1d657132
|
[
"MIT"
] | 7 |
2021-10-15T16:42:09.000Z
|
2022-03-23T18:07:42.000Z
|
src/main/java/com/YTrollman/UniversalGrid/registry/ModItems.java
|
starforcraft/Universal-Grid
|
a77457c12b1d714990b6036876b717fb1d657132
|
[
"MIT"
] | null | null | null | 43.230769 | 90 | 0.839858 | 1,002,015 |
package com.YTrollman.UniversalGrid.registry;
import com.YTrollman.UniversalGrid.UniversalGrid;
import com.YTrollman.UniversalGrid.item.WirelessUniversalGridItem;
import net.minecraftforge.registries.ObjectHolder;
public class ModItems {
@ObjectHolder(UniversalGrid.MOD_ID + ":wireless_universal_grid")
public static final WirelessUniversalGridItem WIRELESS_UNIVERSAL_GRID = null;
@ObjectHolder(UniversalGrid.MOD_ID + ":creative_wireless_universal_grid")
public static final WirelessUniversalGridItem CREATIVE_WIRELESS_UNIVERSAL_GRID = null;
}
|
9241bb7085091db488eb36752582cc1d64cf2212
| 1,278 |
java
|
Java
|
java/342_PowerOfFour.java
|
moonafrose/LeetCode
|
b76a71062dee8bef112ef10e8d03f38fe651b97d
|
[
"MIT"
] | null | null | null |
java/342_PowerOfFour.java
|
moonafrose/LeetCode
|
b76a71062dee8bef112ef10e8d03f38fe651b97d
|
[
"MIT"
] | null | null | null |
java/342_PowerOfFour.java
|
moonafrose/LeetCode
|
b76a71062dee8bef112ef10e8d03f38fe651b97d
|
[
"MIT"
] | null | null | null | 25.058824 | 88 | 0.498435 | 1,002,016 |
/*
https://leetcode.com/problems/power-of-four/
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
*/
public class Solution {
public boolean isPowerOfFour(int num) {
/*
* One solution is to keep dividing the number by 4, i.e, do n = n/4
* iteratively. In any iteration, if n%4 becomes non-zero and n is not 1 then n
* is not a power of 4, otherwise n is a power of 4.
*/
if (num <= 0) {
return false;
}
while (num > 1) {
if (num % 4 != 0) {
return false;
}
num = num / 4;
}
return true;
}
public boolean isPowerOfFourI(int num) {
/*
* Another solution is using bitwise operator. A number is power of 4 if:
* It is a power of 2
* No of zero bits after the only set bit is even
*/
PowerOfTwo p = new PowerOfTwo();
int count = 0;
if (p.isPowerOfTwo(num)) {
while (num > 1) {
count++;
num = num >> 1;
}
return count % 2 == 0;
}
return false;
}
}
|
9241bc80104fa95844286f4382067231137d3730
| 71 |
java
|
Java
|
Functional programming/src/main/java/ru/shemplo/fp/package-info.java
|
Shemplo/Functional-Java
|
2755659efcf902e9257118989efd15ca17c7fe68
|
[
"MIT"
] | 6 |
2018-06-12T14:52:02.000Z
|
2018-06-12T18:34:48.000Z
|
Functional programming/src/main/java/ru/shemplo/fp/package-info.java
|
Shemplo/Functional-Java
|
2755659efcf902e9257118989efd15ca17c7fe68
|
[
"MIT"
] | 4 |
2018-06-12T19:05:02.000Z
|
2018-06-15T10:35:10.000Z
|
Functional programming/src/main/java/ru/shemplo/fp/package-info.java
|
Shemplo/Functional-Java
|
2755659efcf902e9257118989efd15ca17c7fe68
|
[
"MIT"
] | 1 |
2021-12-04T12:01:21.000Z
|
2021-12-04T12:01:21.000Z
| 7.888889 | 23 | 0.408451 | 1,002,017 |
/**
*
*/
/**
* @author Shemp
*
*/
package ru.shemplo.fp;
|
9241bca50ffd1a9409483f0eb9071b121d5fd55a
| 821 |
java
|
Java
|
Day22/AscendingArray.java
|
AmishaTomar0303/Daily-Work
|
1f759f6ee83c00ff34cdd9c992f443429146799b
|
[
"MIT"
] | null | null | null |
Day22/AscendingArray.java
|
AmishaTomar0303/Daily-Work
|
1f759f6ee83c00ff34cdd9c992f443429146799b
|
[
"MIT"
] | null | null | null |
Day22/AscendingArray.java
|
AmishaTomar0303/Daily-Work
|
1f759f6ee83c00ff34cdd9c992f443429146799b
|
[
"MIT"
] | null | null | null | 22.805556 | 68 | 0.526188 | 1,002,018 |
package com.cognizant.classes;
import java.util.Scanner;
//Write a program in C to sort elements of array in ascending order
public class AscendingArray {
public static void main(String[] args) {
int temp;
int i;
int j;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
int n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for( i = 0; i < n; i++)
{
a[i] = s.nextInt();
}for( i=0;i<a.length;i++) {
for( j=0;j<a.length;j++) {
if(a[i]<a[j]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}}
System.out.println("Ascending elements::");
for(i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
}
|
9241bdd0833e7fddc8eb833896e6843d9bbd1244
| 7,942 |
java
|
Java
|
src/main/java/com/datamelt/util/VelocityDataWriter.java
|
kleineroscar/jare
|
7b1eeb28805de38de85ad3cfccfe583c45f6e881
|
[
"Apache-2.0"
] | 26 |
2016-07-14T06:10:39.000Z
|
2022-03-24T02:20:51.000Z
|
src/main/java/com/datamelt/util/VelocityDataWriter.java
|
kleineroscar/jare
|
7b1eeb28805de38de85ad3cfccfe583c45f6e881
|
[
"Apache-2.0"
] | 7 |
2017-08-20T08:50:20.000Z
|
2021-02-12T13:38:23.000Z
|
src/main/java/com/datamelt/util/VelocityDataWriter.java
|
kleineroscar/jare
|
7b1eeb28805de38de85ad3cfccfe583c45f6e881
|
[
"Apache-2.0"
] | 14 |
2015-07-04T15:34:26.000Z
|
2022-03-25T14:56:14.000Z
| 30.546154 | 94 | 0.658776 | 1,002,019 |
/*
* 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.datamelt.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
/**
* Utility class to merge objects and a Apche Velocity template to a ASCII based output.
*
* The format will be specified in external velocity templates.
*
* @author uwegeercken
*
*/
public class VelocityDataWriter
{
public static final String XML_FILE_EXTENSION = ".xml";
public static final String HTML_FILE_EXTENSION = ".html";
private static final String DEFAULT_OBJECT_NAME = "dbObject";
private static final String RESOURCE_PATH = "file.resource.loader.path";
private String templatePath;
private String templateName;
private PrintStream out;
private Template template;
private Hashtable <String,Object>objects= new Hashtable<String,Object>();
/**
* constructor for velocity datawriter class expects the path and the name of a template
*
* @param templatePath the path to the location of the template file
* @param templateName the name of the template file
* @throws Exception exception if the template engine can not be initialized
*/
public VelocityDataWriter(String templatePath, String templateName) throws Exception
{
this.templatePath = templatePath;
this.templateName = templateName;
Properties properties = new Properties();
properties.setProperty(RESOURCE_PATH, templatePath);
VelocityEngine ve = new VelocityEngine();
ve.init(properties);
template = ve.getTemplate(templateName);
}
/**
* re-initializes the datawriter with a new template. this is useful
* to re-use an existing datawriter object
*
* @param templateName the name of the velocity template to be used
* @throws Exception exception if the template was not found
*/
public void reInit(String templateName) throws Exception
{
objects.clear();
this.templateName = templateName;
Properties properties = new Properties();
properties.setProperty(RESOURCE_PATH, templatePath);
VelocityEngine ve = new VelocityEngine();
ve.init(properties);
template = ve.getTemplate(templateName);
}
/**
* removes all objects that had been passed to this datawriter object
*
*/
public void clearObjects()
{
objects.clear();
}
/**
* sets the output stream of the writer
*
* @param out the printstream to be used
*/
public void setOutputStream(PrintStream out)
{
this.out = out;
}
/**
* add an object to a hashtable of objects so that they can be processed
* at a later stage. the objectName argument will be that name which is
* used in the velocity template to identify the object
*
* @param objectName the name of the object to be added
* @param object the object to be added
*/
public void addObject(String objectName, Object object)
{
objects.put(objectName,object);
}
/**
* add an object to a hashtable of objects so that they can be processed
* at a later stage. the object gets a default name of: dbObject which
* identifies it in a velocity template
*
* @param object the object to be added
*/
public void addObject(Object object)
{
objects.put(DEFAULT_OBJECT_NAME,object);
}
/**
* merges all objects that have been passed to this writer with the given
* template and returns the resulting string representation.
*
* @return the String representation from the merge of the objects and the template
* @throws Exception exception if the merge of the objects and the template was unsuccessful
*/
public String merge() throws Exception
{
VelocityContext context = new VelocityContext();
if (objects.size()== 0)
{
throw new Exception("VelocityDataWriter: no objects to process");
}
for (Enumeration<String> e = objects.keys(); e.hasMoreElements() ;)
{
String objectKey = (String)e.nextElement();
context.put(objectKey, objects.get(objectKey));
}
StringWriter writer = new StringWriter();
template.merge(context,writer);
return writer.toString();
}
/**
* first merges the objects that have been passed to this datawriter object
* with the velocity template and then writes the output to the given path
* and file. the filename is amended to contain the current timestamp.
*
* @param path the path where the file shall be written
* @param fileName the name of the file that shall be produced
* @throws Exception exception if the file can not be produced
*
*/
public void write(String path, String fileName) throws Exception
{
String result = merge();
String checkedPath = adjustPath(path);
File f = new File(checkedPath);
f.mkdirs();
OutputStream o = new FileOutputStream(new File(checkedPath + fileName));
out = new PrintStream(o);
out.print(result);
out.close();
}
/**
* first merges the objects that have been passed to this datawriter object
* with the velocity template and then writes the output to the given
* outputstream
*
* @throws Exception exception if the file can not be produced
*/
public void write() throws Exception
{
String result = merge();
out.print(result);
}
/**
* adjusts a given path to that it has a trailing forward slash
* in case it does not have a trailing forward slash.
*
* @param path a given path
* @return the path with a trailing slash character
*/
private String adjustPath(String path)
{
if (path.endsWith("\\") || path.endsWith("/"))
{
return path;
}
else
{
return path + "/";
}
}
/**
* the path to the velocity templates
*
* @return path to the templates
*/
public String getTemplatePath()
{
return templatePath;
}
/**
* sets the path where the template may be found
*
* @param path the path to the folder where the templates are located
*/
public void setTemplatePath(String path)
{
this.templatePath = path;
}
/**
* returns the name of the template
*
* @return the name of the template in use
*/
public String getTemplateName()
{
return templateName;
}
/**
* sets the name of the template to be used
*
* @param templateName the name of the template to be used
*/
public void setTemplateName(String templateName)
{
this.templateName = templateName;
}
}
|
9241bf911c946fd4347a2f43677762f5a6361547
| 594 |
java
|
Java
|
business-center/file-center/src/main/java/com/open/capacity/oss/model/FileExtend.java
|
ObstinateCloud/open-capacity-platform
|
c25fb5880d555e2e97bd8731710ec67fc2f94a45
|
[
"Apache-2.0"
] | 1 |
2020-12-20T16:54:03.000Z
|
2020-12-20T16:54:03.000Z
|
business-center/file-center/src/main/java/com/open/capacity/oss/model/FileExtend.java
|
ObstinateCloud/open-capacity-platform
|
c25fb5880d555e2e97bd8731710ec67fc2f94a45
|
[
"Apache-2.0"
] | 1 |
2021-08-02T17:00:10.000Z
|
2021-08-02T17:00:10.000Z
|
business-center/file-center/src/main/java/com/open/capacity/oss/model/FileExtend.java
|
ObstinateCloud/open-capacity-platform
|
c25fb5880d555e2e97bd8731710ec67fc2f94a45
|
[
"Apache-2.0"
] | null | null | null | 20.482759 | 71 | 0.681818 | 1,002,020 |
package com.open.capacity.oss.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class FileExtend implements Serializable{
private static final long serialVersionUID = -3542330889450919312L;
// md5字段
private String id;
// 文件分片id
private String guid;
// 原始文件名
private String name;
// 文件大小
private long size;
// 冗余字段
private String path;
// oss访问路径 oss需要设置公共读
private String url;
// FileType字段
private String source;
// 主文件id
private String fileId;
private Date createTime;
}
|
9241c09cee179ba8c22be35c6cab9ff530dbddd7
| 950 |
java
|
Java
|
tlog-core/src/main/java/com/yomahub/tlog/core/enhance/log4j/AspectLog4jPatternConverter.java
|
qaqRose/TLog
|
bbad75af2ce5cd9a31f5a3d7a64f2381702438ff
|
[
"MIT"
] | 204 |
2021-03-11T06:57:22.000Z
|
2022-03-28T08:05:10.000Z
|
tlog-core/src/main/java/com/yomahub/tlog/core/enhance/log4j/AspectLog4jPatternConverter.java
|
qaqRose/TLog
|
bbad75af2ce5cd9a31f5a3d7a64f2381702438ff
|
[
"MIT"
] | 6 |
2021-04-09T11:05:00.000Z
|
2022-01-22T03:58:12.000Z
|
tlog-core/src/main/java/com/yomahub/tlog/core/enhance/log4j/AspectLog4jPatternConverter.java
|
qaqRose/TLog
|
bbad75af2ce5cd9a31f5a3d7a64f2381702438ff
|
[
"MIT"
] | 51 |
2021-03-11T06:57:12.000Z
|
2022-03-25T07:23:05.000Z
| 30.645161 | 74 | 0.687368 | 1,002,021 |
package com.yomahub.tlog.core.enhance.log4j;
import com.yomahub.tlog.context.TLogContext;
import com.yomahub.tlog.core.context.AspectLogContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.spi.LoggingEvent;
/**
* 基于日志适配方式的log4j的自定义PatternConvert
*
* @author Bryan.Zhang
* @since 1.0.0
*/
public class AspectLog4jPatternConverter extends PatternConverter {
@Override
protected String convert(LoggingEvent loggingEvent) {
//只有在MDC没有设置的情况下才加到message里
if(!TLogContext.hasTLogMDC()){
String logValue = AspectLogContext.getLogValue();
if(StringUtils.isNotBlank(logValue)){
return logValue + " " + loggingEvent.getRenderedMessage();
}else{
return loggingEvent.getRenderedMessage();
}
}else{
return loggingEvent.getRenderedMessage();
}
}
}
|
9241c0a0eeb22a69460cc6b7e2a7c9f5a6e15c47
| 1,881 |
java
|
Java
|
rd-openid/src/main/java/io/radien/security/openid/service/AuthenticationService.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | 2 |
2021-11-02T21:01:50.000Z
|
2022-01-19T17:06:19.000Z
|
rd-openid/src/main/java/io/radien/security/openid/service/AuthenticationService.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | null | null | null |
rd-openid/src/main/java/io/radien/security/openid/service/AuthenticationService.java
|
radien-org/radien-ce
|
9a44472a9ab39ef874787a9c2d871010e33b5240
|
[
"Apache-2.0"
] | 1 |
2021-11-09T10:17:22.000Z
|
2021-11-09T10:17:22.000Z
| 35.490566 | 105 | 0.779904 | 1,002,022 |
/*
* Copyright (c) 2006-present radien GmbH & its legal owners. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.radien.security.openid.service;
import java.util.Date;
import io.radien.api.model.user.SystemUser;
import org.springframework.security.core.userdetails.UserDetails;
import io.radien.exception.AccountExpiredException;
import io.radien.exception.AccountNotValidException;
import io.radien.exception.AuthenticationFailedException;
/**
* This interface defines the basic authentication contract of the openappframe
*
* @author Marco Weiland
*/
public interface AuthenticationService {
SystemUser authenticate(String logon, String password) throws AuthenticationFailedException;
SystemUser authenticate(String logon, String password, String language, String timezone)
throws AuthenticationFailedException;
SystemUser authenticateExternal(String logon, String language, String timezone, UserDetails userDetails)
throws AuthenticationFailedException;
default void validate(SystemUser user) throws AccountExpiredException, AccountNotValidException {
if (!user.isEnabled()) {
throw new AccountNotValidException("User is disabled!");
}
if (user.getTerminationDate() != null && new Date().before(user.getTerminationDate())) {
throw new AccountExpiredException("User is expired");
}
}
}
|
9241c22d895ac03849d2f641fc1dfbf1be6d7f0d
| 1,677 |
java
|
Java
|
dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java
|
Gouzhong1223/Dubhe
|
8959a51704410dc38b595a0926646b9928451c9a
|
[
"Apache-2.0"
] | 1 |
2022-01-11T07:14:37.000Z
|
2022-01-11T07:14:37.000Z
|
dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java
|
Gouzhong1223/Dubhe
|
8959a51704410dc38b595a0926646b9928451c9a
|
[
"Apache-2.0"
] | 1 |
2022-03-04T07:19:43.000Z
|
2022-03-04T07:19:43.000Z
|
dubhe-server/admin/src/main/java/org/dubhe/admin/domain/dto/DictUpdateDTO.java
|
Gouzhong1223/Dubhe
|
8959a51704410dc38b595a0926646b9928451c9a
|
[
"Apache-2.0"
] | 1 |
2022-03-20T13:09:14.000Z
|
2022-03-20T13:09:14.000Z
| 28.423729 | 75 | 0.715564 | 1,002,023 |
/**
* Copyright 2020 Tianshu AI Platform. 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 org.dubhe.admin.domain.dto;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import org.dubhe.admin.domain.entity.Dict;
import org.dubhe.admin.domain.entity.DictDetail;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
/**
* @description 字典新增DTO
* @date 2020-06-01
*/
@Data
public class DictUpdateDTO implements Serializable {
private static final long serialVersionUID = -901581636964448858L;
@NotNull(groups = Dict.Update.class)
private Long id;
@NotBlank
@Length(max = 255, message = "名称长度不能超过255")
private String name;
@Length(max = 255, message = "备注长度不能超过255")
private String remark;
private Timestamp createTime;
@TableField(exist = false)
private List<DictDetail> dictDetails;
public @interface Update {
}
}
|
9241c3074ddd497b01fb85d314bca8644e496c24
| 36,609 |
java
|
Java
|
android-31/src/android/view/contentcapture/ContentCaptureManager.java
|
Pixelated-Project/aosp-android-jar
|
72ae25d4fc6414e071fc1f52dd78080b84d524f8
|
[
"MIT"
] | 93 |
2020-10-11T04:37:16.000Z
|
2022-03-24T13:18:49.000Z
|
android-31/src/android/view/contentcapture/ContentCaptureManager.java
|
huangjxdev/aosp-android-jar
|
e22b61576b05ff7483180cb4d245921d66c26ee4
|
[
"MIT"
] | 3 |
2020-10-11T04:27:44.000Z
|
2022-01-19T01:31:52.000Z
|
android-31/src/android/view/contentcapture/ContentCaptureManager.java
|
huangjxdev/aosp-android-jar
|
e22b61576b05ff7483180cb4d245921d66c26ee4
|
[
"MIT"
] | 10 |
2020-11-23T02:41:58.000Z
|
2022-03-06T00:56:52.000Z
| 38.78072 | 100 | 0.669808 | 1,002,024 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view.contentcapture;
import static android.view.contentcapture.ContentCaptureHelper.sDebug;
import static android.view.contentcapture.ContentCaptureHelper.sVerbose;
import static android.view.contentcapture.ContentCaptureHelper.toSet;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.annotation.TestApi;
import android.annotation.UiThread;
import android.annotation.UserIdInt;
import android.app.Service;
import android.content.ComponentName;
import android.content.ContentCaptureOptions;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import android.util.Slog;
import android.view.View;
import android.view.ViewStructure;
import android.view.WindowManager;
import android.view.contentcapture.ContentCaptureSession.FlushReason;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;
import com.android.internal.util.SyncResultReceiver;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
/**
* <p>The {@link ContentCaptureManager} provides additional ways for for apps to
* integrate with the content capture subsystem.
*
* <p>Content capture provides real-time, continuous capture of application activity, display and
* events to an intelligence service that is provided by the Android system. The intelligence
* service then uses that info to mediate and speed user journey through different apps. For
* example, when the user receives a restaurant address in a chat app and switches to a map app
* to search for that restaurant, the intelligence service could offer an autofill dialog to
* let the user automatically select its address.
*
* <p>Content capture was designed with two major concerns in mind: privacy and performance.
*
* <ul>
* <li><b>Privacy:</b> the intelligence service is a trusted component provided that is provided
* by the device manufacturer and that cannot be changed by the user (although the user can
* globaly disable content capture using the Android Settings app). This service can only use the
* data for in-device machine learning, which is enforced both by process isolation and
* <a href="https://source.android.com/compatibility/cdd">CDD requirements</a>.
* <li><b>Performance:</b> content capture is highly optimized to minimize its impact in the app
* jankiness and overall device system health. For example, its only enabled on apps (or even
* specific activities from an app) that were explicitly allowlisted by the intelligence service,
* and it buffers the events so they are sent in a batch to the service (see
* {@link #isContentCaptureEnabled()} for other cases when its disabled).
* </ul>
*
* <p>In fact, before using this manager, the app developer should check if it's available. Example:
* <pre><code>
* ContentCaptureManager mgr = context.getSystemService(ContentCaptureManager.class);
* if (mgr != null && mgr.isContentCaptureEnabled()) {
* // ...
* }
* </code></pre>
*
* <p>App developers usually don't need to explicitly interact with content capture, except when the
* app:
*
* <ul>
* <li>Can define a contextual {@link android.content.LocusId} to identify unique state (such as a
* conversation between 2 chat users).
* <li>Can have multiple view hierarchies with different contextual meaning (for example, a
* browser app with multiple tabs, each representing a different URL).
* <li>Contains custom views (that extend View directly and are not provided by the standard
* Android SDK.
* <li>Contains views that provide their own virtual hierarchy (like a web browser that render the
* HTML elements using a Canvas).
* </ul>
*
* <p>The main integration point with content capture is the {@link ContentCaptureSession}. A "main"
* session is automatically created by the Android System when content capture is enabled for the
* activity and its used by the standard Android views to notify the content capture service of
* events such as views being added, views been removed, and text changed by user input. The session
* could have a {@link ContentCaptureContext} to provide more contextual info about it, such as
* the locus associated with the view hierarchy (see {@link android.content.LocusId} for more info
* about locus). By default, the main session doesn't have a {@code ContentCaptureContext}, but you
* can change it after its created. Example:
*
* <pre><code>
* protected void onCreate(Bundle savedInstanceState) {
* // Initialize view structure
* ContentCaptureSession session = rootView.getContentCaptureSession();
* if (session != null) {
* session.setContentCaptureContext(ContentCaptureContext.forLocusId("chat_UserA_UserB"));
* }
* }
* </code></pre>
*
* <p>If your activity contains view hierarchies with a different contextual meaning, you should
* created child sessions for each view hierarchy root. For example, if your activity is a browser,
* you could use the main session for the main URL being rendered, then child sessions for each
* {@code IFRAME}:
*
* <pre><code>
* ContentCaptureSession mMainSession;
*
* protected void onCreate(Bundle savedInstanceState) {
* // Initialize view structure...
* mMainSession = rootView.getContentCaptureSession();
* if (mMainSession != null) {
* mMainSession.setContentCaptureContext(
* ContentCaptureContext.forLocusId("https://example.com"));
* }
* }
*
* private void loadIFrame(View iframeRootView, String url) {
* if (mMainSession != null) {
* ContentCaptureSession iFrameSession = mMainSession.newChild(
* ContentCaptureContext.forLocusId(url));
* }
* iframeRootView.setContentCaptureSession(iFrameSession);
* }
* // Load iframe...
* }
* </code></pre>
*
* <p>If your activity has custom views (i.e., views that extend {@link View} directly and provide
* just one logical view, not a virtual tree hiearchy) and it provides content that's relevant for
* content capture (as of {@link android.os.Build.VERSION_CODES#Q Android Q}, the only relevant
* content is text), then your view implementation should:
*
* <ul>
* <li>Set it as important for content capture.
* <li>Fill {@link ViewStructure} used for content capture.
* <li>Notify the {@link ContentCaptureSession} when the text is changed by user input.
* </ul>
*
* <p>Here's an example of the relevant methods for an {@code EditText}-like view:
*
* <pre><code>
* public class MyEditText extends View {
*
* public MyEditText(...) {
* if (getImportantForContentCapture() == IMPORTANT_FOR_CONTENT_CAPTURE_AUTO) {
* setImportantForContentCapture(IMPORTANT_FOR_CONTENT_CAPTURE_YES);
* }
* }
*
* public void onProvideContentCaptureStructure(@NonNull ViewStructure structure, int flags) {
* super.onProvideContentCaptureStructure(structure, flags);
*
* structure.setText(getText(), getSelectionStart(), getSelectionEnd());
* structure.setHint(getHint());
* structure.setInputType(getInputType());
* // set other properties like setTextIdEntry(), setTextLines(), setTextStyle(),
* // setMinTextEms(), setMaxTextEms(), setMaxTextLength()
* }
*
* private void onTextChanged() {
* if (isLaidOut() && isImportantForContentCapture() && isTextEditable()) {
* ContentCaptureManager mgr = mContext.getSystemService(ContentCaptureManager.class);
* if (cm != null && cm.isContentCaptureEnabled()) {
* ContentCaptureSession session = getContentCaptureSession();
* if (session != null) {
* session.notifyViewTextChanged(getAutofillId(), getText());
* }
* }
* }
* </code></pre>
*
* <p>If your view provides its own virtual hierarchy (for example, if it's a browser that draws
* the HTML using {@link Canvas} or native libraries in a different render process), then the view
* is also responsible to notify the session when the virtual elements appear and disappear - see
* {@link View#onProvideContentCaptureStructure(ViewStructure, int)} for more info.
*/
@SystemService(Context.CONTENT_CAPTURE_MANAGER_SERVICE)
public final class ContentCaptureManager {
private static final String TAG = ContentCaptureManager.class.getSimpleName();
/** @hide */
public static final boolean DEBUG = false;
/** Error happened during the data sharing session. */
public static final int DATA_SHARE_ERROR_UNKNOWN = 1;
/** Request has been rejected, because a concurrent data share sessions is in progress. */
public static final int DATA_SHARE_ERROR_CONCURRENT_REQUEST = 2;
/** Request has been interrupted because of data share session timeout. */
public static final int DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED = 3;
/** @hide */
@IntDef(flag = false, value = {
DATA_SHARE_ERROR_UNKNOWN,
DATA_SHARE_ERROR_CONCURRENT_REQUEST,
DATA_SHARE_ERROR_TIMEOUT_INTERRUPTED
})
@Retention(RetentionPolicy.SOURCE)
public @interface DataShareError {}
/** @hide */
public static final int RESULT_CODE_OK = 0;
/** @hide */
public static final int RESULT_CODE_TRUE = 1;
/** @hide */
public static final int RESULT_CODE_FALSE = 2;
/** @hide */
public static final int RESULT_CODE_SECURITY_EXCEPTION = -1;
/**
* ID used to indicate that a session does not exist
* @hide
*/
@SystemApi
public static final int NO_SESSION_ID = 0;
/**
* Timeout for calls to system_server.
*/
private static final int SYNC_CALLS_TIMEOUT_MS = 5000;
/**
* DeviceConfig property used by {@code com.android.server.SystemServer} on start to decide
* whether the content capture service should be created or not
*
* <p>By default it should *NOT* be set (or set to {@code "default"}, so the decision is based
* on whether the OEM provides an implementation for the service), but it can be overridden to:
*
* <ul>
* <li>Provide a "kill switch" so OEMs can disable it remotely in case of emergency (when
* it's set to {@code "false"}).
* <li>Enable the CTS tests to be run on AOSP builds (when it's set to {@code "true"}).
* </ul>
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_SERVICE_EXPLICITLY_ENABLED =
"service_explicitly_enabled";
/**
* Maximum number of events that are buffered before sent to the app.
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_MAX_BUFFER_SIZE = "max_buffer_size";
/**
* Frequency (in ms) of buffer flushes when no events are received.
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_IDLE_FLUSH_FREQUENCY = "idle_flush_frequency";
/**
* Frequency (in ms) of buffer flushes when no events are received and the last one was a
* text change event.
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_TEXT_CHANGE_FLUSH_FREQUENCY =
"text_change_flush_frequency";
/**
* Size of events that are logging on {@code dump}.
*
* <p>Set it to {@code 0} or less to disable history.
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_LOG_HISTORY_SIZE = "log_history_size";
/**
* Sets the logging level for {@code logcat} statements.
*
* <p>Valid values are: {@link #LOGGING_LEVEL_OFF}, {@value #LOGGING_LEVEL_DEBUG}, and
* {@link #LOGGING_LEVEL_VERBOSE}.
*
* @hide
*/
@TestApi
public static final String DEVICE_CONFIG_PROPERTY_LOGGING_LEVEL = "logging_level";
/**
* Sets how long (in ms) the service is bound while idle.
*
* <p>Use {@code 0} to keep it permanently bound.
*
* @hide
*/
public static final String DEVICE_CONFIG_PROPERTY_IDLE_UNBIND_TIMEOUT = "idle_unbind_timeout";
/** @hide */
@TestApi
public static final int LOGGING_LEVEL_OFF = 0;
/** @hide */
@TestApi
public static final int LOGGING_LEVEL_DEBUG = 1;
/** @hide */
@TestApi
public static final int LOGGING_LEVEL_VERBOSE = 2;
/** @hide */
@IntDef(flag = false, value = {
LOGGING_LEVEL_OFF,
LOGGING_LEVEL_DEBUG,
LOGGING_LEVEL_VERBOSE
})
@Retention(RetentionPolicy.SOURCE)
public @interface LoggingLevel {}
/** @hide */
public static final int DEFAULT_MAX_BUFFER_SIZE = 500; // Enough for typical busy screen.
/** @hide */
public static final int DEFAULT_IDLE_FLUSHING_FREQUENCY_MS = 5_000;
/** @hide */
public static final int DEFAULT_TEXT_CHANGE_FLUSHING_FREQUENCY_MS = 1_000;
/** @hide */
public static final int DEFAULT_LOG_HISTORY_SIZE = 10;
private final Object mLock = new Object();
@NonNull
private final Context mContext;
@NonNull
private final IContentCaptureManager mService;
@GuardedBy("mLock")
private final LocalDataShareAdapterResourceManager mDataShareAdapterResourceManager;
@NonNull
final ContentCaptureOptions mOptions;
// Flags used for starting session.
@GuardedBy("mLock")
private int mFlags;
// TODO(b/119220549): use UI Thread directly (as calls are one-way) or a shared thread / handler
// held at the Application level
@NonNull
private final Handler mHandler;
@GuardedBy("mLock")
private MainContentCaptureSession mMainSession;
/** @hide */
public interface ContentCaptureClient {
/**
* Gets the component name of the client.
*/
@NonNull
ComponentName contentCaptureClientGetComponentName();
}
/** @hide */
public ContentCaptureManager(@NonNull Context context,
@NonNull IContentCaptureManager service, @NonNull ContentCaptureOptions options) {
mContext = Preconditions.checkNotNull(context, "context cannot be null");
mService = Preconditions.checkNotNull(service, "service cannot be null");
mOptions = Preconditions.checkNotNull(options, "options cannot be null");
ContentCaptureHelper.setLoggingLevel(mOptions.loggingLevel);
if (sVerbose) Log.v(TAG, "Constructor for " + context.getPackageName());
// TODO(b/119220549): we might not even need a handler, as the IPCs are oneway. But if we
// do, then we should optimize it to run the tests after the Choreographer finishes the most
// important steps of the frame.
mHandler = Handler.createAsync(Looper.getMainLooper());
mDataShareAdapterResourceManager = new LocalDataShareAdapterResourceManager();
}
/**
* Gets the main session associated with the context.
*
* <p>By default there's just one (associated with the activity lifecycle), but apps could
* explicitly add more using
* {@link ContentCaptureSession#createContentCaptureSession(ContentCaptureContext)}.
*
* @hide
*/
@NonNull
@UiThread
public MainContentCaptureSession getMainContentCaptureSession() {
synchronized (mLock) {
if (mMainSession == null) {
mMainSession = new MainContentCaptureSession(mContext, this, mHandler, mService);
if (sVerbose) Log.v(TAG, "getMainContentCaptureSession(): created " + mMainSession);
}
return mMainSession;
}
}
/** @hide */
@UiThread
public void onActivityCreated(@NonNull IBinder applicationToken,
@NonNull IBinder shareableActivityToken, @NonNull ComponentName activityComponent) {
if (mOptions.lite) return;
synchronized (mLock) {
getMainContentCaptureSession().start(applicationToken, shareableActivityToken,
activityComponent, mFlags);
}
}
/** @hide */
@UiThread
public void onActivityResumed() {
if (mOptions.lite) return;
getMainContentCaptureSession().notifySessionResumed();
}
/** @hide */
@UiThread
public void onActivityPaused() {
if (mOptions.lite) return;
getMainContentCaptureSession().notifySessionPaused();
}
/** @hide */
@UiThread
public void onActivityDestroyed() {
if (mOptions.lite) return;
getMainContentCaptureSession().destroy();
}
/**
* Flushes the content of all sessions.
*
* <p>Typically called by {@code Activity} when it's paused / resumed.
*
* @hide
*/
@UiThread
public void flush(@FlushReason int reason) {
if (mOptions.lite) return;
getMainContentCaptureSession().flush(reason);
}
/**
* Returns the component name of the system service that is consuming the captured events for
* the current user.
*/
@Nullable
public ComponentName getServiceComponentName() {
if (!isContentCaptureEnabled() && !mOptions.lite) return null;
final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
try {
mService.getServiceComponentName(resultReceiver);
return resultReceiver.getParcelableResult();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (SyncResultReceiver.TimeoutException e) {
throw new RuntimeException("Fail to get service componentName.");
}
}
/**
* Gets the (optional) intent used to launch the service-specific settings.
*
* <p>This method is static because it's called by Settings, which might not be allowlisted
* for content capture (in which case the ContentCaptureManager on its context would be null).
*
* @hide
*/
// TODO: use "lite" options as it's done by activities from the content capture service
@Nullable
public static ComponentName getServiceSettingsComponentName() {
final IBinder binder = ServiceManager
.checkService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);
if (binder == null) return null;
final IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(binder);
final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
try {
service.getServiceSettingsActivity(resultReceiver);
final int resultCode = resultReceiver.getIntResult();
if (resultCode == RESULT_CODE_SECURITY_EXCEPTION) {
throw new SecurityException(resultReceiver.getStringResult());
}
return resultReceiver.getParcelableResult();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (SyncResultReceiver.TimeoutException e) {
Log.e(TAG, "Fail to get service settings componentName: " + e);
return null;
}
}
/**
* Checks whether content capture is enabled for this activity.
*
* <p>There are many reasons it could be disabled, such as:
* <ul>
* <li>App itself disabled content capture through {@link #setContentCaptureEnabled(boolean)}.
* <li>Intelligence service did not allowlist content capture for this activity's package.
* <li>Intelligence service did not allowlist content capture for this specific activity.
* <li>Intelligence service disabled content capture globally.
* <li>User disabled content capture globally through the Android Settings app.
* <li>Device manufacturer (OEM) disabled content capture globally.
* <li>Transient errors, such as intelligence service package being updated.
* </ul>
*/
public boolean isContentCaptureEnabled() {
if (mOptions.lite) return false;
final MainContentCaptureSession mainSession;
synchronized (mLock) {
mainSession = mMainSession;
}
// The main session is only set when the activity starts, so we need to return true until
// then.
if (mainSession != null && mainSession.isDisabled()) return false;
return true;
}
/**
* Gets the list of conditions for when content capture should be allowed.
*
* <p>This method is typically used by web browsers so they don't generate unnecessary content
* capture events for websites the content capture service is not interested on.
*
* @return list of conditions, or {@code null} if the service didn't set any restriction
* (in which case content capture events should always be generated). If the list is empty,
* then it should not generate any event at all.
*/
@Nullable
public Set<ContentCaptureCondition> getContentCaptureConditions() {
// NOTE: we could cache the conditions on ContentCaptureOptions, but then it would be stick
// to the lifetime of the app. OTOH, by dynamically calling the server every time, we allow
// the service to fine tune how long-lived apps (like browsers) are allowlisted.
if (!isContentCaptureEnabled() && !mOptions.lite) return null;
final SyncResultReceiver resultReceiver = syncRun(
(r) -> mService.getContentCaptureConditions(mContext.getPackageName(), r));
try {
final ArrayList<ContentCaptureCondition> result = resultReceiver
.getParcelableListResult();
return toSet(result);
} catch (SyncResultReceiver.TimeoutException e) {
throw new RuntimeException("Fail to get content capture conditions.");
}
}
/**
* Called by apps to explicitly enable or disable content capture.
*
* <p><b>Note: </b> this call is not persisted accross reboots, so apps should typically call
* it on {@link android.app.Activity#onCreate(android.os.Bundle, android.os.PersistableBundle)}.
*/
public void setContentCaptureEnabled(boolean enabled) {
if (sDebug) {
Log.d(TAG, "setContentCaptureEnabled(): setting to " + enabled + " for " + mContext);
}
MainContentCaptureSession mainSession;
synchronized (mLock) {
if (enabled) {
mFlags &= ~ContentCaptureContext.FLAG_DISABLED_BY_APP;
} else {
mFlags |= ContentCaptureContext.FLAG_DISABLED_BY_APP;
}
mainSession = mMainSession;
}
if (mainSession != null) {
mainSession.setDisabled(!enabled);
}
}
/**
* Called by apps to update flag secure when window attributes change.
*
* @hide
*/
public void updateWindowAttributes(@NonNull WindowManager.LayoutParams params) {
if (sDebug) {
Log.d(TAG, "updateWindowAttributes(): window flags=" + params.flags);
}
final boolean flagSecureEnabled =
(params.flags & WindowManager.LayoutParams.FLAG_SECURE) != 0;
MainContentCaptureSession mainSession;
synchronized (mLock) {
if (flagSecureEnabled) {
mFlags |= ContentCaptureContext.FLAG_DISABLED_BY_FLAG_SECURE;
} else {
mFlags &= ~ContentCaptureContext.FLAG_DISABLED_BY_FLAG_SECURE;
}
mainSession = mMainSession;
}
if (mainSession != null) {
mainSession.setDisabled(flagSecureEnabled);
}
}
/**
* Gets whether content capture is enabled for the given user.
*
* <p>This method is typically used by the content capture service settings page, so it can
* provide a toggle to enable / disable it.
*
* @throws SecurityException if caller is not the app that owns the content capture service
* associated with the user.
*
* @hide
*/
@SystemApi
public boolean isContentCaptureFeatureEnabled() {
final SyncResultReceiver resultReceiver = syncRun(
(r) -> mService.isContentCaptureFeatureEnabled(r));
try {
final int resultCode = resultReceiver.getIntResult();
switch (resultCode) {
case RESULT_CODE_TRUE:
return true;
case RESULT_CODE_FALSE:
return false;
default:
Log.wtf(TAG, "received invalid result: " + resultCode);
return false;
}
} catch (SyncResultReceiver.TimeoutException e) {
Log.e(TAG, "Fail to get content capture feature enable status: " + e);
return false;
}
}
/**
* Called by the app to request the content capture service to remove content capture data
* associated with some context.
*
* @param request object specifying what user data should be removed.
*/
public void removeData(@NonNull DataRemovalRequest request) {
Preconditions.checkNotNull(request);
try {
mService.removeData(request);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Called by the app to request data sharing via writing to a file.
*
* <p>The ContentCaptureService app will receive a read-only file descriptor pointing to the
* same file and will be able to read data being shared from it.
*
* <p>Note: using this API doesn't guarantee the app staying alive and is "best-effort".
* Starting a foreground service would minimize the chances of the app getting killed during the
* file sharing session.
*
* @param request object specifying details of the data being shared.
*/
public void shareData(@NonNull DataShareRequest request,
@NonNull @CallbackExecutor Executor executor,
@NonNull DataShareWriteAdapter dataShareWriteAdapter) {
Preconditions.checkNotNull(request);
Preconditions.checkNotNull(dataShareWriteAdapter);
Preconditions.checkNotNull(executor);
try {
mService.shareData(request,
new DataShareAdapterDelegate(executor, dataShareWriteAdapter,
mDataShareAdapterResourceManager));
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Runs a sync method in the service, properly handling exceptions.
*
* @throws SecurityException if caller is not allowed to execute the method.
*/
@NonNull
private SyncResultReceiver syncRun(@NonNull MyRunnable r) {
final SyncResultReceiver resultReceiver = new SyncResultReceiver(SYNC_CALLS_TIMEOUT_MS);
try {
r.run(resultReceiver);
final int resultCode = resultReceiver.getIntResult();
if (resultCode == RESULT_CODE_SECURITY_EXCEPTION) {
throw new SecurityException(resultReceiver.getStringResult());
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (SyncResultReceiver.TimeoutException e) {
throw new RuntimeException("Fail to get syn run result from SyncResultReceiver.");
}
return resultReceiver;
}
/** @hide */
public void dump(String prefix, PrintWriter pw) {
pw.print(prefix); pw.println("ContentCaptureManager");
final String prefix2 = prefix + " ";
synchronized (mLock) {
pw.print(prefix2); pw.print("isContentCaptureEnabled(): ");
pw.println(isContentCaptureEnabled());
pw.print(prefix2); pw.print("Debug: "); pw.print(sDebug);
pw.print(" Verbose: "); pw.println(sVerbose);
pw.print(prefix2); pw.print("Context: "); pw.println(mContext);
pw.print(prefix2); pw.print("User: "); pw.println(mContext.getUserId());
pw.print(prefix2); pw.print("Service: "); pw.println(mService);
pw.print(prefix2); pw.print("Flags: "); pw.println(mFlags);
pw.print(prefix2); pw.print("Options: "); mOptions.dumpShort(pw); pw.println();
if (mMainSession != null) {
final String prefix3 = prefix2 + " ";
pw.print(prefix2); pw.println("Main session:");
mMainSession.dump(prefix3, pw);
} else {
pw.print(prefix2); pw.println("No sessions");
}
}
}
/**
* Resets the temporary content capture service implementation to the default component.
*
* @hide
*/
@TestApi
@RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
public static void resetTemporaryService(@UserIdInt int userId) {
final IContentCaptureManager service = getService();
if (service == null) {
Log.e(TAG, "IContentCaptureManager is null");
}
try {
service.resetTemporaryService(userId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Temporarily sets the content capture service implementation.
*
* @param userId user Id to set the temporary service on.
* @param serviceName name of the new component
* @param duration how long the change will be valid (the service will be automatically reset
* to the default component after this timeout expires).
*
* @hide
*/
@TestApi
@RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
public static void setTemporaryService(
@UserIdInt int userId, @NonNull String serviceName, int duration) {
final IContentCaptureManager service = getService();
if (service == null) {
Log.e(TAG, "IContentCaptureManager is null");
}
try {
service.setTemporaryService(userId, serviceName, duration);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Sets whether the default content capture service should be used.
*
* @hide
*/
@TestApi
@RequiresPermission(android.Manifest.permission.MANAGE_CONTENT_CAPTURE)
public static void setDefaultServiceEnabled(@UserIdInt int userId, boolean enabled) {
final IContentCaptureManager service = getService();
if (service == null) {
Log.e(TAG, "IContentCaptureManager is null");
}
try {
service.setDefaultServiceEnabled(userId, enabled);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private static IContentCaptureManager getService() {
return IContentCaptureManager.Stub.asInterface(ServiceManager.getService(
Service.CONTENT_CAPTURE_MANAGER_SERVICE));
}
private interface MyRunnable {
void run(@NonNull SyncResultReceiver receiver) throws RemoteException;
}
private static class DataShareAdapterDelegate extends IDataShareWriteAdapter.Stub {
private final WeakReference<LocalDataShareAdapterResourceManager> mResourceManagerReference;
private DataShareAdapterDelegate(Executor executor, DataShareWriteAdapter adapter,
LocalDataShareAdapterResourceManager resourceManager) {
Preconditions.checkNotNull(executor);
Preconditions.checkNotNull(adapter);
Preconditions.checkNotNull(resourceManager);
resourceManager.initializeForDelegate(this, adapter, executor);
mResourceManagerReference = new WeakReference<>(resourceManager);
}
@Override
public void write(ParcelFileDescriptor destination)
throws RemoteException {
executeAdapterMethodLocked(adapter -> adapter.onWrite(destination), "onWrite");
}
@Override
public void error(int errorCode) throws RemoteException {
executeAdapterMethodLocked(adapter -> adapter.onError(errorCode), "onError");
clearHardReferences();
}
@Override
public void rejected() throws RemoteException {
executeAdapterMethodLocked(DataShareWriteAdapter::onRejected, "onRejected");
clearHardReferences();
}
@Override
public void finish() throws RemoteException {
clearHardReferences();
}
private void executeAdapterMethodLocked(Consumer<DataShareWriteAdapter> adapterFn,
String methodName) {
LocalDataShareAdapterResourceManager resourceManager = mResourceManagerReference.get();
if (resourceManager == null) {
Slog.w(TAG, "Can't execute " + methodName + "(), resource manager has been GC'ed");
return;
}
DataShareWriteAdapter adapter = resourceManager.getAdapter(this);
Executor executor = resourceManager.getExecutor(this);
if (adapter == null || executor == null) {
Slog.w(TAG, "Can't execute " + methodName + "(), references are null");
return;
}
final long identity = Binder.clearCallingIdentity();
try {
executor.execute(() -> adapterFn.accept(adapter));
} finally {
Binder.restoreCallingIdentity(identity);
}
}
private void clearHardReferences() {
LocalDataShareAdapterResourceManager resourceManager = mResourceManagerReference.get();
if (resourceManager == null) {
Slog.w(TAG, "Can't clear references, resource manager has been GC'ed");
return;
}
resourceManager.clearHardReferences(this);
}
}
/**
* Wrapper class making sure dependencies on the current application stay in the application
* context.
*/
private static class LocalDataShareAdapterResourceManager {
// Keeping hard references to the remote objects in the current process (static context)
// to prevent them to be gc'ed during the lifetime of the application. This is an
// artifact of only operating with weak references remotely: there has to be at least 1
// hard reference in order for this to not be killed.
private Map<DataShareAdapterDelegate, DataShareWriteAdapter> mWriteAdapterHardReferences =
new HashMap<>();
private Map<DataShareAdapterDelegate, Executor> mExecutorHardReferences =
new HashMap<>();
void initializeForDelegate(DataShareAdapterDelegate delegate, DataShareWriteAdapter adapter,
Executor executor) {
mWriteAdapterHardReferences.put(delegate, adapter);
mExecutorHardReferences.put(delegate, executor);
}
Executor getExecutor(DataShareAdapterDelegate delegate) {
return mExecutorHardReferences.get(delegate);
}
DataShareWriteAdapter getAdapter(DataShareAdapterDelegate delegate) {
return mWriteAdapterHardReferences.get(delegate);
}
void clearHardReferences(DataShareAdapterDelegate delegate) {
mWriteAdapterHardReferences.remove(delegate);
mExecutorHardReferences.remove(delegate);
}
}
}
|
9241c344d54a5adf252de3986804dbcb8343a0c3
| 947 |
java
|
Java
|
M-Tribes/app/src/main/java/m/tribes/test/app/core/presenter/MapPresenter.java
|
nemanjasdev/mTribesTest
|
ed594ee98ad88e3e67a78b985bce8308a63383de
|
[
"MIT"
] | null | null | null |
M-Tribes/app/src/main/java/m/tribes/test/app/core/presenter/MapPresenter.java
|
nemanjasdev/mTribesTest
|
ed594ee98ad88e3e67a78b985bce8308a63383de
|
[
"MIT"
] | null | null | null |
M-Tribes/app/src/main/java/m/tribes/test/app/core/presenter/MapPresenter.java
|
nemanjasdev/mTribesTest
|
ed594ee98ad88e3e67a78b985bce8308a63383de
|
[
"MIT"
] | null | null | null | 27.852941 | 117 | 0.793031 | 1,002,025 |
package m.tribes.test.app.core.presenter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.maps.GoogleMap;
import m.tribes.test.app.core.interactor.HomeInteractor;
import m.tribes.test.app.core.interactor.MapInteractor;
public class MapPresenter {
private IPresenter presenter;
public MapInteractor mapInteractor;
public MapPresenter(IPresenter presenter, MapInteractor mapInteractor) {
this.presenter = presenter;
this.mapInteractor = mapInteractor;
}
public void returnPlacemarksMap(Context context, GoogleMap map, FusedLocationProviderClient mFusedLocationClient) {
mapInteractor.findMapItems(context, mFusedLocationClient, map);
}
public void returnCarsByName(String title) {
mapInteractor.displayCarsByName(title);
}
public void onDestroy() {
presenter = null;
}
}
|
9241c413d3018845ed07f00c5a830ef913208f28
| 1,503 |
java
|
Java
|
Mage.Sets/src/mage/cards/s/Sandskin.java
|
dsenginr/mage
|
94e9aeedc20dcb74264e58fd198f46215828ef5c
|
[
"MIT"
] | 1,444 |
2015-01-02T00:25:38.000Z
|
2022-03-31T13:57:18.000Z
|
Mage.Sets/src/mage/cards/s/Sandskin.java
|
dsenginr/mage
|
94e9aeedc20dcb74264e58fd198f46215828ef5c
|
[
"MIT"
] | 6,180 |
2015-01-02T19:10:09.000Z
|
2022-03-31T21:10:44.000Z
|
Mage.Sets/src/mage/cards/s/Sandskin.java
|
dsenginr/mage
|
94e9aeedc20dcb74264e58fd198f46215828ef5c
|
[
"MIT"
] | 1,001 |
2015-01-01T01:15:20.000Z
|
2022-03-30T20:23:04.000Z
| 30.673469 | 167 | 0.738523 | 1,002,026 |
package mage.cards.s;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.PreventAllDamageToAndByAttachedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author TheElk801
*/
public final class Sandskin extends CardImpl {
public Sandskin(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{W}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature));
Ability ability = new EnchantAbility(auraTarget.getTargetName());
this.addAbility(ability);
// Prevent all combat damage that would be dealt to and dealt by enchanted creature.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new PreventAllDamageToAndByAttachedEffect(Duration.WhileOnBattlefield, "enchanted creature", true)));
}
private Sandskin(final Sandskin card) {
super(card);
}
@Override
public Sandskin copy() {
return new Sandskin(this);
}
}
|
9241c4d845cc4d82edcb8dfb4da3f2b8a0215be5
| 147 |
java
|
Java
|
Java/Algorithms/Math/Main.java
|
arnishb/hacktoberfest2021
|
9d89734c5e5d922901b5a6a7492aa97130564d62
|
[
"MIT"
] | 380 |
2021-10-01T10:22:20.000Z
|
2022-03-06T14:34:22.000Z
|
Java/Algorithms/Math/Main.java
|
arnishb/hacktoberfest2021
|
9d89734c5e5d922901b5a6a7492aa97130564d62
|
[
"MIT"
] | 146 |
2021-10-01T09:49:54.000Z
|
2022-01-20T14:40:52.000Z
|
Java/Algorithms/Math/Main.java
|
arnishb/hacktoberfest2021
|
9d89734c5e5d922901b5a6a7492aa97130564d62
|
[
"MIT"
] | 1,335 |
2021-10-01T10:00:18.000Z
|
2022-03-03T20:07:35.000Z
| 13.363636 | 44 | 0.496599 | 1,002,027 |
import java.util.*;
class Main{
public static void main(String[] args) {
}
// static int countNo(int n){
// }
}
|
9241c4f8a91f5cc2b381eeeb141475735d018903
| 3,520 |
java
|
Java
|
src/main/java/de/tracetronic/jenkins/plugins/ecutest/report/log/ETLogBuildAction.java
|
timja/ecutest-plugin
|
a2478f0d4b7a19b300fd20bca8c05a7d00616057
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/de/tracetronic/jenkins/plugins/ecutest/report/log/ETLogBuildAction.java
|
timja/ecutest-plugin
|
a2478f0d4b7a19b300fd20bca8c05a7d00616057
|
[
"BSD-3-Clause"
] | null | null | null |
src/main/java/de/tracetronic/jenkins/plugins/ecutest/report/log/ETLogBuildAction.java
|
timja/ecutest-plugin
|
a2478f0d4b7a19b300fd20bca8c05a7d00616057
|
[
"BSD-3-Clause"
] | null | null | null | 30.482759 | 103 | 0.631787 | 1,002,028 |
/*
* Copyright (c) 2015-2019 TraceTronic GmbH
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package de.tracetronic.jenkins.plugins.ecutest.report.log;
import de.tracetronic.jenkins.plugins.ecutest.report.AbstractTestReport;
import hudson.model.Action;
import jenkins.tasks.SimpleBuildStep;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Action to show a link to {@link ETLogReport}s at the build page.
*
* @author Christian Pönisch <[email protected]>
*/
public class ETLogBuildAction extends AbstractETLogAction implements SimpleBuildStep.LastBuildAction {
private final List<ETLogReport> logReports = new ArrayList<>();
/**
* Instantiates a new {@link ETLogBuildAction}.
*
* @param projectLevel specifies whether archiving is restricted to project level only
*/
public ETLogBuildAction(final boolean projectLevel) {
super(projectLevel);
}
/**
* Gets the ECU-TEST log reports.
*
* @return the log reports
*/
public List<ETLogReport> getLogReports() {
return logReports;
}
/**
* Adds a ECU-TEST log report.
*
* @param report the ECU-TEST log report to add
* @return {@code true} if successful, {@code false} otherwise
*/
public boolean add(final ETLogReport report) {
return getLogReports().add(report);
}
/**
* Adds a bundle of ECU-TEST log reports.
*
* @param reports the collection of ECU-TEST log reports
* @return {@code true} if successful, {@code false} otherwise
*/
public boolean addAll(final Collection<ETLogReport> reports) {
return getLogReports().addAll(reports);
}
/**
* Returns {@link ETLogReport} specified by the URL.
*
* @param token the URL token
* @return the {@link ETLogReport} or {@code null} if no proper report exists
*/
public ETLogReport getDynamic(final String token) {
for (final ETLogReport report : getLogReports()) {
if (token.equals(report.getId())) {
return report;
} else {
final ETLogReport potentialReport = traverseSubReports(token, report);
if (potentialReport != null) {
return potentialReport;
}
}
}
return null;
}
/**
* Traverses the sub-reports recursively and searches
* for the {@link ETLogReport} matching the given token id.
*
* @param token the token id
* @param report the report
* @return the {@link ETLogReport} or {@code null} if no proper report exists
*/
private ETLogReport traverseSubReports(final String token, final ETLogReport report) {
for (final AbstractTestReport subReport : report.getSubReports()) {
if (token.equals(subReport.getId())) {
return (ETLogReport) subReport;
} else {
final ETLogReport potentialReport = traverseSubReports(token, (ETLogReport) subReport);
if (potentialReport != null) {
return potentialReport;
}
}
}
return null;
}
@Override
public String getDisplayName() {
return Messages.ETLogBuildAction_DisplayName();
}
@Override
public Collection<? extends Action> getProjectActions() {
return Collections.singleton(new ETLogProjectAction(isProjectLevel()));
}
}
|
9241c53fb4afbd2eab96ec5b00049260f5bfb511
| 1,687 |
java
|
Java
|
src/ecrm-s/src/main/java/com/maven/service/ApiSoltGametypeEnterpriseService.java
|
Douglas890116/Atom
|
bd0627d744abcff881f5de9a101215949e0c3f3e
|
[
"Unlicense"
] | 2 |
2019-01-04T03:00:26.000Z
|
2019-09-18T10:33:19.000Z
|
src/ecrm-s/src/main/java/com/maven/service/ApiSoltGametypeEnterpriseService.java
|
Douglas890116/Atom
|
bd0627d744abcff881f5de9a101215949e0c3f3e
|
[
"Unlicense"
] | null | null | null |
src/ecrm-s/src/main/java/com/maven/service/ApiSoltGametypeEnterpriseService.java
|
Douglas890116/Atom
|
bd0627d744abcff881f5de9a101215949e0c3f3e
|
[
"Unlicense"
] | 2 |
2019-01-04T03:02:52.000Z
|
2020-12-16T04:50:48.000Z
| 22.197368 | 97 | 0.746295 | 1,002,029 |
package com.maven.service;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.maven.base.dao.DataSource;
import com.maven.base.service.BaseServcie;
import com.maven.entity.ActivityBetRecord;
import com.maven.entity.ApiSoltGametypeEnterprise;
import com.maven.entity.TakeDepositRecord;
@Service
public interface ApiSoltGametypeEnterpriseService extends BaseServcie<ApiSoltGametypeEnterprise>{
@DataSource("slave")
List<ApiSoltGametypeEnterprise> selectTypes(Map<String, Object> parameter) throws Exception;
@DataSource("master")
void deleteByEnterprisecode(String enterprisecode) throws Exception;
/**
* 获取需要投注列表
* @return
*/
@DataSource("slave")
List<ApiSoltGametypeEnterprise> selectBetRecord(Map<String, Object> parameter) throws Exception;
/**
* 需要投注列表总数
* @param parameter
* @return
* @throws Exception
*/
@DataSource("slave")
int selectBetRecordCount(Map<String, Object> parameter) throws Exception;
/**
* 获取需要投注列表
* @return
*/
@DataSource("slave")
List<ApiSoltGametypeEnterprise> selectAdd(Map<String, Object> parameter) throws Exception;
/**
* 需要投注列表总数
* @param parameter
* @return
* @throws Exception
*/
@DataSource("slave")
int selectAddCount(Map<String, Object> parameter) throws Exception;
/**
* 获取需要投注列表
* @return
*/
@DataSource("slave")
List<ApiSoltGametypeEnterprise> select(Map<String, Object> parameter) throws Exception;
/**
* 增加需要打码的记录
* @param amount
* @param brandcode
* @return
* @throws Exception
*/
@DataSource("master")
void addActivityBetRecord(ApiSoltGametypeEnterprise activityBetRecord) throws Exception;
}
|
9241c5fa85abaac8fb7ca0aafce009b883077cf4
| 207 |
java
|
Java
|
src/main/java/tt/service/bussiness/InspectItemServiceI.java
|
luopotaotao/staticLoad
|
8942cf2276775152f3cc865dda8393e365d4982e
|
[
"MIT"
] | null | null | null |
src/main/java/tt/service/bussiness/InspectItemServiceI.java
|
luopotaotao/staticLoad
|
8942cf2276775152f3cc865dda8393e365d4982e
|
[
"MIT"
] | 2 |
2021-01-20T22:33:37.000Z
|
2021-12-09T20:06:59.000Z
|
src/main/java/tt/service/bussiness/InspectItemServiceI.java
|
luopotaotao/staticLoad
|
8942cf2276775152f3cc865dda8393e365d4982e
|
[
"MIT"
] | null | null | null | 17.25 | 71 | 0.763285 | 1,002,030 |
package tt.service.bussiness;
import tt.model.business.InspectItem;
import java.util.List;
/**
* Created by tt on 2016/10/2.
*/
public interface InspectItemServiceI extends BaseService<InspectItem> {
}
|
9241c7169aa5bd381ec6764c515e6c0cc8828b09
| 2,646 |
java
|
Java
|
java/classes/android/support/v7/view/a.java
|
gaoht/house
|
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
|
[
"Apache-2.0"
] | 1 |
2020-05-08T05:35:32.000Z
|
2020-05-08T05:35:32.000Z
|
java/classes/android/support/v7/view/a.java
|
gaoht/house
|
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
|
[
"Apache-2.0"
] | null | null | null |
java/classes/android/support/v7/view/a.java
|
gaoht/house
|
b9e63db1a4975b614c422fed3b5b33ee57ea23fd
|
[
"Apache-2.0"
] | 3 |
2018-09-07T08:15:08.000Z
|
2020-05-22T03:59:12.000Z
| 28.148936 | 128 | 0.691232 | 1,002,031 |
package android.support.v7.view;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Build.VERSION;
import android.support.v7.appcompat.R.attr;
import android.support.v7.appcompat.R.bool;
import android.support.v7.appcompat.R.dimen;
import android.support.v7.appcompat.R.styleable;
import android.util.DisplayMetrics;
import android.view.ViewConfiguration;
public class a
{
private Context a;
private a(Context paramContext)
{
this.a = paramContext;
}
public static a get(Context paramContext)
{
return new a(paramContext);
}
public boolean enableHomeButtonByDefault()
{
return this.a.getApplicationInfo().targetSdkVersion < 14;
}
public int getEmbeddedMenuWidthLimit()
{
return this.a.getResources().getDisplayMetrics().widthPixels / 2;
}
public int getMaxActionButtons()
{
Configuration localConfiguration = this.a.getResources().getConfiguration();
int i = localConfiguration.screenWidthDp;
int j = localConfiguration.screenHeightDp;
if ((localConfiguration.smallestScreenWidthDp > 600) || (i > 600) || ((i > 960) && (j > 720)) || ((i > 720) && (j > 960))) {
return 5;
}
if ((i >= 500) || ((i > 640) && (j > 480)) || ((i > 480) && (j > 640))) {
return 4;
}
if (i >= 360) {
return 3;
}
return 2;
}
public int getStackedTabMaxWidth()
{
return this.a.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_stacked_tab_max_width);
}
public int getTabContainerHeight()
{
TypedArray localTypedArray = this.a.obtainStyledAttributes(null, R.styleable.ActionBar, R.attr.actionBarStyle, 0);
int j = localTypedArray.getLayoutDimension(R.styleable.ActionBar_height, 0);
Resources localResources = this.a.getResources();
int i = j;
if (!hasEmbeddedTabs()) {
i = Math.min(j, localResources.getDimensionPixelSize(R.dimen.abc_action_bar_stacked_max_height));
}
localTypedArray.recycle();
return i;
}
public boolean hasEmbeddedTabs()
{
return this.a.getResources().getBoolean(R.bool.abc_action_bar_embed_tabs);
}
public boolean showsOverflowMenuButton()
{
if (Build.VERSION.SDK_INT >= 19) {}
while (!ViewConfiguration.get(this.a).hasPermanentMenuKey()) {
return true;
}
return false;
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/android/support/v7/view/a.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
|
9241c724c78cc9dd304f3f072e9c4f836bc933ae
| 1,604 |
java
|
Java
|
dsa-java/dsa/src/main/java/dsa/lists/KthToLast.java
|
mervinyan/dsa-playground
|
12612e6fd455890b08c90468e11cf47dd4e03a61
|
[
"MIT"
] | null | null | null |
dsa-java/dsa/src/main/java/dsa/lists/KthToLast.java
|
mervinyan/dsa-playground
|
12612e6fd455890b08c90468e11cf47dd4e03a61
|
[
"MIT"
] | null | null | null |
dsa-java/dsa/src/main/java/dsa/lists/KthToLast.java
|
mervinyan/dsa-playground
|
12612e6fd455890b08c90468e11cf47dd4e03a61
|
[
"MIT"
] | null | null | null | 25.0625 | 87 | 0.604115 | 1,002,032 |
package dsa.lists;
public class KthToLast {
static int printKthToLast(LinkedListNode head, int k) {
if (head == null) {
return 0;
}
int index = printKthToLast(head.next, k) + 1;
if (index == k) {
System.out.println(k + "th to last node is " + head.data);
}
return index;
}
static class Index {
public int value = 0;
}
static LinkedListNode kthToLast(LinkedListNode head, int k) {
Index idx = new Index();
return kthToLast(head, k, idx);
}
static LinkedListNode kthToLast(LinkedListNode head, int k, Index idx) {
if (head == null) {
return null;
}
LinkedListNode node = kthToLast(head.next, k, idx);
idx.value = idx.value + 1;
if (idx.value == k) {
return head;
}
return node;
}
/**
* use two pointers p1 and p2. place them k nodes apart in the linked list
* by putting p2 at the beginning and moving p1 k nodes into the list. then
* when we move them at the same pace, p1 will hit the end of the linked list
* after LENGTH-k steps. at that point p2 will be LENGTH - k nodes into the list,
* or k nodes from the end
*/
static LinkedListNode nthToLast(LinkedListNode head, int k) {
LinkedListNode p1 = head;
LinkedListNode p2 = head;
//move p1 k nodes into the list
for (int i = 0; i < k; i++) {
if (p1 == null) {
return null;
}
p1 = p1.next;
}
//move them at the same pace, when p1 hits the end, p2 will be at the right element
while (p1 != null) {
p1 = p1.next;
p2 = p2.next;
}
return p2;
}
}
|
9241c7bd96255c3ce6f2ce3b24692c932cbdd5ae
| 7,209 |
java
|
Java
|
src/java/org/apache/cassandra/index/sai/memory/RowMapping.java
|
jkzilla/cassandra
|
4078626dddbc8bb620e306e9c12e2c5189db3746
|
[
"Apache-2.0"
] | 1 |
2019-07-24T01:03:40.000Z
|
2019-07-24T01:03:40.000Z
|
src/java/org/apache/cassandra/index/sai/memory/RowMapping.java
|
jkzilla/cassandra
|
4078626dddbc8bb620e306e9c12e2c5189db3746
|
[
"Apache-2.0"
] | null | null | null |
src/java/org/apache/cassandra/index/sai/memory/RowMapping.java
|
jkzilla/cassandra
|
4078626dddbc8bb620e306e9c12e2c5189db3746
|
[
"Apache-2.0"
] | 1 |
2019-07-12T10:40:28.000Z
|
2019-07-12T10:40:28.000Z
| 34.995146 | 126 | 0.625329 | 1,002,033 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.index.sai.memory;
import java.util.Collections;
import java.util.Iterator;
import com.carrotsearch.hppc.IntArrayList;
import org.apache.cassandra.db.Clustering;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.rows.RangeTombstoneMarker;
import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.db.rows.Unfiltered;
import org.apache.cassandra.db.tries.MemtableTrie;
import org.apache.cassandra.db.tries.Trie;
import org.apache.cassandra.index.sai.disk.SegmentBuilder;
import org.apache.cassandra.index.sai.utils.AbstractIterator;
import org.apache.cassandra.index.sai.utils.PrimaryKey;
import org.apache.cassandra.index.sai.utils.PrimaryKeys;
import org.apache.cassandra.io.compress.BufferType;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.bytecomparable.ByteComparable;
import org.apache.cassandra.utils.bytecomparable.ByteSource;
/**
* In memory representation of {@link PrimaryKey} to row ID mappings which only contains
* {@link Row} regardless it's live or deleted. ({@link RangeTombstoneMarker} is not included.)
*
* For JBOD, we can make use of sstable min/max partition key to filter irrelevant {@link MemtableIndex} subranges.
* For Tiered Storage, in most cases, it flushes to tiered 0.
*/
public class RowMapping
{
public static final RowMapping DUMMY = new RowMapping()
{
@Override
public Iterator<Pair<ByteComparable, IntArrayList>> merge(MemtableIndex index) { return Collections.emptyIterator(); }
@Override
public void complete() {}
@Override
public void add(DecoratedKey key, Unfiltered unfiltered, long sstableRowId) {}
};
private final MemtableTrie<Integer> rowMapping = new MemtableTrie<>(BufferType.OFF_HEAP);
private volatile boolean complete = false;
public DecoratedKey minKey;
public DecoratedKey maxKey;
public int maxSegmentRowId = -1;
private RowMapping()
{
}
/**
* Create row mapping for FLUSH operation only.
*/
public static RowMapping create(OperationType opType)
{
if (opType == OperationType.FLUSH)
return new RowMapping();
return DUMMY;
}
/**
* Merge IndexMemtable(index term to PrimaryKeys mappings) with row mapping of a sstable
* (PrimaryKey to RowId mappings).
*
* @param index a Memtable-attached column index
*
* @return iterator of index term to postings mapping exists in the sstable
*/
public Iterator<Pair<ByteComparable, IntArrayList>> merge(MemtableIndex index)
{
assert complete : "RowMapping is not built.";
Iterator<Pair<ByteComparable, PrimaryKeys>> iterator = index.iterator();
return new AbstractIterator<Pair<ByteComparable, IntArrayList>>()
{
@Override
protected Pair<ByteComparable, IntArrayList> computeNext()
{
while (iterator.hasNext())
{
Pair<ByteComparable, PrimaryKeys> pair = iterator.next();
IntArrayList postings = null;
Iterator<PrimaryKey> primaryKeys = pair.right.iterator();
while (primaryKeys.hasNext())
{
PrimaryKey primaryKey = primaryKeys.next();
ByteComparable byteComparable = asComparableBytes(primaryKey.partitionKey(), primaryKey.clustering());
Integer segmentRowId = rowMapping.get(byteComparable);
if (segmentRowId != null)
{
postings = postings == null ? new IntArrayList() : postings;
postings.add(segmentRowId);
}
}
if (postings != null && !postings.isEmpty())
return Pair.create(pair.left, postings);
}
return endOfData();
}
};
}
/**
* Complete building in memory RowMapping, mark it as immutable.
*/
public void complete()
{
assert !complete : "RowMapping can only be built once.";
this.complete = true;
}
/**
* Include PrimaryKey to RowId mapping
*/
public void add(DecoratedKey key, Unfiltered unfiltered, long sstableRowId)
{
assert !complete : "Cannot modify built RowMapping.";
if (unfiltered.isRangeTombstoneMarker())
{
// currently we don't record range tombstones..
}
else
{
assert unfiltered.isRow();
Row row = (Row) unfiltered;
ByteComparable byteComparable = asComparableBytes(key, row.clustering());
int segmentRowId = SegmentBuilder.castToSegmentRowId(sstableRowId, 0);
try
{
rowMapping.apply(Trie.singleton(byteComparable, segmentRowId), (existing, neww) -> neww);
}
catch (MemtableTrie.SpaceExhaustedException e)
{
//TODO Work out how to handle this properly
throw new RuntimeException(e);
}
maxSegmentRowId = Math.max(maxSegmentRowId, segmentRowId);
// data is written in token sorted order
if (minKey == null)
minKey = key;
maxKey = key;
}
}
public boolean hasRows()
{
return maxSegmentRowId >= 0;
}
private ByteComparable asComparableBytes(DecoratedKey key, Clustering clustering)
{
return v -> new ByteSource()
{
ByteSource source = key.asComparableBytes(v);
int index = -1;
@Override
public int next()
{
if (index == clustering.size())
return END_OF_STREAM;
int b = source.next();
if (b > END_OF_STREAM)
return b;
if (++index == clustering.size())
return v == ByteComparable.Version.LEGACY ? ByteSource.END_OF_STREAM : ByteSource.TERMINATOR;
source = ByteSource.of(clustering.accessor(), clustering.get(index), v);
return NEXT_COMPONENT;
}
};
}
}
|
9241c7e4958c5d9029999d0ce485bc729baf2b95
| 5,715 |
java
|
Java
|
library/src/main/java/at/allaboutapps/web/webview/WebViewSettings.java
|
allaboutapps/A3WebView
|
8986636c64aa07f18aacb990f33cdcedca18bfac
|
[
"MIT"
] | 1 |
2017-05-16T10:59:04.000Z
|
2017-05-16T10:59:04.000Z
|
library/src/main/java/at/allaboutapps/web/webview/WebViewSettings.java
|
allaboutapps/A3WebView
|
8986636c64aa07f18aacb990f33cdcedca18bfac
|
[
"MIT"
] | null | null | null |
library/src/main/java/at/allaboutapps/web/webview/WebViewSettings.java
|
allaboutapps/A3WebView
|
8986636c64aa07f18aacb990f33cdcedca18bfac
|
[
"MIT"
] | null | null | null | 30.891892 | 100 | 0.698338 | 1,002,034 |
package at.allaboutapps.web.webview;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import android.webkit.WebView;
/**
* Settings for {@link A3WebView} that define what and how gets loaded, as well as error and loading
* states.
*
* @see A3WebView
*/
@SuppressWarnings("WeakerAccess")
public class WebViewSettings implements Parcelable {
public static final Creator<WebViewSettings> CREATOR =
new Creator<WebViewSettings>() {
@Override
public WebViewSettings createFromParcel(Parcel source) {
return new WebViewSettings(source);
}
@Override
public WebViewSettings[] newArray(int size) {
return new WebViewSettings[size];
}
};
public static final String PATH_TO_ASSETS = "file:///android_asset/";
private static final String MIME_TEXT_HTML = "text/html";
private static final String CHARSET_UTF_8 = "UTF-8";
/*package*/ final WebViewLoadingMethod loadingMethod;
/*package*/ boolean showLoading = true;
/*package*/ boolean javaScriptEnabled = false;
/*package*/ boolean openLinksExternally = false;
/*package*/ int errorLayout = R.layout.a3_webview_error_layout;
private WebViewSettings(@NonNull WebViewLoadingMethod urlLoadingMethod) {
loadingMethod = urlLoadingMethod;
}
protected WebViewSettings(Parcel in) {
this.showLoading = in.readByte() != 0;
this.javaScriptEnabled = in.readByte() != 0;
this.openLinksExternally = in.readByte() != 0;
this.errorLayout = in.readInt();
this.loadingMethod = in.readParcelable(WebViewLoadingMethod.class.getClassLoader());
}
/**
* Load a url into the {@code WebView}.
*
* @param url the url including its http or https prefix.
* @return the settings
*/
public static WebViewSettings loadUrl(String url) {
return new WebViewSettings(new UrlWebViewLoadingMethod(url));
}
/**
* Load a file from assets into the {@code WebView}. If the file is at {@code assets/index.html}
* you would call this method with {@code "index.html"}
*
* @param assetFilePath the file path <i>within</i> the assets folder. A file in {@code
* assets/index.html} would be {@code "index.html"}
* @return the settings
*/
public static WebViewSettings loadAssetFile(String assetFilePath) {
return loadUrl(PATH_TO_ASSETS + assetFilePath);
}
/**
* Display HTML data within the {@code WebView}.
*
* @param data Encoded in UTF-8 of type text/html. If you need different settings please use
* {@link #using(WebViewLoadingMethod)} with a custom {@link DataWebViewLoadingMethod}.
* @return the settings
* @see DataWebViewLoadingMethod
*/
public static WebViewSettings loadData(@NonNull String data) {
return new WebViewSettings(new DataWebViewLoadingMethod(data, MIME_TEXT_HTML, CHARSET_UTF_8));
}
/**
* Display HTML data within the {@code WebView}.
*
* @param data Encoded in UTF-8 of type text/html. If you need different settings please use
* {@link #using(WebViewLoadingMethod)} with a custom {@link DataWebViewLoadingMethod}.
* @param baseUrl the baseUrl to use along with {@link WebView#loadDataWithBaseURL(String, String,
* String, String, String)}
* @return the settings
* @see DataWebViewLoadingMethod
*/
public static WebViewSettings loadData(@NonNull String data, String baseUrl) {
return new WebViewSettings(
new DataWebViewLoadingMethod(data, MIME_TEXT_HTML, CHARSET_UTF_8, baseUrl));
}
/**
* Provide a custom implementation of {@link WebViewLoadingMethod}
*
* @param loadingMethod the loading method you want to use
* @return the settings
* @see WebViewLoadingMethod
*/
public static WebViewSettings using(@NonNull WebViewLoadingMethod loadingMethod) {
return new WebViewSettings(loadingMethod);
}
/**
* Disable the default indeterminate progress view.
*
* @return the settings
*/
public WebViewSettings disableLoadingIndicator() {
showLoading = false;
return this;
}
/**
* Enables javascript.
*
* @return the settings
*/
public WebViewSettings enableJavaScript() {
javaScriptEnabled = true;
return this;
}
/**
* When set, all links clicked will open in the browser. This is useful if you don't want to
* handle outbound links.
*
* @return the settings
*/
public WebViewSettings openLinksExternally() {
openLinksExternally = true;
return this;
}
/**
* Set a custom error layout. The layout must contain a clickable view with {@link
* at.allaboutapps.utilities.R.id#action_reload}
*
* @param layoutResId the layout including a view with id {@link
* at.allaboutapps.utilities.R.id#action_reload}
* @return the settings
*/
public WebViewSettings setErrorLayoutId(@LayoutRes int layoutResId) {
errorLayout = layoutResId;
return this;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeByte(this.showLoading ? (byte) 1 : (byte) 0);
dest.writeByte(this.javaScriptEnabled ? (byte) 1 : (byte) 0);
dest.writeByte(this.openLinksExternally ? (byte) 1 : (byte) 0);
dest.writeInt(this.errorLayout);
dest.writeParcelable(this.loadingMethod, flags);
}
/**
* Handler interface for the content loading.
*
* @see DataWebViewLoadingMethod
*/
public interface WebViewLoadingMethod extends Parcelable {
/**
* Load the content into the {@code webView}
*
* @param webView the loading target
*/
void startLoading(WebView webView);
}
}
|
9241c85d5a817a9407976e945cc492fe9a3037c8
| 3,881 |
java
|
Java
|
src/main/java/link/infra/funkyforcefields/transport/FluidContainerComponentImpl.java
|
comp500/FunkyForcefields
|
5f2f76ebaad511a1cd20493faf1738f4e355e0a7
|
[
"MIT"
] | null | null | null |
src/main/java/link/infra/funkyforcefields/transport/FluidContainerComponentImpl.java
|
comp500/FunkyForcefields
|
5f2f76ebaad511a1cd20493faf1738f4e355e0a7
|
[
"MIT"
] | null | null | null |
src/main/java/link/infra/funkyforcefields/transport/FluidContainerComponentImpl.java
|
comp500/FunkyForcefields
|
5f2f76ebaad511a1cd20493faf1738f4e355e0a7
|
[
"MIT"
] | 1 |
2021-10-04T13:19:36.000Z
|
2021-10-04T13:19:36.000Z
| 31.048 | 123 | 0.746199 | 1,002,035 |
package link.infra.funkyforcefields.transport;
import link.infra.funkyforcefields.regions.ForcefieldFluid;
import net.minecraft.nbt.CompoundTag;
import java.util.Objects;
public class FluidContainerComponentImpl implements FluidContainerComponent {
final float containerVolume;
float pressure = TransportUtilities.NOMINAL_PRESSURE;
final float thermalDiffusivity;
float temperature = TransportUtilities.NOMINAL_TEMPERATURE;
ForcefieldFluid containedFluid;
public FluidContainerComponentImpl(float containerVolume, float thermalDiffusivity) {
this.containerVolume = containerVolume;
this.thermalDiffusivity = thermalDiffusivity;
}
@Override
public float getContainerVolume() {
return containerVolume;
}
@Override
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
@Override
public float getThermalDiffusivity() {
return thermalDiffusivity;
}
@Override
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
@Override
public ForcefieldFluid getContainedFluid() {
return containedFluid;
}
public void setContainedFluid(ForcefieldFluid containedFluid) {
this.containedFluid = containedFluid;
}
@Override
public void fromTag(CompoundTag compoundTag) {
pressure = compoundTag.getFloat("pressure");
temperature = compoundTag.getFloat("temperature");
if (compoundTag.getInt("containedFluid") != -1) {
containedFluid = ForcefieldFluid.REGISTRY.get(compoundTag.getInt("containedFluid"));
}
}
@Override
public CompoundTag toTag(CompoundTag compoundTag) {
compoundTag.putFloat("pressure", pressure);
compoundTag.putFloat("temperature", temperature);
if (containedFluid != null) {
compoundTag.putInt("containedFluid", ForcefieldFluid.REGISTRY.getRawId(containedFluid));
} else {
compoundTag.putInt("containedFluid", -1);
}
return compoundTag;
}
public void tick(FluidContainerComponent... neighbors) {
if (containedFluid == null) {
FluidContainerComponent biggestNeighbor = null;
for (FluidContainerComponent neighbor : neighbors) {
if (neighbor.getContainedFluid() != null) {
if (biggestNeighbor == null) {
biggestNeighbor = neighbor;
} else if (neighbor.getPressure() > biggestNeighbor.getPressure()) {
biggestNeighbor = neighbor;
}
}
}
if (biggestNeighbor != null && biggestNeighbor.getPressure() > pressure) {
containedFluid = biggestNeighbor.getContainedFluid();
}
}
float[] neighborValues = new float[neighbors.length];
for (int i = 0; i < neighbors.length; i++) {
neighborValues[i] = neighbors[i].getPressure();
}
pressure = TransportUtilities.tickPressure(containerVolume, pressure, neighborValues);
for (int i = 0; i < neighbors.length; i++) {
neighborValues[i] = neighbors[i].getTemperature();
}
temperature = TransportUtilities.tickTemperature(thermalDiffusivity, temperature, neighborValues);
if (Math.abs(pressure - TransportUtilities.NOMINAL_PRESSURE) <= TransportUtilities.NEGLIGIBILITY) {
containedFluid = null;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FluidContainerComponentImpl that = (FluidContainerComponentImpl) o;
return Float.compare(that.getContainerVolume(), getContainerVolume()) == 0 &&
Float.compare(that.getPressure(), getPressure()) == 0 &&
Float.compare(that.getThermalDiffusivity(), getThermalDiffusivity()) == 0 &&
Float.compare(that.getTemperature(), getTemperature()) == 0 &&
Objects.equals(getContainedFluid(), that.getContainedFluid());
}
@Override
public int hashCode() {
return Objects.hash(getContainerVolume(), getPressure(), getThermalDiffusivity(), getTemperature(), getContainedFluid());
}
}
|
9241c9f5c0d3d767c0e96acb1f2f75a7df3365b5
| 1,662 |
java
|
Java
|
src/main/java/com/techmisal/medium/NumberOfIslands.java
|
arvydasdev/leetcode-solutions
|
b73e28a508246d2cab6c8b52126bc62ef832a120
|
[
"MIT"
] | 3 |
2019-02-16T10:49:56.000Z
|
2019-09-11T19:33:54.000Z
|
src/main/java/com/techmisal/medium/NumberOfIslands.java
|
arvydasdev/leetcode-solutions
|
b73e28a508246d2cab6c8b52126bc62ef832a120
|
[
"MIT"
] | null | null | null |
src/main/java/com/techmisal/medium/NumberOfIslands.java
|
arvydasdev/leetcode-solutions
|
b73e28a508246d2cab6c8b52126bc62ef832a120
|
[
"MIT"
] | null | null | null | 25.96875 | 62 | 0.531288 | 1,002,036 |
package com.techmisal.medium;
import java.util.Arrays;
public class NumberOfIslands {
private static char isLand = '1';
private static int size = 1000;
private Boolean[][] islandsMemo = new Boolean[size][size];
private int xRange;
private int yRange;
public NumberOfIslands() {
for(int x=0;x<size;x++) {
Arrays.fill(islandsMemo[x], true);
}
}
private void initSolution(char[][] grid) {
xRange = grid.length;
if(xRange == 0) return;
yRange = grid[0].length;
}
public Boolean isIsland(char a) {
return a == isLand;
}
private void flood(int x, int y, char[][] grid) {
Boolean isOutOfXBound = ( x < 0 ) || (x >= xRange);
Boolean isOutOfYBound = ( y < 0 ) || (y >= yRange);
if(isOutOfXBound || isOutOfYBound) return;
Boolean isWater = !isIsland(grid[x][y]);
Boolean isFoundBefore = !islandsMemo[x][y];
if(isWater || isFoundBefore) return;
islandsMemo[x][y] = false;
this.flood(x,y+1, grid);
this.flood(x,y-1, grid);
this.flood(x+1,y, grid);
this.flood(x-1,y, grid);
}
public int numIslands(char[][] grid) {
initSolution(grid);
int result = 0;
for(int x=0;x<grid.length;x++)
for(int y=0;y<grid[x].length;y++) {
char currentPosition = grid[x][y];
Boolean isNewIsland = islandsMemo[x][y];
if(isIsland(currentPosition) && isNewIsland) {
result++;
flood(x, y, grid);
}
}
return result;
}
}
|
9241caaba83052a1a795492db545001662608034
| 5,860 |
java
|
Java
|
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/FixingTimeSeriesVisitor.java
|
Incapture/OG-Platform
|
76be42671e692483125582d6dce1245b81de03a1
|
[
"Apache-2.0"
] | null | null | null |
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/FixingTimeSeriesVisitor.java
|
Incapture/OG-Platform
|
76be42671e692483125582d6dce1245b81de03a1
|
[
"Apache-2.0"
] | null | null | null |
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/conversion/FixingTimeSeriesVisitor.java
|
Incapture/OG-Platform
|
76be42671e692483125582d6dce1245b81de03a1
|
[
"Apache-2.0"
] | null | null | null | 58.019802 | 185 | 0.82116 | 1,002,037 |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.conversion;
import javax.time.calendar.LocalDate;
import javax.time.calendar.LocalTime;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.value.MarketDataRequirementNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType;
import com.opengamma.financial.analytics.timeseries.DateConstraint;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils;
import com.opengamma.financial.convention.ConventionBundle;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.security.FinancialSecurityVisitorAdapter;
import com.opengamma.financial.security.swap.FixedInterestRateLeg;
import com.opengamma.financial.security.swap.FloatingInterestRateLeg;
import com.opengamma.financial.security.swap.FloatingRateType;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver;
import com.opengamma.util.timeseries.DoubleTimeSeries;
import com.opengamma.util.timeseries.FastBackedDoubleTimeSeries;
import com.opengamma.util.timeseries.fast.DateTimeNumericEncoding;
import com.opengamma.util.timeseries.fast.longint.FastLongDoubleTimeSeries;
import com.opengamma.util.timeseries.zoneddatetime.ArrayZonedDateTimeDoubleTimeSeries;
import com.opengamma.util.timeseries.zoneddatetime.ZonedDateTimeEpochMillisConverter;
/**
* Produces a value requirement that will query the fixing time series for a security.
*/
public class FixingTimeSeriesVisitor extends FinancialSecurityVisitorAdapter<ValueRequirement> { //CSIGNORE
//TODO a lot of this code is repeated in FixedIncomeConverterDataProvider - that class should use this one
private final ConventionBundleSource _conventionSource;
private final HistoricalTimeSeriesResolver _resolver;
private final DateConstraint _now;
public FixingTimeSeriesVisitor(final ConventionBundleSource conventionSource, final HistoricalTimeSeriesResolver resolver, final DateConstraint now) {
_conventionSource = conventionSource;
_resolver = resolver;
_now = now;
}
@Override
public ValueRequirement visitSwapSecurity(final SwapSecurity security) {
final InterestRateInstrumentType type = InterestRateInstrumentType.getInstrumentTypeFromSecurity(security);
if (type != InterestRateInstrumentType.SWAP_FIXED_IBOR &&
type != InterestRateInstrumentType.SWAP_FIXED_OIS &&
type != InterestRateInstrumentType.SWAP_FIXED_IBOR_WITH_SPREAD) {
throw new OpenGammaRuntimeException("Can only get series for fixed / float swaps; have " + type);
}
final FloatingInterestRateLeg floatingLeg = (FloatingInterestRateLeg) (security.getPayLeg() instanceof FixedInterestRateLeg ? security.getReceiveLeg() : security.getPayLeg());
final ZonedDateTime swapStartDate = security.getEffectiveDate();
return getIndexTimeSeries(floatingLeg, swapStartDate, _now, true, _resolver);
}
private ValueRequirement getIndexTimeSeries(final FloatingInterestRateLeg leg, final ZonedDateTime swapEffectiveDate, final DateConstraint now,
final boolean includeEndDate, final HistoricalTimeSeriesResolver resolver) {
final FloatingInterestRateLeg floatingLeg = leg;
final ExternalIdBundle id = getIndexIdForSwap(floatingLeg);
final LocalDate startDate = swapEffectiveDate.toLocalDate().minusDays(30); // To catch first fixing. SwapSecurity does not have this date.
final HistoricalTimeSeriesResolutionResult ts = resolver.resolve(id, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get time series of underlying index " + id.getExternalIds().toString() + " bundle used was " + id);
}
return HistoricalTimeSeriesFunctionUtils.createHTSRequirement(ts, MarketDataRequirementNames.MARKET_VALUE, DateConstraint.of(startDate), true, now, includeEndDate);
}
public static DoubleTimeSeries<ZonedDateTime> convertTimeSeries(final HistoricalTimeSeries ts, final ZonedDateTime now) {
final FastBackedDoubleTimeSeries<LocalDate> localDateTS = ts.getTimeSeries();
final FastLongDoubleTimeSeries convertedTS = localDateTS.toFastLongDoubleTimeSeries(DateTimeNumericEncoding.TIME_EPOCH_MILLIS);
final LocalTime fixingTime = LocalTime.of(0, 0); // FIXME CASE Converting a daily historical time series to an arbitrary time. Bad idea
return new ArrayZonedDateTimeDoubleTimeSeries(new ZonedDateTimeEpochMillisConverter(now.getZone(), fixingTime), convertedTS);
}
private ExternalIdBundle getIndexIdForSwap(final FloatingInterestRateLeg floatingLeg) {
if (floatingLeg.getFloatingRateType().isIbor() || floatingLeg.getFloatingRateType().equals(FloatingRateType.OIS) || floatingLeg.getFloatingRateType().equals(FloatingRateType.CMS)) {
return getIndexIdBundle(floatingLeg.getFloatingReferenceRateId());
}
return ExternalIdBundle.of(floatingLeg.getFloatingReferenceRateId());
}
private ExternalIdBundle getIndexIdBundle(final ExternalId indexId) {
final ConventionBundle indexConvention = _conventionSource.getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
return indexConvention.getIdentifiers();
}
}
|
9241cc537ae38c444ae76c30a3d33c9b089ec5c6
| 13,613 |
java
|
Java
|
aura-impl/src/main/java/org/auraframework/impl/system/BundleAwareDefRegistry.java
|
augustyakaravat/aura
|
98d7ba491172c7ea44cbbf74be5eb858040c9c46
|
[
"Apache-2.0"
] | 587 |
2015-01-01T00:42:17.000Z
|
2022-01-23T00:14:13.000Z
|
aura-impl/src/main/java/org/auraframework/impl/system/BundleAwareDefRegistry.java
|
augustyakaravat/aura
|
98d7ba491172c7ea44cbbf74be5eb858040c9c46
|
[
"Apache-2.0"
] | 156 |
2015-02-06T17:56:21.000Z
|
2019-02-27T05:19:11.000Z
|
aura-impl/src/main/java/org/auraframework/impl/system/BundleAwareDefRegistry.java
|
augustyakaravat/aura
|
98d7ba491172c7ea44cbbf74be5eb858040c9c46
|
[
"Apache-2.0"
] | 340 |
2015-01-13T14:13:38.000Z
|
2022-03-21T04:05:29.000Z
| 37.501377 | 151 | 0.621097 | 1,002,038 |
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.system;
import java.util.EnumSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.auraframework.def.BundleDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.Definition;
import org.auraframework.def.DescriptorFilter;
import org.auraframework.def.PlatformDef;
import org.auraframework.service.CompilerService;
import org.auraframework.system.BundleSource;
import org.auraframework.system.BundleSourceLoader;
import org.auraframework.system.BundleSourceOption;
import org.auraframework.system.CompileOptions;
import org.auraframework.system.DefRegistry;
import org.auraframework.system.Source;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.text.GlobMatcher;
/**
* A bundle aware registry.
*
* This registry is used in the case that we are loading bundles from a source. I.e. anytime we want to load
* XML files. This is needed because we need to compile the entire bundle together, e.g. if you request a controller
* it needs to find the top level (application or compoenent) and compile that, then drill in to find the controller.
* This is especially important for things like 'find' which need to do lots of extra work to find the proper
* items.
*/
public class BundleAwareDefRegistry implements DefRegistry {
private static final long serialVersionUID = -4852130888436267039L;
private final BundleSourceLoader sourceLoader;
private final Set<DefType> defTypes;
private final Set<String> prefixes;
private final boolean constantNamespaces;
private final Set<String> namespaces;
private final Map<String, DefHolder> registry;
private final CompilerService compilerService;
private final boolean cacheable;
private String name;
private final long creationTime;
private static class DefHolder {
public DefHolder(DefDescriptor<BundleDef> descriptor) {
this.descriptor = descriptor;
}
public final DefDescriptor<BundleDef> descriptor;
public BundleDef def;
public QuickFixException qfe;
public BundleSource<BundleDef> source;
public boolean initialized;
}
public BundleAwareDefRegistry(BundleSourceLoader sourceLoader, Set<String> prefixes, Set<DefType> defTypes,
CompilerService compilerService, boolean cacheable) {
this(sourceLoader, prefixes, defTypes, null, compilerService, cacheable);
}
public BundleAwareDefRegistry(BundleSourceLoader sourceLoader, Set<String> prefixes, Set<DefType> defTypes,
Collection<String> namespaces, CompilerService compilerService,
boolean cacheable) {
this.sourceLoader = sourceLoader;
this.registry = new HashMap<>();
this.prefixes = new HashSet<>();
this.creationTime = System.currentTimeMillis();
for (String prefix : prefixes) {
this.prefixes.add(prefix.toLowerCase());
}
this.defTypes = defTypes;
this.compilerService = compilerService;
if (namespaces == null) {
this.namespaces = new HashSet<>();
this.constantNamespaces = false;
} else {
this.namespaces = new HashSet<>(namespaces);
this.constantNamespaces = true;
}
this.cacheable = cacheable;
reset();
}
/**
* Reset the registry.
*
* This routine is really only important for file based registries that are being used at runtime.
* It allows us to notice changes even in the case where we go and update the filesystem.
*/
@Override
public synchronized void reset() {
sourceLoader.reset();
if (!constantNamespaces) {
namespaces.clear();
namespaces.addAll(sourceLoader.getNamespaces());
}
registry.clear();
if (!constantNamespaces || this.name == null) {
this.name = getClass().getSimpleName()+defTypes+prefixes+namespaces;
}
if (cacheable) {
Set<DefDescriptor<?>> descriptors = sourceLoader.find(new DescriptorFilter("*://*:*"));
//
// Initialize our map to hold all bundles.
//
for (DefDescriptor<?> descriptor : descriptors) {
@SuppressWarnings("unchecked")
DefDescriptor<BundleDef> rootDescriptor = (DefDescriptor<BundleDef>)descriptor;
String key = descriptor.getDescriptorName().toLowerCase();
registry.put(key, new DefHolder(rootDescriptor));
}
}
}
private DefHolder getHolder(DefDescriptor<?> descriptor) {
if (cacheable) {
synchronized (this) {
return registry.get(BundleSourceLoader.getBundleName(descriptor));
}
} else {
@SuppressWarnings("unchecked")
BundleSource<BundleDef> source = (BundleSource<BundleDef>)sourceLoader.getBundle(descriptor);
if (source == null) {
return null;
}
DefHolder holder = new DefHolder(source.getDescriptor());
holder.source = source;
return holder;
}
}
private BundleSource<BundleDef> getSource(DefHolder holder) {
if (holder == null) {
return null;
}
if (holder.source != null) {
return holder.source;
} else {
return (BundleSource<BundleDef>)sourceLoader.getSource(holder.descriptor);
}
}
private <T extends Definition> T getDefWithHolder(DefDescriptor<T> descriptor, DefHolder holder) throws QuickFixException {
if (holder == null) {
return null;
}
synchronized (holder) {
if (!holder.initialized) {
try {
DefDescriptor<BundleDef> canonical = holder.descriptor;
BundleSource<BundleDef> source = getSource(holder);
// check if compilation should be invoked with namespace aliasing
HashMap<String, String> namespaceMapping = null;
String namespace = source.getDescriptor().getNamespace();
if (namespace != null && !namespace.equals("c")) {
namespaceMapping = Maps.newHashMap(ImmutableMap.of("c", namespace));
}
CompileOptions compileOptions = new CompileOptions(EnumSet.noneOf(BundleSourceOption.class), namespaceMapping);
holder.def = compilerService.compile(canonical, source, compileOptions);
} catch (QuickFixException qfe) {
holder.qfe = qfe;
}
holder.initialized = true;
}
}
if (holder.qfe != null) {
throw holder.qfe;
}
if (holder.descriptor.equals(descriptor)) {
@SuppressWarnings("unchecked")
T def = (T)holder.def;
return def;
}
return holder.def.getBundledDefinition(descriptor);
}
@Override
public <T extends Definition> T getDef(DefDescriptor<T> descriptor) throws QuickFixException {
return getDefWithHolder(descriptor, getHolder(descriptor));
}
@Override
public boolean hasFind() {
return true;
}
private void addBundleSubDefinitions(DefDescriptor<?> bundleDesc, DescriptorFilter matcher,
Set<DefDescriptor<?>> matches) {
BundleSource<?> bundleSource = (BundleSource<?>)sourceLoader.getSource(bundleDesc);
for (DefDescriptor<?> subDescriptor : bundleSource.getBundledParts().keySet()) {
if (matcher.matchDescriptor(subDescriptor)) {
matches.add(subDescriptor);
}
}
}
@Override
public Set<DefDescriptor<?>> find(DescriptorFilter matcher) {
Set<DefDescriptor<?>> matches = new HashSet<>();
boolean nonBundle = true;
if (matcher.getDefTypes() != null) {
Set<DefType> tmp = new HashSet<>(matcher.getDefTypes());
tmp.removeAll(BundleSource.bundleDefTypes);
nonBundle = (tmp.size() > 0);
}
if (cacheable) {
for (DefHolder holder : registry.values()) {
if (matcher.matchDescriptor(holder.descriptor)) {
matches.add(holder.descriptor);
}
if (nonBundle && matcher.matchNamespace(holder.descriptor.getNamespace())
&& matcher.matchName(holder.descriptor.getName())) {
addBundleSubDefinitions(holder.descriptor, matcher, matches);
}
}
} else if (!nonBundle) {
return sourceLoader.find(matcher);
} else {
//
// This is really ugly.
//
DescriptorFilter bundleMatcher = new DescriptorFilter(new GlobMatcher(DefDescriptor.MARKUP_PREFIX),
matcher.getNamespaceMatch(), matcher.getNameMatch(), BundleSource.bundleDefTypes);
Set<DefDescriptor<?>> bundles = sourceLoader.find(bundleMatcher);
for (DefDescriptor<?> bundleDesc : bundles) {
if (matcher.matchDescriptor(bundleDesc)) {
matches.add(bundleDesc);
}
addBundleSubDefinitions(bundleDesc, matcher, matches);
}
}
return matches;
}
@Override
public Set<DefDescriptor<?>> findByTags(@Nonnull Set<String> tags) {
Collection<DefHolder> defHolders;
if(cacheable) {
defHolders = registry.values();
} else {
defHolders = Lists.newArrayList();
Set<DefDescriptor<?>> descriptors = sourceLoader.find(new DescriptorFilter("*://*:*", Sets.newHashSet(DefType.COMPONENT, DefType.MODULE)));
if(descriptors != null) {
descriptors.stream().forEach(descriptor -> {
@SuppressWarnings("unchecked")
DefDescriptor<BundleDef> rootDescriptor = (DefDescriptor<BundleDef>) descriptor;
defHolders.add(new DefHolder(rootDescriptor));
});
}
}
defHolders.stream().forEach(h -> { try { getDefWithHolder(h.descriptor, h); } catch (QuickFixException qfe) {}});
return defHolders.stream().filter(h ->
h.def != null
&& h.def instanceof PlatformDef
&& !Collections.disjoint(((PlatformDef)h.def).getTargets(), tags))
.map(h -> h.descriptor).collect(Collectors.toSet());
}
@Override
public <T extends Definition> boolean exists(DefDescriptor<T> descriptor) {
return getSource(descriptor) != null;
}
@Override
public Set<DefType> getDefTypes() {
return defTypes;
}
@Override
public Set<String> getPrefixes() {
return prefixes;
}
@Override
public Set<String> getNamespaces() {
return namespaces;
}
@Override
public long getCreationTime() {
return creationTime;
}
@Override
public <T extends Definition> Source<T> getSource(DefDescriptor<T> descriptor) {
DefHolder holder = getHolder(descriptor);
BundleSource<?> bundleSource = getSource(holder);
if (bundleSource == null) {
return null;
}
if (holder.descriptor.equals(descriptor)) {
@SuppressWarnings("unchecked")
Source<T> source = (Source<T>)bundleSource;
return source;
} else {
if (descriptor.getPrefix().equals(DefDescriptor.TEMPLATE_CSS_PREFIX)
&& holder.descriptor.getDefType() == DefType.COMPONENT) {
//
// This is horrific.
//
@SuppressWarnings("unchecked")
Class<T> defClass = (Class<T>)descriptor.getDefType().getPrimaryInterface();
descriptor = new DefDescriptorImpl<>(DefDescriptor.CSS_PREFIX, descriptor.getNamespace(),
descriptor.getName(), defClass);
}
@SuppressWarnings("unchecked")
Source<T> source = (Source<T>)bundleSource.getBundledParts().get(descriptor);
return source;
}
}
@Override
public boolean isCacheable() {
return cacheable;
}
@Override
public boolean isStatic() {
return true;
}
@Override
public String toString() {
return name;
}
}
|
9241cc6e77cace0b9840c1abd210562191b4bd4b
| 2,710 |
java
|
Java
|
src/main/java/br/com/zup/academy/tania/casadocodigo/fluxopagto/Cliente.java
|
tania202162/orange-talents-06-template-casa-do-codigo
|
0fb0a87a96d34f6dc372ebc8f2972bf965f647af
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/br/com/zup/academy/tania/casadocodigo/fluxopagto/Cliente.java
|
tania202162/orange-talents-06-template-casa-do-codigo
|
0fb0a87a96d34f6dc372ebc8f2972bf965f647af
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/br/com/zup/academy/tania/casadocodigo/fluxopagto/Cliente.java
|
tania202162/orange-talents-06-template-casa-do-codigo
|
0fb0a87a96d34f6dc372ebc8f2972bf965f647af
|
[
"Apache-2.0"
] | null | null | null | 19.357143 | 92 | 0.699631 | 1,002,039 |
package br.com.zup.academy.tania.casadocodigo.fluxopagto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
@Entity
public class Cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
@NotBlank
@Email
private String email;
@NotBlank
@Column(nullable = false)
private String nome;
@Column(nullable = false)
@NotBlank
private String sobrenome;
@Column(nullable = false)
@NotBlank
private String documento; // cpf/cnpj
@Column(nullable = false)
@NotBlank
private String endereco;
@Column(nullable = false)
@NotBlank
private String complemento;
@Column(nullable = false)
@NotBlank
private String cidade;
@Column(nullable = false)
@NotBlank
private String pais;
private String estado;
@Column(nullable = false)
@NotBlank
private String telefone;
@Column(nullable = false)
@NotBlank
private String cep;
public Cliente(@NotBlank String email, @NotBlank String nome, @NotBlank String sobrenome,
@NotBlank String documento, @NotBlank String endereco, @NotBlank String complemento,
@NotBlank String cidade, @NotBlank String pais, String estado, @NotBlank String telefone,
@NotBlank String cep) {
this.email = email;
this.nome = nome;
this.sobrenome = sobrenome;
this.documento = documento;
this.endereco = endereco;
this.complemento = complemento;
this.cidade = cidade;
this.pais = pais;
this.estado = estado;
this.telefone = telefone;
this.cep = cep;
}
public String getEmail() {
return email;
}
public String getNome() {
return nome;
}
public String getSobrenome() {
return sobrenome;
}
public String getDocumento() {
return documento;
}
public String getEndereco() {
return endereco;
}
public String getComplemento() {
return complemento;
}
public String getCidade() {
return cidade;
}
public String getPais() {
return pais;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getTelefone() {
return telefone;
}
public String getCep() {
return cep;
}
@Override
public String toString() {
return "Cliente: [id= " + id + "]";
/*
* ",email=" + email + ", nome=" + nome + ", sobrenome=" + sobrenome +
* ", documento=" + documento + ",endereco=" + endereco + ",complemento=" +
* complemento + ", cidade=" + cidade + ",pais=" + pais + ", estado=" + estado +
* ", telefone=" + telefone + ", cep=" + cep +
*/
}
}
|
9241cc9ffa2594c826814889294a59760baff444
| 9,702 |
java
|
Java
|
proctor-common/src/main/java/com/indeed/proctor/common/model/TestDefinition.java
|
truthiswill/proctor
|
670b0bba563d72943f0e5eba4eacf7595d461e57
|
[
"Apache-2.0"
] | null | null | null |
proctor-common/src/main/java/com/indeed/proctor/common/model/TestDefinition.java
|
truthiswill/proctor
|
670b0bba563d72943f0e5eba4eacf7595d461e57
|
[
"Apache-2.0"
] | 3 |
2020-05-15T21:40:55.000Z
|
2021-12-09T21:29:30.000Z
|
proctor-common/src/main/java/com/indeed/proctor/common/model/TestDefinition.java
|
whitemike889/proctor
|
670b0bba563d72943f0e5eba4eacf7595d461e57
|
[
"Apache-2.0"
] | null | null | null | 30.898089 | 142 | 0.599052 | 1,002,040 |
package com.indeed.proctor.common.model;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Models a single test
* @author ketan
*/
public class TestDefinition {
private String version;
@Nonnull
private Map<String, Object> constants = Collections.emptyMap();
@Nonnull
private Map<String, Object> specialConstants = Collections.emptyMap();
@Nonnull
private String salt;
@Nullable
private String rule;
@Nonnull
private List<TestBucket> buckets = Collections.emptyList();
// there are multiple ways to allocate the buckets based on rules, but most tests will probably just have one Allocation
@Nonnull
private List<Allocation> allocations = Collections.emptyList();
private boolean silent;
/**
* For advisory purposes only
*/
@Nonnull
private TestType testType;
@Nullable
private String description;
public TestDefinition() { /* intentionally empty */ }
@Deprecated
public TestDefinition(
final String version,
@Nullable final String rule,
@Nonnull final TestType testType,
@Nonnull final String salt,
@Nonnull final List<TestBucket> buckets,
@Nonnull final List<Allocation> allocations,
@Nonnull final Map<String, Object> constants,
@Nonnull final Map<String, Object> specialConstants,
@Nullable final String description
) {
this(version,
rule,
testType,
salt,
buckets,
allocations,
false,
constants,
specialConstants,
description);
}
public TestDefinition(
final String version,
@Nullable final String rule,
@Nonnull final TestType testType,
@Nonnull final String salt,
@Nonnull final List<TestBucket> buckets,
@Nonnull final List<Allocation> allocations,
final boolean silent,
@Nonnull final Map<String, Object> constants,
@Nonnull final Map<String, Object> specialConstants,
@Nullable final String description
) {
this.version = version;
this.constants = constants;
this.specialConstants = specialConstants;
this.salt = salt;
this.rule = rule;
this.buckets = buckets;
this.allocations = allocations;
this.silent = silent;
this.testType = testType;
this.description = description;
}
public TestDefinition(@Nonnull final TestDefinition other) {
this.version = other.version;
this.salt = other.salt;
this.rule = other.rule;
this.silent = other.silent;
this.description = other.description;
if (other.constants != null) {
this.constants = Maps.newHashMap(other.constants);
}
if (other.specialConstants != null) {
this.specialConstants = Maps.newHashMap(other.specialConstants);
}
if (other.buckets != null) {
this.buckets = new ArrayList<TestBucket>();
for (final TestBucket bucket : other.buckets) {
this.buckets.add(new TestBucket(bucket));
}
}
if (other.allocations != null) {
this.allocations = new ArrayList<Allocation>();
for (final Allocation allocation : other.allocations) {
this.allocations.add(new Allocation(allocation));
}
}
this.testType = other.testType;
}
public String getVersion() {
return version;
}
public void setVersion(final String version) {
this.version = version;
}
@Nonnull
public Map<String, Object> getConstants() {
return constants;
}
@SuppressWarnings("UnusedDeclaration")
public void setConstants(@Nonnull final Map<String, Object> constants) {
this.constants = constants;
}
@Nonnull
public Map<String, Object> getSpecialConstants() {
return specialConstants;
}
@SuppressWarnings("UnusedDeclaration")
public void setSpecialConstants(@Nonnull final Map<String, Object> specialConstants) {
this.specialConstants = specialConstants;
}
@Nullable
public String getRule() {
return rule;
}
@SuppressWarnings("UnusedDeclaration")
@Deprecated()
/**
* Provided only for backwards-compatibility when parsing JSON data that still uses 'subrule'
*/
public void setSubrule(@Nullable final String subrule) {
setRule(subrule);
}
@SuppressWarnings("UnusedDeclaration")
public void setRule(@Nullable final String rule) {
this.rule = rule;
}
@Nonnull
public String getSalt() {
return salt;
}
@SuppressWarnings("UnusedDeclaration")
public void setSalt(@Nonnull final String salt) {
this.salt = salt;
}
@Nonnull
public List<TestBucket> getBuckets() {
return buckets;
}
@SuppressWarnings("UnusedDeclaration")
public void setBuckets(@Nonnull final List<TestBucket> buckets) {
this.buckets = buckets;
}
@Nonnull
public List<Allocation> getAllocations() {
return allocations;
}
@SuppressWarnings("UnusedDeclaration")
public void setAllocations(@Nonnull final List<Allocation> allocations) {
this.allocations = allocations;
}
public void setSilent(final boolean silent) {
this.silent = silent;
}
public boolean getSilent() {
return silent;
}
@Nonnull
public TestType getTestType() {
return testType;
}
@SuppressWarnings("UnusedDeclaration")
public void setTestType(final TestType testType) {
this.testType = testType;
}
public void setDescription(final String description) {
this.description = description;
}
@Nullable
public String getDescription() {
return description;
}
@Override
public String toString() {
return "TestDefinition{" +
"version='" + version + '\'' +
", constants=" + constants +
", specialConstants=" + specialConstants +
", salt='" + salt + '\'' +
", rule='" + rule + '\'' +
", buckets=" + buckets +
", allocations=" + allocations +
", silent=" + silent +
", testType=" + testType +
", description='" + description + '\'' +
'}';
}
@Override
public int hashCode() {
// because TestBuckets.hashCode() only considers name for unknown reasons, need to use testBuckets.fullHashCode()
final List<Object> bucketWrappers = new ArrayList<>();
if (buckets != null) {
for (final TestBucket bucket: buckets) {
bucketWrappers.add(new Object() {
@Override
public int hashCode() {
return bucket.fullHashCode();
}
});
}
}
return Objects.hashCode(version, constants, specialConstants, salt, rule, bucketWrappers, allocations, silent, testType, description);
}
/**
* similar to generated equals() method, but special treatment of buckets,
* because testBucket has unconventional equals/hashcode implementation for undocumented reason.
*
* Difference is checked by Unit test.
*/
@Override
public boolean equals(final Object otherDefinition) {
if (this == otherDefinition) {
return true;
}
if (otherDefinition == null || getClass() != otherDefinition.getClass()) {
return false;
}
final TestDefinition that = (TestDefinition) otherDefinition;
return silent == that.silent &&
Objects.equal(version, that.version) &&
Objects.equal(constants, that.constants) &&
Objects.equal(specialConstants, that.specialConstants) &&
Objects.equal(salt, that.salt) &&
Objects.equal(rule, that.rule) &&
bucketListEqual(buckets, that.buckets) && // difference here
Objects.equal(allocations, that.allocations) &&
Objects.equal(testType, that.testType) &&
Objects.equal(description, that.description);
}
@VisibleForTesting
static boolean bucketListEqual(final List<TestBucket> bucketsA, final List<TestBucket> bucketsB) {
if (bucketsA == bucketsB) {
return true;
}
// TestBucket Equal returns true too often, but false means false. This also handles single-sided null cases and different list size.
if (!Objects.equal(bucketsA, bucketsB)) {
return false;
}
final Iterator<TestBucket> itA = bucketsA.iterator();
final Iterator<TestBucket> itB = bucketsB.iterator();
while (itA.hasNext() && itB.hasNext()) {
final TestBucket bucketA = itA.next();
final TestBucket bucketB = itB.next();
if ((bucketA != null) && !bucketA.fullEquals(bucketB)) {
return false;
}
}
return true;
}
}
|
9241ccc985774d793f49cef4a525c8444b89d5cc
| 4,505 |
java
|
Java
|
src/org/springframework/beans/BeanWrapper.java
|
pleuvoir/spring-framework-1.2.9
|
ad1ee7062dcbb2554e64a8f98262d9b0dea7def4
|
[
"Apache-2.0"
] | null | null | null |
src/org/springframework/beans/BeanWrapper.java
|
pleuvoir/spring-framework-1.2.9
|
ad1ee7062dcbb2554e64a8f98262d9b0dea7def4
|
[
"Apache-2.0"
] | null | null | null |
src/org/springframework/beans/BeanWrapper.java
|
pleuvoir/spring-framework-1.2.9
|
ad1ee7062dcbb2554e64a8f98262d9b0dea7def4
|
[
"Apache-2.0"
] | null | null | null | 33.87218 | 85 | 0.74606 | 1,002,041 |
/*
* Copyright 2002-2007 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.beans;
import java.beans.PropertyDescriptor;
/**
* Spring的低级JavaBeans基础设施的中央接口。
* 扩展@link propertyaccessor和@link propertyeditorregistry接口。
*
* <p>通常不直接使用,而是通过
* {@link org.springframework.beans.factory.BeanFactory} or a
* {@link org.springframework.validation.DataBinder}.
*
* <p>提供分析和操作标准JavaBeans的操作:
* 获取和设置属性值(单独或批量)的能力,
* 获取属性描述符,并查询属性的可读性/可写性.
*
* <p>此接口支持启用设置子属性的属性的深度不受限制
* A <code>BeanWrapper</code> 可以重复使用, with its
* {@link #setWrappedInstance(Object) target object} (包装的javaBean实例)根据需要更改
*
* <p>可以重复使用beanwrapper实例及其目标对象, (封装的JavaBean实例)更改
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 13 April 2001
* @see PropertyAccessor
* @see PropertyEditorRegistry
* @see BeanWrapperImpl
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.validation.DataBinder
*/
public interface BeanWrapper extends PropertyAccessor, PropertyEditorRegistry {
/**
* Change the wrapped JavaBean object.
* @param obj the bean instance to wrap
*/
void setWrappedInstance(Object obj);
/**
* Return the bean instance wrapped by this object, if any.
* @return the bean instance, or <code>null</code> if none set
*/
Object getWrappedInstance();
/**
* Return the type of the wrapped JavaBean object.
* @return the type of the wrapped bean instance,
* or <code>null</code> if no wrapped object has been set
*/
Class getWrappedClass();
/**
* Set whether to extract the old property value when applying a
* property editor to a new value for a property.
* <p>Default is "false", avoiding side effects caused by getters.
* Turn this to "true" to expose previous property values to custom editors.
*/
void setExtractOldValueForEditor(boolean extractOldValueForEditor);
/**
* Return whether to extract the old property value when applying a
* property editor to a new value for a property.
*/
boolean isExtractOldValueForEditor();
/**
* Obtain the PropertyDescriptors for the wrapped object
* (as determined by standard JavaBeans introspection).
* @return the PropertyDescriptors for the wrapped object
*/
PropertyDescriptor[] getPropertyDescriptors();
/**
* Obtain the property descriptor for a specific property
* of the wrapped object.
* @param propertyName the property to obtain the descriptor for
* (may be a nested path, but no indexed/mapped property)
* @return the property descriptor for the specified property
* @throws InvalidPropertyException if there is no such property
*/
PropertyDescriptor getPropertyDescriptor(String propertyName) throws BeansException;
/**
* Determine the property type for the specified property,
* either checking the property descriptor or checking the value
* in case of an indexed or mapped element.
* @param propertyName property to check status for
* (may be a nested path and/or an indexed/mapped property)
* @return the property type for the particular property,
* or <code>null</code> if not determinable
* @throws InvalidPropertyException if there is no such property or
* if the property isn't readable
*/
Class getPropertyType(String propertyName) throws BeansException;
/**
* Determine whether the specified property is readable.
* <p>Returns <code>false</code> if the property doesn't exist.
* @param propertyName property to check status for
* (may be a nested path and/or an indexed/mapped property)
* @return whether the property is readable
*/
boolean isReadableProperty(String propertyName);
/**
* Determine whether the specified property is writable.
* <p>Returns <code>false</code> if the property doesn't exist.
* @param propertyName property to check status for
* (may be a nested path and/or an indexed/mapped property)
* @return whether the property is writable
*/
boolean isWritableProperty(String propertyName);
}
|
9241cde60f3163ec3e52cb107721a05b60e18a51
| 27,576 |
java
|
Java
|
vas/src/main/java/co/edu/usbcali/vas/presentation/businessDelegate/IBusinessDelegatorView.java
|
vigilanciaCali/vigilanciacali_publico
|
f953370ac191cbbd21312e16d9dca5b9831aa98a
|
[
"Apache-2.0"
] | 1 |
2020-08-12T21:56:39.000Z
|
2020-08-12T21:56:39.000Z
|
vas/src/main/java/co/edu/usbcali/vas/presentation/businessDelegate/IBusinessDelegatorView.java
|
vigilanciaCali/vigilanciacali
|
f953370ac191cbbd21312e16d9dca5b9831aa98a
|
[
"Apache-2.0"
] | 32 |
2020-04-23T17:51:53.000Z
|
2022-02-16T01:06:21.000Z
|
vas/src/main/java/co/edu/usbcali/vas/presentation/businessDelegate/IBusinessDelegatorView.java
|
vigilanciaCali/vigilanciacali_publico
|
f953370ac191cbbd21312e16d9dca5b9831aa98a
|
[
"Apache-2.0"
] | null | null | null | 36.047059 | 124 | 0.767298 | 1,002,042 |
package co.edu.usbcali.vas.presentation.businessDelegate;
import java.io.InputStream;
import java.util.List;
import co.edu.usbcali.vas.model.CronJob;
import co.edu.usbcali.vas.model.CronJobMonitoring;
import co.edu.usbcali.vas.model.Device;
import co.edu.usbcali.vas.model.DeviceLog;
import co.edu.usbcali.vas.model.Document;
import co.edu.usbcali.vas.model.MailServer;
import co.edu.usbcali.vas.model.MailTemplate;
import co.edu.usbcali.vas.model.MessageBox;
import co.edu.usbcali.vas.model.News;
import co.edu.usbcali.vas.model.SystemCompanyParameter;
import co.edu.usbcali.vas.model.SystemConfig;
import co.edu.usbcali.vas.model.SystemCronLog;
import co.edu.usbcali.vas.model.SystemLog;
import co.edu.usbcali.vas.model.SystemMailLog;
import co.edu.usbcali.vas.model.SystemMonitoringLog;
import co.edu.usbcali.vas.model.SystemParameter;
import co.edu.usbcali.vas.model.SystemRestLog;
import co.edu.usbcali.vas.model.SystemVideoLog;
import co.edu.usbcali.vas.model.Ticket;
import co.edu.usbcali.vas.model.TicketType;
import co.edu.usbcali.vas.model.UserType;
import co.edu.usbcali.vas.model.Users;
import co.edu.usbcali.vas.model.Video;
import co.edu.usbcali.vas.model.VideoDocument;
import co.edu.usbcali.vas.model.VideoTemp;
import co.edu.usbcali.vas.model.VideoTransaction;
import co.edu.usbcali.vas.model.dto.CronJobDTO;
import co.edu.usbcali.vas.model.dto.CronJobMonitoringDTO;
import co.edu.usbcali.vas.model.dto.DeviceDTO;
import co.edu.usbcali.vas.model.dto.DeviceLogDTO;
import co.edu.usbcali.vas.model.dto.DocumentDTO;
import co.edu.usbcali.vas.model.dto.MailServerDTO;
import co.edu.usbcali.vas.model.dto.MailTemplateDTO;
import co.edu.usbcali.vas.model.dto.MessageBoxDTO;
import co.edu.usbcali.vas.model.dto.NewsDTO;
import co.edu.usbcali.vas.model.dto.SystemCompanyParameterDTO;
import co.edu.usbcali.vas.model.dto.SystemConfigDTO;
import co.edu.usbcali.vas.model.dto.SystemCronLogDTO;
import co.edu.usbcali.vas.model.dto.SystemLogDTO;
import co.edu.usbcali.vas.model.dto.SystemMailLogDTO;
import co.edu.usbcali.vas.model.dto.SystemMonitoringLogDTO;
import co.edu.usbcali.vas.model.dto.SystemParameterDTO;
import co.edu.usbcali.vas.model.dto.SystemRestLogDTO;
import co.edu.usbcali.vas.model.dto.SystemVideoLogDTO;
import co.edu.usbcali.vas.model.dto.TicketDTO;
import co.edu.usbcali.vas.model.dto.TicketTypeDTO;
import co.edu.usbcali.vas.model.dto.UserTypeDTO;
import co.edu.usbcali.vas.model.dto.UsersDTO;
import co.edu.usbcali.vas.model.dto.VideoDTO;
import co.edu.usbcali.vas.model.dto.VideoDocumentDTO;
import co.edu.usbcali.vas.model.dto.VideoTempDTO;
import co.edu.usbcali.vas.model.dto.VideoTransactionDTO;
public interface IBusinessDelegatorView {
public List<SystemParameter> getSystemParameter() throws Exception;
public void saveSystemParameter(SystemParameter entity)
throws Exception;
public void deleteSystemParameter(SystemParameter entity)
throws Exception;
public void updateSystemParameter(SystemParameter entity)
throws Exception;
public SystemParameter getSystemParameter(Integer id)
throws Exception;
public List<SystemParameter> findByCriteriaInSystemParameter(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemParameter> findPageSystemParameter(
String sortColumnName, boolean sortAscending, int startRow,
int maxResults) throws Exception;
public Long findTotalNumberSystemParameter() throws Exception;
public List<SystemParameterDTO> getDataSystemParameter()
throws Exception;
public List<Ticket> getTicket() throws Exception;
public void saveTicket(Ticket entity) throws Exception;
public void deleteTicket(Ticket entity) throws Exception;
public void updateTicket(Ticket entity) throws Exception;
public Ticket getTicket(Long id) throws Exception;
public List<Ticket> findByCriteriaInTicket(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Ticket> findPageTicket(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberTicket() throws Exception;
public List<TicketDTO> getDataTicket() throws Exception;
public List<SystemCronLog> getSystemCronLog() throws Exception;
public void saveSystemCronLog(SystemCronLog entity)
throws Exception;
public void deleteSystemCronLog(SystemCronLog entity)
throws Exception;
public void updateSystemCronLog(SystemCronLog entity)
throws Exception;
public SystemCronLog getSystemCronLog(Long id) throws Exception;
public List<SystemCronLog> findByCriteriaInSystemCronLog(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemCronLog> findPageSystemCronLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemCronLog() throws Exception;
public List<SystemCronLogDTO> getDataSystemCronLog()
throws Exception;
public List<SystemMonitoringLog> getSystemMonitoringLog()
throws Exception;
public void saveSystemMonitoringLog(SystemMonitoringLog entity)
throws Exception;
public void deleteSystemMonitoringLog(SystemMonitoringLog entity)
throws Exception;
public void updateSystemMonitoringLog(SystemMonitoringLog entity)
throws Exception;
public SystemMonitoringLog getSystemMonitoringLog(Long id)
throws Exception;
public List<SystemMonitoringLog> findByCriteriaInSystemMonitoringLog(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemMonitoringLog> findPageSystemMonitoringLog(
String sortColumnName, boolean sortAscending, int startRow,
int maxResults) throws Exception;
public Long findTotalNumberSystemMonitoringLog() throws Exception;
public List<SystemMonitoringLogDTO> getDataSystemMonitoringLog()
throws Exception;
public List<Device> getDevice() throws Exception;
public void saveDevice(Device entity) throws Exception;
public void deleteDevice(Device entity) throws Exception;
public void updateDevice(Device entity) throws Exception;
public Device getDevice(Integer id) throws Exception;
public List<Device> findByCriteriaInDevice(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Device> findPageDevice(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberDevice() throws Exception;
public List<DeviceDTO> getDataDevice() throws Exception;
public List<SystemRestLog> getSystemRestLog() throws Exception;
public void saveSystemRestLog(SystemRestLog entity)
throws Exception;
public void deleteSystemRestLog(SystemRestLog entity)
throws Exception;
public void updateSystemRestLog(SystemRestLog entity)
throws Exception;
public SystemRestLog getSystemRestLog(Long id) throws Exception;
public List<SystemRestLog> findByCriteriaInSystemRestLog(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemRestLog> findPageSystemRestLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemRestLog() throws Exception;
public List<SystemRestLogDTO> getDataSystemRestLog()
throws Exception;
public List<Document> getDocument() throws Exception;
public void saveDocument(Document entity) throws Exception;
public void deleteDocument(Document entity) throws Exception;
public void updateDocument(Document entity) throws Exception;
public Document getDocument(Long id) throws Exception;
public List<Document> findByCriteriaInDocument(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Document> findPageDocument(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberDocument() throws Exception;
public List<DocumentDTO> getDataDocument() throws Exception;
public List<Users> getUsers() throws Exception;
public void saveUsers(Users entity) throws Exception;
public void deleteUsers(Users entity) throws Exception;
public void updateUsers(Users entity) throws Exception;
public Users getUsers(Integer id) throws Exception;
public List<Users> findByCriteriaInUsers(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Users> findPageUsers(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberUsers() throws Exception;
public List<UsersDTO> getDataUsers() throws Exception;
public List<CronJob> getCronJob() throws Exception;
public void saveCronJob(CronJob entity) throws Exception;
public void deleteCronJob(CronJob entity) throws Exception;
public void updateCronJob(CronJob entity) throws Exception;
public CronJob getCronJob(Integer id) throws Exception;
public List<CronJob> findByCriteriaInCronJob(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<CronJob> findPageCronJob(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberCronJob() throws Exception;
public List<CronJobDTO> getDataCronJob() throws Exception;
public List<MailTemplate> getMailTemplate() throws Exception;
public void saveMailTemplate(MailTemplate entity) throws Exception;
public void deleteMailTemplate(MailTemplate entity)
throws Exception;
public void updateMailTemplate(MailTemplate entity)
throws Exception;
public MailTemplate getMailTemplate(Integer id) throws Exception;
public List<MailTemplate> findByCriteriaInMailTemplate(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<MailTemplate> findPageMailTemplate(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberMailTemplate() throws Exception;
public List<MailTemplateDTO> getDataMailTemplate()
throws Exception;
public List<SystemConfig> getSystemConfig() throws Exception;
public void saveSystemConfig(SystemConfig entity) throws Exception;
public void deleteSystemConfig(SystemConfig entity)
throws Exception;
public void updateSystemConfig(SystemConfig entity)
throws Exception;
public SystemConfig getSystemConfig(Integer id) throws Exception;
public List<SystemConfig> findByCriteriaInSystemConfig(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<SystemConfig> findPageSystemConfig(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemConfig() throws Exception;
public List<SystemConfigDTO> getDataSystemConfig()
throws Exception;
public List<MessageBox> getMessageBox() throws Exception;
public void saveMessageBox(MessageBox entity) throws Exception;
public void deleteMessageBox(MessageBox entity) throws Exception;
public void updateMessageBox(MessageBox entity) throws Exception;
public MessageBox getMessageBox(Long id) throws Exception;
public List<MessageBox> findByCriteriaInMessageBox(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<MessageBox> findPageMessageBox(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberMessageBox() throws Exception;
public List<MessageBoxDTO> getDataMessageBox() throws Exception;
public List<DeviceLog> getDeviceLog() throws Exception;
public void saveDeviceLog(DeviceLog entity) throws Exception;
public void deleteDeviceLog(DeviceLog entity) throws Exception;
public void updateDeviceLog(DeviceLog entity) throws Exception;
public DeviceLog getDeviceLog(Long id) throws Exception;
public List<DeviceLog> findByCriteriaInDeviceLog(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<DeviceLog> findPageDeviceLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberDeviceLog() throws Exception;
public List<DeviceLogDTO> getDataDeviceLog() throws Exception;
public List<Video> getVideo() throws Exception;
public void saveVideo(Video entity) throws Exception;
public void deleteVideo(Video entity) throws Exception;
public void updateVideo(Video entity) throws Exception;
public Video getVideo(Long id) throws Exception;
public List<Video> findByCriteriaInVideo(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<Video> findPageVideo(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberVideo() throws Exception;
public List<VideoDTO> getDataVideo() throws Exception;
public List<SystemCompanyParameter> getSystemCompanyParameter()
throws Exception;
public void saveSystemCompanyParameter(SystemCompanyParameter entity)
throws Exception;
public void deleteSystemCompanyParameter(SystemCompanyParameter entity)
throws Exception;
public void updateSystemCompanyParameter(SystemCompanyParameter entity)
throws Exception;
public SystemCompanyParameter getSystemCompanyParameter(Integer id)
throws Exception;
public List<SystemCompanyParameter> findByCriteriaInSystemCompanyParameter(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemCompanyParameter> findPageSystemCompanyParameter(
String sortColumnName, boolean sortAscending, int startRow,
int maxResults) throws Exception;
public Long findTotalNumberSystemCompanyParameter()
throws Exception;
public List<SystemCompanyParameterDTO> getDataSystemCompanyParameter()
throws Exception;
public List<UserType> getUserType() throws Exception;
public void saveUserType(UserType entity) throws Exception;
public void deleteUserType(UserType entity) throws Exception;
public void updateUserType(UserType entity) throws Exception;
public UserType getUserType(Integer id) throws Exception;
public List<UserType> findByCriteriaInUserType(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<UserType> findPageUserType(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberUserType() throws Exception;
public List<UserTypeDTO> getDataUserType() throws Exception;
public List<MailServer> getMailServer() throws Exception;
public void saveMailServer(MailServer entity) throws Exception;
public void deleteMailServer(MailServer entity) throws Exception;
public void updateMailServer(MailServer entity) throws Exception;
public MailServer getMailServer(Integer id) throws Exception;
public List<MailServer> findByCriteriaInMailServer(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<MailServer> findPageMailServer(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberMailServer() throws Exception;
public List<MailServerDTO> getDataMailServer() throws Exception;
public List<SystemMailLog> getSystemMailLog() throws Exception;
public void saveSystemMailLog(SystemMailLog entity)
throws Exception;
public void deleteSystemMailLog(SystemMailLog entity)
throws Exception;
public void updateSystemMailLog(SystemMailLog entity)
throws Exception;
public SystemMailLog getSystemMailLog(Long id) throws Exception;
public List<SystemMailLog> findByCriteriaInSystemMailLog(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemMailLog> findPageSystemMailLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemMailLog() throws Exception;
public List<SystemMailLogDTO> getDataSystemMailLog()
throws Exception;
public List<CronJobMonitoring> getCronJobMonitoring()
throws Exception;
public void saveCronJobMonitoring(CronJobMonitoring entity)
throws Exception;
public void deleteCronJobMonitoring(CronJobMonitoring entity)
throws Exception;
public void updateCronJobMonitoring(CronJobMonitoring entity)
throws Exception;
public CronJobMonitoring getCronJobMonitoring(Integer id)
throws Exception;
public List<CronJobMonitoring> findByCriteriaInCronJobMonitoring(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<CronJobMonitoring> findPageCronJobMonitoring(
String sortColumnName, boolean sortAscending, int startRow,
int maxResults) throws Exception;
public Long findTotalNumberCronJobMonitoring() throws Exception;
public List<CronJobMonitoringDTO> getDataCronJobMonitoring()
throws Exception;
public List<VideoDocument> getVideoDocument() throws Exception;
public void saveVideoDocument(VideoDocument entity)
throws Exception;
public void deleteVideoDocument(VideoDocument entity)
throws Exception;
public void updateVideoDocument(VideoDocument entity)
throws Exception;
public VideoDocument getVideoDocument(Long id) throws Exception;
public List<VideoDocument> findByCriteriaInVideoDocument(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<VideoDocument> findPageVideoDocument(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberVideoDocument() throws Exception;
public List<VideoDocumentDTO> getDataVideoDocument()
throws Exception;
public List<SystemVideoLog> getSystemVideoLog() throws Exception;
public void saveSystemVideoLog(SystemVideoLog entity)
throws Exception;
public void deleteSystemVideoLog(SystemVideoLog entity)
throws Exception;
public void updateSystemVideoLog(SystemVideoLog entity)
throws Exception;
public SystemVideoLog getSystemVideoLog(Long id) throws Exception;
public List<SystemVideoLog> findByCriteriaInSystemVideoLog(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<SystemVideoLog> findPageSystemVideoLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemVideoLog() throws Exception;
public List<SystemVideoLogDTO> getDataSystemVideoLog()
throws Exception;
public List<News> getNews() throws Exception;
public void saveNews(News entity) throws Exception;
public void deleteNews(News entity) throws Exception;
public void updateNews(News entity) throws Exception;
public News getNews(Long id) throws Exception;
public List<News> findByCriteriaInNews(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<News> findPageNews(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberNews() throws Exception;
public List<NewsDTO> getDataNews() throws Exception;
public List<TicketType> getTicketType() throws Exception;
public void saveTicketType(TicketType entity) throws Exception;
public void deleteTicketType(TicketType entity) throws Exception;
public void updateTicketType(TicketType entity) throws Exception;
public TicketType getTicketType(Integer id) throws Exception;
public List<TicketType> findByCriteriaInTicketType(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<TicketType> findPageTicketType(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberTicketType() throws Exception;
public List<TicketTypeDTO> getDataTicketType() throws Exception;
public List<SystemLog> getSystemLog() throws Exception;
public void saveSystemLog(SystemLog entity) throws Exception;
public void deleteSystemLog(SystemLog entity) throws Exception;
public void updateSystemLog(SystemLog entity) throws Exception;
public SystemLog getSystemLog(Long id) throws Exception;
public List<SystemLog> findByCriteriaInSystemLog(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<SystemLog> findPageSystemLog(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberSystemLog() throws Exception;
public List<SystemLogDTO> getDataSystemLog() throws Exception;
public List<VideoTemp> getVideoTemp() throws Exception;
public void saveVideoTemp(VideoTemp entity) throws Exception;
public void deleteVideoTemp(VideoTemp entity) throws Exception;
public void updateVideoTemp(VideoTemp entity) throws Exception;
public VideoTemp getVideoTemp(Long id) throws Exception;
public List<VideoTemp> findByCriteriaInVideoTemp(Object[] variables,
Object[] variablesBetween, Object[] variablesBetweenDates)
throws Exception;
public List<VideoTemp> findPageVideoTemp(String sortColumnName,
boolean sortAscending, int startRow, int maxResults)
throws Exception;
public Long findTotalNumberVideoTemp() throws Exception;
public List<VideoTempDTO> getDataVideoTemp() throws Exception;
public List<VideoTransaction> getVideoTransaction()
throws Exception;
public void saveVideoTransaction(VideoTransaction entity)
throws Exception;
public void deleteVideoTransaction(VideoTransaction entity)
throws Exception;
public void updateVideoTransaction(VideoTransaction entity)
throws Exception;
public VideoTransaction getVideoTransaction(Long id)
throws Exception;
public List<VideoTransaction> findByCriteriaInVideoTransaction(
Object[] variables, Object[] variablesBetween,
Object[] variablesBetweenDates) throws Exception;
public List<VideoTransaction> findPageVideoTransaction(
String sortColumnName, boolean sortAscending, int startRow,
int maxResults) throws Exception;
public Long findTotalNumberVideoTransaction() throws Exception;
public List<VideoTransactionDTO> getDataVideoTransaction()
throws Exception;
//AUTH-------------------------------------------------------------------------
public Users authenticate(String usuLogin, String usuPassword) throws Exception;
public Users getUserByLogin(String usuLogin) throws Exception;
public void restoreUserPassword(String usuLogin) throws Exception;
//VIDEO
//TEMP
public String saveVideoToTempLocation(String contentType, String fileName, Long size, InputStream inputFile, String type)
throws Exception;
//TRACKER
public void analyze_trackerAlg(String contentType, String fileName, Long size, InputStream inputFile) throws Exception;
public void analyze_anomalousAlg(String contentType, String fileName, Long size, InputStream inputFile) throws Exception;
//LOCATIONS
public String getTemp_video_folder() throws Exception;
public String getWeb_server_temp() throws Exception;
//SERVER LOCATIONS
public String getAlg_anl_output_server() throws Exception;
public String getAlg_trc_output_server() throws Exception;
//VIDEO DATA
public List<VideoDTO> getDataVideoTracker() throws Exception;
public List<VideoDTO> getDataVideoAnomalous() throws Exception;
public List<VideoTempDTO> getDataVideoTempTracker() throws Exception;
public List<VideoTempDTO> getDataVideoTempAnomalous() throws Exception;
//VIDEO TRANSACTION
public List<VideoTransactionDTO> getDataVideoTrabnsaction(String videoTransactionId) throws Exception;
//DELETE
public void deleteVideoTemp(Long id, String file) throws Exception;
//MONITOR STATUS
public Boolean isAlgAnlAvailable();
public Boolean isAlgTrackerAvailable();
public Boolean serverMonitorControllerStatus() throws Exception;
//ANALYZE ALG
public String analyze_anomalousAlgFromTempLocationREST(String videoFileTemp, String videoSize, String initTimeParam,
String finalTimeParam, String info) throws Exception;
//TEST
public String analyze_anomalousAlgFromTempLocationRestTEST(String videoFileTemp, String videoSize, String initTimeParam,
String finalTimeParam, String info) throws Exception;
public void processVideoWithAnomalousAlgRest() throws Exception;
//ANALYZE TRACKER
public String analyze_trackerAlgFromTempLocationREST(String videoFileTemp, String videoSize, String posXParam,
String posYParam, String posX2Param, String posY2Param, String info) throws Exception;
//TEST
public String analyze_trackerAlgFromTempLocationRestTEST(String videoFileTemp, String videoSize, String posXParam,
String posYParam, String posX2Param, String posY2Param, String info) throws Exception;
public void processVideoWithTrackerAlgRest() throws Exception;
//ANL REST DATA
public void getAnlDataFromRest(String data) throws Exception;
public VideoTransactionDTO getVideoTransactionDTOByTransactionId(String videoTransactionId) throws Exception;
public void updateVideoTransactionStatusByTransactionIdRest(VideoTransactionDTO videoTransactionDTO) throws Exception;
public void startAlgResult() throws Exception;
//TRACE
public void save_systemLogRest(String actionName, String note) throws Exception;
public void save_systemLogRestDTO(SystemLogDTO entity) throws Exception;
}
|
9241ce5f7d994643000704fa64541c32d1f79f57
| 4,194 |
java
|
Java
|
app/src/main/java/com/wen/bangumi/util/JsoupUtils.java
|
BelieveOP5/Bangumi
|
f6992c917f99a18eda307b5b8cc91a056f64846c
|
[
"Apache-2.0"
] | 3 |
2017-01-27T08:22:05.000Z
|
2019-02-17T04:20:35.000Z
|
app/src/main/java/com/wen/bangumi/util/JsoupUtils.java
|
BelieveOP5/Bangumi
|
f6992c917f99a18eda307b5b8cc91a056f64846c
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/wen/bangumi/util/JsoupUtils.java
|
BelieveOP5/Bangumi
|
f6992c917f99a18eda307b5b8cc91a056f64846c
|
[
"Apache-2.0"
] | null | null | null | 29.957143 | 100 | 0.546495 | 1,002,043 |
package com.wen.bangumi.util;
import com.wen.bangumi.entity.bangumi.EpisodesEntity;
import com.wen.bangumi.greenDAO.BangumiItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by BelieveOP5 on 2017/1/28.
*/
public class JsoupUtils {
/**
* 解析网页{@see <a href="http://bangumi.tv/subject/185762"></a>}
* @param html
* @return
*/
public static BangumiItem parseBangumiHtml(String html) {
return null;
}
/**
* 解析网页{@see <a href="http://bangumi.tv/anime/list/believeop5/do"></a>}
* @param html
* @return
*/
public static List<BangumiItem> parseCollHtml(String html) {
Document doc = Jsoup.parse(html);
Elements div = doc.select("div.column");
Elements li = div.select("ul#browserItemList>li");
List<BangumiItem> mList = new ArrayList<>();
for (int i = 0; i < li.size(); ++i) {
Element element = li.get(i);
BangumiItem entity = new BangumiItem();
String id = element.select("a").attr("href").replace("/subject/", "").trim();
String image = "https:" + element.select("a>span>img").attr("src");
String name = element.select("div>h3>a").text();
// 这个是自己做的,这张图不一定存在
String largeImage = image.replace("/s/", "/l/");
entity.setBangumi_id(Integer.valueOf(id));
entity.setName_cn(name);
entity.setAir_weekday(0);
entity.setLarge_image(largeImage);
mList.add(entity);
}
return mList;
}
/**
* 解析网页{@see <a href="http://bangumi.tv/subject/975/ep"></a>}
* @param html
*/
public static List<EpisodesEntity> parseBangumiEpi(String html) {
Document doc = Jsoup.parse(html);
Elements div = doc.select("div.line_detail");
Elements li = div.select("ul.line_list>li");
List<EpisodesEntity> episodesEntityList = new ArrayList<>();
for(int i = 0; i < li.size(); ++i) {
/**
* 先将本篇,特别篇等章节种类存储下来
*/
Element element = li.get(i);
if (element.hasClass("cat")) {
EpisodesEntity episodesEntity = new EpisodesEntity();
episodesEntity.setType(element.text());
episodesEntity.setEpisodeList(new ArrayList<EpisodesEntity.Episode>());
episodesEntityList.add(episodesEntity);
}
}
for(int i = 0, k = -1; i < li.size(); ++i) {
Element element = li.get(i);
if (element.hasClass("cat")) {
k++;
continue;
}
EpisodesEntity.Episode episode = new EpisodesEntity.Episode();
episode.setId(Integer.valueOf(element.select("h6>a").attr("href").replace("/ep/", "")));
episode.setStatus(element.select("h6>span.epAirStatus>span").attr("class"));
//从该网页中不能获取到用户的观看状态,所以只能先暂时初始化为默认状态
episode.setMy_status("status");
//将"13.穢れなき世界"分离开来,提取章节编号和标题
String title = element.select("h6>a").text();
if (k == 0 && !title.isEmpty()) {
List<String> strList;
strList = Arrays.asList(title.split("\\."));
episode.setEpisode_id(Integer.valueOf(strList.get(0)));
if (strList.size() == 1) {
episode.setName("");
} else {
episode.setName(strList.get(1));
}
} else {
episode.setName(title);
}
//将" / 复仇"中的" / "去掉,如果为空则不需要
String subTitle = element.select("h6>span.tip").text();
if (!subTitle.isEmpty()) {
subTitle = subTitle.substring(2);
}
episode.setName_cn(subTitle);
episode.setInfo(element.select("small.grey").get(0).text());
episodesEntityList.get(k).getEpisodeList().add(episode);
}
return episodesEntityList;
}
}
|
9241cf81f2472d441ecfde40a9ea1182090e5aca
| 13,705 |
java
|
Java
|
src/edu/pitt/cs/people/guy/wind/benchmarks/NoiseAllowed.java
|
RetractableWind/retractable-wind
|
26299f8c60e7b867669b95335eeb2bc364a26b2a
|
[
"MIT"
] | null | null | null |
src/edu/pitt/cs/people/guy/wind/benchmarks/NoiseAllowed.java
|
RetractableWind/retractable-wind
|
26299f8c60e7b867669b95335eeb2bc364a26b2a
|
[
"MIT"
] | null | null | null |
src/edu/pitt/cs/people/guy/wind/benchmarks/NoiseAllowed.java
|
RetractableWind/retractable-wind
|
26299f8c60e7b867669b95335eeb2bc364a26b2a
|
[
"MIT"
] | null | null | null | 22.652893 | 143 | 0.672018 | 1,002,044 |
package edu.pitt.cs.people.guy.wind.benchmarks;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class NoiseAllowed {
public final int STATION = 0;
public final int MON_THU_DAYTIME_START = 1;
public final int MON_THU_DAYTIME_END = 2;
public final int FRI_DAYTIME_START = 3;
public final int FRI_DAYTIME_END = 4;
public final int SAT_DAYTIME_START = 5;
public final int SAT_DAYTIME_END = 6;
public final int SUN_DAYTIME_START = 7;
public final int SUN_DAYTIME_END = 8;
public final int FEDERAL_HOLIDAY_DAYTIME_START = 9;
public final int FEDERAL_HOLIDAY_DAYTIME_END = 10;
public final int TOTAL_NUMBER_OF_FIELDS = 11;
public LocalTime localTime[] = new LocalTime[TOTAL_NUMBER_OF_FIELDS];
public boolean bFederalHolidaysObserved = true;
public boolean bUseSunsetEveryDayExcept = false; //Except if Daytime Start and End Times Equal
final int VALUE_INDICATING_LOCAL_TIME_AFTER_SUNSET_INDEX_HAS_NOT_BEEN_INITIALIZED = -99; //do not use -1
int localTimeAfterSunsetIndex = VALUE_INDICATING_LOCAL_TIME_AFTER_SUNSET_INDEX_HAS_NOT_BEEN_INITIALIZED;
final int INITIAL_VALUE_FOR_prevDayOfMonth = -1;
int prevDayOfMonth = INITIAL_VALUE_FOR_prevDayOfMonth;
public void reset() {
localTimeAfterSunsetIndex = VALUE_INDICATING_LOCAL_TIME_AFTER_SUNSET_INDEX_HAS_NOT_BEEN_INITIALIZED;
prevDayOfMonth = INITIAL_VALUE_FOR_prevDayOfMonth;
}
private LocalTime processField(String fieldValue) {
final int DEFAULT_HOUR = 1;
final int DEFAULT_MINUTE = 1;
LocalTime lt = LocalTime.of(DEFAULT_HOUR, DEFAULT_MINUTE);
final char FIRST_CHARACTER_OF_NEVER_STRING = 'N';
final char FIRST_CHARACTER_OF_WITH_DAY_OF_WEEK_STRING = 'W';
final char FIRST_CHARACTER_SUNSET_STRING = 's';
switch(fieldValue.charAt(0)) {
case FIRST_CHARACTER_OF_NEVER_STRING:
// defer to default time, which is set above
break;
case FIRST_CHARACTER_OF_WITH_DAY_OF_WEEK_STRING:
bFederalHolidaysObserved = false;
break;
case FIRST_CHARACTER_SUNSET_STRING:
bUseSunsetEveryDayExcept = true;
System.out.println("Using sunset for all noise-allowed days");
break;
default:
// Parse hour and minute
String timeParts[] = fieldValue.split(":");
lt = LocalTime.of(Integer.parseInt(timeParts[0]),
Integer.parseInt(timeParts[1]));
}
return(lt);
}
public NoiseAllowed(String station) {
final String FILENAME = "/Noise_Allowed_Time_Definitions_All_Stations.csv";
final String FILENAME_SUNSET_STL = "/STL_Sunset_Times.csv";
// Load definition from .csv file
/// Open .csv file
BufferedReader br = openFile(FILENAME);
String line = null;
/// Find the station in the .csv file
try {
while (
((line = br.readLine()) != null)
&&
!(line.substring(0, station.length()).equals(station))
) {
// do nothing
}
} catch (IOException e) {
e.printStackTrace();
}
if (line == null) {
System.out.println("NoiseAllowed record not found for station:" + station);
} else {
String tokens[] = line.split(",");
// load record
System.out.println("The station is the record is " + tokens[0]);
for (int i = MON_THU_DAYTIME_START; i < TOTAL_NUMBER_OF_FIELDS; i++) {
// process field
localTime[i] = processField(tokens[i]);
}
}
if (station.equals("KSTL")) {
System.out.println("Reading sunset data for KSTL");
BufferedReader brSunsetTimesSTL = openFile(FILENAME_SUNSET_STL);
loadSunsetTimesIntoMemory(brSunsetTimesSTL);
}
}
private boolean bDaytimeGivenStartAndEndConstants(int daytime_start_constant, int daytime_end_constant, LocalDateTime ldt) {
boolean bDaytimeStartBeforeLocalTime = localTime[daytime_start_constant].isBefore(ldt.toLocalTime());
localTimeThatDaytimeEndsPreliminary = ldt.toLocalTime();
boolean bLocalTimeBeforeDaytimeEnd = bUseSunsetEveryDayExcept ?
bLocalTimeBeforeSunset(ldt) :
ldt.toLocalTime().isBefore(localTime[daytime_end_constant]);
return(
!(localTime[daytime_start_constant].equals(localTime[daytime_end_constant])) && // if start and end equal, then return false
bDaytimeStartBeforeLocalTime &&
bLocalTimeBeforeDaytimeEnd
);
}
public double getMembershipValueForApproachingQuietHours(LocalDateTime ldt,
double minutesAwayFromStartOfQuietHoursXIntercept) {
final int MAXIMUM_MEMBERSHIP_VALUE = 1;
final int LEAST_MEMBERSHIP_VALUE = 0;
double membershipValue = MAXIMUM_MEMBERSHIP_VALUE; // default
if (bIsNoiseAllowed(ldt)) {
long minutesUntilEndOfDay =
ldt.toLocalTime().until(localTimeThatDaytimeEndsPreliminary, ChronoUnit.MINUTES);
if (minutesUntilEndOfDay < 0) {
System.out.println("Warning: minutesUntilEndOfDay is unexpectedly negative");
}
membershipValue = (-MAXIMUM_MEMBERSHIP_VALUE/((double) minutesAwayFromStartOfQuietHoursXIntercept))
*minutesUntilEndOfDay
+ MAXIMUM_MEMBERSHIP_VALUE;
if (membershipValue < LEAST_MEMBERSHIP_VALUE) {
membershipValue = LEAST_MEMBERSHIP_VALUE;
}
} // else return default value set above
return(membershipValue);
}
LocalTime localTimeThatDaytimeEndsPreliminary;
public boolean bIsNoiseAllowed(LocalDateTime ldt) {
if (
bUseSunsetEveryDayExcept &&
(VALUE_INDICATING_LOCAL_TIME_AFTER_SUNSET_INDEX_HAS_NOT_BEEN_INITIALIZED == localTimeAfterSunsetIndex)
) {
localTimeAfterSunsetIndex = getIndexOfLocalDateTimeSunsetStandardTime(ldt) - 1; //Subtract 1 since the index is advanced before it is used
// if there is a day change.
}
// TODO: ensure that ldt observes Daylight Savings Time appropriately
boolean bNoiseAllowed = false;
// if sunset times are used, then adjust DAYTIME end
if (bFederalHolidaysObserved && FederalHolidays.bFederalHoliday(ldt.toLocalDate())) {
bNoiseAllowed = bDaytimeGivenStartAndEndConstants(FEDERAL_HOLIDAY_DAYTIME_START,
FEDERAL_HOLIDAY_DAYTIME_END, ldt);
} else {
switch(ldt.getDayOfWeek()) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
bNoiseAllowed = bDaytimeGivenStartAndEndConstants(MON_THU_DAYTIME_START,
MON_THU_DAYTIME_END, ldt);
break;
case FRIDAY:
bNoiseAllowed = bDaytimeGivenStartAndEndConstants(FRI_DAYTIME_START,
FRI_DAYTIME_END, ldt);
break;
case SATURDAY:
bNoiseAllowed = bDaytimeGivenStartAndEndConstants(SAT_DAYTIME_START,
SAT_DAYTIME_END, ldt);
break;
case SUNDAY:
bNoiseAllowed = bDaytimeGivenStartAndEndConstants(SUN_DAYTIME_START,
SUN_DAYTIME_END, ldt);
break;
}
}
return(bNoiseAllowed);
}
boolean bLocalTimeBeforeSunset(LocalDateTime ldt) {
//if new day, then advance index
if (prevDayOfMonth != ldt.getDayOfMonth()) {
localTimeAfterSunsetIndex++;
prevDayOfMonth = ldt.getDayOfMonth();
}
if (localTimeAfterSunsetIndex<0) {
System.out.println("Warning: localTimeAfterSunsetIndex unexpectedly negative; setting to 0.");
localTimeAfterSunsetIndex=0;
}
//assume that localTimeAfterSunsetIndex has been set correctly
localTimeThatDaytimeEndsPreliminary = localDateTimeSunsetStandardTime[localTimeAfterSunsetIndex].toLocalTime();
boolean bLocalTimeBeforeSunset = ldt.toLocalTime().isBefore(localTimeThatDaytimeEndsPreliminary);
// check that date matches
if (
!(ldt.toLocalDate().equals(localDateTimeSunsetStandardTime[localTimeAfterSunsetIndex].toLocalDate()))
) {
// System.out.println("Error: LocalTimeBeforeSunset: Dates out-of-sync: passed" +
// ldt.toLocalDate() + " Indexed: " +
// localDateTimeSunsetStandardTime[localTimeAfterSunsetIndex].toLocalDate());
System.out.println("Error: LocalTimeBeforeSunset: Dates out-of-sync: passed" +
ldt + " Indexed: " +
localDateTimeSunsetStandardTime[localTimeAfterSunsetIndex]);
System.exit(0);
}
return(bLocalTimeBeforeSunset);
}
final int NUMBER_DAYS_IN_2004_2014 = 4018;
LocalDateTime localDateTimeSunsetStandardTime[] = new LocalDateTime[NUMBER_DAYS_IN_2004_2014];
private void loadSunsetTimesIntoMemory(BufferedReader brSunsetTimes) {
String line;
try {
int i = 0;
while((line = brSunsetTimes.readLine()) != null) {
String tokens[] = line.split(",");
String date = tokens[0];
String sunsetTime = tokens[1];
String dateTokens[] = date.split("-");
int year = Integer.parseInt(dateTokens[0]);
int month = Integer.parseInt(dateTokens[1]);
int dayOfMonth = Integer.parseInt(dateTokens[2]);
int hour = Integer.parseInt(sunsetTime.substring(0, 2));
int minute = Integer.parseInt(sunsetTime.substring(2));
localDateTimeSunsetStandardTime[i] = LocalDateTime.of(year, month, dayOfMonth, hour, minute);
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public LocalTime localTimeSunset(int index, boolean bAdjustOutputForDaylightSavingsTime) {
int hour = localDateTimeSunsetStandardTime[index].getHour();
int minute = localDateTimeSunsetStandardTime[index].getMinute();
if (bAdjustOutputForDaylightSavingsTime) {
hour++;
}
return(LocalTime.of(hour, minute));
}
int getIndexOfLocalDateTimeSunsetStandardTime(LocalDateTime ldt) {
// search forward until the proper date is found
int i = 0;
int yearToMatch = ldt.getYear();
int monthValueToMatch = ldt.getMonthValue();
int dayToMatch = ldt.getDayOfMonth();
for (i = 0; i < localDateTimeSunsetStandardTime.length; i++) {
if ((yearToMatch == localDateTimeSunsetStandardTime[i].getYear()) &&
(monthValueToMatch == localDateTimeSunsetStandardTime[i].getMonthValue()) &&
(dayToMatch == localDateTimeSunsetStandardTime[i].getDayOfMonth())) {
break;
};
}
if (i == localDateTimeSunsetStandardTime.length) {
System.out.println("Error: getIndexOfLocalDateTimeSunsetStandardTime: Date not found " + ldt);
System.exit(0);
}
return(i);
}
public void getFields() {
for (int i = MON_THU_DAYTIME_START; i < TOTAL_NUMBER_OF_FIELDS; i++) {
// process field
System.out.println(i + " " + localTime[i]);
}
System.out.println("Federal Holidays Observed:" + bFederalHolidaysObserved);
}
public void getSunsetTimes() {
for (LocalDateTime ldt : localDateTimeSunsetStandardTime) {
System.out.println("ldt:"+ldt);
}
}
public BufferedReader openFile(String filename) {
BufferedReader bufferedReader = null;
try {
InputStream inputStream = this.getClass().getResourceAsStream(filename);
if (inputStream == null) {
System.out.println("Null for " + filename);
} else {
System.out.println("Success: " + filename + " found.");
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
if (bufferedReader != null) {
// advance past header
if ((bufferedReader.readLine()) != null) {
// //System.out.println("The header of the training file is " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return (bufferedReader);
}
public static class FederalHolidays {
public static boolean bFederalHoliday(LocalDate date) {
boolean bIsHoliday = false;
switch (date.getMonth()) {
case JANUARY:
switch (date.getDayOfMonth()) {
case 1: // New Year's Day
bIsHoliday = true;
break;
default:
// MLK, Jr.
// Determine whether incoming date is the third Monday in January
if ((date.getDayOfWeek() == DayOfWeek.MONDAY) && (date.getDayOfMonth() >= 15)
&& (date.getDayOfMonth() <= 21)) {
bIsHoliday = true;
}
break;
}
break; // break January
case MAY:
// Determine whether last Monday in May
if ((date.getDayOfWeek() == DayOfWeek.MONDAY) && (date.getDayOfMonth() >= 25)
&& (date.getDayOfMonth() <= 31)) {
bIsHoliday = true;
}
break; // break May
case JULY:
if (date.getDayOfMonth() == 4) {
bIsHoliday = true;
}
break; // break July
case SEPTEMBER:
// Determine whether first Monday in September
if ((date.getDayOfWeek() == DayOfWeek.MONDAY) && (date.getDayOfMonth() >= 1)
&& (date.getDayOfMonth() <= 7)) {
bIsHoliday = true;
}
break; // break September
case NOVEMBER:
// Determine whether forth Thursday in November
if ((date.getDayOfWeek() == DayOfWeek.THURSDAY) && (date.getDayOfMonth() >= 22)
&& (date.getDayOfMonth() <= 28)) {
bIsHoliday = true;
}
break; // break November
case DECEMBER:
if (date.getDayOfMonth() == 25) {
bIsHoliday = true;
}
break; // break December
default:
break;
}
return (bIsHoliday);
}
}
}
|
9241cfc9256cd3787b025bc577c5cc6c2b56fb73
| 1,198 |
java
|
Java
|
yanwu-spring-cloud-common/src/main/java/com/yanwu/spring/cloud/common/demo/d05io/d01socket/D02SocketClient.java
|
yanwu12138/spring-cloud
|
f8a9320faa42a2d5a1d1633f5d33530a339613ca
|
[
"MIT"
] | 2 |
2020-04-10T01:36:42.000Z
|
2020-10-20T08:30:23.000Z
|
yanwu-spring-cloud-common/src/main/java/com/yanwu/spring/cloud/common/demo/d05io/d01socket/D02SocketClient.java
|
yanwu12138/spring-cloud
|
f8a9320faa42a2d5a1d1633f5d33530a339613ca
|
[
"MIT"
] | 7 |
2020-04-03T02:48:52.000Z
|
2020-05-11T12:26:33.000Z
|
yanwu-spring-cloud-common/src/main/java/com/yanwu/spring/cloud/common/demo/d05io/d01socket/D02SocketClient.java
|
yanwu12138/spring-cloud
|
f8a9320faa42a2d5a1d1633f5d33530a339613ca
|
[
"MIT"
] | 1 |
2020-11-24T04:11:09.000Z
|
2020-11-24T04:11:09.000Z
| 29.95 | 96 | 0.594324 | 1,002,045 |
package com.yanwu.spring.cloud.common.demo.d05io.d01socket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
/**
* @author <a herf="mailto:[email protected]">XuBaofeng</a>
* @date 2020/6/15 11:46.
* <p>
* description:
*/
@Slf4j
public class D02SocketClient {
private static final String IP = "127.0.0.1";
private static final Integer PORT = 8080;
public static void main(String[] args) throws Exception {
try (Socket socket = new Socket(IP, PORT)) {
socket.setSendBufferSize(20);
socket.setTcpNoDelay(true);
try (OutputStream os = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
String line = reader.readLine();
if (StringUtils.isNotBlank(line)) {
log.info("socket client write: {}", line);
os.write(line.getBytes());
}
}
}
}
}
}
|
9241d0d2ac0d879918fe8906ef65b888faf24587
| 11,437 |
java
|
Java
|
appinventor/components/src/com/google/appinventor/components/runtime/util/CsvUtil.java
|
daki7711/appinventor-sources
|
85ff32316820aedc0ad21ac0c9de4799e5039fd2
|
[
"Apache-2.0"
] | 1,169 |
2015-01-06T21:26:16.000Z
|
2022-03-28T09:29:44.000Z
|
appinventor/components/src/com/google/appinventor/components/runtime/util/CsvUtil.java
|
Tomislav-Tomsic/appinventor-sources
|
c73ff916a1b3c763f71c9f944f8d77845a11f9a6
|
[
"Apache-2.0"
] | 2,240 |
2015-01-01T14:30:42.000Z
|
2022-03-28T14:42:21.000Z
|
appinventor/components/src/com/google/appinventor/components/runtime/util/CsvUtil.java
|
Tomislav-Tomsic/appinventor-sources
|
c73ff916a1b3c763f71c9f944f8d77845a11f9a6
|
[
"Apache-2.0"
] | 2,123 |
2015-01-03T18:52:35.000Z
|
2022-03-28T07:19:47.000Z
| 32.864943 | 99 | 0.607415 | 1,002,046 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.components.runtime.util;
import com.google.appinventor.components.runtime.collect.Lists;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
* Static methods to convert between CSV-formatted strings and YailLists.
*
* @author [email protected] (Sharon Perl)
*/
public final class CsvUtil {
private CsvUtil() {
}
public static YailList fromCsvTable(String csvString) throws Exception {
CsvParser csvParser = new CsvParser(new StringReader(csvString));
ArrayList<YailList> csvList = new ArrayList<YailList>();
while (csvParser.hasNext()) {
csvList.add(YailList.makeList(csvParser.next()));
}
csvParser.throwAnyProblem();
return YailList.makeList(csvList);
}
public static YailList fromCsvRow(String csvString) throws Exception {
CsvParser csvParser = new CsvParser(new StringReader(csvString));
if (csvParser.hasNext()) {
YailList row = YailList.makeList(csvParser.next());
if (csvParser.hasNext()) {
// more than one row is an error
throw new IllegalArgumentException("CSV text has multiple rows. Expected just one row.");
}
csvParser.throwAnyProblem();
return row;
}
throw new IllegalArgumentException("CSV text cannot be parsed as a row.");
}
// Requires: elements of csvRow are strings
public static String toCsvRow(YailList csvRow) {
StringBuilder csvStringBuilder = new StringBuilder();
makeCsvRow(csvRow, csvStringBuilder);
return csvStringBuilder.toString();
}
// Requires: elements of rows are strings
// TODO(sharon): do we want to enforce any consistency constraints here, e.g.,
// all rows have same number of elements?
public static String toCsvTable(YailList csvList) {
StringBuilder csvStringBuilder = new StringBuilder();
for (Object rowObj : csvList.toArray()) {
makeCsvRow((YailList) rowObj, csvStringBuilder);
// http://tools.ietf.org/html/rfc4180 suggests that CSV lines should be
// terminated
// by CRLF, hence the \r\n.
csvStringBuilder.append("\r\n");
}
return csvStringBuilder.toString();
}
private static void makeCsvRow(YailList row, StringBuilder csvStringBuilder) {
String fieldDelim = "";
for (Object fieldObj : row.toArray()) {
String field = fieldObj.toString();
field = field.replaceAll("\"", "\"\"");
csvStringBuilder.append(fieldDelim).append("\"").append(field).append("\"");
fieldDelim = ",";
}
}
/*
* Note: The CsvParser class was adapted from
* java/com/google/devtools/ode/server/util/CsvParser.java, which in turn was
* copied from: java/com/google/collaboration/tables/util/CsvParser.java
*
*/
private static class CsvParser implements Iterator<List<String>> {
/**
* Escaped quotes in quoted cells are doubled.
*/
private final Pattern ESCAPED_QUOTE_PATTERN = Pattern.compile("\"\"");
/**
* Character buffer for cell parsing. The size limits the largest parsable
* cell. Specifically, if an unquoted cell and its trailing delimiter exceed
* this limit, the cell will be split at the limit. Moreover, a quoted large
* cell will cause a syntax error as when we reach end-of-file without
* reading a closing quote.
*/
private final char[] buf = new char[10240];
private final Reader in;
/**
* The beginning of the currently parsed cell in {@code buf}. Everything
* before it is discarded during compaction. The beginning includes the
* quote for a quoted cell.
*/
private int pos;
/**
* The end of valid content in {@code buf}.
*/
private int limit;
/**
* Indicates whether more content might be in the reader.
*/
private boolean opened = true;
/**
* Length of a successfully parsed cell. For a quoted cell this includes the
* closing quote. Set whenever parsing of a cell succeeds. The value should
* be ignored when cell parsing fails, but is set to -1 to help debugging.
*/
private int cellLength = -1;
/**
* Length of a successfully parsed cell including its trailing delimiter.
* Set whenever parsing of a cell with trailing delimiter succeeds. The
* value should be ignored when cell parsing fails, but is set to -1 to help
* debugging.
*/
private int delimitedCellLength = -1;
/**
* Last exception encountered. Saved here to properly implement {@code
* Iterator}.
*/
private Exception lastException;
private long previouslyRead;
public CsvParser(Reader in) {
this.in = in;
}
public void skip(long charPosition) throws IOException {
while (charPosition > 0) {
int n = in.read(buf, 0, Math.min((int) charPosition, buf.length));
if (n < 0) {
break;
}
previouslyRead += n;
charPosition -= n;
}
}
public boolean hasNext() {
if (limit == 0) {
fill();
}
return (pos < limit || indexAfterCompactionAndFilling(pos) < limit) && lookingAtCell();
}
public ArrayList<String> next() {
ArrayList<String> result = Lists.newArrayList();
boolean trailingComma;
boolean haveMoreData;
do {
// Invariant: pos < limit && lookingAtCell() from hasNext() or previous
// iteration
if (buf[pos] != '"') {
// trim the string tokens we pull from the CSV entries, since it's common to include
// leading an trailing spaces here
result.add(new String(buf, pos, cellLength).trim());
} else {
String cell = new String(buf, pos + 1, cellLength - 2);
result.add(ESCAPED_QUOTE_PATTERN.matcher(cell).replaceAll("\"").trim());
}
trailingComma = delimitedCellLength > 0 && buf[pos + delimitedCellLength - 1] == ',';
pos += delimitedCellLength;
delimitedCellLength = cellLength = -1;
int oldLimit = limit;
haveMoreData = pos < limit || indexAfterCompactionAndFilling(pos) < limit;
// If the CSV data ends with a trailing comma, haveMoreData will be false even though there
// is one (empty) cell remaining. The cell "appears" if a trailing carriage return is added
// to the input CSV. The following code handles this edge case by checking that we have no
// more data and if the last character in the buffer was a comma. If so, it appends the
// empty cell that would otherwise be dropped.
if (!haveMoreData && buf[oldLimit - 1] == ',') {
result.add("");
}
} while (trailingComma && haveMoreData && lookingAtCell());
return result;
}
public long getCharPosition() {
return previouslyRead + pos;
}
/**
* Compacts and fills the buffer. Returns the possibly shifted index for the
* given index.
*/
private int indexAfterCompactionAndFilling(int i) {
if (pos > 0) {
i = compact(i);
}
fill();
return i;
}
/**
* Moves the contents between {@code pos} and {@code limit} to the beginning
* of {@code buf}. Returns the new position of the given index.
*/
private int compact(int i) {
int oldPos = pos;
pos = 0;
int toMove = limit - oldPos;
if (toMove > 0) {
System.arraycopy(buf, oldPos, buf, 0, toMove);
}
limit -= oldPos;
previouslyRead += oldPos;
return i - oldPos;
}
/**
* Fills {@code buf} from the reader.
*/
private void fill() {
int toFill = buf.length - limit;
while (opened && toFill > 0) {
try {
int n = in.read(buf, limit, toFill);
if (n == -1) {
opened = false;
} else {
limit += n;
toFill -= n;
}
} catch (IOException e) {
lastException = e;
opened = false;
}
}
}
private boolean lookingAtCell() {
return (buf[pos] == '"' ? findUnescapedEndQuote(pos + 1) : findUnquotedCellEnd(pos));
}
private boolean findUnescapedEndQuote(int i) {
for (; i < limit || (i = indexAfterCompactionAndFilling(i)) < limit; i++) {
if (buf[i] == '"') {
i = checkedIndex(i + 1);
if (i == limit || buf[i] != '"') {
cellLength = i - pos;
return findDelimOrEnd(i);
}
}
}
lastException = new IllegalArgumentException("Syntax Error. unclosed quoted cell");
return false;
}
/**
* Determines that we are looking at the end of a cell, tolerating some
* whitespace. Called after consuming the end quote of a quoted cell.
*/
private boolean findDelimOrEnd(int i) {
for (; i < limit || (i = indexAfterCompactionAndFilling(i)) < limit; i++) {
switch (buf[i]) {
case ' ':
case '\t':
// whitespace after closing quote
continue;
case '\r':
// In standard CSV \r\n terminates a cell. However, Macintosh uses
// one \r instead of \n.
int j = checkedIndex(i + 1);
delimitedCellLength = (buf[j] == '\n' ? checkedIndex(j + 1) : j) - pos;
return true;
case ',':
case '\n':
delimitedCellLength = (checkedIndex(i + 1) - pos);
return true;
default:
lastException = new IOException(
"Syntax Error: non-whitespace between closing quote and delimiter or end");
return false;
}
}
delimitedCellLength = (limit - pos);
return true;
}
/**
* Returns the given index, after trying to read its corresponding buffered
* character. The resulting index will be shifted if compaction was
* triggered.
*/
private int checkedIndex(int i) {
return i < limit ? i : indexAfterCompactionAndFilling(i);
}
private boolean findUnquotedCellEnd(int i) {
for (; i < limit || (i = indexAfterCompactionAndFilling(i)) < limit; i++) {
switch (buf[i]) {
case ',':
case '\n':
cellLength = i - pos;
delimitedCellLength = cellLength + 1;
return true;
case '\r':
// In standard CSV \r\n terminates a cell. However, Macintosh uses
// one \r instead of \n.
cellLength = i - pos;
int j = checkedIndex(i + 1);
delimitedCellLength = (buf[j] == '\n' ? checkedIndex(j + 1) : j) - pos;
return true;
case '"':
lastException = new IllegalArgumentException("Syntax Error: quote in unquoted cell");
return false;
}
}
delimitedCellLength = cellLength = (limit - pos);
return true;
}
public void remove() {
throw new UnsupportedOperationException();
}
public void throwAnyProblem() throws Exception {
if (lastException != null) {
throw lastException;
}
}
}
}
|
9241d0f6931e7cc0d05ad78a530c875e2d80345c
| 434 |
java
|
Java
|
etc/squareRoot/SquareRoot.java
|
KoKumagai/exercises
|
256b226d3e094f9f67352d75619b392a168eb4d1
|
[
"MIT"
] | null | null | null |
etc/squareRoot/SquareRoot.java
|
KoKumagai/exercises
|
256b226d3e094f9f67352d75619b392a168eb4d1
|
[
"MIT"
] | null | null | null |
etc/squareRoot/SquareRoot.java
|
KoKumagai/exercises
|
256b226d3e094f9f67352d75619b392a168eb4d1
|
[
"MIT"
] | null | null | null | 16.074074 | 50 | 0.52765 | 1,002,047 |
public class SquareRoot {
private static double squareRoot(double num) {
double result = num / 2;
double last = 0;
while (result != last) {
last = result;
result = (result + num / result) / 2;
}
return result;
}
public static void main(String[] args) {
System.out.println(squareRoot(2));
System.out.println(squareRoot(4));
}
}
|
9241d16504ccdef5075ad8ccb89f1bb9221e13d5
| 12,118 |
java
|
Java
|
Notifellow/app/src/main/java/com/notifellow/su/notifellow/ExploreFragment.java
|
egealpay/Notifellow
|
947aff95423496c828de069f47886d8d9af767b7
|
[
"MIT"
] | null | null | null |
Notifellow/app/src/main/java/com/notifellow/su/notifellow/ExploreFragment.java
|
egealpay/Notifellow
|
947aff95423496c828de069f47886d8d9af767b7
|
[
"MIT"
] | null | null | null |
Notifellow/app/src/main/java/com/notifellow/su/notifellow/ExploreFragment.java
|
egealpay/Notifellow
|
947aff95423496c828de069f47886d8d9af767b7
|
[
"MIT"
] | 1 |
2018-11-21T11:01:35.000Z
|
2018-11-21T11:01:35.000Z
| 48.087302 | 147 | 0.486962 | 1,002,048 |
package com.notifellow.su.notifellow;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static android.content.Context.MODE_PRIVATE;
public class ExploreFragment extends Fragment {
ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
UsersAdapter adapter;
String[] nameSurname;
String[] username;
Uri[] userPicture;
private String lastQ;
private static RequestQueue MyRequestQueue;
private static SharedPreferences shared;
ArrayList<card_user> arrayList = new ArrayList<card_user>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
MyRequestQueue = Volley.newRequestQueue(getActivity());
shared = getActivity().getSharedPreferences("shared", MODE_PRIVATE);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_explore, container, false);
getActivity().setTitle(null);
setHasOptionsMenu(true);
listView = view.findViewById(R.id.listView);
arrayList.clear();
adapter = new UsersAdapter(this.getActivity(), arrayList);
listView.setAdapter(adapter);
//// SWIPE TO REFRESH ////
swipeRefreshLayout = view.findViewById(R.id.usersLayout);
swipeRefreshLayout.setColorSchemeResources(
R.color.refresh_progress_3,
R.color.refresh_progress_3,
R.color.refresh_progress_3); //CHANGE COLOR SCHEME
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
final String email = shared.getString("email", null);
StringRequest postRequest = new StringRequest(Request.Method.POST, "http://188.166.149.168:3030/searchDB",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
try {
arrayList.clear(); //Clear for new results
JSONArray jsonARR = new JSONArray(response);
for (int i = 0; i < jsonARR.length(); i++) {
JSONObject oneUser = jsonARR.getJSONObject(i);
String name = oneUser.getString("fullName");
String username = oneUser.getString("username");
String userEmail = oneUser.getString("email");
String ppDEST = oneUser.getString("ppDest");
String Status = oneUser.getString("status");
if (name.equals(""))
name = "-";
if (Status.equals("2"))
Status = "Friends With This User";
else if (Status.equals("0"))
Status = "Friend Request Sent!";
else if (Status.equals("1"))
Status = "Friend Request Has Been Received!";
else if (Status.equals("-1"))
Status = "You Can Add This User As A Friend.";
card_user user = new card_user(name, username, userEmail, Status, null);
arrayList.add(user);
}
adapter.notifyDataSetChanged(); // REFRESH THE LIST (I GUESS :P)
swipeRefreshLayout.setRefreshing(false); // STOP ANIMATION
} catch (JSONException e) {
Snackbar snackbar = Snackbar
.make(getActivity().findViewById(android.R.id.content), e.getMessage(), Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorGray));
snackbar.show();
swipeRefreshLayout.setRefreshing(false); // STOP ANIMATION
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Snackbar snackbar = Snackbar
.make(getActivity().findViewById(android.R.id.content), "Internet Connection Fail!", Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorGray));
snackbar.show();
swipeRefreshLayout.setRefreshing(false); // STOP ANIMATION
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("emailGiven", email); //Add the data you'd like to send to the server.
params.put("queryGiv", lastQ); //Add the data you'd like to send to the server.
return params;
}
};
MyRequestQueue.add(postRequest);
}
});
//// END OF SWIPE TO REFRESH ///
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(final String query) {
lastQ = query;
final String email = shared.getString("email", null);
StringRequest postRequest = new StringRequest(Request.Method.POST, "http://188.166.149.168:3030/searchDB",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
try {
arrayList.clear(); //Clear for new results
JSONArray jsonARR = new JSONArray(response);
for (int i = 0; i < jsonARR.length(); i++) {
JSONObject oneUser = jsonARR.getJSONObject(i);
String name = oneUser.getString("fullName");
String username = oneUser.getString("username");
String userEmail = oneUser.getString("email");
String ppDEST = oneUser.getString("ppDest");
String Status = oneUser.getString("status");
if (name.equals(""))
name = "-";
if (Status.equals("2"))
Status = "Friends With This User";
else if (Status.equals("0"))
Status = "Friend Request Sent!";
else if (Status.equals("1"))
Status = "Friend Request Has Been Received!";
else if (Status.equals("-1"))
Status = "You Can Add This User As A Friend.";
card_user user = new card_user(name, username, userEmail, Status, null);
arrayList.add(user);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
Snackbar snackbar = Snackbar
.make(getActivity().findViewById(android.R.id.content), e.getMessage(), Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorGray));
snackbar.show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
Snackbar snackbar = Snackbar
.make(getActivity().findViewById(android.R.id.content), "Internet Connection Fail!", Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorGray));
snackbar.show();
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("emailGiven", email); //Add the data you'd like to send to the server.
params.put("queryGiv", query); //Add the data you'd like to send to the server.
return params;
}
};
MyRequestQueue.add(postRequest);
Log.i("well", " this worked");
return false;
}
@Override
public boolean onQueryTextChange(String query) {
Log.i("well", " this worked");
return true;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case (R.id.action_search):
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
9241d2277f7752a9c40a3a7291bb6a5de051cd28
| 4,817 |
java
|
Java
|
src/main/java/net/markus/projects/rdfrpg/RectBinPack.java
|
mschroeder-github/rdf-rpg
|
425f3f8e1597d3edfd9877eb7fa77f0ed6deac61
|
[
"Apache-2.0"
] | 2 |
2019-06-14T18:17:30.000Z
|
2021-08-14T22:10:13.000Z
|
src/main/java/net/markus/projects/rdfrpg/RectBinPack.java
|
mschroeder-github/rdf-rpg
|
425f3f8e1597d3edfd9877eb7fa77f0ed6deac61
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/markus/projects/rdfrpg/RectBinPack.java
|
mschroeder-github/rdf-rpg
|
425f3f8e1597d3edfd9877eb7fa77f0ed6deac61
|
[
"Apache-2.0"
] | null | null | null | 26.322404 | 115 | 0.441354 | 1,002,049 |
package net.markus.projects.rdfrpg;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;
import javax.imageio.ImageIO;
/**
*
* @author Markus Schröder
*/
public class RectBinPack {
public static void main(String[] args) {
//random test data
Random rnd = new Random(1234);
List<Dimension> input = new LinkedList<>();
for(int i = 0; i < 100; i++) {
input.add(new Dimension(1 + rnd.nextInt(100), 1 + rnd.nextInt(100)));
}
Result<Dimension> result =
run(
input,
d -> d
);
//System.out.println(result.minD);
//System.out.println(result.as);
saveImage(result);
}
public static <T> void saveImage(Result<T> result) {
BufferedImage img = new BufferedImage(result.minD.width, result.minD.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
int c = 0;
List<Color> cs = Arrays.asList(Color.blue, Color.green, Color.gray, Color.orange, Color.red, Color.yellow);
for(A a : result.as) {
g.setColor(cs.get(c % cs.size()));
c++;
System.out.println(a.p + " " + a.d);
g.fillRect(a.p.x, a.p.y, a.d.width, a.d.height);
}
g.dispose();
try {
ImageIO.write(img, "png", new File("rectbintest.png"));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static <T> Result<T> run(List<T> l, Function<T, Dimension> f) {
//https://en.wikipedia.org/wiki/Bin_packing_problem
List<A<T>> as = new LinkedList<>();
for(T t : l) {
as.add(new A(t, f.apply(t)));
}
//first the largest areas
as.sort((o1, o2) -> {
return Integer.compare(o2.area(), o1.area());
});
Dimension minD = new Dimension();
Result<T> result = new Result<>();
while(!as.isEmpty()) {
A<T> a = as.get(0);
as.remove(a);
//place it
a.p = new Point(0,0);
//try to place it on a free place
boolean placed = false;
for(int y = 0; y < minD.height - a.d.height; y++) {
for(int x = 0; x < minD.width - a.d.width; x++) {
//move it
a.p.x = x;
a.p.y = y;
if(!intersects(a, result.as)) {
placed = true;
break;
}
}
if(placed)
break;
}
if(!placed) {
//have to extend the area
a.p = new Point(0,0);
if(minD.width < minD.height) {
//on the right
a.p.x = minD.width;
minD.height = Math.max(minD.height, a.d.height);
minD.width += a.d.width;
} else {
//on the bottom
a.p.y = minD.height;
minD.width = Math.max(minD.width, a.d.width);
minD.height += a.d.height;
}
}
//put placed point
result.as.add(a);
}
result.minD = minD;
return result;
}
private static <T> boolean intersects(A<T> a, List<A<T>> l) {
for(A other : l) {
if(new Rectangle(a.p, a.d).intersects(new Rectangle(other.p, other.d))) {
return true;
}
}
return false;
}
//class
public static class Result<T> {
Dimension minD;
List<A<T>> as;
public Result() {
as = new LinkedList<>();
}
}
public static class A<T> {
T t;
Point p;
Dimension d;
public A(T t, Dimension d) {
this.t = t;
this.d = d;
}
public int area() {
return d.width * d.height;
}
}
}
|
9241d4564dcbb702b580afe1c532cc75d3344e5d
| 1,364 |
java
|
Java
|
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/DatabaseImpl.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 1,350 |
2015-01-17T05:22:05.000Z
|
2022-03-29T21:00:37.000Z
|
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/DatabaseImpl.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 16,834 |
2015-01-07T02:19:09.000Z
|
2022-03-31T23:29:10.000Z
|
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/DatabaseImpl.java
|
Manny27nyc/azure-sdk-for-java
|
d8d70f14cfd509bca10aaf042f45b2f23b62cdc9
|
[
"MIT"
] | 1,586 |
2015-01-02T01:50:28.000Z
|
2022-03-31T11:25:34.000Z
| 27.836735 | 110 | 0.711144 | 1,002,050 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.synapse.implementation;
import com.azure.core.management.SystemData;
import com.azure.resourcemanager.synapse.fluent.models.DatabaseInner;
import com.azure.resourcemanager.synapse.models.Database;
public final class DatabaseImpl implements Database {
private DatabaseInner innerObject;
private final com.azure.resourcemanager.synapse.SynapseManager serviceManager;
DatabaseImpl(DatabaseInner innerObject, com.azure.resourcemanager.synapse.SynapseManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public String id() {
return this.innerModel().id();
}
public String name() {
return this.innerModel().name();
}
public String type() {
return this.innerModel().type();
}
public String location() {
return this.innerModel().location();
}
public SystemData systemData() {
return this.innerModel().systemData();
}
public DatabaseInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.synapse.SynapseManager manager() {
return this.serviceManager;
}
}
|
9241d50f3af8827385fda388e8a0c070a5945781
| 2,970 |
java
|
Java
|
app/src/main/java/com/openjfx/database/app/utils/DialogUtils.java
|
qqwarcraft/openjfx-database
|
c46a7c654681d80ca083d1ea8566642bb307ba76
|
[
"Apache-2.0"
] | 1 |
2020-05-10T02:02:53.000Z
|
2020-05-10T02:02:53.000Z
|
app/src/main/java/com/openjfx/database/app/utils/DialogUtils.java
|
qqwarcraft/openjfx-database
|
c46a7c654681d80ca083d1ea8566642bb307ba76
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/openjfx/database/app/utils/DialogUtils.java
|
qqwarcraft/openjfx-database
|
c46a7c654681d80ca083d1ea8566642bb307ba76
|
[
"Apache-2.0"
] | null | null | null | 29.117647 | 86 | 0.594276 | 1,002,051 |
package com.openjfx.database.app.utils;
import com.openjfx.database.app.enums.NotificationType;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.controlsfx.control.Notifications;
import org.controlsfx.dialog.ExceptionDialog;
import java.util.Optional;
/**
* 显示对话框
*
* @author yangkui
* @since 1.0
*/
public class DialogUtils {
private final static Logger LOGGER = LogManager.getLogger();
/**
* 显示错误对话框
*
* @param title 对话框顶部信息
* @param throwable 错误信息
*/
public static void showErrorDialog(Throwable throwable, String title) {
LOGGER.error(throwable.getMessage(), throwable);
Platform.runLater(() -> {
ExceptionDialog dialog = new ExceptionDialog(throwable);
dialog.setTitle(title);
dialog.setHeaderText("异常堆栈信息:");
dialog.setResizable(false);
dialog.getDialogPane().getStylesheets().add(AssetUtils.BASE_STYLE);
dialog.show();
});
}
/**
* 显示通知
*
* @param text 通知内容
* @param pos 通知显示位置
* @param type 通知类型
*/
public static void showNotification(String text, Pos pos, NotificationType type) {
Platform.runLater(() -> {
Notifications notifications = Notifications.create();
notifications.position(pos);
notifications.text(text);
switch (type) {
case ERROR:
notifications.showError();
break;
case WARNING:
notifications.showWarning();
break;
case INFORMATION:
notifications.showInformation();
break;
case CONFIRMATION:
notifications.showConfirm();
break;
default:
notifications.show();
}
});
}
/**
* 显示确认对话框
*
* @param message 消息内容
* @return 返回确认结果, 如果点击ok则返回true 否则返回false
* @apiNote 调用该方法得在Fx ui线程之中
*/
public static boolean showAlertConfirm(String message) {
var alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setContentText(message);
alert.getDialogPane().getStylesheets().add(AssetUtils.BASE_STYLE);
var optional = alert.showAndWait();
return optional.isPresent() && optional.get() == ButtonType.OK;
}
/**
* 显示对话框信息
*
* @param message 消息内容
*/
public static void showAlertInfo(String message) {
var alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("消息");
alert.setContentText(message);
alert.getDialogPane().getStylesheets().add(AssetUtils.BASE_STYLE);
alert.showAndWait();
}
}
|
9241d57ed75cb466ff92676d7d5af77252ee1339
| 715 |
java
|
Java
|
src/roulette/bets/OddEven.java
|
mym987/example_roulette
|
0ee3dc8cf5685afc6168da8937b5c809205a2c48
|
[
"MIT"
] | 2 |
2017-12-22T10:22:14.000Z
|
2021-06-15T15:23:36.000Z
|
src/roulette/bets/OddEven.java
|
mym987/example_roulette
|
0ee3dc8cf5685afc6168da8937b5c809205a2c48
|
[
"MIT"
] | 2 |
2015-01-30T21:12:35.000Z
|
2015-01-30T21:13:38.000Z
|
src/roulette/bets/OddEven.java
|
mym987/example_roulette
|
0ee3dc8cf5685afc6168da8937b5c809205a2c48
|
[
"MIT"
] | 69 |
2015-09-10T19:09:29.000Z
|
2018-01-18T09:23:59.000Z
| 21.666667 | 74 | 0.583217 | 1,002,052 |
package roulette.bets;
import roulette.Bet;
import roulette.Wheel;
import util.ConsoleReader;
public class OddEven extends Bet {
private String myChoice;
public OddEven (String description, int odds) {
super(description, odds);
myChoice = "";
}
/**
* @see Bet#place()
*/
@Override
public void place () {
myChoice = ConsoleReader.promptOneOf("Please bet", "even", "odd");
}
/**
* @see Bet#isMade(String, Wheel)
*/
@Override
public boolean isMade (Wheel.SpinResult wheel) {
return (wheel.getNumber() % 2 == 0 && myChoice.equals("even")) ||
(wheel.getNumber() % 2 == 1 && myChoice.equals("odd"));
}
}
|
9241d5840a74c934f23de93bbc7bd7efbea42d43
| 5,340 |
java
|
Java
|
tck/api/src/main/java/org/eclipse/microprofile/metrics/tck/metrics/MeteredClassBeanTest.java
|
JOpsDev/microprofile-metrics
|
9cc6e8af8ba6a236c05ab3a05dacfc294959cd4c
|
[
"Apache-2.0"
] | 88 |
2017-07-31T07:50:20.000Z
|
2022-03-06T08:47:26.000Z
|
tck/api/src/main/java/org/eclipse/microprofile/metrics/tck/metrics/MeteredClassBeanTest.java
|
JOpsDev/microprofile-metrics
|
9cc6e8af8ba6a236c05ab3a05dacfc294959cd4c
|
[
"Apache-2.0"
] | 526 |
2017-07-05T14:23:55.000Z
|
2022-02-04T20:24:29.000Z
|
tck/api/src/main/java/org/eclipse/microprofile/metrics/tck/metrics/MeteredClassBeanTest.java
|
JOpsDev/microprofile-metrics
|
9cc6e8af8ba6a236c05ab3a05dacfc294959cd4c
|
[
"Apache-2.0"
] | 65 |
2017-06-28T14:43:32.000Z
|
2022-02-27T01:46:32.000Z
| 39.345588 | 118 | 0.727528 | 1,002,053 |
/**
* Copyright © 2013 Antonin Stefanutti ([email protected])
*
* 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.eclipse.microprofile.metrics.tck.metrics;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.microprofile.metrics.Meter;
import org.eclipse.microprofile.metrics.Metric;
import org.eclipse.microprofile.metrics.MetricFilter;
import org.eclipse.microprofile.metrics.MetricID;
import org.eclipse.microprofile.metrics.MetricRegistry;
import org.eclipse.microprofile.metrics.tck.util.MetricsUtil;
import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
@RunWith(Arquillian.class)
public class MeteredClassBeanTest {
private static final String CONSTRUCTOR_NAME = "MeteredClassBean";
private static final String CONSTRUCTOR_METER_NAME =
MetricsUtil.absoluteMetricName(MeteredClassBean.class, "meteredClass", CONSTRUCTOR_NAME);
private static MetricID constructorMID;
private static final String[] METHOD_NAMES =
{"meteredMethodOne", "meteredMethodTwo", "meteredMethodProtected", "meteredMethodPackagedPrivate"};
private static final Set<String> METHOD_METER_NAMES =
MetricsUtil.absoluteMetricNames(MeteredClassBean.class, "meteredClass", METHOD_NAMES);
private static final MetricFilter METHOD_METERS = new MetricFilter() {
@Override
public boolean matches(MetricID metricID, Metric metric) {
return METHOD_METER_NAMES.contains(metricID.getName());
}
};
private static final Set<String> METER_NAMES =
MetricsUtil.absoluteMetricNames(MeteredClassBean.class, "meteredClass", METHOD_NAMES,
CONSTRUCTOR_NAME);
private static Set<MetricID> meterMIDs;
private final static AtomicLong METHOD_COUNT = new AtomicLong();
@Deployment
static Archive<?> createTestArchive() {
return ShrinkWrap.create(WebArchive.class)
// Test bean
.addClasses(MeteredClassBean.class, MetricsUtil.class)
// Bean archive deployment descriptor
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Before
public void instantiateTest() {
/*
* The MetricID relies on the MicroProfile Config API. Running a managed arquillian container will result with
* the MetricID being created in a client process that does not contain the MPConfig impl.
*
* This will cause client instantiated MetricIDs to throw an exception. (i.e the global MetricIDs)
*/
constructorMID = new MetricID(CONSTRUCTOR_METER_NAME);
meterMIDs = MetricsUtil.createMetricIDs(METER_NAMES);
}
@Inject
private MetricRegistry registry;
@Inject
private MeteredClassBean bean;
@Test
@InSequence(1)
public void meteredMethodsNotCalledYet() {
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(meterMIDs)));
// Make sure that the method meters haven't been marked yet
assertThat("Method meter counts are incorrect", registry.getMeters(METHOD_METERS).values(),
everyItem(Matchers.<Meter>hasProperty("count", equalTo(METHOD_COUNT.get()))));
}
@Test
@InSequence(2)
public void callMeteredMethodsOnce() {
assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(meterMIDs)));
// Call the metered methods and assert they've been marked
bean.meteredMethodOne();
bean.meteredMethodTwo();
// Let's call the non-public methods as well
bean.meteredMethodProtected();
bean.meteredMethodPackagedPrivate();
// Make sure that the method meters have been marked
assertThat("Method meter counts are incorrect", registry.getMeters(METHOD_METERS).values(),
everyItem(Matchers.<Meter>hasProperty("count", equalTo(METHOD_COUNT.incrementAndGet()))));
assertThat("Constructor's metric should be incremented at least once",
registry.getMeter(constructorMID).getCount(), is(greaterThanOrEqualTo(1L)));
}
}
|
9241d678c8a0c80d9986d6f77a4cbd80f392bed4
| 2,512 |
java
|
Java
|
src/main/java/org/pinae/mufasa/client/http/HttpClientRequest.java
|
PinaeOS/mufasa
|
7799a57bc39cd80d307d65b3e75e2608053b06ca
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/pinae/mufasa/client/http/HttpClientRequest.java
|
PinaeOS/mufasa
|
7799a57bc39cd80d307d65b3e75e2608053b06ca
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/pinae/mufasa/client/http/HttpClientRequest.java
|
PinaeOS/mufasa
|
7799a57bc39cd80d307d65b3e75e2608053b06ca
|
[
"Apache-2.0"
] | null | null | null | 18.202899 | 73 | 0.676354 | 1,002,054 |
package org.pinae.mufasa.client.http;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.TreeMap;
public class HttpClientRequest {
private boolean ssl;
private X509Certificate cert;
private int connectTimeout;
private int readTimeout;
private String url;
private String method;
private Map<String, String> headers = new TreeMap<String, String>();
private Map<String, String> parameters = new TreeMap<String, String>();
private String contentType;
private String charset;
private String content;
public HttpClientRequest(X509Certificate cert) {
this.cert = cert;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public X509Certificate getCert() {
return cert;
}
public void setCert(X509Certificate cert) {
this.cert = cert;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public void addHeader(String key, String value) {
this.headers.put(key, value);
}
public void addHeaders(Map<String, String> headers) {
this.headers.putAll(headers);
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public void addParameter(String key, String value) {
this.parameters.put(key, value);
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
9241dabc788a5e56f7f7bb1a3aff19b894ba1a8f
| 1,316 |
java
|
Java
|
services/identity/src/main/java/com/crapi/utils/UserData.java
|
csplrs/crAPI
|
9e7c6bfcb674a21045057296cdadf4300b6f2498
|
[
"Apache-2.0",
"0BSD"
] | 89 |
2021-02-09T16:30:26.000Z
|
2022-03-27T17:14:18.000Z
|
services/identity/src/main/java/com/crapi/utils/UserData.java
|
csplrs/crAPI
|
9e7c6bfcb674a21045057296cdadf4300b6f2498
|
[
"Apache-2.0",
"0BSD"
] | 12 |
2021-02-23T12:34:56.000Z
|
2022-03-12T07:54:47.000Z
|
services/identity/src/main/java/com/crapi/utils/UserData.java
|
csplrs/crAPI
|
9e7c6bfcb674a21045057296cdadf4300b6f2498
|
[
"Apache-2.0",
"0BSD"
] | 38 |
2021-02-10T07:11:00.000Z
|
2022-03-28T13:58:58.000Z
| 29.909091 | 75 | 0.716565 | 1,002,055 |
/*
* Copyright 2020 Traceable, Inc.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.crapi.utils;
import com.crapi.entity.User;
import com.crapi.entity.UserDetails;
import com.crapi.enums.ERole;
import com.crapi.enums.EStatus;
public class UserData {
public UserDetails getPredefineUser(String name, User loginForm){
UserDetails userDetails = null;
userDetails = getUserDetails(name, loginForm);
return userDetails;
}
public UserDetails getUserDetails(String name, User user){
UserDetails userDetails = new UserDetails();
userDetails.setName(name);
userDetails.setUser(user);
userDetails.setAvailable_credit(100.0);
userDetails.setStatus(EStatus.ACTIVE.toString());
return userDetails;
}
}
|
9241db161708355ba10e0398536ac64cc91c57d6
| 105,098 |
java
|
Java
|
src/com/facebook/buck/cli/Main.java
|
thelvis4/buck
|
dd55ad3373c1dc01d83bc3780dfc205a923c8088
|
[
"Apache-2.0"
] | 1 |
2021-06-14T22:35:29.000Z
|
2021-06-14T22:35:29.000Z
|
src/com/facebook/buck/cli/Main.java
|
brettwooldridge/buck
|
800a31272feed9c7c198c8414aaec276fd265a7b
|
[
"Apache-2.0"
] | null | null | null |
src/com/facebook/buck/cli/Main.java
|
brettwooldridge/buck
|
800a31272feed9c7c198c8414aaec276fd265a7b
|
[
"Apache-2.0"
] | null | null | null | 43.681629 | 119 | 0.677463 | 1,002,056 |
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import static com.facebook.buck.util.AnsiEnvironmentChecking.NAILGUN_STDERR_ISTTY_ENV;
import static com.facebook.buck.util.AnsiEnvironmentChecking.NAILGUN_STDOUT_ISTTY_ENV;
import static com.facebook.buck.util.string.MoreStrings.linesToText;
import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import com.facebook.buck.artifact_cache.ArtifactCaches;
import com.facebook.buck.artifact_cache.ClientCertificateHandler;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig.Executor;
import com.facebook.buck.cli.exceptions.handlers.ExceptionHandlerRegistryFactory;
import com.facebook.buck.core.build.engine.cache.manager.BuildInfoStoreManager;
import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.cell.CellName;
import com.facebook.buck.core.cell.InvalidCellOverrideException;
import com.facebook.buck.core.cell.impl.DefaultCellPathResolver;
import com.facebook.buck.core.cell.impl.LocalCellProviderFactory;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.exceptions.handler.HumanReadableExceptionAugmentor;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphCache;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphFactory;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphProvider;
import com.facebook.buck.core.module.BuckModuleManager;
import com.facebook.buck.core.module.impl.BuckModuleJarHashProvider;
import com.facebook.buck.core.module.impl.DefaultBuckModuleManager;
import com.facebook.buck.core.parser.buildtargetparser.BuildTargetParser;
import com.facebook.buck.core.parser.buildtargetparser.BuildTargetPatternParser;
import com.facebook.buck.core.plugin.impl.BuckPluginManagerFactory;
import com.facebook.buck.core.resources.ResourcesConfig;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.core.rules.config.ConfigurationRuleDescription;
import com.facebook.buck.core.rules.config.impl.PluginBasedKnownConfigurationDescriptionsFactory;
import com.facebook.buck.core.rules.knowntypes.DefaultKnownRuleTypesFactory;
import com.facebook.buck.core.rules.knowntypes.KnownRuleTypesFactory;
import com.facebook.buck.core.rules.knowntypes.KnownRuleTypesProvider;
import com.facebook.buck.core.toolchain.ToolchainProviderFactory;
import com.facebook.buck.core.toolchain.impl.DefaultToolchainProviderFactory;
import com.facebook.buck.core.util.immutables.BuckStyleTuple;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.counters.CounterRegistry;
import com.facebook.buck.counters.CounterRegistryImpl;
import com.facebook.buck.distributed.DistBuildConfig;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.event.BuckInitializationDurationEvent;
import com.facebook.buck.event.CacheStatsEvent;
import com.facebook.buck.event.CommandEvent;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.event.DaemonEvent;
import com.facebook.buck.event.DefaultBuckEventBus;
import com.facebook.buck.event.chrome_trace.ChromeTraceBuckConfig;
import com.facebook.buck.event.listener.AbstractConsoleEventBusListener;
import com.facebook.buck.event.listener.BuildTargetDurationListener;
import com.facebook.buck.event.listener.CacheRateStatsListener;
import com.facebook.buck.event.listener.ChromeTraceBuildListener;
import com.facebook.buck.event.listener.FileSerializationEventBusListener;
import com.facebook.buck.event.listener.JavaUtilsLoggingBuildListener;
import com.facebook.buck.event.listener.LoadBalancerEventsListener;
import com.facebook.buck.event.listener.LogUploaderListener;
import com.facebook.buck.event.listener.LoggingBuildListener;
import com.facebook.buck.event.listener.MachineReadableLoggerListener;
import com.facebook.buck.event.listener.ParserProfilerLoggerListener;
import com.facebook.buck.event.listener.ProgressEstimator;
import com.facebook.buck.event.listener.PublicAnnouncementManager;
import com.facebook.buck.event.listener.RenderingConsole;
import com.facebook.buck.event.listener.RuleKeyDiagnosticsListener;
import com.facebook.buck.event.listener.RuleKeyLoggerListener;
import com.facebook.buck.event.listener.SimpleConsoleEventBusListener;
import com.facebook.buck.event.listener.SuperConsoleConfig;
import com.facebook.buck.event.listener.SuperConsoleEventBusListener;
import com.facebook.buck.event.listener.devspeed.DevspeedTelemetryPlugin;
import com.facebook.buck.event.listener.interfaces.AdditionalConsoleLineProvider;
import com.facebook.buck.httpserver.WebServer;
import com.facebook.buck.io.AsynchronousDirectoryContentsCleaner;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.file.MostFiles;
import com.facebook.buck.io.filesystem.BuckPaths;
import com.facebook.buck.io.filesystem.ExactPathMatcher;
import com.facebook.buck.io.filesystem.FileExtensionMatcher;
import com.facebook.buck.io.filesystem.GlobPatternMatcher;
import com.facebook.buck.io.filesystem.PathMatcher;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.ProjectFilesystemFactory;
import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemFactory;
import com.facebook.buck.io.watchman.Watchman;
import com.facebook.buck.io.watchman.WatchmanDiagnosticEventListener;
import com.facebook.buck.io.watchman.WatchmanFactory;
import com.facebook.buck.io.watchman.WatchmanWatcher;
import com.facebook.buck.io.watchman.WatchmanWatcher.FreshInstanceAction;
import com.facebook.buck.io.watchman.WatchmanWatcherException;
import com.facebook.buck.jvm.java.JavaBuckConfig;
import com.facebook.buck.log.ConsoleHandlerState;
import com.facebook.buck.log.GlobalStateManager;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.log.LogConfig;
import com.facebook.buck.log.TraceInfoProvider;
import com.facebook.buck.manifestservice.ManifestService;
import com.facebook.buck.manifestservice.ManifestServiceConfig;
import com.facebook.buck.parser.DaemonicParserState;
import com.facebook.buck.parser.Parser;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.ParserFactory;
import com.facebook.buck.parser.ParserPythonInterpreterProvider;
import com.facebook.buck.parser.TargetSpecResolver;
import com.facebook.buck.remoteexecution.RemoteExecutionConsoleLineProvider;
import com.facebook.buck.remoteexecution.RemoteExecutionEventListener;
import com.facebook.buck.remoteexecution.config.RemoteExecutionConfig;
import com.facebook.buck.rules.coercer.DefaultConstructorArgMarshaller;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.rules.keys.RuleKeyCacheRecycler;
import com.facebook.buck.rules.keys.config.RuleKeyConfiguration;
import com.facebook.buck.rules.keys.config.impl.ConfigRuleKeyConfigurationFactory;
import com.facebook.buck.rules.modern.config.ModernBuildRuleBuildStrategy;
import com.facebook.buck.rules.modern.config.ModernBuildRuleConfig;
import com.facebook.buck.rules.modern.config.ModernBuildRuleStrategyConfig;
import com.facebook.buck.sandbox.SandboxExecutionStrategyFactory;
import com.facebook.buck.sandbox.impl.PlatformSandboxExecutionStrategyFactory;
import com.facebook.buck.step.ExecutorPool;
import com.facebook.buck.support.bgtasks.AsyncBackgroundTaskManager;
import com.facebook.buck.support.bgtasks.BackgroundTaskManager;
import com.facebook.buck.support.bgtasks.TaskManagerScope;
import com.facebook.buck.support.cli.args.BuckArgsMethods;
import com.facebook.buck.test.TestConfig;
import com.facebook.buck.test.TestResultSummaryVerbosity;
import com.facebook.buck.util.Ansi;
import com.facebook.buck.util.AnsiEnvironmentChecking;
import com.facebook.buck.util.BgProcessKiller;
import com.facebook.buck.util.CloseableMemoizedSupplier;
import com.facebook.buck.util.CloseableWrapper;
import com.facebook.buck.util.CommandLineException;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.ErrorLogger;
import com.facebook.buck.util.ErrorLogger.LogImpl;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.Libc;
import com.facebook.buck.util.PkillProcessManager;
import com.facebook.buck.util.PrintStreamProcessExecutorFactory;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessManager;
import com.facebook.buck.util.Scope;
import com.facebook.buck.util.ThrowingCloseableMemoizedSupplier;
import com.facebook.buck.util.ThrowingCloseableWrapper;
import com.facebook.buck.util.Verbosity;
import com.facebook.buck.util.cache.FileHashCache;
import com.facebook.buck.util.cache.InstrumentingCacheStatsTracker;
import com.facebook.buck.util.cache.ProjectFileHashCache;
import com.facebook.buck.util.cache.impl.DefaultFileHashCache;
import com.facebook.buck.util.cache.impl.StackedFileHashCache;
import com.facebook.buck.util.concurrent.CommandThreadFactory;
import com.facebook.buck.util.concurrent.CommonThreadFactoryState;
import com.facebook.buck.util.concurrent.MostExecutors;
import com.facebook.buck.util.config.Config;
import com.facebook.buck.util.config.Configs;
import com.facebook.buck.util.config.RawConfig;
import com.facebook.buck.util.environment.Architecture;
import com.facebook.buck.util.environment.BuildEnvironmentDescription;
import com.facebook.buck.util.environment.CommandMode;
import com.facebook.buck.util.environment.DefaultExecutionEnvironment;
import com.facebook.buck.util.environment.EnvVariablesProvider;
import com.facebook.buck.util.environment.ExecutionEnvironment;
import com.facebook.buck.util.environment.NetworkInfo;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.network.MacIpv6BugWorkaround;
import com.facebook.buck.util.network.RemoteLogBuckConfig;
import com.facebook.buck.util.perf.PerfStatsTracking;
import com.facebook.buck.util.perf.ProcessTracker;
import com.facebook.buck.util.shutdown.NonReentrantSystemExit;
import com.facebook.buck.util.timing.Clock;
import com.facebook.buck.util.timing.DefaultClock;
import com.facebook.buck.util.timing.NanosAdjustedClock;
import com.facebook.buck.util.versioncontrol.DelegatingVersionControlCmdLineInterface;
import com.facebook.buck.util.versioncontrol.VersionControlBuckConfig;
import com.facebook.buck.util.versioncontrol.VersionControlStatsGenerator;
import com.facebook.buck.versions.InstrumentedVersionedTargetGraphCache;
import com.facebook.buck.versions.VersionedTargetGraphCache;
import com.facebook.buck.worker.WorkerProcessPool;
import com.facebook.nailgun.NGClientDisconnectReason;
import com.facebook.nailgun.NGContext;
import com.facebook.nailgun.NGListeningAddress;
import com.facebook.nailgun.NGServer;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.eventbus.EventBus;
import com.google.common.reflect.ClassPath;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.sun.jna.LastErrorException;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.immutables.value.Value;
import org.kohsuke.args4j.CmdLineException;
import org.pf4j.PluginManager;
public final class Main {
/**
* Force JNA to be initialized early to avoid deadlock race condition.
*
* <p>
*
* <p>See: https://github.com/java-native-access/jna/issues/652
*/
public static final int JNA_POINTER_SIZE = Pointer.SIZE;
private static final Optional<String> BUCKD_LAUNCH_TIME_NANOS =
Optional.ofNullable(System.getProperty("buck.buckd_launch_time_nanos"));
private static final String BUCK_BUILD_ID_ENV_VAR = "BUCK_BUILD_ID";
private static final String BUCKD_COLOR_DEFAULT_ENV_VAR = "BUCKD_COLOR_DEFAULT";
private static final Duration DAEMON_SLAYER_TIMEOUT = Duration.ofDays(1);
private static final Duration HANG_DETECTOR_TIMEOUT = Duration.ofMinutes(5);
/** Path to a directory of static content that should be served by the {@link WebServer}. */
private static final int DISK_IO_STATS_TIMEOUT_SECONDS = 10;
private static final int EXECUTOR_SERVICES_TIMEOUT_SECONDS = 60;
private static final int EVENT_BUS_TIMEOUT_SECONDS = 15;
private static final int COUNTER_AGGREGATOR_SERVICE_TIMEOUT_SECONDS = 20;
private final InputStream stdIn;
private final PrintStream stdOut;
private final PrintStream stdErr;
private final Architecture architecture;
private static final Semaphore commandSemaphore = new Semaphore(1);
private static AtomicReference<ImmutableList<String>> activeCommandArgs = new AtomicReference<>();
private static volatile Optional<NGContext> commandSemaphoreNgClient = Optional.empty();
private static final DaemonLifecycleManager daemonLifecycleManager = new DaemonLifecycleManager();
// Ensure we only have one instance of this, so multiple trash cleaning
// operations are serialized on one queue.
private static final AsynchronousDirectoryContentsCleaner TRASH_CLEANER =
new AsynchronousDirectoryContentsCleaner();
private final Platform platform;
private Console console;
private Optional<NGContext> context;
// Ignore changes to generated Xcode project files and editors' backup files
// so we don't dump buckd caches on every command.
private static final ImmutableSet<PathMatcher> DEFAULT_IGNORE_GLOBS =
ImmutableSet.of(
FileExtensionMatcher.of("pbxproj"),
FileExtensionMatcher.of("xcscheme"),
FileExtensionMatcher.of("xcworkspacedata"),
// Various editors' temporary files
GlobPatternMatcher.of("**/*~"),
// Emacs
GlobPatternMatcher.of("**/#*#"),
GlobPatternMatcher.of("**/.#*"),
// Vim
FileExtensionMatcher.of("swo"),
FileExtensionMatcher.of("swp"),
FileExtensionMatcher.of("swpx"),
FileExtensionMatcher.of("un~"),
FileExtensionMatcher.of("netrhwist"),
// Eclipse
ExactPathMatcher.of(".idea"),
ExactPathMatcher.of(".iml"),
FileExtensionMatcher.of("pydevproject"),
ExactPathMatcher.of(".project"),
ExactPathMatcher.of(".metadata"),
FileExtensionMatcher.of("tmp"),
FileExtensionMatcher.of("bak"),
FileExtensionMatcher.of("nib"),
ExactPathMatcher.of(".classpath"),
ExactPathMatcher.of(".settings"),
ExactPathMatcher.of(".loadpath"),
ExactPathMatcher.of(".externalToolBuilders"),
ExactPathMatcher.of(".cproject"),
ExactPathMatcher.of(".buildpath"),
// Mac OS temp files
ExactPathMatcher.of(".DS_Store"),
ExactPathMatcher.of(".AppleDouble"),
ExactPathMatcher.of(".LSOverride"),
ExactPathMatcher.of(".Spotlight-V100"),
ExactPathMatcher.of(".Trashes"),
// Windows
ExactPathMatcher.of("$RECYCLE.BIN"),
// Sublime
FileExtensionMatcher.of("sublime-workspace"));
private static final Logger LOG = Logger.get(Main.class);
private static boolean isSessionLeader;
private static PluginManager pluginManager;
private static BuckModuleManager moduleManager;
@Nullable private static FileLock resourcesFileLock = null;
private static final HangMonitor.AutoStartInstance HANG_MONITOR =
new HangMonitor.AutoStartInstance(
(input) -> {
LOG.info(
"No recent activity, dumping thread stacks (`tr , '\\n'` to decode): %s", input);
},
HANG_DETECTOR_TIMEOUT);
private static final NonReentrantSystemExit NON_REENTRANT_SYSTEM_EXIT =
new NonReentrantSystemExit();
public interface KnownRuleTypesFactoryFactory {
KnownRuleTypesFactory create(
ProcessExecutor executor,
PluginManager pluginManager,
SandboxExecutionStrategyFactory sandboxExecutionStrategyFactory,
ImmutableList<ConfigurationRuleDescription<?>> knownConfigurationDescriptions);
}
private final KnownRuleTypesFactoryFactory knownRuleTypesFactoryFactory;
private Optional<BuckConfig> parsedRootConfig = Optional.empty();
static {
MacIpv6BugWorkaround.apply();
}
/**
* This constructor allows integration tests to add/remove/modify known build rules (aka
* descriptions).
*/
@VisibleForTesting
public Main(
PrintStream stdOut,
PrintStream stdErr,
InputStream stdIn,
KnownRuleTypesFactoryFactory knownRuleTypesFactoryFactory,
Optional<NGContext> context) {
this.stdOut = stdOut;
this.stdErr = stdErr;
this.stdIn = stdIn;
this.knownRuleTypesFactoryFactory = knownRuleTypesFactoryFactory;
this.architecture = Architecture.detect();
this.platform = Platform.detect();
this.context = context;
// Create default console to start outputting errors immediately, if any
// console may be overridden with custom console later once we have enough information to
// construct it
this.console =
new Console(
Verbosity.STANDARD_INFORMATION,
stdOut,
stdErr,
new Ansi(
AnsiEnvironmentChecking.environmentSupportsAnsiEscapes(
platform, getClientEnvironment(context))));
}
@VisibleForTesting
public Main(
PrintStream stdOut, PrintStream stdErr, InputStream stdIn, Optional<NGContext> context) {
this(stdOut, stdErr, stdIn, DefaultKnownRuleTypesFactory::new, context);
}
/* Define all error handling surrounding main command */
private void runMainThenExit(String[] args, long initTimestamp) {
ExitCode exitCode = ExitCode.SUCCESS;
try {
installUncaughtExceptionHandler(context);
Path projectRoot = Paths.get(".");
BuildId buildId = getBuildId(context);
// Only post an overflow event if Watchman indicates a fresh instance event
// after our initial query.
WatchmanWatcher.FreshInstanceAction watchmanFreshInstanceAction =
daemonLifecycleManager.hasDaemon()
? WatchmanWatcher.FreshInstanceAction.POST_OVERFLOW_EVENT
: WatchmanWatcher.FreshInstanceAction.NONE;
// Get the client environment, either from this process or from the Nailgun context.
ImmutableMap<String, String> clientEnvironment = getClientEnvironment(context);
CommandMode commandMode = CommandMode.RELEASE;
exitCode =
runMainWithExitCode(
buildId,
projectRoot,
clientEnvironment,
commandMode,
watchmanFreshInstanceAction,
initTimestamp,
ImmutableList.copyOf(args));
} catch (Throwable t) {
HumanReadableExceptionAugmentor augmentor;
try {
augmentor =
new HumanReadableExceptionAugmentor(
parsedRootConfig
.map(BuckConfig::getErrorMessageAugmentations)
.orElse(ImmutableMap.of()));
} catch (HumanReadableException e) {
console.printErrorText(e.getHumanReadableErrorMessage());
augmentor = new HumanReadableExceptionAugmentor(ImmutableMap.of());
}
ErrorLogger logger =
new ErrorLogger(
new LogImpl() {
@Override
public void logUserVisible(String message) {
console.printFailure(message);
}
@Override
public void logUserVisibleInternalError(String message) {
console.printFailure(linesToText("Buck encountered an internal error", message));
}
@Override
public void logVerbose(Throwable e) {
String message = "Command failed:";
if (e instanceof InterruptedException
|| e instanceof ClosedByInterruptException) {
message = "Command was interrupted:";
}
LOG.warn(e, message);
}
},
augmentor);
logger.logException(t);
exitCode = ExceptionHandlerRegistryFactory.create().handleException(t);
} finally {
LOG.debug("Done.");
LogConfig.flushLogs();
// Exit explicitly so that non-daemon threads (of which we use many) don't
// keep the VM alive.
System.exit(exitCode.getCode());
}
}
private void setupLogging(
CommandMode commandMode, BuckCommand command, ImmutableList<String> args) throws IOException {
// Setup logging.
if (commandMode.isLoggingEnabled()) {
// Reset logging each time we run a command while daemonized.
// This will cause us to write a new log per command.
LOG.debug("Rotating log.");
LogConfig.flushLogs();
LogConfig.setupLogging(command.getLogConfig());
if (LOG.isDebugEnabled()) {
Long gitCommitTimestamp = Long.getLong("buck.git_commit_timestamp");
String buildDateStr;
if (gitCommitTimestamp == null) {
buildDateStr = "(unknown)";
} else {
buildDateStr =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US)
.format(new Date(TimeUnit.SECONDS.toMillis(gitCommitTimestamp)));
}
String buildRev = System.getProperty("buck.git_commit", "(unknown)");
LOG.debug("Starting up (build date %s, rev %s), args: %s", buildDateStr, buildRev, args);
LOG.debug("System properties: %s", System.getProperties());
}
}
}
private ImmutableMap<CellName, Path> getCellMapping(Path canonicalRootPath) throws IOException {
return DefaultCellPathResolver.bootstrapPathMapping(
canonicalRootPath, Configs.createDefaultConfig(canonicalRootPath));
}
private Config setupDefaultConfig(ImmutableMap<CellName, Path> cellMapping, BuckCommand command)
throws IOException {
Path rootPath = cellMapping.get(CellName.ROOT_CELL_NAME);
Objects.requireNonNull(rootPath, "Root cell should be implicitly added");
RawConfig rootCellConfigOverrides;
try {
ImmutableMap<Path, RawConfig> overridesByPath =
command.getConfigOverrides(cellMapping).getOverridesByPath(cellMapping);
rootCellConfigOverrides =
Optional.ofNullable(overridesByPath.get(rootPath)).orElse(RawConfig.of());
} catch (InvalidCellOverrideException exception) {
rootCellConfigOverrides =
command.getConfigOverrides(cellMapping).getForCell(CellName.ROOT_CELL_NAME);
}
return Configs.createDefaultConfig(rootPath, rootCellConfigOverrides);
}
private ImmutableSet<Path> getProjectWatchList(
Path canonicalRootPath, BuckConfig buckConfig, DefaultCellPathResolver cellPathResolver) {
return ImmutableSet.<Path>builder()
.add(canonicalRootPath)
.addAll(
buckConfig.getView(ParserConfig.class).getWatchCells()
? cellPathResolver.getPathMapping().values()
: ImmutableList.of())
.build();
}
private void checkJavaSpecificationVersions(BuckConfig buckConfig) {
Optional<ImmutableList<String>> allowedJavaSpecificationVersions =
buckConfig.getAllowedJavaSpecificationVersions();
if (allowedJavaSpecificationVersions.isPresent()) {
String specificationVersion = System.getProperty("java.specification.version");
boolean javaSpecificationVersionIsAllowed =
allowedJavaSpecificationVersions.get().contains(specificationVersion);
if (!javaSpecificationVersionIsAllowed) {
throw new HumanReadableException(
"Current Java version '%s' is not in the allowed java specification versions:\n%s",
specificationVersion, Joiner.on(", ").join(allowedJavaSpecificationVersions.get()));
}
}
}
/**
* @param buildId an identifier for this command execution.
* @param initTimestamp Value of System.nanoTime() when process got main()/nailMain() invoked.
* @param unexpandedCommandLineArgs command line arguments
* @return an ExitCode representing the result of the command
*/
@SuppressWarnings("PMD.PrematureDeclaration")
public ExitCode runMainWithExitCode(
BuildId buildId,
Path projectRoot,
ImmutableMap<String, String> clientEnvironment,
CommandMode commandMode,
WatchmanWatcher.FreshInstanceAction watchmanFreshInstanceAction,
long initTimestamp,
ImmutableList<String> unexpandedCommandLineArgs)
throws Exception {
// Set initial exitCode value to FATAL. This will eventually get reassigned unless an exception
// happens
ExitCode exitCode = ExitCode.FATAL_GENERIC;
// Setup filesystem and buck config.
Path canonicalRootPath = projectRoot.toRealPath().normalize();
ImmutableMap<CellName, Path> rootCellMapping = getCellMapping(canonicalRootPath);
ImmutableList<String> args =
BuckArgsMethods.expandAtFiles(unexpandedCommandLineArgs, rootCellMapping);
if (moduleManager == null) {
pluginManager = BuckPluginManagerFactory.createPluginManager();
moduleManager = new DefaultBuckModuleManager(pluginManager, new BuckModuleJarHashProvider());
}
// Parse command line arguments
BuckCommand command = new BuckCommand();
command.setPluginManager(pluginManager);
// Parse the command line args.
AdditionalOptionsCmdLineParser cmdLineParser =
new AdditionalOptionsCmdLineParser(pluginManager, command);
try {
cmdLineParser.parseArgument(args);
} catch (CmdLineException e) {
throw new CommandLineException(e, e.getLocalizedMessage() + "\nFor help see 'buck --help'.");
}
// Return help strings fast if the command is a help request.
Optional<ExitCode> result = command.runHelp(stdOut);
if (result.isPresent()) {
return result.get();
}
// If this command is not read only, acquire the command semaphore to become the only executing
// read/write command. Early out will also help to not rotate log on each BUSY status which
// happens in setupLogging().
ImmutableList.Builder<String> previousCommandArgsBuilder = new ImmutableList.Builder<>();
try (CloseableWrapper<Semaphore> semaphore =
getSemaphoreWrapper(command, unexpandedCommandLineArgs, previousCommandArgsBuilder)) {
if (!command.isReadOnly() && semaphore == null) {
// buck_tool will set BUCK_BUSY_DISPLAYED if it already displayed the busy error
if (!clientEnvironment.containsKey("BUCK_BUSY_DISPLAYED")) {
String activeCommandLine = "buck " + String.join(" ", previousCommandArgsBuilder.build());
if (activeCommandLine.length() > 80) {
activeCommandLine = activeCommandLine.substring(0, 76) + "...";
}
System.err.println(
String.format("Buck Daemon is busy executing '%s'.", activeCommandLine));
LOG.warn(
"Buck server was busy executing '%s'. Maybe retrying later will help.",
activeCommandLine);
}
return ExitCode.BUSY;
}
// statically configure Buck logging environment based on Buck config, usually buck-x.log
// files
setupLogging(commandMode, command, args);
Config config = setupDefaultConfig(rootCellMapping, command);
ProjectFilesystemFactory projectFilesystemFactory = new DefaultProjectFilesystemFactory();
ProjectFilesystem filesystem =
projectFilesystemFactory.createProjectFilesystem(canonicalRootPath, config);
DefaultCellPathResolver cellPathResolver =
DefaultCellPathResolver.of(filesystem.getRootPath(), config);
BuckConfig buckConfig =
new BuckConfig(
config,
filesystem,
architecture,
platform,
clientEnvironment,
target ->
BuildTargetParser.INSTANCE.parse(
target, BuildTargetPatternParser.fullyQualified(), cellPathResolver));
// Set so that we can use some settings when we print out messages to users
parsedRootConfig = Optional.of(buckConfig);
warnAboutConfigFileOverrides(filesystem.getRootPath(), buckConfig, console);
ImmutableSet<Path> projectWatchList =
getProjectWatchList(canonicalRootPath, buckConfig, cellPathResolver);
checkJavaSpecificationVersions(buckConfig);
Verbosity verbosity = VerbosityParser.parse(args);
// Setup the console.
console = makeCustomConsole(context, verbosity, buckConfig);
DistBuildConfig distBuildConfig = new DistBuildConfig(buckConfig);
boolean isUsingDistributedBuild = false;
ExecutionEnvironment executionEnvironment =
new DefaultExecutionEnvironment(clientEnvironment, System.getProperties());
// Automatically use distributed build for supported repositories and users.
if (command.subcommand instanceof BuildCommand) {
BuildCommand subcommand = (BuildCommand) command.subcommand;
isUsingDistributedBuild = subcommand.isUsingDistributedBuild();
if (!isUsingDistributedBuild
&& (distBuildConfig.shouldUseDistributedBuild(
buildId, executionEnvironment.getUsername(), subcommand.getArguments()))) {
isUsingDistributedBuild = subcommand.tryConvertingToStampede(distBuildConfig);
}
}
// Switch to async file logging, if configured. A few log samples will have already gone
// via the regular file logger, but that's OK.
boolean isDistBuildCommand = command.subcommand instanceof DistBuildCommand;
if (isDistBuildCommand) {
LogConfig.setUseAsyncFileLogging(distBuildConfig.isAsyncLoggingEnabled());
}
RuleKeyConfiguration ruleKeyConfiguration =
ConfigRuleKeyConfigurationFactory.create(buckConfig, moduleManager);
String previousBuckCoreKey;
if (!command.isReadOnly()) {
Optional<String> currentBuckCoreKey =
filesystem.readFileIfItExists(filesystem.getBuckPaths().getCurrentVersionFile());
BuckPaths unconfiguredPaths =
filesystem.getBuckPaths().withConfiguredBuckOut(filesystem.getBuckPaths().getBuckOut());
previousBuckCoreKey = currentBuckCoreKey.orElse("<NOT_FOUND>");
if (!currentBuckCoreKey.isPresent()
|| !currentBuckCoreKey.get().equals(ruleKeyConfiguration.getCoreKey())
|| (filesystem.exists(unconfiguredPaths.getGenDir(), LinkOption.NOFOLLOW_LINKS)
&& (filesystem.isSymLink(unconfiguredPaths.getGenDir())
^ buckConfig.getBuckOutCompatLink()))) {
// Migrate any version-dependent directories (which might be huge) to a trash directory
// so we can delete it asynchronously after the command is done.
moveToTrash(
filesystem,
console,
buildId,
filesystem.getBuckPaths().getAnnotationDir(),
filesystem.getBuckPaths().getGenDir(),
filesystem.getBuckPaths().getScratchDir(),
filesystem.getBuckPaths().getResDir());
filesystem.mkdirs(filesystem.getBuckPaths().getCurrentVersionFile().getParent());
filesystem.writeContentsToPath(
ruleKeyConfiguration.getCoreKey(), filesystem.getBuckPaths().getCurrentVersionFile());
}
} else {
previousBuckCoreKey = "";
}
LOG.verbose("Buck core key from the previous Buck instance: %s", previousBuckCoreKey);
ProcessExecutor processExecutor = new DefaultProcessExecutor(console);
SandboxExecutionStrategyFactory sandboxExecutionStrategyFactory =
new PlatformSandboxExecutionStrategyFactory();
Clock clock;
boolean enableThreadCpuTime =
buckConfig.getBooleanValue("build", "enable_thread_cpu_time", true);
if (BUCKD_LAUNCH_TIME_NANOS.isPresent()) {
long nanosEpoch = Long.parseLong(BUCKD_LAUNCH_TIME_NANOS.get(), 10);
LOG.verbose("Using nanos epoch: %d", nanosEpoch);
clock = new NanosAdjustedClock(nanosEpoch, enableThreadCpuTime);
} else {
clock = new DefaultClock(enableThreadCpuTime);
}
ParserConfig parserConfig = buckConfig.getView(ParserConfig.class);
Watchman watchman =
buildWatchman(context, parserConfig, projectWatchList, clientEnvironment, console, clock);
ImmutableList<ConfigurationRuleDescription<?>> knownConfigurationDescriptions =
PluginBasedKnownConfigurationDescriptionsFactory.createFromPlugins(pluginManager);
KnownRuleTypesProvider knownRuleTypesProvider =
new KnownRuleTypesProvider(
knownRuleTypesFactoryFactory.create(
processExecutor,
pluginManager,
sandboxExecutionStrategyFactory,
knownConfigurationDescriptions));
ExecutableFinder executableFinder = new ExecutableFinder();
ToolchainProviderFactory toolchainProviderFactory =
new DefaultToolchainProviderFactory(
pluginManager, clientEnvironment, processExecutor, executableFinder);
DefaultCellPathResolver rootCellCellPathResolver =
DefaultCellPathResolver.of(filesystem.getRootPath(), buckConfig.getConfig());
Cell rootCell =
LocalCellProviderFactory.create(
filesystem,
buckConfig,
command.getConfigOverrides(rootCellMapping),
rootCellCellPathResolver.getPathMapping(),
rootCellCellPathResolver,
moduleManager,
toolchainProviderFactory,
projectFilesystemFactory)
.getCellByPath(filesystem.getRootPath());
Optional<Daemon> daemon = Optional.empty();
if (context.isPresent() && (watchman != WatchmanFactory.NULL_WATCHMAN)) {
List<DevspeedTelemetryPlugin> telemetryPlugins =
pluginManager.getExtensions(DevspeedTelemetryPlugin.class);
daemon =
Optional.of(
daemonLifecycleManager.getDaemon(
rootCell,
knownRuleTypesProvider,
watchman,
console,
clock,
telemetryPlugins.isEmpty()
? Optional::empty
: () ->
telemetryPlugins
.get(0)
.newBuildListenerFactoryForDaemon(
rootCell.getFilesystem(), System.getProperties())));
}
if (!daemon.isPresent()) {
// Clean up the trash on a background thread if this was a
// non-buckd read-write command. (We don't bother waiting
// for it to complete; the thread is a daemon thread which
// will just be terminated at shutdown time.)
TRASH_CLEANER.startCleaningDirectory(filesystem.getBuckPaths().getTrashDir());
}
BackgroundTaskManager bgTaskManager;
boolean blocking = rootCell.getBuckConfig().getFlushEventsBeforeExit();
if (!blocking && !daemon.isPresent()) {
LOG.warn(
"Manager cannot be async (as currently set in config) when not on daemon. Initializing blocking manager.");
}
bgTaskManager =
daemon.map((d) -> d.getBgTaskManager()).orElse(new AsyncBackgroundTaskManager(true));
TaskManagerScope managerScope = bgTaskManager.getNewScope(buildId);
ImmutableList<BuckEventListener> eventListeners = ImmutableList.of();
ImmutableList.Builder<ProjectFileHashCache> allCaches = ImmutableList.builder();
// Build up the hash cache, which is a collection of the stateful cell cache and some
// per-run caches.
//
// TODO(coneko, ruibm, agallagher): Determine whether we can use the existing filesystem
// object that is in scope instead of creating a new rootCellProjectFilesystem. The primary
// difference appears to be that filesystem is created with a Config that is used to produce
// ImmutableSet<PathMatcher> and BuckPaths for the ProjectFilesystem, whereas this one
// uses the defaults.
ProjectFilesystem rootCellProjectFilesystem =
projectFilesystemFactory.createOrThrow(rootCell.getFilesystem().getRootPath());
if (daemon.isPresent()) {
allCaches.addAll(getFileHashCachesFromDaemon(daemon.get()));
} else {
rootCell
.getAllCells()
.stream()
.map(
cell ->
DefaultFileHashCache.createDefaultFileHashCache(
cell.getFilesystem(), rootCell.getBuckConfig().getFileHashCacheMode()))
.forEach(allCaches::add);
// The Daemon caches a buck-out filehashcache for the root cell, so the non-daemon case
// needs to create that itself.
allCaches.add(
DefaultFileHashCache.createBuckOutFileHashCache(
rootCell.getFilesystem(), rootCell.getBuckConfig().getFileHashCacheMode()));
}
rootCell
.getAllCells()
.forEach(
cell -> {
if (!cell.equals(rootCell)) {
allCaches.add(
DefaultFileHashCache.createBuckOutFileHashCache(
cell.getFilesystem(), rootCell.getBuckConfig().getFileHashCacheMode()));
}
});
// A cache which caches hashes of cell-relative paths which may have been ignore by
// the main cell cache, and only serves to prevent rehashing the same file multiple
// times in a single run.
allCaches.add(
DefaultFileHashCache.createDefaultFileHashCache(
rootCellProjectFilesystem, rootCell.getBuckConfig().getFileHashCacheMode()));
allCaches.addAll(
DefaultFileHashCache.createOsRootDirectoriesCaches(
projectFilesystemFactory, rootCell.getBuckConfig().getFileHashCacheMode()));
StackedFileHashCache fileHashCache = new StackedFileHashCache(allCaches.build());
Optional<WebServer> webServer = daemon.flatMap(Daemon::getWebServer);
Optional<ConcurrentMap<String, WorkerProcessPool>> persistentWorkerPools =
daemon.map(Daemon::getPersistentWorkerPools);
TestConfig testConfig = new TestConfig(buckConfig);
ArtifactCacheBuckConfig cacheBuckConfig = new ArtifactCacheBuckConfig(buckConfig);
SuperConsoleConfig superConsoleConfig = new SuperConsoleConfig(buckConfig);
// Eventually, we'll want to get allow websocket and/or nailgun clients to specify locale
// when connecting. For now, we'll use the default from the server environment.
Locale locale = Locale.getDefault();
InvocationInfo invocationInfo =
InvocationInfo.of(
buildId,
superConsoleConfig.isEnabled(console.getAnsi(), console.getVerbosity()),
daemon.isPresent(),
command.getSubCommandNameForLogging(),
args,
unexpandedCommandLineArgs,
filesystem.getBuckPaths().getLogDir());
RemoteExecutionConfig remoteExecutionConfig = buckConfig.getView(RemoteExecutionConfig.class);
Optional<RemoteExecutionEventListener> remoteExecutionListener =
remoteExecutionConfig.isSuperConsoleEnabled()
? Optional.of(new RemoteExecutionEventListener())
: Optional.empty();
try (GlobalStateManager.LoggerIsMappedToThreadScope loggerThreadMappingScope =
GlobalStateManager.singleton()
.setupLoggers(invocationInfo, console.getStdErr(), stdErr, verbosity);
DefaultBuckEventBus buildEventBus = new DefaultBuckEventBus(clock, buildId);
ThrowingCloseableMemoizedSupplier<ManifestService, IOException> manifestServiceSupplier =
ThrowingCloseableMemoizedSupplier.of(
() -> {
ManifestServiceConfig manifestServiceConfig =
new ManifestServiceConfig(buckConfig);
return manifestServiceConfig.createManifestService(
clock, buildEventBus, newDirectExecutorService());
},
ManifestService::close);
) {
CommonThreadFactoryState commonThreadFactoryState =
GlobalStateManager.singleton().getThreadToCommandRegister();
try (ThrowingCloseableWrapper<ExecutorService, InterruptedException> diskIoExecutorService =
getExecutorWrapper(
MostExecutors.newSingleThreadExecutor("Disk I/O"),
"Disk IO",
DISK_IO_STATS_TIMEOUT_SECONDS);
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
httpWriteExecutorService =
getExecutorWrapper(
getHttpWriteExecutorService(cacheBuckConfig, isUsingDistributedBuild),
"HTTP Write",
cacheBuckConfig.getHttpWriterShutdownTimeout());
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
stampedeSyncBuildHttpFetchExecutorService =
getExecutorWrapper(
getHttpFetchExecutorService(
"heavy", cacheBuckConfig.getDownloadHeavyBuildHttpFetchConcurrency()),
"Download Heavy Build HTTP Read",
cacheBuckConfig.getHttpWriterShutdownTimeout());
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
httpFetchExecutorService =
getExecutorWrapper(
getHttpFetchExecutorService(
"standard", cacheBuckConfig.getHttpFetchConcurrency()),
"HTTP Read",
cacheBuckConfig.getHttpWriterShutdownTimeout());
ThrowingCloseableWrapper<ScheduledExecutorService, InterruptedException>
counterAggregatorExecutor =
getExecutorWrapper(
Executors.newSingleThreadScheduledExecutor(
new CommandThreadFactory(
"CounterAggregatorThread", commonThreadFactoryState)),
"CounterAggregatorExecutor",
COUNTER_AGGREGATOR_SERVICE_TIMEOUT_SECONDS);
ThrowingCloseableWrapper<ScheduledExecutorService, InterruptedException>
scheduledExecutorPool =
getExecutorWrapper(
Executors.newScheduledThreadPool(
buckConfig.getNumThreadsForSchedulerPool(),
new CommandThreadFactory(
getClass().getName() + "SchedulerThreadPool",
commonThreadFactoryState)),
"ScheduledExecutorService",
EXECUTOR_SERVICES_TIMEOUT_SECONDS);
// Create a cached thread pool for cpu intensive tasks
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
cpuExecutorService =
getExecutorWrapper(
listeningDecorator(Executors.newCachedThreadPool()),
ExecutorPool.CPU.toString(),
EXECUTOR_SERVICES_TIMEOUT_SECONDS);
// Create a thread pool for network I/O tasks
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
networkExecutorService =
getExecutorWrapper(
newDirectExecutorService(),
ExecutorPool.NETWORK.toString(),
EXECUTOR_SERVICES_TIMEOUT_SECONDS);
ThrowingCloseableWrapper<ListeningExecutorService, InterruptedException>
projectExecutorService =
getExecutorWrapper(
listeningDecorator(
MostExecutors.newMultiThreadExecutor(
"Project", buckConfig.getNumThreads())),
ExecutorPool.PROJECT.toString(),
EXECUTOR_SERVICES_TIMEOUT_SECONDS);
BuildInfoStoreManager storeManager = new BuildInfoStoreManager();
AbstractConsoleEventBusListener consoleListener =
createConsoleEventListener(
clock,
superConsoleConfig,
console,
testConfig.getResultSummaryVerbosity(),
executionEnvironment,
locale,
filesystem.getBuckPaths().getLogDir().resolve("test.log"),
buildId,
buckConfig.isLogBuildIdToConsoleEnabled(),
buckConfig.getBuildDetailsTemplate(),
createAdditionalConsoleLinesProviders(
remoteExecutionListener, remoteExecutionConfig));
// This makes calls to LOG.error(...) post to the EventBus, instead of writing to
// stderr.
Closeable logErrorToEventBus =
loggerThreadMappingScope.setWriter(createWriterForConsole(consoleListener));
Scope ddmLibLogRedirector = DdmLibLogRedirector.redirectDdmLogger(buildEventBus);
// NOTE: This will only run during the lifetime of the process and will flush on close.
CounterRegistry counterRegistry =
new CounterRegistryImpl(
counterAggregatorExecutor.get(),
buildEventBus,
buckConfig.getCountersFirstFlushIntervalMillis(),
buckConfig.getCountersFlushIntervalMillis());
PerfStatsTracking perfStatsTracking =
new PerfStatsTracking(buildEventBus, invocationInfo);
ProcessTracker processTracker =
buckConfig.isProcessTrackerEnabled() && platform != Platform.WINDOWS
? new ProcessTracker(
buildEventBus,
invocationInfo,
daemon.isPresent(),
buckConfig.isProcessTrackerDeepEnabled())
: null;
ArtifactCaches artifactCacheFactory =
new ArtifactCaches(
cacheBuckConfig,
buildEventBus,
filesystem,
executionEnvironment.getWifiSsid(),
httpWriteExecutorService.get(),
httpFetchExecutorService.get(),
stampedeSyncBuildHttpFetchExecutorService.get(),
getDirCacheStoreExecutor(cacheBuckConfig, diskIoExecutorService),
managerScope,
getArtifactProducerId(executionEnvironment),
executionEnvironment.getHostname(),
ClientCertificateHandler.fromConfiguration(cacheBuckConfig));
// Once command completes it should be safe to not wait for executors and other stateful
// objects to terminate and release semaphore right away. It will help to retry
// command faster if user terminated with Ctrl+C.
// Ideally, we should come up with a better lifecycle management strategy for the
// semaphore object
CloseableWrapper<Optional<CloseableWrapper<Semaphore>>> semaphoreCloser =
CloseableWrapper.of(
Optional.ofNullable(semaphore),
s -> {
if (s.isPresent()) {
s.get().close();
}
});
// This will get executed first once it gets out of try block and just wait for
// event bus to dispatch all pending events before we proceed to termination
// procedures
CloseableWrapper<BuckEventBus> waitEvents = getWaitEventsWrapper(buildEventBus)) {
LOG.debug(invocationInfo.toLogLine());
buildEventBus.register(HANG_MONITOR.getHangMonitor());
ImmutableMap<ExecutorPool, ListeningExecutorService> executors =
ImmutableMap.of(
ExecutorPool.CPU,
cpuExecutorService.get(),
ExecutorPool.NETWORK,
networkExecutorService.get(),
ExecutorPool.PROJECT,
projectExecutorService.get());
// No need to kick off ProgressEstimator for commands that
// don't build anything -- it has overhead and doesn't seem
// to work for (e.g.) query anyway. ProgressEstimator has
// special support for project so we have to include it
// there too.
if (consoleListener.displaysEstimatedProgress()
&& (command.performsBuild() || command.subcommand instanceof ProjectCommand)) {
ProgressEstimator progressEstimator =
new ProgressEstimator(
filesystem
.resolve(filesystem.getBuckPaths().getBuckOut())
.resolve(ProgressEstimator.PROGRESS_ESTIMATIONS_JSON),
buildEventBus);
consoleListener.setProgressEstimator(progressEstimator);
}
BuildEnvironmentDescription buildEnvironmentDescription =
getBuildEnvironmentDescription(
executionEnvironment,
buckConfig);
Iterable<BuckEventListener> commandEventListeners =
command.getSubcommand().isPresent()
? command
.getSubcommand()
.get()
.getEventListeners(executors, scheduledExecutorPool.get())
: ImmutableList.of();
Optional<TraceInfoProvider> traceInfoProvider = Optional.empty();
if (isRemoteExecutionBuild(command, buckConfig)) {
List<BuckEventListener> remoteExecutionsListeners = Lists.newArrayList();
if (remoteExecutionListener.isPresent()) {
remoteExecutionsListeners.add(remoteExecutionListener.get());
}
commandEventListeners =
new ImmutableList.Builder<BuckEventListener>()
.addAll(commandEventListeners)
.addAll(remoteExecutionsListeners)
.build();
}
eventListeners =
addEventListeners(
daemon.flatMap(Daemon::getDevspeedDaemonListener),
buildEventBus,
daemon.map(d -> d.getFileEventBus()),
rootCell.getFilesystem(),
invocationInfo,
rootCell.getBuckConfig(),
webServer,
clock,
counterRegistry,
commandEventListeners,
managerScope);
buildEventBus.register(consoleListener);
if (buckConfig.isBuckConfigLocalWarningEnabled() && !console.getVerbosity().isSilent()) {
ImmutableList<Path> localConfigFiles =
rootCell
.getAllCells()
.stream()
.map(
cell ->
cell.getRoot().resolve(Configs.DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME))
.filter(path -> Files.isRegularFile(path))
.collect(ImmutableList.toImmutableList());
if (localConfigFiles.size() > 0) {
String message =
localConfigFiles.size() == 1
? "Using local configuration:"
: "Using local configurations:";
buildEventBus.post(ConsoleEvent.warning(message));
for (Path localConfigFile : localConfigFiles) {
buildEventBus.post(ConsoleEvent.warning(String.format("- %s", localConfigFile)));
}
}
}
if (commandMode == CommandMode.RELEASE && buckConfig.isPublicAnnouncementsEnabled()) {
PublicAnnouncementManager announcementManager =
new PublicAnnouncementManager(
clock,
buildEventBus,
consoleListener,
buckConfig.getRepository().orElse("unknown"),
new RemoteLogBuckConfig(buckConfig),
executors.get(ExecutorPool.CPU));
announcementManager.getAndPostAnnouncements();
}
// This needs to be after the registration of the event listener so they can pick it up.
if (watchmanFreshInstanceAction == WatchmanWatcher.FreshInstanceAction.NONE) {
LOG.debug("new Buck daemon");
buildEventBus.post(DaemonEvent.newDaemonInstance());
}
VersionControlBuckConfig vcBuckConfig = new VersionControlBuckConfig(buckConfig);
VersionControlStatsGenerator vcStatsGenerator =
new VersionControlStatsGenerator(
new DelegatingVersionControlCmdLineInterface(
rootCell.getFilesystem().getRootPath(),
new PrintStreamProcessExecutorFactory(),
vcBuckConfig.getHgCmd(),
buckConfig.getEnvironment()),
vcBuckConfig.getPregeneratedVersionControlStats());
if (vcBuckConfig.shouldGenerateStatistics()
&& command.subcommand instanceof AbstractCommand
&& !(command.subcommand instanceof DistBuildCommand)) {
AbstractCommand subcommand = (AbstractCommand) command.subcommand;
if (!commandMode.equals(CommandMode.TEST)) {
vcStatsGenerator.generateStatsAsync(
subcommand.isSourceControlStatsGatheringEnabled(),
diskIoExecutorService.get(),
buildEventBus);
}
}
NetworkInfo.generateActiveNetworkAsync(diskIoExecutorService.get(), buildEventBus);
ImmutableList<String> remainingArgs =
args.isEmpty() ? ImmutableList.of() : args.subList(1, args.size());
CommandEvent.Started startedEvent =
CommandEvent.started(
command.getDeclaredSubCommandName(),
remainingArgs,
daemon.isPresent()
? OptionalLong.of(daemon.get().getUptime())
: OptionalLong.empty(),
getBuckPID());
buildEventBus.post(startedEvent);
CloseableMemoizedSupplier<ForkJoinPool> forkJoinPoolSupplier =
getForkJoinPoolSupplier(buckConfig);
ParserAndCaches parserAndCaches =
getParserAndCaches(
context,
watchmanFreshInstanceAction,
filesystem,
buckConfig,
watchman,
knownRuleTypesProvider,
rootCell,
command::getTargetPlatforms,
daemon,
buildEventBus,
forkJoinPoolSupplier,
ruleKeyConfiguration,
executableFinder,
manifestServiceSupplier,
fileHashCache);
// Because the Parser is potentially constructed before the CounterRegistry,
// we need to manually register its counters after it's created.
//
// The counters will be unregistered once the counter registry is closed.
counterRegistry.registerCounters(
parserAndCaches.getParser().getPermState().getCounters());
Optional<ProcessManager> processManager;
if (platform == Platform.WINDOWS) {
processManager = Optional.empty();
} else {
processManager = Optional.of(new PkillProcessManager(processExecutor));
}
// At this point, we have parsed options but haven't started
// running the command yet. This is a good opportunity to
// augment the event bus with our serialize-to-file
// event-listener.
if (command.subcommand instanceof AbstractCommand) {
AbstractCommand subcommand = (AbstractCommand) command.subcommand;
Optional<Path> eventsOutputPath = subcommand.getEventsOutputPath();
if (eventsOutputPath.isPresent()) {
BuckEventListener listener =
new FileSerializationEventBusListener(eventsOutputPath.get());
buildEventBus.register(listener);
}
}
buildEventBus.post(
new BuckInitializationDurationEvent(
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - initTimestamp)));
try {
exitCode =
command.run(
CommandRunnerParams.of(
console,
stdIn,
rootCell,
watchman,
parserAndCaches.getVersionedTargetGraphCache(),
artifactCacheFactory,
parserAndCaches.getTypeCoercerFactory(),
parserAndCaches.getParser(),
buildEventBus,
platform,
clientEnvironment,
rootCell
.getBuckConfig()
.getView(JavaBuckConfig.class)
.createDefaultJavaPackageFinder(),
clock,
vcStatsGenerator,
processManager,
webServer,
persistentWorkerPools,
buckConfig,
fileHashCache,
executors,
scheduledExecutorPool.get(),
buildEnvironmentDescription,
parserAndCaches.getActionGraphProvider(),
knownRuleTypesProvider,
storeManager,
Optional.of(invocationInfo),
parserAndCaches.getDefaultRuleKeyFactoryCacheRecycler(),
projectFilesystemFactory,
ruleKeyConfiguration,
processExecutor,
executableFinder,
pluginManager,
moduleManager,
forkJoinPoolSupplier,
traceInfoProvider,
manifestServiceSupplier));
} catch (InterruptedException | ClosedByInterruptException e) {
buildEventBus.post(CommandEvent.interrupted(startedEvent, ExitCode.SIGNAL_INTERRUPT));
throw e;
} finally {
buildEventBus.post(CommandEvent.finished(startedEvent, exitCode));
buildEventBus.post(
new CacheStatsEvent(
"versioned_target_graph_cache",
parserAndCaches.getVersionedTargetGraphCache().getCacheStats()));
}
} finally {
// signal nailgun that we are not interested in client disconnect events anymore
context.ifPresent(c -> c.removeAllClientListeners());
if (daemon.isPresent()) {
// Clean up the trash in the background if this was a buckd
// read-write command. (We don't bother waiting for it to
// complete; the cleaner will ensure subsequent cleans are
// serialized with this one.)
TRASH_CLEANER.startCleaningDirectory(filesystem.getBuckPaths().getTrashDir());
}
// Exit Nailgun earlier if command succeeded to now block the client while performing
// telemetry upload in background
// For failures, always do it synchronously because exitCode in fact may be overridden up
// the stack
// TODO(buck_team): refactor this as in case of exception exitCode is reported incorrectly
// to the CommandEvent listener
if (exitCode == ExitCode.SUCCESS
&& context.isPresent()
&& !rootCell.getBuckConfig().getFlushEventsBeforeExit()) {
context.get().in.close(); // Avoid client exit triggering client disconnection handling.
context.get().exit(exitCode.getCode());
}
// TODO(buck_team): refactor eventListeners for RAII
flushAndCloseEventListeners(console, eventListeners);
managerScope.close();
}
}
}
return exitCode;
}
private void warnAboutConfigFileOverrides(Path root, BuckConfig config, Console console)
throws IOException {
if (!config.getWarnOnConfigFileOverrides()) {
return;
}
if (!console.getVerbosity().shouldPrintStandardInformation()) {
return;
}
// Useful for filtering out things like system wide buckconfigs in /etc that might be managed
// by the system. We don't want to warn users about files that they have not necessarily
// created.
ImmutableSet<Path> overridesToIgnore = config.getWarnOnConfigFileOverridesIgnoredFiles();
Path mainConfigPath = Configs.getMainConfigurationFile(root);
ImmutableSortedSet<Path> userSpecifiedOverrides =
Configs.getDefaultConfigurationFiles(root)
.stream()
.filter(
path ->
!overridesToIgnore.contains(path.getFileName()) && !mainConfigPath.equals(path))
.map(path -> path.startsWith(root) ? root.relativize(path) : path)
.collect(ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder()));
if (userSpecifiedOverrides.isEmpty()) {
return;
}
// Use the raw stream because otherwise this will stop superconsole from ever printing again
console
.getStdErr()
.getRawStream()
.println(
console
.getAnsi()
.asWarningText(
String.format(
"Using additional configuration options from %s",
Joiner.on(", ").join(userSpecifiedOverrides))));
}
private ListeningExecutorService getDirCacheStoreExecutor(
ArtifactCacheBuckConfig cacheBuckConfig,
ThrowingCloseableWrapper<ExecutorService, InterruptedException> diskIoExecutorService) {
Executor dirCacheStoreExecutor = cacheBuckConfig.getDirCacheStoreExecutor();
switch (dirCacheStoreExecutor) {
case DISK_IO:
return listeningDecorator(diskIoExecutorService.get());
case DIRECT:
return newDirectExecutorService();
default:
throw new IllegalStateException(
"Executor service for " + dirCacheStoreExecutor + " is not configured.");
}
}
private boolean isRemoteExecutionBuild(BuckCommand command, BuckConfig config) {
if (!command.getSubcommand().isPresent()
|| !(command.getSubcommand().get() instanceof BuildCommand)) {
return false;
}
ModernBuildRuleStrategyConfig strategyConfig =
config.getView(ModernBuildRuleConfig.class).getDefaultStrategyConfig();
while (strategyConfig.getBuildStrategy() == ModernBuildRuleBuildStrategy.HYBRID_LOCAL) {
strategyConfig = strategyConfig.getHybridLocalConfig().getDelegateConfig();
}
return strategyConfig.getBuildStrategy() == ModernBuildRuleBuildStrategy.REMOTE;
}
private ImmutableList<AdditionalConsoleLineProvider> createAdditionalConsoleLinesProviders(
Optional<RemoteExecutionEventListener> remoteExecutionListener,
RemoteExecutionConfig remoteExecutionConfig) {
if (!remoteExecutionListener.isPresent() || !remoteExecutionConfig.isSuperConsoleEnabled()) {
return ImmutableList.of();
}
return ImmutableList.of(new RemoteExecutionConsoleLineProvider(remoteExecutionListener.get()));
}
/** Struct for the multiple values returned by {@link #getParserAndCaches}. */
@Value.Immutable(copy = false, builder = false)
@BuckStyleTuple
abstract static class AbstractParserAndCaches {
public abstract Parser getParser();
public abstract TypeCoercerFactory getTypeCoercerFactory();
public abstract InstrumentedVersionedTargetGraphCache getVersionedTargetGraphCache();
public abstract ActionGraphProvider getActionGraphProvider();
public abstract Optional<RuleKeyCacheRecycler<RuleKey>> getDefaultRuleKeyFactoryCacheRecycler();
}
private static ParserAndCaches getParserAndCaches(
Optional<NGContext> context,
FreshInstanceAction watchmanFreshInstanceAction,
ProjectFilesystem filesystem,
BuckConfig buckConfig,
Watchman watchman,
KnownRuleTypesProvider knownRuleTypesProvider,
Cell rootCell,
Supplier<ImmutableList<String>> targetPlatforms,
Optional<Daemon> daemonOptional,
BuckEventBus buildEventBus,
CloseableMemoizedSupplier<ForkJoinPool> forkJoinPoolSupplier,
RuleKeyConfiguration ruleKeyConfiguration,
ExecutableFinder executableFinder,
ThrowingCloseableMemoizedSupplier<ManifestService, IOException> manifestServiceSupplier,
FileHashCache fileHashCache)
throws IOException, InterruptedException {
WatchmanWatcher watchmanWatcher = null;
if (daemonOptional.isPresent() && watchman.getTransportPath().isPresent()) {
Daemon daemon = daemonOptional.get();
try {
watchmanWatcher =
new WatchmanWatcher(
watchman,
daemon.getFileEventBus(),
ImmutableSet.<PathMatcher>builder()
.addAll(filesystem.getIgnorePaths())
.addAll(DEFAULT_IGNORE_GLOBS)
.build(),
daemon.getWatchmanCursor(),
buckConfig.getNumThreads());
} catch (WatchmanWatcherException e) {
buildEventBus.post(
ConsoleEvent.warning(
"Watchman threw an exception while parsing file changes.\n%s", e.getMessage()));
}
}
ParserConfig parserConfig = rootCell.getBuckConfig().getView(ParserConfig.class);
// Create or get Parser and invalidate cached command parameters.
ParserAndCaches parserAndCaches;
if (watchmanWatcher != null) {
// Note that watchmanWatcher is non-null only when daemon.isPresent().
Daemon daemon = daemonOptional.get();
registerClientDisconnectedListener(context.get(), daemon);
daemon.watchFileSystem(buildEventBus, watchmanWatcher, watchmanFreshInstanceAction);
Optional<RuleKeyCacheRecycler<RuleKey>> defaultRuleKeyFactoryCacheRecycler;
if (buckConfig.getRuleKeyCaching()) {
LOG.debug("Using rule key calculation caching");
defaultRuleKeyFactoryCacheRecycler =
Optional.of(daemon.getDefaultRuleKeyFactoryCacheRecycler());
} else {
defaultRuleKeyFactoryCacheRecycler = Optional.empty();
}
TypeCoercerFactory typeCoercerFactory = daemon.getTypeCoercerFactory();
Parser parser =
ParserFactory.create(
typeCoercerFactory,
new DefaultConstructorArgMarshaller(typeCoercerFactory),
knownRuleTypesProvider,
new ParserPythonInterpreterProvider(parserConfig, executableFinder),
rootCell.getBuckConfig(),
daemon.getDaemonicParserState(),
new TargetSpecResolver(),
watchman,
buildEventBus,
targetPlatforms,
manifestServiceSupplier,
fileHashCache);
daemon.getFileEventBus().register(daemon.getDaemonicParserState());
parserAndCaches =
ParserAndCaches.of(
parser,
daemon.getTypeCoercerFactory(),
new InstrumentedVersionedTargetGraphCache(
daemon.getVersionedTargetGraphCache(), new InstrumentingCacheStatsTracker()),
new ActionGraphProvider(
buildEventBus,
ActionGraphFactory.create(
buildEventBus, rootCell.getCellProvider(), forkJoinPoolSupplier, buckConfig),
daemon.getActionGraphCache(),
ruleKeyConfiguration,
buckConfig),
defaultRuleKeyFactoryCacheRecycler);
} else {
TypeCoercerFactory typeCoercerFactory = new DefaultTypeCoercerFactory();
parserAndCaches =
ParserAndCaches.of(
ParserFactory.create(
typeCoercerFactory,
new DefaultConstructorArgMarshaller(typeCoercerFactory),
knownRuleTypesProvider,
new ParserPythonInterpreterProvider(parserConfig, executableFinder),
rootCell.getBuckConfig(),
new DaemonicParserState(parserConfig.getNumParsingThreads()),
new TargetSpecResolver(),
watchman,
buildEventBus,
targetPlatforms,
manifestServiceSupplier,
fileHashCache),
typeCoercerFactory,
new InstrumentedVersionedTargetGraphCache(
new VersionedTargetGraphCache(), new InstrumentingCacheStatsTracker()),
new ActionGraphProvider(
buildEventBus,
ActionGraphFactory.create(
buildEventBus, rootCell.getCellProvider(), forkJoinPoolSupplier, buckConfig),
new ActionGraphCache(buckConfig.getMaxActionGraphCacheEntries()),
ruleKeyConfiguration,
buckConfig),
/* defaultRuleKeyFactoryCacheRecycler */ Optional.empty());
}
return parserAndCaches;
}
private static void registerClientDisconnectedListener(NGContext context, Daemon daemon) {
Thread mainThread = Thread.currentThread();
context.addClientListener(
reason -> {
LOG.info("Nailgun client disconnected with " + reason);
if (Main.isSessionLeader && Main.commandSemaphoreNgClient.orElse(null) == context) {
// Process no longer wants work done on its behalf.
LOG.debug("Killing background processes on client disconnect");
BgProcessKiller.interruptBgProcesses();
}
if (reason != NGClientDisconnectReason.SESSION_SHUTDOWN) {
LOG.debug("Killing all Buck jobs on client disconnect by interrupting the main thread");
// signal daemon to complete required tasks and interrupt main thread
// this will hopefully trigger InterruptedException and program shutdown
daemon.interruptOnClientExit(mainThread);
}
});
}
private Console makeCustomConsole(
Optional<NGContext> context, Verbosity verbosity, BuckConfig buckConfig) {
Optional<String> color;
if (context.isPresent() && (context.get().getEnv() != null)) {
String colorString = context.get().getEnv().getProperty(BUCKD_COLOR_DEFAULT_ENV_VAR);
color = Optional.ofNullable(colorString);
} else {
color = Optional.empty();
}
return new Console(
verbosity, stdOut, stdErr, buckConfig.getView(CliConfig.class).createAnsi(color));
}
private void flushAndCloseEventListeners(
Console console, ImmutableList<BuckEventListener> eventListeners) throws IOException {
for (BuckEventListener eventListener : eventListeners) {
try {
eventListener.close();
} catch (RuntimeException e) {
PrintStream stdErr = console.getStdErr();
stdErr.println("Ignoring non-fatal error! The stack trace is below:");
e.printStackTrace(stdErr);
}
}
}
private static void moveToTrash(
ProjectFilesystem filesystem, Console console, BuildId buildId, Path... pathsToMove)
throws IOException {
Path trashPath = filesystem.getBuckPaths().getTrashDir().resolve(buildId.toString());
filesystem.mkdirs(trashPath);
for (Path pathToMove : pathsToMove) {
try {
// Technically this might throw AtomicMoveNotSupportedException,
// but we're moving a path within buck-out, so we don't expect this
// to throw.
//
// If it does throw, we'll complain loudly and synchronously delete
// the file instead.
filesystem.move(
pathToMove,
trashPath.resolve(pathToMove.getFileName()),
StandardCopyOption.ATOMIC_MOVE);
} catch (NoSuchFileException e) {
LOG.verbose(e, "Ignoring missing path %s", pathToMove);
} catch (AtomicMoveNotSupportedException e) {
console
.getStdErr()
.format("Atomic moves not supported, falling back to synchronous delete: %s", e);
MostFiles.deleteRecursivelyIfExists(pathToMove);
}
}
}
private static final Watchman buildWatchman(
Optional<NGContext> context,
ParserConfig parserConfig,
ImmutableSet<Path> projectWatchList,
ImmutableMap<String, String> clientEnvironment,
Console console,
Clock clock)
throws InterruptedException {
Watchman watchman;
if (context.isPresent() || parserConfig.getGlobHandler() == ParserConfig.GlobHandler.WATCHMAN) {
WatchmanFactory watchmanFactory = new WatchmanFactory();
watchman =
watchmanFactory.build(
projectWatchList,
clientEnvironment,
console,
clock,
parserConfig.getWatchmanQueryTimeoutMs());
LOG.debug(
"Watchman capabilities: %s Project watches: %s Glob handler config: %s "
+ "Query timeout ms config: %s",
watchman.getCapabilities(),
watchman.getProjectWatches(),
parserConfig.getGlobHandler(),
parserConfig.getWatchmanQueryTimeoutMs());
} else {
watchman = WatchmanFactory.NULL_WATCHMAN;
LOG.debug(
"Not using Watchman, context present: %s, glob handler: %s",
context.isPresent(), parserConfig.getGlobHandler());
}
return watchman;
}
/**
* RAII wrapper which does not really close any object but waits for all events in given event bus
* to complete. We want to have it this way to safely start deinitializing event listeners
*/
private static CloseableWrapper<BuckEventBus> getWaitEventsWrapper(BuckEventBus buildEventBus) {
return CloseableWrapper.of(
buildEventBus,
eventBus -> {
// wait for event bus to process all pending events
if (!eventBus.waitEvents(EVENT_BUS_TIMEOUT_SECONDS * 1000)) {
LOG.warn(
"Event bus did not complete all events within timeout; event listener's data"
+ "may be incorrect");
}
});
}
private static <T extends ExecutorService>
ThrowingCloseableWrapper<T, InterruptedException> getExecutorWrapper(
T executor, String executorName, long closeTimeoutSeconds) {
return ThrowingCloseableWrapper.of(
executor,
service -> {
executor.shutdown();
LOG.info(
"Awaiting termination of %s executor service. Waiting for all jobs to complete, "
+ "or up to maximum of %s seconds...",
executorName, closeTimeoutSeconds);
executor.awaitTermination(closeTimeoutSeconds, TimeUnit.SECONDS);
if (!executor.isTerminated()) {
LOG.warn(
"%s executor service is still running after shutdown request and "
+ "%s second timeout. Shutting down forcefully..",
executorName, closeTimeoutSeconds);
executor.shutdownNow();
} else {
LOG.info("Successfully terminated %s executor service.", executorName);
}
});
}
private static ListeningExecutorService getHttpWriteExecutorService(
ArtifactCacheBuckConfig buckConfig, boolean isUsingDistributedBuild) {
if (isUsingDistributedBuild || buckConfig.hasAtLeastOneWriteableRemoteCache()) {
// Distributed builds need to upload from the local cache to the remote cache.
ExecutorService executorService =
MostExecutors.newMultiThreadExecutor(
"HTTP Write", buckConfig.getHttpMaxConcurrentWrites());
return listeningDecorator(executorService);
} else {
return newDirectExecutorService();
}
}
private static ListeningExecutorService getHttpFetchExecutorService(
String prefix, int fetchConcurrency) {
return listeningDecorator(
MostExecutors.newMultiThreadExecutor(
new ThreadFactoryBuilder().setNameFormat(prefix + "-cache-fetch-%d").build(),
fetchConcurrency));
}
private static ConsoleHandlerState.Writer createWriterForConsole(
AbstractConsoleEventBusListener console) {
return new ConsoleHandlerState.Writer() {
@Override
public void write(String line) {
console.printSevereWarningDirectly(line);
}
@Override
public void flush() {
// Intentional no-op.
}
@Override
public void close() {
// Intentional no-op.
}
};
}
/**
* @return the client environment, which is either the process environment or the environment sent
* to the daemon by the Nailgun client. This method should always be used in preference to
* System.getenv() and should be the only call to System.getenv() within the Buck codebase to
* ensure that the use of the Buck daemon is transparent. This also scrubs NG environment
* variables if no context is actually present.
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // Safe as Property is a Map<String, String>.
private static ImmutableMap<String, String> getClientEnvironment(Optional<NGContext> context) {
if (context.isPresent()) {
return ImmutableMap.<String, String>copyOf((Map) context.get().getEnv());
} else {
ImmutableMap<String, String> systemEnv = EnvVariablesProvider.getSystemEnv();
ImmutableMap.Builder<String, String> builder =
ImmutableMap.builderWithExpectedSize(systemEnv.size());
systemEnv
.entrySet()
.stream()
.filter(
e ->
!NAILGUN_STDOUT_ISTTY_ENV.equals(e.getKey())
&& !NAILGUN_STDERR_ISTTY_ENV.equals(e.getKey()))
.forEach(builder::put);
return builder.build();
}
}
private ImmutableList<ProjectFileHashCache> getFileHashCachesFromDaemon(Daemon daemon) {
return daemon.getFileHashCaches();
}
private void loadListenersFromBuckConfig(
ImmutableList.Builder<BuckEventListener> eventListeners,
ProjectFilesystem projectFilesystem,
BuckConfig config) {
ImmutableSet<String> paths = config.getListenerJars();
if (paths.isEmpty()) {
return;
}
URL[] urlsArray = new URL[paths.size()];
try {
int i = 0;
for (String path : paths) {
String urlString = "file://" + projectFilesystem.resolve(Paths.get(path));
urlsArray[i] = new URL(urlString);
i++;
}
} catch (MalformedURLException e) {
throw new HumanReadableException(e.getMessage());
}
// This ClassLoader is disconnected to allow searching the JARs (and just the JARs) for classes.
ClassLoader isolatedClassLoader = URLClassLoader.newInstance(urlsArray, null);
ImmutableSet<ClassPath.ClassInfo> classInfos;
try {
ClassPath classPath = ClassPath.from(isolatedClassLoader);
classInfos = classPath.getTopLevelClasses();
} catch (IOException e) {
throw new HumanReadableException(e.getMessage());
}
// This ClassLoader will actually work, because it is joined to the parent ClassLoader.
URLClassLoader workingClassLoader = URLClassLoader.newInstance(urlsArray);
for (ClassPath.ClassInfo classInfo : classInfos) {
String className = classInfo.getName();
try {
Class<?> aClass = Class.forName(className, true, workingClassLoader);
if (BuckEventListener.class.isAssignableFrom(aClass)) {
BuckEventListener listener = aClass.asSubclass(BuckEventListener.class).newInstance();
eventListeners.add(listener);
}
} catch (ReflectiveOperationException e) {
throw new HumanReadableException(
"Error loading event listener class '%s': %s: %s",
className, e.getClass(), e.getMessage());
}
}
}
/**
* Try to acquire global semaphore if needed to do so. Attach closer to acquired semaphore in a
* form of a wrapper object so it can be used with try-with-resources.
*
* @return (semaphore, previous args) If we successfully acquire the semaphore, return (semaphore,
* null). If there is already a command running but the command to run is readonly, return
* (null, null) and allow the execution. Otherwise, return (null, previously running command
* args) and block this command.
*/
private @Nullable CloseableWrapper<Semaphore> getSemaphoreWrapper(
BuckCommand command,
ImmutableList<String> currentArgs,
ImmutableList.Builder<String> previousArgs) {
// we can execute read-only commands (query, targets, etc) in parallel
if (command.isReadOnly()) {
// using nullable instead of Optional<> to use the object with try-with-resources
return null;
}
while (!commandSemaphore.tryAcquire()) {
ImmutableList<String> activeCommandArgsCopy = activeCommandArgs.get();
if (activeCommandArgsCopy != null) {
// Keep retrying until we either 1) successfully acquire the semaphore or 2) failed to
// acquire the semaphore and obtain a valid list of args for on going command.
// In theory, this can stuck in a loop if it never observes such state if other commands
// winning the race, but I consider this to be a rare corner case.
previousArgs.addAll(activeCommandArgsCopy);
return null;
}
// Avoid hogging CPU
Thread.yield();
}
commandSemaphoreNgClient = context;
// Keep track of command that is in progress
activeCommandArgs.set(currentArgs);
CloseableWrapper<Semaphore> semaphore =
CloseableWrapper.of(
commandSemaphore,
commandSemaphore -> {
activeCommandArgs.set(null);
commandSemaphoreNgClient = Optional.empty();
// TODO(buck_team): have background process killer have its own lifetime management
BgProcessKiller.disarm();
commandSemaphore.release();
});
return semaphore;
}
@SuppressWarnings("PMD.PrematureDeclaration")
private ImmutableList<BuckEventListener> addEventListeners(
Optional<BuckEventListener> devspeedDaemonEventListener,
BuckEventBus buckEventBus,
Optional<EventBus> fileEventBus,
ProjectFilesystem projectFilesystem,
InvocationInfo invocationInfo,
BuckConfig buckConfig,
Optional<WebServer> webServer,
Clock clock,
CounterRegistry counterRegistry,
Iterable<BuckEventListener> commandSpecificEventListeners,
TaskManagerScope managerScope) {
ImmutableList.Builder<BuckEventListener> eventListenersBuilder =
ImmutableList.<BuckEventListener>builder().add(new LoggingBuildListener());
if (buckConfig.getBooleanValue("log", "jul_build_log", false)) {
eventListenersBuilder.add(new JavaUtilsLoggingBuildListener(projectFilesystem));
}
ChromeTraceBuckConfig chromeTraceConfig = buckConfig.getView(ChromeTraceBuckConfig.class);
if (chromeTraceConfig.isChromeTraceCreationEnabled()) {
try {
ChromeTraceBuildListener chromeTraceBuildListener =
new ChromeTraceBuildListener(
projectFilesystem, invocationInfo, clock, chromeTraceConfig, managerScope);
eventListenersBuilder.add(chromeTraceBuildListener);
fileEventBus.ifPresent(bus -> bus.register(chromeTraceBuildListener));
} catch (IOException e) {
LOG.error("Unable to create ChromeTrace listener!");
}
} else {
LOG.warn("::: ChromeTrace listener disabled");
}
if (webServer.isPresent()) {
eventListenersBuilder.add(webServer.get().createListener());
}
loadListenersFromBuckConfig(eventListenersBuilder, projectFilesystem, buckConfig);
ArtifactCacheBuckConfig artifactCacheConfig = new ArtifactCacheBuckConfig(buckConfig);
devspeedDaemonEventListener.ifPresent(eventListenersBuilder::add);
CommonThreadFactoryState commonThreadFactoryState =
GlobalStateManager.singleton().getThreadToCommandRegister();
eventListenersBuilder.add(
new LogUploaderListener(
chromeTraceConfig,
invocationInfo.getLogFilePath(),
invocationInfo.getLogDirectoryPath(),
invocationInfo.getBuildId(),
managerScope));
if (buckConfig.isRuleKeyLoggerEnabled()) {
eventListenersBuilder.add(
new RuleKeyLoggerListener(
projectFilesystem,
invocationInfo,
MostExecutors.newSingleThreadExecutor(
new CommandThreadFactory(getClass().getName(), commonThreadFactoryState)),
managerScope));
}
eventListenersBuilder.add(
new RuleKeyDiagnosticsListener(
projectFilesystem,
invocationInfo,
MostExecutors.newSingleThreadExecutor(
new CommandThreadFactory(getClass().getName(), commonThreadFactoryState)),
managerScope));
if (buckConfig.isMachineReadableLoggerEnabled()) {
try {
eventListenersBuilder.add(
new MachineReadableLoggerListener(
invocationInfo,
projectFilesystem,
MostExecutors.newSingleThreadExecutor(
new CommandThreadFactory(getClass().getName(), commonThreadFactoryState)),
artifactCacheConfig.getArtifactCacheModes(),
managerScope));
} catch (FileNotFoundException e) {
LOG.warn("Unable to open stream for machine readable log file.");
}
}
eventListenersBuilder.add(new ParserProfilerLoggerListener(invocationInfo, projectFilesystem));
eventListenersBuilder.add(new LoadBalancerEventsListener(counterRegistry));
eventListenersBuilder.add(new CacheRateStatsListener(buckEventBus));
eventListenersBuilder.add(new WatchmanDiagnosticEventListener(buckEventBus));
if (buckConfig.isCriticalPathAnalysisEnabled()) {
eventListenersBuilder.add(
new BuildTargetDurationListener(
invocationInfo, projectFilesystem, buckConfig.getCriticalPathCount(), managerScope));
}
eventListenersBuilder.addAll(commandSpecificEventListeners);
ImmutableList<BuckEventListener> eventListeners = eventListenersBuilder.build();
eventListeners.forEach(buckEventBus::register);
return eventListeners;
}
private BuildEnvironmentDescription getBuildEnvironmentDescription(
ExecutionEnvironment executionEnvironment,
BuckConfig buckConfig) {
ImmutableMap.Builder<String, String> environmentExtraData = ImmutableMap.builder();
return BuildEnvironmentDescription.of(
executionEnvironment,
new ArtifactCacheBuckConfig(buckConfig).getArtifactCacheModesRaw(),
environmentExtraData.build());
}
private AbstractConsoleEventBusListener createConsoleEventListener(
Clock clock,
SuperConsoleConfig config,
Console console,
TestResultSummaryVerbosity testResultSummaryVerbosity,
ExecutionEnvironment executionEnvironment,
Locale locale,
Path testLogPath,
BuildId buildId,
boolean printBuildId,
Optional<String> buildDetailsTemplate,
ImmutableList<AdditionalConsoleLineProvider> remoteExecutionConsoleLineProvider) {
RenderingConsole renderingConsole = new RenderingConsole(clock, console);
if (config.isEnabled(console.getAnsi(), console.getVerbosity())) {
SuperConsoleEventBusListener superConsole =
new SuperConsoleEventBusListener(
config,
renderingConsole,
clock,
testResultSummaryVerbosity,
executionEnvironment,
locale,
testLogPath,
TimeZone.getDefault(),
buildId,
printBuildId,
buildDetailsTemplate,
remoteExecutionConsoleLineProvider);
return superConsole;
}
return new SimpleConsoleEventBusListener(
renderingConsole,
clock,
testResultSummaryVerbosity,
config.getHideSucceededRulesInLogMode(),
config.getNumberOfSlowRulesToShow(),
config.shouldShowSlowRulesInConsole(),
locale,
testLogPath,
executionEnvironment,
buildId,
printBuildId,
buildDetailsTemplate);
}
/**
* A helper method to retrieve the process ID of Buck. The return value from the JVM has to match
* the following pattern: {PID}@{Hostname}. It it does not match the return value is 0.
*
* @return the PID or 0L.
*/
private static long getBuckPID() {
String pid = ManagementFactory.getRuntimeMXBean().getName();
return (pid != null && pid.matches("^\\d+@.*$")) ? Long.parseLong(pid.split("@")[0]) : 0L;
}
private static BuildId getBuildId(Optional<NGContext> context) {
String specifiedBuildId;
if (context.isPresent()) {
specifiedBuildId = context.get().getEnv().getProperty(BUCK_BUILD_ID_ENV_VAR);
} else {
specifiedBuildId = EnvVariablesProvider.getSystemEnv().get(BUCK_BUILD_ID_ENV_VAR);
}
if (specifiedBuildId == null) {
specifiedBuildId = UUID.randomUUID().toString();
}
return new BuildId(specifiedBuildId);
}
private static String getArtifactProducerId(ExecutionEnvironment executionEnvironment) {
String artifactProducerId = "user://" + executionEnvironment.getUsername();
return artifactProducerId;
}
/**
* @param buckConfig the configuration for resources
* @return a memoized supplier for a ForkJoinPool that will be closed properly if initialized
*/
@VisibleForTesting
static CloseableMemoizedSupplier<ForkJoinPool> getForkJoinPoolSupplier(BuckConfig buckConfig) {
ResourcesConfig resource = buckConfig.getView(ResourcesConfig.class);
return CloseableMemoizedSupplier.of(
() ->
MostExecutors.forkJoinPoolWithThreadLimit(
resource.getMaximumResourceAmounts().getCpu(), 16),
ForkJoinPool::shutdownNow);
}
private static void installUncaughtExceptionHandler(Optional<NGContext> context) {
// Override the default uncaught exception handler for background threads to log
// to java.util.logging then exit the JVM with an error code.
//
// (We do this because the default is to just print to stderr and not exit the JVM,
// which is not safe in a multithreaded environment if the thread held a lock or
// resource which other threads need.)
Thread.setDefaultUncaughtExceptionHandler(
(t, e) -> {
ExitCode exitCode = ExitCode.FATAL_GENERIC;
if (e instanceof OutOfMemoryError) {
exitCode = ExitCode.FATAL_OOM;
} else if (e instanceof IOException) {
exitCode =
e.getMessage().startsWith("No space left on device")
? ExitCode.FATAL_DISK_FULL
: ExitCode.FATAL_IO;
}
// Do not log anything in case we do not have space on the disk
if (exitCode != ExitCode.FATAL_DISK_FULL) {
LOG.error(e, "Uncaught exception from thread %s", t);
}
if (context.isPresent()) {
// Shut down the Nailgun server and make sure it stops trapping System.exit().
context.get().getNGServer().shutdown();
}
NON_REENTRANT_SYSTEM_EXIT.shutdownSoon(exitCode.getCode());
});
}
public static void main(String[] args) {
new Main(System.out, System.err, System.in, Optional.empty())
.runMainThenExit(args, System.nanoTime());
}
private static void markFdCloseOnExec(int fd) {
int fdFlags;
fdFlags = Libc.INSTANCE.fcntl(fd, Libc.Constants.rFGETFD);
if (fdFlags == -1) {
throw new LastErrorException(Native.getLastError());
}
fdFlags |= Libc.Constants.rFDCLOEXEC;
if (Libc.INSTANCE.fcntl(fd, Libc.Constants.rFSETFD, fdFlags) == -1) {
throw new LastErrorException(Native.getLastError());
}
}
private static void daemonizeIfPossible() {
String osName = System.getProperty("os.name");
Libc.OpenPtyLibrary openPtyLibrary;
Platform platform = Platform.detect();
if (platform == Platform.LINUX) {
Libc.Constants.rTIOCSCTTY = Libc.Constants.LINUX_TIOCSCTTY;
Libc.Constants.rFDCLOEXEC = Libc.Constants.LINUX_FD_CLOEXEC;
Libc.Constants.rFGETFD = Libc.Constants.LINUX_F_GETFD;
Libc.Constants.rFSETFD = Libc.Constants.LINUX_F_SETFD;
openPtyLibrary = Native.loadLibrary("libutil", Libc.OpenPtyLibrary.class);
} else if (platform == Platform.MACOS) {
Libc.Constants.rTIOCSCTTY = Libc.Constants.DARWIN_TIOCSCTTY;
Libc.Constants.rFDCLOEXEC = Libc.Constants.DARWIN_FD_CLOEXEC;
Libc.Constants.rFGETFD = Libc.Constants.DARWIN_F_GETFD;
Libc.Constants.rFSETFD = Libc.Constants.DARWIN_F_SETFD;
openPtyLibrary =
Native.loadLibrary(com.sun.jna.Platform.C_LIBRARY_NAME, Libc.OpenPtyLibrary.class);
} else {
LOG.info("not enabling process killing on nailgun exit: unknown OS %s", osName);
return;
}
// Making ourselves a session leader with setsid disconnects us from our controlling terminal
int ret = Libc.INSTANCE.setsid();
if (ret < 0) {
LOG.warn("cannot enable background process killing: %s", Native.getLastError());
return;
}
LOG.info("enabling background process killing for buckd");
IntByReference master = new IntByReference();
IntByReference slave = new IntByReference();
if (openPtyLibrary.openpty(master, slave, Pointer.NULL, Pointer.NULL, Pointer.NULL) != 0) {
throw new RuntimeException("Failed to open pty");
}
// Deliberately leak the file descriptors for the lifetime of this process; NuProcess can
// sometimes leak file descriptors to children, so make sure these FDs are marked close-on-exec.
markFdCloseOnExec(master.getValue());
markFdCloseOnExec(slave.getValue());
// Make the pty our controlling terminal; works because we disconnected above with setsid.
if (Libc.INSTANCE.ioctl(slave.getValue(), Pointer.createConstant(Libc.Constants.rTIOCSCTTY), 0)
== -1) {
throw new RuntimeException("Failed to set pty");
}
LOG.info("enabled background process killing for buckd");
isSessionLeader = true;
}
public static final class DaemonBootstrap {
private static final int AFTER_COMMAND_AUTO_GC_DELAY_MS = 5000;
private static final int SUBSEQUENT_GC_DELAY_MS = 10000;
private static @Nullable DaemonKillers daemonKillers;
private static AtomicInteger activeTasks = new AtomicInteger(0);
/** Single thread for running short-lived tasks outside the command context. */
private static final ScheduledExecutorService housekeepingExecutorService =
Executors.newSingleThreadScheduledExecutor();
private static final boolean isCMS =
ManagementFactory.getGarbageCollectorMXBeans()
.stream()
.filter(GarbageCollectorMXBean::isValid)
.map(GarbageCollectorMXBean::getName)
.anyMatch(Predicate.isEqual("ConcurrentMarkSweep"));
public static void main(String[] args) {
try {
daemonizeIfPossible();
if (isSessionLeader) {
BgProcessKiller.init();
LOG.info("initialized bg session killer");
}
} catch (Throwable ex) {
System.err.println(String.format("buckd: fatal error %s", ex));
System.exit(1);
}
if (args.length != 2) {
System.err.println("Usage: buckd socketpath heartbeatTimeout");
return;
}
String socketPath = args[0];
int heartbeatTimeout = Integer.parseInt(args[1]);
// Strip out optional local: prefix. This server only use domain sockets.
if (socketPath.startsWith("local:")) {
socketPath = socketPath.substring("local:".length());
}
NGServer server =
new NGServer(
new NGListeningAddress(socketPath),
1, // store only 1 NGSession in a pool to avoid excessive memory usage
heartbeatTimeout);
daemonKillers = new DaemonKillers(housekeepingExecutorService, server, Paths.get(socketPath));
server.run();
System.exit(0);
}
static DaemonKillers getDaemonKillers() {
return Objects.requireNonNull(daemonKillers, "Daemon killers should be initialized.");
}
static void commandStarted() {
activeTasks.incrementAndGet();
}
static void commandFinished() {
// Concurrent Mark and Sweep (CMS) garbage collector releases memory to operating system
// in multiple steps, even given that full collection is performed at each step. So if CMS
// collector is used we call System.gc() up to 4 times with some interval, and call it
// just once for any other major collector.
// With Java 9 we could just use -XX:-ShrinkHeapInSteps flag.
int nTimes = isCMS ? 4 : 1;
housekeepingExecutorService.schedule(
() -> collectGarbage(nTimes), AFTER_COMMAND_AUTO_GC_DELAY_MS, TimeUnit.MILLISECONDS);
}
private static void collectGarbage(int nTimes) {
int tasks = activeTasks.decrementAndGet();
if (tasks > 0) {
return;
}
// Potentially there is a race condition - new command comes exactly at this point and got
// under GC right away. Unlucky. We ignore that.
System.gc();
// schedule next collection to release more memory to operating system if garbage collector
// releases it in steps
if (nTimes > 1) {
activeTasks.incrementAndGet();
housekeepingExecutorService.schedule(
() -> collectGarbage(nTimes - 1), SUBSEQUENT_GC_DELAY_MS, TimeUnit.MILLISECONDS);
}
}
}
private static class DaemonKillers {
private final NGServer server;
private final IdleKiller idleKiller;
private final SocketLossKiller unixDomainSocketLossKiller;
DaemonKillers(ScheduledExecutorService executorService, NGServer server, Path socketPath) {
this.server = server;
this.idleKiller = new IdleKiller(executorService, DAEMON_SLAYER_TIMEOUT, this::killServer);
this.unixDomainSocketLossKiller =
Platform.detect() == Platform.WINDOWS
? null
: new SocketLossKiller(
executorService, socketPath.toAbsolutePath(), this::killServer);
}
IdleKiller.CommandExecutionScope newCommandExecutionScope() {
if (unixDomainSocketLossKiller != null) {
unixDomainSocketLossKiller.arm(); // Arm the socket loss killer also.
}
return idleKiller.newCommandExecutionScope();
}
private void killServer() {
server.shutdown();
}
}
/**
* To prevent 'buck kill' from deleting resources from underneath a 'live' buckd we hold on to the
* FileLock for the entire lifetime of the process. We depend on the fact that on Linux and MacOS
* Java FileLock is implemented using the same mechanism as the Python fcntl.lockf method. Should
* this not be the case we'll simply have a small race between buckd start and `buck kill`.
*/
private static void obtainResourceFileLock() {
if (resourcesFileLock != null) {
return;
}
String resourceLockFilePath = System.getProperties().getProperty("buck.resource_lock_path");
if (resourceLockFilePath == null) {
// Running from ant, no resource lock needed.
return;
}
try {
// R+W+A is equivalent to 'a+' in Python (which is how the lock file is opened in Python)
// because WRITE in Java does not imply truncating the file.
FileChannel fileChannel =
FileChannel.open(
Paths.get(resourceLockFilePath),
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE);
resourcesFileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, true);
} catch (IOException | OverlappingFileLockException e) {
LOG.debug(e, "Error when attempting to acquire resources file lock.");
}
}
/**
* When running as a daemon in the NailGun server, {@link #nailMain(NGContext)} is called instead
* of {@link #main(String[])} so that the given context can be used to listen for client
* disconnections and interrupt command processing when they occur.
*/
public static void nailMain(NGContext context) {
obtainResourceFileLock();
try (IdleKiller.CommandExecutionScope ignored =
DaemonBootstrap.getDaemonKillers().newCommandExecutionScope()) {
DaemonBootstrap.commandStarted();
new Main(context.out, context.err, context.in, Optional.of(context))
.runMainThenExit(context.getArgs(), System.nanoTime());
} finally {
// Reclaim memory after a command finishes.
DaemonBootstrap.commandFinished();
}
}
/** Used to clean up the daemon after running integration tests that exercise it. */
@VisibleForTesting
static void resetDaemon() {
daemonLifecycleManager.resetDaemon();
}
}
|
9241dc458de68538c530091539db60e9d2dbb319
| 5,585 |
java
|
Java
|
src/main/java/net/hydromatic/toolbox/checkstyle/HydromaticFileSetCheck.java
|
vlsi/toolbox
|
a264a94d659bedb6748b5e6639645362e2f2b34e
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/net/hydromatic/toolbox/checkstyle/HydromaticFileSetCheck.java
|
vlsi/toolbox
|
a264a94d659bedb6748b5e6639645362e2f2b34e
|
[
"Apache-2.0"
] | 5 |
2015-12-22T03:56:11.000Z
|
2019-11-19T21:36:44.000Z
|
src/main/java/net/hydromatic/toolbox/checkstyle/HydromaticFileSetCheck.java
|
vlsi/toolbox
|
a264a94d659bedb6748b5e6639645362e2f2b34e
|
[
"Apache-2.0"
] | 2 |
2018-04-29T20:04:27.000Z
|
2019-11-19T17:23:20.000Z
| 30.353261 | 99 | 0.547538 | 1,002,057 |
/*
* Licensed to Julian Hyde under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Julian Hyde
* 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 net.hydromatic.toolbox.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;
/**
* Checker that applies some custom checks to each file.
*/
public class HydromaticFileSetCheck extends AbstractFileSetCheck {
private static final Pattern PATTERN1 = Pattern.compile(".*\\\\n\" \\+ .*");
private static final Pattern PATTERN2 = Pattern.compile("^\\{@link .*\\}$");
private static final Pattern PATTERN3 = Pattern.compile(".*@param +[^ ]+ *$");
private static final Pattern PATTERN4 = Pattern.compile(".* href=.*CALCITE-.*");
private static final Pattern PATTERN5 = Pattern.compile(
".*<a href=\"https://issues.apache.org/jira/browse/CALCITE-[0-9]+\">\\[CALCITE-[0-9]+\\].*");
boolean isProto(File file) {
return file.getAbsolutePath().contains("/proto/")
|| file.getName().endsWith("Base64.java");
}
static <E> E last(List<E> list) {
return list.get(list.size() - 1);
}
void afterFile(File file, List<String> lines) {
if (file.getName().endsWith(".java")) {
String b = file.getName().replaceAll(".*/", "");
final String line = "// End " + b;
if (!last(lines).equals(line) && !isProto(file)) {
log(lines.size(), "Last line should be ''{0}''", line);
}
}
}
protected void processFiltered(File file, List<String> list) {
boolean off = false;
int endCount = 0;
int maxLineLength = 80;
final String path = file.getAbsolutePath()
.replace('\\', '/'); // for windows
if (path.contains("/calcite/")) {
maxLineLength = 100;
}
int i = 0;
for (String line : list) {
++i;
if (line.contains("\t")) {
log(i, "Tab");
}
if (line.contains("CHECKSTYLE: ON")) {
off = false;
}
if (line.contains("CHECKSTYLE: OFF")) {
off = true;
}
if (off) {
continue;
}
if (line.startsWith("// End ")) {
if (endCount++ > 0) {
log(i, "End seen more than once");
}
}
if (isMatches(PATTERN1, line)) {
log(i, "Newline in string should be at end of line");
}
if (line.contains("{@link")) {
if (!line.contains("}")) {
log(i, "Split @link");
}
}
if (line.endsWith("@Override")) {
log(i, "@Override should not be on its own line");
}
if (line.endsWith("<p>") && !isProto(file)) {
log(i, "Orphan <p>. Make it the first line of a paragraph");
}
if (line.contains("@")
&& !line.contains("@see")
&& line.length() > maxLineLength) {
String s = line
.replaceAll("^ *\\* *", "")
.replaceAll(" \\*/$", "")
.replaceAll("[;.,]$", "")
.replaceAll("<li>", "");
if (!isMatches(PATTERN2, s)
&& !file.getName().endsWith("CalciteResource.java")) {
log(i, "Javadoc line too long ({0} chars)", line.length());
}
}
if (isMatches(PATTERN3, line)) {
log(i, "Parameter with no description");
}
if (isMatches(PATTERN4, line) && !isMatches(PATTERN5, line)) {
log(i, "Bad JIRA reference");
}
if (file.getName().endsWith(".java")
&& (line.contains("(") || line.contains(")"))) {
String s = deString(line);
int o = 0;
for (int j = 0; j < s.length(); j++) {
char c = s.charAt(j);
if (c == '('
&& j > 0
&& Character.isJavaIdentifierPart(s.charAt(j - 1))) {
++o;
} else if (c == ')') {
--o;
}
}
if (o > 1) {
log(i, "Open parentheses exceed closes by 2 or more");
}
}
}
afterFile(file, list);
}
private boolean isMatches(Pattern pattern, String line) {
return pattern.matcher(line).matches();
}
static String deString(String line) {
if (!line.contains("\"")) {
return line;
}
final StringBuilder b = new StringBuilder();
int i = 0;
outer:
for (;;) {
int j = line.indexOf('"', i);
if (j < 0) {
b.append(line, i, line.length());
return b.toString();
}
b.append(line, i, j);
for (int k = j + 1;;) {
if (k >= line.length()) {
b.append("string");
i = line.length();
continue outer;
}
char c = line.charAt(k++);
switch (c) {
case '\\':
k++;
break;
case '"':
b.append("string");
i = k;
continue outer;
}
}
}
}
public void fireErrors2(File fileName) {
fireErrors(fileName.getAbsolutePath());
}
}
// End HydromaticFileSetCheck.java
|
9241dc5a75ce3e35310202f737cf6cf48e97926c
| 6,557 |
java
|
Java
|
testData/generator/PsiStart.PSI.expected.java
|
ocadaruma/Grammar-Kit
|
02b77fa28402da8baaa9be8b111518d61291bc00
|
[
"Apache-2.0"
] | 511 |
2015-01-01T10:57:09.000Z
|
2022-03-19T06:44:57.000Z
|
testData/generator/PsiStart.PSI.expected.java
|
ocadaruma/Grammar-Kit
|
02b77fa28402da8baaa9be8b111518d61291bc00
|
[
"Apache-2.0"
] | 222 |
2015-01-28T07:12:23.000Z
|
2022-02-23T17:47:59.000Z
|
testData/generator/PsiStart.PSI.expected.java
|
ocadaruma/Grammar-Kit
|
02b77fa28402da8baaa9be8b111518d61291bc00
|
[
"Apache-2.0"
] | 132 |
2015-01-01T17:25:35.000Z
|
2022-03-19T07:30:12.000Z
| 25.814961 | 74 | 0.717554 | 1,002,058 |
// ---- GeneratedTypes.java -----------------
// This is a generated file. Not intended for manual editing.
package generated;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.PsiElement;
import com.intellij.lang.ASTNode;
import generated.psi.impl.*;
public interface GeneratedTypes {
IElementType ELEMENT = new IElementType("ELEMENT", null);
IElementType ENTRY = new IElementType("ENTRY", null);
IElementType LIST = new IElementType("LIST", null);
IElementType MAP = new IElementType("MAP", null);
class Factory {
public static PsiElement createElement(ASTNode node) {
IElementType type = node.getElementType();
if (type == ELEMENT) {
return new ElementImpl(node);
}
else if (type == ENTRY) {
return new EntryImpl(node);
}
else if (type == LIST) {
return new ListImpl(node);
}
else if (type == MAP) {
return new MapImpl(node);
}
throw new AssertionError("Unknown element type: " + type);
}
}
}
// ---- Element.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface Element extends PsiElement {
}
// ---- Entry.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface Entry extends PsiElement {
@NotNull
Element getElement();
}
// ---- List.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface List extends PsiElement {
@NotNull
java.util.List<Element> getElementList();
}
// ---- Map.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface Map extends PsiElement {
@NotNull
java.util.List<Entry> getEntryList();
}
// ---- ElementImpl.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi.impl;
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 generated.GeneratedTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import generated.psi.*;
public class ElementImpl extends ASTWrapperPsiElement implements Element {
public ElementImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull Visitor visitor) {
visitor.visitElement(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof Visitor) accept((Visitor)visitor);
else super.accept(visitor);
}
}
// ---- EntryImpl.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi.impl;
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 generated.GeneratedTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import generated.psi.*;
public class EntryImpl extends ASTWrapperPsiElement implements Entry {
public EntryImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull Visitor visitor) {
visitor.visitEntry(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof Visitor) accept((Visitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public Element getElement() {
return findNotNullChildByClass(Element.class);
}
}
// ---- ListImpl.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi.impl;
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 generated.GeneratedTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import generated.psi.*;
public class ListImpl extends ASTWrapperPsiElement implements List {
public ListImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull Visitor visitor) {
visitor.visitList(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof Visitor) accept((Visitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public java.util.List<Element> getElementList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, Element.class);
}
}
// ---- MapImpl.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi.impl;
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 generated.GeneratedTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import generated.psi.*;
public class MapImpl extends ASTWrapperPsiElement implements Map {
public MapImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull Visitor visitor) {
visitor.visitMap(this);
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof Visitor) accept((Visitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public java.util.List<Entry> getEntryList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, Entry.class);
}
}
// ---- Visitor.java -----------------
// This is a generated file. Not intended for manual editing.
package generated.psi;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiElement;
public class Visitor extends PsiElementVisitor {
public void visitElement(@NotNull Element o) {
visitPsiElement(o);
}
public void visitEntry(@NotNull Entry o) {
visitPsiElement(o);
}
public void visitList(@NotNull List o) {
visitPsiElement(o);
}
public void visitMap(@NotNull Map o) {
visitPsiElement(o);
}
public void visitPsiElement(@NotNull PsiElement o) {
visitElement(o);
}
}
|
9241df693d81d7de8952f6f68853bccc0c1fc5fd
| 204 |
java
|
Java
|
sdk/src/main/java/com/vk/api/sdk/exceptions/ApiParamPageIdException.java
|
6rayWa1cher/vk-java-sdk
|
fbda989bb5ce2d290a19bca2125cbce319bd9d21
|
[
"MIT"
] | 1 |
2020-04-23T17:17:03.000Z
|
2020-04-23T17:17:03.000Z
|
sdk/src/main/java/com/vk/api/sdk/exceptions/ApiParamPageIdException.java
|
6rayWa1cher/vk-java-sdk
|
fbda989bb5ce2d290a19bca2125cbce319bd9d21
|
[
"MIT"
] | null | null | null |
sdk/src/main/java/com/vk/api/sdk/exceptions/ApiParamPageIdException.java
|
6rayWa1cher/vk-java-sdk
|
fbda989bb5ce2d290a19bca2125cbce319bd9d21
|
[
"MIT"
] | 1 |
2018-10-01T09:43:32.000Z
|
2018-10-01T09:43:32.000Z
| 25.5 | 59 | 0.735294 | 1,002,059 |
package com.vk.api.sdk.exceptions;
public class ApiParamPageIdException extends ApiException {
public ApiParamPageIdException(String message) {
super(140, "Page not found", message);
}
}
|
9241e02e35cadeb724fc9e6ff41b2ee8ac8ff7ad
| 229 |
java
|
Java
|
my_boot05_adminServer/src/test/java/com/atguigu/www/MyBoot05AdminServerApplicationTests.java
|
daponi/springboot2
|
c012dc1e44d268287d96052eff96d56e5d35a991
|
[
"Apache-2.0"
] | null | null | null |
my_boot05_adminServer/src/test/java/com/atguigu/www/MyBoot05AdminServerApplicationTests.java
|
daponi/springboot2
|
c012dc1e44d268287d96052eff96d56e5d35a991
|
[
"Apache-2.0"
] | null | null | null |
my_boot05_adminServer/src/test/java/com/atguigu/www/MyBoot05AdminServerApplicationTests.java
|
daponi/springboot2
|
c012dc1e44d268287d96052eff96d56e5d35a991
|
[
"Apache-2.0"
] | null | null | null | 16.357143 | 60 | 0.764192 | 1,002,060 |
package com.atguigu.www;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MyBoot05AdminServerApplicationTests {
@Test
void contextLoads() {
}
}
|
9241e0b8dd58b8eee1e8258bd859035b6c7e4dcb
| 15,528 |
java
|
Java
|
fr.unice.polytech.si5.smarthome.am.xtext.ui/src-gen/fr/unice/polytech/si5/smarthome/am/shome/ui/AbstractShomeUiModule.java
|
Corentin-Luc-Artaud/Interpretation
|
240f3d115baa87f9b10b8dafa679efa6f61b01a5
|
[
"MIT"
] | null | null | null |
fr.unice.polytech.si5.smarthome.am.xtext.ui/src-gen/fr/unice/polytech/si5/smarthome/am/shome/ui/AbstractShomeUiModule.java
|
Corentin-Luc-Artaud/Interpretation
|
240f3d115baa87f9b10b8dafa679efa6f61b01a5
|
[
"MIT"
] | null | null | null |
fr.unice.polytech.si5.smarthome.am.xtext.ui/src-gen/fr/unice/polytech/si5/smarthome/am/shome/ui/AbstractShomeUiModule.java
|
Corentin-Luc-Artaud/Interpretation
|
240f3d115baa87f9b10b8dafa679efa6f61b01a5
|
[
"MIT"
] | null | null | null | 51.58804 | 168 | 0.826571 | 1,002,061 |
/*
* generated by Xtext 2.14.0
*/
package fr.unice.polytech.si5.smarthome.am.shome.ui;
import com.google.inject.Binder;
import com.google.inject.Provider;
import com.google.inject.name.Names;
import fr.unice.polytech.si5.smarthome.am.shome.ide.contentassist.antlr.PartialShomeContentAssistParser;
import fr.unice.polytech.si5.smarthome.am.shome.ide.contentassist.antlr.ShomeParser;
import fr.unice.polytech.si5.smarthome.am.shome.ide.contentassist.antlr.internal.InternalShomeLexer;
import fr.unice.polytech.si5.smarthome.am.shome.ui.contentassist.ShomeProposalProvider;
import fr.unice.polytech.si5.smarthome.am.shome.ui.labeling.ShomeDescriptionLabelProvider;
import fr.unice.polytech.si5.smarthome.am.shome.ui.labeling.ShomeLabelProvider;
import fr.unice.polytech.si5.smarthome.am.shome.ui.outline.ShomeOutlineTreeProvider;
import fr.unice.polytech.si5.smarthome.am.shome.ui.quickfix.ShomeQuickfixProvider;
import fr.unice.polytech.si5.smarthome.am.shome.validation.ShomeValidatorConfigurationBlock;
import org.eclipse.compare.IViewerCreator;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.xtext.builder.BuilderParticipant;
import org.eclipse.xtext.builder.EclipseOutputConfigurationProvider;
import org.eclipse.xtext.builder.IXtextBuilderParticipant;
import org.eclipse.xtext.builder.builderState.IBuilderState;
import org.eclipse.xtext.builder.clustering.CurrentDescriptions;
import org.eclipse.xtext.builder.impl.PersistentDataAwareDirtyResource;
import org.eclipse.xtext.builder.nature.NatureAddingEditorCallback;
import org.eclipse.xtext.builder.preferences.BuilderPreferenceAccess;
import org.eclipse.xtext.generator.IContextualOutputConfigurationProvider;
import org.eclipse.xtext.ide.LexerIdeBindings;
import org.eclipse.xtext.ide.editor.contentassist.antlr.IContentAssistParser;
import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.Lexer;
import org.eclipse.xtext.ide.editor.partialEditing.IPartialEditingContentAssistParser;
import org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider;
import org.eclipse.xtext.parser.antlr.ITokenDefProvider;
import org.eclipse.xtext.parser.antlr.LexerProvider;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.containers.IAllContainersState;
import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider;
import org.eclipse.xtext.service.SingletonBinding;
import org.eclipse.xtext.ui.DefaultUiModule;
import org.eclipse.xtext.ui.UIBindings;
import org.eclipse.xtext.ui.codetemplates.ui.AccessibleCodetemplatesActivator;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialEditingContentAssistContextFactory;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.PartialEditingContentAssistContextFactory;
import org.eclipse.xtext.ui.codetemplates.ui.preferences.AdvancedTemplatesPreferencePage;
import org.eclipse.xtext.ui.codetemplates.ui.preferences.TemplatesLanguageConfiguration;
import org.eclipse.xtext.ui.codetemplates.ui.registry.LanguageRegistrar;
import org.eclipse.xtext.ui.codetemplates.ui.registry.LanguageRegistry;
import org.eclipse.xtext.ui.compare.DefaultViewerCreator;
import org.eclipse.xtext.ui.editor.DocumentBasedDirtyResource;
import org.eclipse.xtext.ui.editor.IXtextEditorCallback;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.FQNPrefixMatcher;
import org.eclipse.xtext.ui.editor.contentassist.IContentProposalProvider;
import org.eclipse.xtext.ui.editor.contentassist.IProposalConflictHelper;
import org.eclipse.xtext.ui.editor.contentassist.PrefixMatcher;
import org.eclipse.xtext.ui.editor.contentassist.antlr.AntlrProposalConflictHelper;
import org.eclipse.xtext.ui.editor.contentassist.antlr.DelegatingContentAssistContextFactory;
import org.eclipse.xtext.ui.editor.formatting.IContentFormatterFactory;
import org.eclipse.xtext.ui.editor.formatting2.ContentFormatterFactory;
import org.eclipse.xtext.ui.editor.outline.IOutlineTreeProvider;
import org.eclipse.xtext.ui.editor.outline.impl.IOutlineTreeStructureProvider;
import org.eclipse.xtext.ui.editor.preferences.IPreferenceStoreInitializer;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider;
import org.eclipse.xtext.ui.editor.templates.XtextTemplatePreferencePage;
import org.eclipse.xtext.ui.refactoring.IDependentElementsCalculator;
import org.eclipse.xtext.ui.refactoring.IReferenceUpdater;
import org.eclipse.xtext.ui.refactoring.IRenameRefactoringProvider;
import org.eclipse.xtext.ui.refactoring.IRenameStrategy;
import org.eclipse.xtext.ui.refactoring.impl.DefaultDependentElementsCalculator;
import org.eclipse.xtext.ui.refactoring.impl.DefaultReferenceUpdater;
import org.eclipse.xtext.ui.refactoring.impl.DefaultRenameRefactoringProvider;
import org.eclipse.xtext.ui.refactoring.impl.DefaultRenameStrategy;
import org.eclipse.xtext.ui.refactoring.ui.DefaultRenameSupport;
import org.eclipse.xtext.ui.refactoring.ui.IRenameSupport;
import org.eclipse.xtext.ui.refactoring.ui.RefactoringPreferences;
import org.eclipse.xtext.ui.resource.ResourceServiceDescriptionLabelProvider;
import org.eclipse.xtext.ui.shared.Access;
import org.eclipse.xtext.ui.validation.AbstractValidatorConfigurationBlock;
/**
* Manual modifications go to {@link ShomeUiModule}.
*/
@SuppressWarnings("all")
public abstract class AbstractShomeUiModule extends DefaultUiModule {
public AbstractShomeUiModule(AbstractUIPlugin plugin) {
super(plugin);
}
// contributed by org.eclipse.xtext.xtext.generator.ImplicitFragment
public Provider<? extends IAllContainersState> provideIAllContainersState() {
return Access.getJavaProjectsState();
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IProposalConflictHelper> bindIProposalConflictHelper() {
return AntlrProposalConflictHelper.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureContentAssistLexer(Binder binder) {
binder.bind(Lexer.class)
.annotatedWith(Names.named(LexerIdeBindings.CONTENT_ASSIST))
.to(InternalShomeLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureHighlightingLexer(Binder binder) {
binder.bind(org.eclipse.xtext.parser.antlr.Lexer.class)
.annotatedWith(Names.named(LexerIdeBindings.HIGHLIGHTING))
.to(fr.unice.polytech.si5.smarthome.am.shome.parser.antlr.internal.InternalShomeLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureHighlightingTokenDefProvider(Binder binder) {
binder.bind(ITokenDefProvider.class)
.annotatedWith(Names.named(LexerIdeBindings.HIGHLIGHTING))
.to(AntlrTokenDefProvider.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ContentAssistContext.Factory> bindContentAssistContext$Factory() {
return DelegatingContentAssistContextFactory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IContentAssistParser> bindIContentAssistParser() {
return ShomeParser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureContentAssistLexerProvider(Binder binder) {
binder.bind(InternalShomeLexer.class).toProvider(LexerProvider.create(InternalShomeLexer.class));
}
// contributed by org.eclipse.xtext.xtext.generator.validation.ValidatorFragment2
public Class<? extends AbstractValidatorConfigurationBlock> bindAbstractValidatorConfigurationBlock() {
return ShomeValidatorConfigurationBlock.class;
}
// contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2
public Class<? extends PrefixMatcher> bindPrefixMatcher() {
return FQNPrefixMatcher.class;
}
// contributed by org.eclipse.xtext.xtext.generator.exporting.QualifiedNamesFragment2
public Class<? extends IDependentElementsCalculator> bindIDependentElementsCalculator() {
return DefaultDependentElementsCalculator.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptionsBuilderScope(Binder binder) {
binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.NAMED_BUILDER_SCOPE)).to(CurrentDescriptions.ResourceSetAware.class);
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IXtextEditorCallback> bindIXtextEditorCallback() {
return NatureAddingEditorCallback.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends IContextualOutputConfigurationProvider> bindIContextualOutputConfigurationProvider() {
return EclipseOutputConfigurationProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public void configureIResourceDescriptionsPersisted(Binder binder) {
binder.bind(IResourceDescriptions.class).annotatedWith(Names.named(ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS)).to(IBuilderState.class);
}
// contributed by org.eclipse.xtext.xtext.generator.builder.BuilderIntegrationFragment2
public Class<? extends DocumentBasedDirtyResource> bindDocumentBasedDirtyResource() {
return PersistentDataAwareDirtyResource.class;
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public Class<? extends IXtextBuilderParticipant> bindIXtextBuilderParticipant() {
return BuilderParticipant.class;
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public IWorkspaceRoot bindIWorkspaceRootToInstance() {
return ResourcesPlugin.getWorkspace().getRoot();
}
// contributed by org.eclipse.xtext.xtext.generator.generator.GeneratorFragment2
public void configureBuilderPreferenceStoreInitializer(Binder binder) {
binder.bind(IPreferenceStoreInitializer.class)
.annotatedWith(Names.named("builderPreferenceInitializer"))
.to(BuilderPreferenceAccess.Initializer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.formatting.Formatter2Fragment2
public Class<? extends IContentFormatterFactory> bindIContentFormatterFactory() {
return ContentFormatterFactory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.labeling.LabelProviderFragment2
public Class<? extends ILabelProvider> bindILabelProvider() {
return ShomeLabelProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.labeling.LabelProviderFragment2
public void configureResourceUIServiceLabelProvider(Binder binder) {
binder.bind(ILabelProvider.class).annotatedWith(ResourceServiceDescriptionLabelProvider.class).to(ShomeDescriptionLabelProvider.class);
}
// contributed by org.eclipse.xtext.xtext.generator.ui.outline.OutlineTreeProviderFragment2
public Class<? extends IOutlineTreeProvider> bindIOutlineTreeProvider() {
return ShomeOutlineTreeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.outline.OutlineTreeProviderFragment2
public Class<? extends IOutlineTreeStructureProvider> bindIOutlineTreeStructureProvider() {
return ShomeOutlineTreeProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.quickfix.QuickfixProviderFragment2
public Class<? extends IssueResolutionProvider> bindIssueResolutionProvider() {
return ShomeQuickfixProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.contentAssist.ContentAssistFragment2
public Class<? extends IContentProposalProvider> bindIContentProposalProvider() {
return ShomeProposalProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public void configureIPreferenceStoreInitializer(Binder binder) {
binder.bind(IPreferenceStoreInitializer.class)
.annotatedWith(Names.named("RefactoringPreferences"))
.to(RefactoringPreferences.Initializer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameStrategy> bindIRenameStrategy() {
return DefaultRenameStrategy.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IReferenceUpdater> bindIReferenceUpdater() {
return DefaultReferenceUpdater.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameRefactoringProvider> bindIRenameRefactoringProvider() {
return DefaultRenameRefactoringProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.refactoring.RefactorElementNameFragment2
public Class<? extends IRenameSupport.Factory> bindIRenameSupport$Factory() {
return DefaultRenameSupport.Factory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Provider<? extends TemplatesLanguageConfiguration> provideTemplatesLanguageConfiguration() {
return AccessibleCodetemplatesActivator.getTemplatesLanguageConfigurationProvider();
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Provider<? extends LanguageRegistry> provideLanguageRegistry() {
return AccessibleCodetemplatesActivator.getLanguageRegistry();
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
@SingletonBinding(eager=true)
public Class<? extends LanguageRegistrar> bindLanguageRegistrar() {
return LanguageRegistrar.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends XtextTemplatePreferencePage> bindXtextTemplatePreferencePage() {
return AdvancedTemplatesPreferencePage.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends IPartialEditingContentAssistParser> bindIPartialEditingContentAssistParser() {
return PartialShomeContentAssistParser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.templates.CodetemplatesGeneratorFragment2
public Class<? extends IPartialEditingContentAssistContextFactory> bindIPartialEditingContentAssistContextFactory() {
return PartialEditingContentAssistContextFactory.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.compare.CompareFragment2
public Class<? extends IViewerCreator> bindIViewerCreator() {
return DefaultViewerCreator.class;
}
// contributed by org.eclipse.xtext.xtext.generator.ui.compare.CompareFragment2
public void configureCompareViewerTitle(Binder binder) {
binder.bind(String.class).annotatedWith(Names.named(UIBindings.COMPARE_VIEWER_TITLE)).toInstance("Shome Compare");
}
}
|
9241e102b576d37be60d847d9d0fbd73501d6cb9
| 1,599 |
java
|
Java
|
presentation/src/main/java/com/kienht/presentation/features/OICViewModelFactory.java
|
hantrungkien/android-clean-architecture-components-boilerplate
|
08e19446025eb8d598ec873ec60ee0836595eaac
|
[
"Apache-2.0"
] | 13 |
2018-05-03T08:47:28.000Z
|
2020-06-07T10:52:38.000Z
|
presentation/src/main/java/com/kienht/presentation/features/OICViewModelFactory.java
|
hantrungkien/android-clean-architecture-components-boilerplate
|
08e19446025eb8d598ec873ec60ee0836595eaac
|
[
"Apache-2.0"
] | 1 |
2021-05-17T10:01:00.000Z
|
2021-05-17T12:03:32.000Z
|
presentation/src/main/java/com/kienht/presentation/features/OICViewModelFactory.java
|
hantrungkien/android-clean-architecture-components-boilerplate
|
08e19446025eb8d598ec873ec60ee0836595eaac
|
[
"Apache-2.0"
] | 4 |
2018-12-02T20:18:28.000Z
|
2019-08-08T14:50:32.000Z
| 31.352941 | 180 | 0.657286 | 1,002,062 |
package com.kienht.presentation.features;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.support.annotation.NonNull;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Note:
* Created by kienht on 5/30/18.
* https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/viewmodel/GithubViewModelFactory.kt
*/
@Singleton
public class OICViewModelFactory implements ViewModelProvider.Factory {
private Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
@Inject
public OICViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
9241e14ce2569222173d7148cc2133a4f06c3ff6
| 2,177 |
java
|
Java
|
src/test/java/cambio/simulator/entities/microservice/MicroserviceInstanceTest.java
|
ittaq/resilience-simulator
|
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/cambio/simulator/entities/microservice/MicroserviceInstanceTest.java
|
ittaq/resilience-simulator
|
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
|
[
"Apache-2.0"
] | 21 |
2021-07-23T17:52:51.000Z
|
2022-03-19T19:31:39.000Z
|
src/test/java/cambio/simulator/entities/microservice/MicroserviceInstanceTest.java
|
ittaq/resilience-simulator
|
fe70b73637c59fb72e8ba0ab1ee2893ffa807332
|
[
"Apache-2.0"
] | null | null | null | 36.898305 | 114 | 0.656408 | 1,002,063 |
package cambio.simulator.entities.microservice;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import cambio.simulator.testutils.RandomTieredModel;
import cambio.simulator.testutils.TestUtils;
import co.paralleluniverse.fibers.SuspendExecution;
import desmoj.core.simulator.Experiment;
import desmoj.core.simulator.ExternalEvent;
import desmoj.core.simulator.TimeInstant;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MicroserviceInstanceTest {
@Test
void shutDownTest() {
RandomTieredModel model = new RandomTieredModel("MSTestModel", 3, 3);
Experiment exp = TestUtils.getExampleExperiment(model, 300);
final List<MicroserviceInstance> instanceList = new LinkedList<>();
ExternalEvent instanceCollection = new ExternalEvent(model, "InstanceCollection", false) {
@Override
public void eventRoutine() throws SuspendExecution {
model.getAllMicroservices().forEach(microservice -> {
try {
Field f = Microservice.class.getDeclaredField("instancesSet");
f.setAccessible(true);
instanceList.addAll((Collection<? extends MicroserviceInstance>) f.get(microservice));
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
});
}
};
instanceCollection.schedule(new TimeInstant(10));
ExternalEvent shutdown = new ExternalEvent(model, "ShutdownEvent", false) {
@Override
public void eventRoutine() throws SuspendExecution {
model.getAllMicroservices().forEach(microservice -> microservice.scaleToInstancesCount(0));
}
};
shutdown.schedule(new TimeInstant(200));
exp.start();
exp.finish();
instanceList.forEach(instance -> Assertions.assertTrue(
instance.getState() == InstanceState.SHUTDOWN || instance.getState() == InstanceState.SHUTTING_DOWN));
}
}
|
9241e1aa2fbf4c49d60e7e336bcb0af85e15cc6d
| 631 |
java
|
Java
|
gold-mr/mr-website-analyse/src/main/java/com/platform/website/transformer/service/rpc/IDimensionConverter.java
|
yurenfangzhou/bdp-gold
|
7320588bb629b63965baeb4818fda811a82d1405
|
[
"Apache-2.0"
] | 13 |
2021-01-23T10:10:23.000Z
|
2021-11-08T08:40:53.000Z
|
gold-mr/mr-website-analyse/src/main/java/com/platform/website/transformer/service/rpc/IDimensionConverter.java
|
yurenfangzhou/bdp-gold
|
7320588bb629b63965baeb4818fda811a82d1405
|
[
"Apache-2.0"
] | 1 |
2021-05-14T06:59:14.000Z
|
2021-05-14T06:59:14.000Z
|
gold-mr/mr-website-analyse/src/main/java/com/platform/website/transformer/service/rpc/IDimensionConverter.java
|
bdpteam/bdp-gold
|
4ad442fdf9d9d312c9422d262c65854544a55604
|
[
"Apache-2.0"
] | 10 |
2021-01-28T15:17:57.000Z
|
2022-01-24T02:54:34.000Z
| 23.37037 | 81 | 0.721078 | 1,002,064 |
package com.platform.website.transformer.service.rpc;
import com.platform.website.transformer.model.dim.base.BaseDimension;
import java.io.IOException;
import org.apache.hadoop.ipc.VersionedProtocol;
/**
* 提供专门操作dimension表的接口
*
* @author wlhbdp
*
*/
public interface IDimensionConverter extends VersionedProtocol {
// 版本id
public static final long versionID = 1;
/**
* 根据dimension的value值获取id<br/>
* 如果数据库中有,那么直接返回。如果没有,那么进行插入后返回新的id值
*
* @param dimension
* @return
* @throws IOException
*/
public int getDimensionIdByValue(BaseDimension dimension) throws IOException;
}
|
9241e1c0ec18a67496587cc0887382102ec166e6
| 961 |
java
|
Java
|
hzero-starter-core/src/main/java/org/hzero/core/base/TokenConstants.java
|
JodenHe/hzero-starter-parent
|
c1f642f18e7a0001bc16d1d12eff30d9c6f39fe4
|
[
"Apache-2.0"
] | 27 |
2020-09-23T03:05:26.000Z
|
2022-03-29T08:08:54.000Z
|
hzero-starter-core/src/main/java/org/hzero/core/base/TokenConstants.java
|
JodenHe/hzero-starter-parent
|
c1f642f18e7a0001bc16d1d12eff30d9c6f39fe4
|
[
"Apache-2.0"
] | 3 |
2020-09-24T06:34:27.000Z
|
2020-12-02T01:47:52.000Z
|
hzero-starter-core/src/main/java/org/hzero/core/base/TokenConstants.java
|
JodenHe/hzero-starter-parent
|
c1f642f18e7a0001bc16d1d12eff30d9c6f39fe4
|
[
"Apache-2.0"
] | 23 |
2020-09-23T07:51:23.000Z
|
2021-11-23T13:52:10.000Z
| 27.457143 | 101 | 0.694069 | 1,002,065 |
package org.hzero.core.base;
import io.choerodon.core.convertor.ApplicationContextHelper;
import org.hzero.core.properties.CoreProperties;
/**
* Token 相关常量
*
* @author bojiangzhou 2020/06/24
*/
public final class TokenConstants {
public static final String HEADER_JWT = "Jwt_Token";
public static final String HEADER_BEARER = "Bearer";
public static final String HEADER_AUTH = getAuthHeaderName();
public static final String ACCESS_TOKEN = "access_token";
public static final String JWT_TOKEN = "jwt_token";
private static CoreProperties coreProperties;
/**
* @return 认证令牌请求头名称
*/
public static String getAuthHeaderName() {
if (coreProperties == null) {
synchronized (BaseHeaders.class) {
coreProperties = ApplicationContextHelper.getContext().getBean(CoreProperties.class);
}
}
return coreProperties.getResource().getAuthHeaderName();
}
}
|
9241e29ba8b1c6db4557ead1138126e6e87334ff
| 3,143 |
java
|
Java
|
nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotMetadataResult.java
|
CefBoud/nifi
|
de88ce7a618aac4f7c886ccd1be39d3047313adb
|
[
"Apache-2.0"
] | 3,212 |
2015-07-18T01:39:17.000Z
|
2022-03-31T04:10:07.000Z
|
nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotMetadataResult.java
|
CefBoud/nifi
|
de88ce7a618aac4f7c886ccd1be39d3047313adb
|
[
"Apache-2.0"
] | 4,786 |
2015-07-24T18:57:19.000Z
|
2022-03-31T22:21:57.000Z
|
nifi-toolkit/nifi-toolkit-cli/src/main/java/org/apache/nifi/toolkit/cli/impl/result/registry/VersionedFlowSnapshotMetadataResult.java
|
CefBoud/nifi
|
de88ce7a618aac4f7c886ccd1be39d3047313adb
|
[
"Apache-2.0"
] | 2,715 |
2015-07-20T11:26:22.000Z
|
2022-03-31T13:42:28.000Z
| 38.802469 | 129 | 0.691696 | 1,002,066 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.toolkit.cli.impl.result.registry;
import org.apache.commons.lang3.Validate;
import org.apache.nifi.registry.flow.VersionedFlowSnapshotMetadata;
import org.apache.nifi.toolkit.cli.api.ResultType;
import org.apache.nifi.toolkit.cli.impl.result.AbstractWritableResult;
import org.apache.nifi.toolkit.cli.impl.result.writer.DynamicTableWriter;
import org.apache.nifi.toolkit.cli.impl.result.writer.Table;
import org.apache.nifi.toolkit.cli.impl.result.writer.TableWriter;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* Result for a list of VersionedFlowSnapshotMetadata.
*/
public class VersionedFlowSnapshotMetadataResult extends AbstractWritableResult<List<VersionedFlowSnapshotMetadata>> {
private final List<VersionedFlowSnapshotMetadata> versions;
public VersionedFlowSnapshotMetadataResult(final ResultType resultType, final List<VersionedFlowSnapshotMetadata> versions) {
super(resultType);
this.versions = versions;
Validate.notNull(this.versions);
this.versions.sort(Comparator.comparing(VersionedFlowSnapshotMetadata::getVersion));
}
@Override
public List<VersionedFlowSnapshotMetadata> getResult() {
return this.versions;
}
@Override
protected void writeSimpleResult(final PrintStream output) {
if (versions == null || versions.isEmpty()) {
return;
}
// date length, with locale specifics
final String datePattern = "%1$ta, %<tb %<td %<tY %<tR %<tZ";
final int dateLength = String.format(datePattern, new Date()).length();
final Table table = new Table.Builder()
.column("Ver", 3, 3, false)
.column("Date", dateLength, dateLength, false)
.column("Author", 20, 200, true)
.column("Message", 8, 40, true)
.build();
versions.forEach(vfs -> {
table.addRow(
String.valueOf(vfs.getVersion()),
String.format(datePattern, new Date(vfs.getTimestamp())),
vfs.getAuthor(),
vfs.getComments()
);
});
final TableWriter tableWriter = new DynamicTableWriter();
tableWriter.write(table, output);
}
}
|
9241e2b4bae79665202b418b85aa68d8249688d7
| 2,164 |
java
|
Java
|
src/jy/ola/Receiver.java
|
jryantz/project-mercury
|
5ec39cbc295ebaeab561f5932363582e14784415
|
[
"MIT"
] | null | null | null |
src/jy/ola/Receiver.java
|
jryantz/project-mercury
|
5ec39cbc295ebaeab561f5932363582e14784415
|
[
"MIT"
] | null | null | null |
src/jy/ola/Receiver.java
|
jryantz/project-mercury
|
5ec39cbc295ebaeab561f5932363582e14784415
|
[
"MIT"
] | null | null | null | 27.74359 | 118 | 0.44963 | 1,002,067 |
package jy.ola;
import java.io.IOException;
import java.net.DatagramPacket;
/**
*
* @author jonathanyantz
*/
public class Receiver implements Runnable {
private boolean running = true;
public boolean server = false;
public boolean client = false;
/**
* Starts the receiver thread, allowing the Node to send and receive simultaneously.
*
* <p>Makes sure the receiver should be running, then checks for whether this is for the client or the server.</p>
* <p>Sets up the receiving socket then waits for a message to be received.</p>
*/
@Override
public void run() {
while(running && (server || client)) {
byte[] receive = new byte[1074];
try {
DatagramPacket receivePkt = new DatagramPacket(receive, receive.length);
if(server) {
Node.socket.receive(receivePkt);
if(Node.remPort == 0) {
Node.waitflip();
try {
Thread.sleep(300);
} catch(InterruptedException e) {}
System.out.println("\nClient connected!");
Node.remPort = receivePkt.getPort();
Node.remAddr = receivePkt.getAddress();
}
}
if(client) {
Node.socket.receive(receivePkt);
}
String messageIn = new String(receivePkt.getData());
Packet.unpack(messageIn);
} catch(IOException e) {}
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
}
} // end run
/**
* Ends execution of the receiver thread.
*/
public void quit() {
running = false;
} // end quit
} // end class Receiver
|
9241e313d90f8296dfa31584d527fb2d80e94312
| 3,347 |
java
|
Java
|
tech-services/jbb-lib-mvc/src/main/java/org/jbb/lib/mvc/session/JbbSessionRepository.java
|
jbb-project/jbb
|
cefa12cda40804395b2d6e8bea0fb8352610b761
|
[
"Apache-2.0"
] | 4 |
2017-02-23T15:35:33.000Z
|
2020-08-03T22:00:17.000Z
|
tech-services/jbb-lib-mvc/src/main/java/org/jbb/lib/mvc/session/JbbSessionRepository.java
|
jbb-project/jbb
|
cefa12cda40804395b2d6e8bea0fb8352610b761
|
[
"Apache-2.0"
] | 1 |
2019-05-14T18:54:24.000Z
|
2019-05-14T18:54:24.000Z
|
tech-services/jbb-lib-mvc/src/main/java/org/jbb/lib/mvc/session/JbbSessionRepository.java
|
jbb-project/jbb
|
cefa12cda40804395b2d6e8bea0fb8352610b761
|
[
"Apache-2.0"
] | 3 |
2018-03-29T15:51:09.000Z
|
2019-11-25T02:46:41.000Z
| 34.864583 | 135 | 0.72692 | 1,002,068 |
/*
* Copyright (C) 2017 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.lib.mvc.session;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.session.ExpiringSession;
import org.springframework.session.MapSession;
import org.springframework.session.SessionRepository;
import org.springframework.session.events.SessionDeletedEvent;
import org.springframework.session.events.SessionExpiredEvent;
import org.springframework.stereotype.Repository;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* This is own implementation of MapSessionRepository. The only change with compare to original implementation is method @getSessionMap
* Method is using in ACP in session management
*/
@Repository
public class JbbSessionRepository implements SessionRepository<ExpiringSession> {
private final Map<String, ExpiringSession> sessions;
private final ApplicationEventPublisher eventPublisher;
private Integer defaultMaxInactiveInterval;
@Autowired
public JbbSessionRepository(ApplicationEventPublisher applicationEventPublisher) {
this(new ConcurrentHashMap<>(), applicationEventPublisher);
}
public JbbSessionRepository(Map<String, ExpiringSession> sessions, ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
if (sessions == null) {
throw new IllegalArgumentException("sessions cannot be null");
}
this.sessions = sessions;
}
public Integer getDefaultMaxInactiveInterval() {
return defaultMaxInactiveInterval;
}
public void setDefaultMaxInactiveInterval(int defaultMaxInactiveInterval) {
this.defaultMaxInactiveInterval = Integer.valueOf(defaultMaxInactiveInterval);
}
public void save(ExpiringSession session) {
this.sessions.put(session.getId(), new MapSession(session));
}
public ExpiringSession getSession(String id) {
ExpiringSession saved = this.sessions.get(id);
if (saved == null) {
return null;
}
if (saved.isExpired()) {
this.eventPublisher.publishEvent(new SessionExpiredEvent(this, saved));
this.sessions.remove(id);
return null;
}
return new MapSession(saved);
}
public Map<String, ExpiringSession> getSessionMap() {
sessions.entrySet().forEach(entry -> getSession(entry.getKey()));
return ImmutableMap.copyOf(sessions);
}
public void delete(String id) {
ExpiringSession toRemove = this.sessions.get(id);
this.sessions.remove(id);
this.eventPublisher.publishEvent(new SessionDeletedEvent(this, toRemove));
}
public ExpiringSession createSession() {
ExpiringSession result = new MapSession();
if (this.defaultMaxInactiveInterval != null) {
result.setMaxInactiveIntervalInSeconds(this.defaultMaxInactiveInterval);
}
return result;
}
}
|
9241e62ccc2614d8fbecaf83a2c6d0481bb24067
| 896 |
java
|
Java
|
LACCPlus/Hadoop/621_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
LACCPlus/Hadoop/621_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
LACCPlus/Hadoop/621_1.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null | 35.84 | 73 | 0.659598 | 1,002,069 |
//,temp,RMStateStore.java,486,505,temp,RMStateStore.java,436,456
//,3
public class xxx {
@Override
public void transition(RMStateStore store, RMStateStoreEvent event) {
if (!(event instanceof RMStateStoreStoreReservationEvent)) {
// should never happen
LOG.error("Illegal event type: " + event.getClass());
return;
}
RMStateStoreStoreReservationEvent reservationEvent =
(RMStateStoreStoreReservationEvent) event;
try {
LOG.info("Removing reservation allocation." + reservationEvent
.getReservationIdName());
store.removeReservationState(
reservationEvent.getPlanName(),
reservationEvent.getReservationIdName());
} catch (Exception e) {
LOG.error("Error while removing reservation allocation.", e);
store.notifyStoreOperationFailed(e);
}
}
};
|
9241e636f47f9a6552389632f11c03f8b65790f0
| 2,367 |
java
|
Java
|
pocs/terraform-cdk-fun/src/main/java/imports/kubernetes/DataKubernetesPodSpecAffinity.java
|
ladybug/java-pocs
|
6aa683dc5b0c3cc6fb9695713bac73d38aca53fd
|
[
"Unlicense"
] | 36 |
2019-08-29T12:24:31.000Z
|
2022-03-31T13:25:58.000Z
|
pocs/terraform-cdk-fun/src/main/java/imports/kubernetes/DataKubernetesPodSpecAffinity.java
|
ladybug/java-pocs
|
6aa683dc5b0c3cc6fb9695713bac73d38aca53fd
|
[
"Unlicense"
] | 68 |
2020-06-23T16:34:50.000Z
|
2022-03-23T07:24:09.000Z
|
pocs/terraform-cdk-fun/src/main/java/imports/kubernetes/DataKubernetesPodSpecAffinity.java
|
ladybug/java-pocs
|
6aa683dc5b0c3cc6fb9695713bac73d38aca53fd
|
[
"Unlicense"
] | 30 |
2018-04-06T22:08:22.000Z
|
2022-03-31T17:57:24.000Z
| 62.289474 | 367 | 0.780735 | 1,002,070 |
package imports.kubernetes;
@javax.annotation.Generated(value = "jsii-pacmak/1.30.0 (build adae23f)", date = "2021-06-16T06:12:12.508Z")
@software.amazon.jsii.Jsii(module = imports.kubernetes.$Module.class, fqn = "kubernetes.DataKubernetesPodSpecAffinity")
public class DataKubernetesPodSpecAffinity extends com.hashicorp.cdktf.ComplexComputedList {
protected DataKubernetesPodSpecAffinity(final software.amazon.jsii.JsiiObjectRef objRef) {
super(objRef);
}
protected DataKubernetesPodSpecAffinity(final software.amazon.jsii.JsiiObject.InitializationMode initializationMode) {
super(initializationMode);
}
/**
* @param terraformResource This parameter is required.
* @param terraformAttribute This parameter is required.
* @param complexComputedListIndex This parameter is required.
*/
@software.amazon.jsii.Stability(software.amazon.jsii.Stability.Level.Experimental)
public DataKubernetesPodSpecAffinity(final @org.jetbrains.annotations.NotNull com.hashicorp.cdktf.ITerraformResource terraformResource, final @org.jetbrains.annotations.NotNull java.lang.String terraformAttribute, final @org.jetbrains.annotations.NotNull java.lang.String complexComputedListIndex) {
super(software.amazon.jsii.JsiiObject.InitializationMode.JSII);
software.amazon.jsii.JsiiEngine.getInstance().createNewObject(this, new Object[] { java.util.Objects.requireNonNull(terraformResource, "terraformResource is required"), java.util.Objects.requireNonNull(terraformAttribute, "terraformAttribute is required"), java.util.Objects.requireNonNull(complexComputedListIndex, "complexComputedListIndex is required") });
}
public @org.jetbrains.annotations.NotNull java.lang.Object getNodeAffinity() {
return software.amazon.jsii.Kernel.get(this, "nodeAffinity", software.amazon.jsii.NativeType.forClass(java.lang.Object.class));
}
public @org.jetbrains.annotations.NotNull java.lang.Object getPodAffinity() {
return software.amazon.jsii.Kernel.get(this, "podAffinity", software.amazon.jsii.NativeType.forClass(java.lang.Object.class));
}
public @org.jetbrains.annotations.NotNull java.lang.Object getPodAntiAffinity() {
return software.amazon.jsii.Kernel.get(this, "podAntiAffinity", software.amazon.jsii.NativeType.forClass(java.lang.Object.class));
}
}
|
9241e68f15432dd325b399df9a3835574eab97f9
| 626 |
java
|
Java
|
app/src/main/java/dragons/android/bakingtime/ViewHolders/StepsHeaderViewHolder.java
|
jgebbeken/BakingTime
|
aa7df056489887ee700c0511bb275e69eeb63185
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/dragons/android/bakingtime/ViewHolders/StepsHeaderViewHolder.java
|
jgebbeken/BakingTime
|
aa7df056489887ee700c0511bb275e69eeb63185
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/dragons/android/bakingtime/ViewHolders/StepsHeaderViewHolder.java
|
jgebbeken/BakingTime
|
aa7df056489887ee700c0511bb275e69eeb63185
|
[
"Apache-2.0"
] | null | null | null | 21.586207 | 67 | 0.760383 | 1,002,071 |
package dragons.android.bakingtime.ViewHolders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import dragons.android.bakingtime.R;
public class StepsHeaderViewHolder extends RecyclerView.ViewHolder{
@SuppressWarnings("WeakerAccess")
@BindView(R.id.tvStepsHeader) TextView tvStepsHeader;
public StepsHeaderViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
public TextView getTvStepsHeader() {
return tvStepsHeader;
}
}
|
9241e77cefebffff48473e85e84e4301adba00d7
| 3,357 |
java
|
Java
|
aliyun-java-sdk-das/src/main/java/com/aliyuncs/das/model/v20200116/GetQueryOptimizeRuleListResponse.java
|
rnarla123/aliyun-openapi-java-sdk
|
8dc187b1487d2713663710a1d97e23d72a87ffd9
|
[
"Apache-2.0"
] | 1 |
2022-02-12T06:01:36.000Z
|
2022-02-12T06:01:36.000Z
|
aliyun-java-sdk-das/src/main/java/com/aliyuncs/das/model/v20200116/GetQueryOptimizeRuleListResponse.java
|
rnarla123/aliyun-openapi-java-sdk
|
8dc187b1487d2713663710a1d97e23d72a87ffd9
|
[
"Apache-2.0"
] | null | null | null |
aliyun-java-sdk-das/src/main/java/com/aliyuncs/das/model/v20200116/GetQueryOptimizeRuleListResponse.java
|
rnarla123/aliyun-openapi-java-sdk
|
8dc187b1487d2713663710a1d97e23d72a87ffd9
|
[
"Apache-2.0"
] | null | null | null | 19.293103 | 89 | 0.67471 | 1,002,072 |
/*
* 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.aliyuncs.das.model.v20200116;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.das.transform.v20200116.GetQueryOptimizeRuleListResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class GetQueryOptimizeRuleListResponse extends AcsResponse {
private String code;
private String message;
private String requestId;
private String success;
private Data data;
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getSuccess() {
return this.success;
}
public void setSuccess(String success) {
this.success = success;
}
public Data getData() {
return this.data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data {
private Long total;
private Integer pageNo;
private Integer pageSize;
private String extra;
private List<Rules> list;
public Long getTotal() {
return this.total;
}
public void setTotal(Long total) {
this.total = total;
}
public Integer getPageNo() {
return this.pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return this.pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String getExtra() {
return this.extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public List<Rules> getList() {
return this.list;
}
public void setList(List<Rules> list) {
this.list = list;
}
public static class Rules {
private String type;
private String name;
private String ruleId;
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRuleId() {
return this.ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
}
}
@Override
public GetQueryOptimizeRuleListResponse getInstance(UnmarshallerContext context) {
return GetQueryOptimizeRuleListResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
|
9241e83af4a49f8e9fbd05cab3096a3b0ec1b190
| 4,188 |
java
|
Java
|
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GrokClassifierJsonUnmarshaller.java
|
rjappala/aws-sdkjava
|
78d074030ad3683d6664e1f87213f4a441c1b343
|
[
"Apache-2.0"
] | 1 |
2021-06-05T16:58:52.000Z
|
2021-06-05T16:58:52.000Z
|
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GrokClassifierJsonUnmarshaller.java
|
rjappala/aws-sdkjava
|
78d074030ad3683d6664e1f87213f4a441c1b343
|
[
"Apache-2.0"
] | 16 |
2018-05-15T05:35:42.000Z
|
2018-05-15T07:54:48.000Z
|
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GrokClassifierJsonUnmarshaller.java
|
rjappala/aws-sdkjava
|
78d074030ad3683d6664e1f87213f4a441c1b343
|
[
"Apache-2.0"
] | 3 |
2018-07-13T14:46:29.000Z
|
2021-02-15T13:12:55.000Z
| 42.30303 | 136 | 0.63276 | 1,002,073 |
/*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.glue.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.glue.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* GrokClassifier JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GrokClassifierJsonUnmarshaller implements Unmarshaller<GrokClassifier, JsonUnmarshallerContext> {
public GrokClassifier unmarshall(JsonUnmarshallerContext context) throws Exception {
GrokClassifier grokClassifier = new GrokClassifier();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
grokClassifier.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Classification", targetDepth)) {
context.nextToken();
grokClassifier.setClassification(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreationTime", targetDepth)) {
context.nextToken();
grokClassifier.setCreationTime(context.getUnmarshaller(java.util.Date.class).unmarshall(context));
}
if (context.testExpression("LastUpdated", targetDepth)) {
context.nextToken();
grokClassifier.setLastUpdated(context.getUnmarshaller(java.util.Date.class).unmarshall(context));
}
if (context.testExpression("Version", targetDepth)) {
context.nextToken();
grokClassifier.setVersion(context.getUnmarshaller(Long.class).unmarshall(context));
}
if (context.testExpression("GrokPattern", targetDepth)) {
context.nextToken();
grokClassifier.setGrokPattern(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CustomPatterns", targetDepth)) {
context.nextToken();
grokClassifier.setCustomPatterns(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return grokClassifier;
}
private static GrokClassifierJsonUnmarshaller instance;
public static GrokClassifierJsonUnmarshaller getInstance() {
if (instance == null)
instance = new GrokClassifierJsonUnmarshaller();
return instance;
}
}
|
9241ea65d32234a814d49672637e62ea065f8634
| 1,091 |
java
|
Java
|
admin-backend/src/main/java/io/webapp/module/business/log/userloginlog/domain/UserLoginLogDTO.java
|
wangxian/smart-admin
|
68ac49fc00b28286e081b900914e07f154ac85de
|
[
"MIT"
] | 1 |
2021-02-22T04:05:25.000Z
|
2021-02-22T04:05:25.000Z
|
admin-backend/src/main/java/io/webapp/module/business/log/userloginlog/domain/UserLoginLogDTO.java
|
wangxian/smart-admin
|
68ac49fc00b28286e081b900914e07f154ac85de
|
[
"MIT"
] | null | null | null |
admin-backend/src/main/java/io/webapp/module/business/log/userloginlog/domain/UserLoginLogDTO.java
|
wangxian/smart-admin
|
68ac49fc00b28286e081b900914e07f154ac85de
|
[
"MIT"
] | null | null | null | 20.203704 | 68 | 0.690192 | 1,002,074 |
package io.webapp.module.business.log.userloginlog.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* [ 用户登录日志 ]
*
* @author yandanyang
* @version 1.0
* @date 2019/3/27 0027 下午 12:27
* @since JDK1.8
*/
@Data
public class UserLoginLogDTO {
@ApiModelProperty("主键")
private Long id;
@ApiModelProperty("员工id")
private Long userId;
@ApiModelProperty("用户名")
private String userName;
@ApiModelProperty("用户ip")
private String remoteIp;
@ApiModelProperty("用户端口")
private Integer remotePort;
@ApiModelProperty("浏览器")
private String remoteBrowser;
@ApiModelProperty("操作系统")
private String remoteOs;
@ApiModelProperty("登录状态")
private Integer loginStatus;
@ApiModelProperty("更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updatedAt;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdAt;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.