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
9236e1550845787a1686a1d833d160d7b7f3fa16
621
java
Java
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/kr/co/popone/fitts/viewmodel/store/bridge/ShopBridgeViewModel$registerProductLikeEvent$1.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
4
2019-10-07T05:17:21.000Z
2020-11-02T08:29:13.000Z
analysis/reverse-engineering/decompile-fitts-with-gradle-20191031-2200/src/main/java/kr/co/popone/fitts/viewmodel/store/bridge/ShopBridgeViewModel$registerProductLikeEvent$1.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
38
2019-10-07T02:40:35.000Z
2019-12-12T09:15:24.000Z
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/store/bridge/ShopBridgeViewModel$registerProductLikeEvent$1.java
skkuse-adv/2019Fall_team2
3ea84c6be39855f54634a7f9b1093e80893886eb
[ "Apache-2.0" ]
5
2019-10-07T02:41:15.000Z
2020-10-30T01:36:08.000Z
36.529412
106
0.771337
997,857
package kr.co.popone.fitts.viewmodel.store.bridge; import io.reactivex.functions.Consumer; import kr.co.popone.fitts.event.WishStateUpdateEvent; final class ShopBridgeViewModel$registerProductLikeEvent$1<T> implements Consumer<WishStateUpdateEvent> { final /* synthetic */ ShopBridgeViewModel this$0; ShopBridgeViewModel$registerProductLikeEvent$1(ShopBridgeViewModel shopBridgeViewModel) { this.this$0 = shopBridgeViewModel; } public final void accept(WishStateUpdateEvent wishStateUpdateEvent) { this.this$0._productLikeEvent.postValue(wishStateUpdateEvent); } }
9236e1613ece66411158aa9944c59ef05f944faa
1,043
java
Java
weixin/weixin-admin/src/main/java/com/kotall/oms/weixin/entity/SysAccessTokenEntity.java
kotall/kotall-root
7e5dfe7eb006833a0d9e5e1972d6227a2e59f4bd
[ "MIT" ]
null
null
null
weixin/weixin-admin/src/main/java/com/kotall/oms/weixin/entity/SysAccessTokenEntity.java
kotall/kotall-root
7e5dfe7eb006833a0d9e5e1972d6227a2e59f4bd
[ "MIT" ]
null
null
null
weixin/weixin-admin/src/main/java/com/kotall/oms/weixin/entity/SysAccessTokenEntity.java
kotall/kotall-root
7e5dfe7eb006833a0d9e5e1972d6227a2e59f4bd
[ "MIT" ]
null
null
null
19.679245
81
0.688399
997,858
package com.kotall.oms.weixin.entity; import lombok.Data; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * @author : aracwong * @version : 1.0.0 * @date : 2018/3/4 0004 上午 10:12 */ @Data @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "sys_user_token") public class SysAccessTokenEntity { @Id private String uid; /** * access token */ private String accessToken; /** * 有效时间 */ private Long expiresIn; /** * 更新时间 */ @LastModifiedDate private Date updateTime; public SysAccessTokenEntity() { } public SysAccessTokenEntity(String uid, String accessToken, Long expiresIn) { this.uid = uid; this.accessToken = accessToken; this.expiresIn = expiresIn; } }
9236e195b66fd70cf6b8c2a5fb366a9d94ae10e7
151
java
Java
app/src/main/java/com/homains/daliloffline/media/FFTData.java
freetraveler87/140offline-android-daliloffline1
c196cb99f1280ae062ddfe836b66bc8bda1bee97
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/homains/daliloffline/media/FFTData.java
freetraveler87/140offline-android-daliloffline1
c196cb99f1280ae062ddfe836b66bc8bda1bee97
[ "Apache-2.0" ]
1
2018-12-17T15:38:15.000Z
2018-12-17T15:38:15.000Z
app/src/main/java/com/homains/daliloffline/media/FFTData.java
freetraveler87/140offline-android-daliloffline1
c196cb99f1280ae062ddfe836b66bc8bda1bee97
[ "Apache-2.0" ]
null
null
null
15.1
39
0.682119
997,859
package com.homains.daliloffline.media; public class FFTData { public FFTData(byte[] bytes) { this.bytes = bytes; } public byte[] bytes; }
9236e22dc82103ddbdfb4ecea69314739d485bcd
727
java
Java
src/main/java/com/spring/configuration/WebConfiguration.java
super-newbie94/bg-nt
28bfbc069662c080c303c48c1ac2ef75e2daae8c
[ "MIT" ]
null
null
null
src/main/java/com/spring/configuration/WebConfiguration.java
super-newbie94/bg-nt
28bfbc069662c080c303c48c1ac2ef75e2daae8c
[ "MIT" ]
null
null
null
src/main/java/com/spring/configuration/WebConfiguration.java
super-newbie94/bg-nt
28bfbc069662c080c303c48c1ac2ef75e2daae8c
[ "MIT" ]
null
null
null
27.961538
81
0.679505
997,860
package com.spring.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * User: GaoYuan * Date: 17/12/13 * Time: 13:50 */ @Configuration public class WebConfiguration extends WebMvcConfigurerAdapter { /** * 设置前端请求跨域 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "OPTIONS", "PUT", "DELETE") .allowCredentials(false).maxAge(3600); } }
9236e230dc87c890252bc24e5c63b5fb6c88b61f
5,980
java
Java
src/main/java/mesh/polyhedra/plato/Dodecahedron.java
ChiralBehaviors/inviscid
9bce7c61bbaace3fd239164e8e4061d6cfd72594
[ "Apache-2.0" ]
null
null
null
src/main/java/mesh/polyhedra/plato/Dodecahedron.java
ChiralBehaviors/inviscid
9bce7c61bbaace3fd239164e8e4061d6cfd72594
[ "Apache-2.0" ]
null
null
null
src/main/java/mesh/polyhedra/plato/Dodecahedron.java
ChiralBehaviors/inviscid
9bce7c61bbaace3fd239164e8e4061d6cfd72594
[ "Apache-2.0" ]
null
null
null
39.342105
78
0.483445
997,861
package mesh.polyhedra.plato; import javax.vecmath.Vector3d; import mesh.Face; /** * An implementation of a regular dodecahedron mesh. * * @author Brian Yao */ public class Dodecahedron extends PlatonicSolid { private static final double RADIUS_FACTOR = Math.sqrt(3.0) / 4.0 * (1.0 + Math.sqrt(5)); /** * Construct a dodecahedron mesh centered at the origin with the specified * edge length. * * @param edgeLength * The length of each edge of this mesh. */ public Dodecahedron(double edgeLength) { super(edgeLength); // Construct vertices double goldenRatio = (1.0 + Math.sqrt(5.0)) / 2.0; double goldenRatioInv = 1.0 / goldenRatio; double edgeScaleFactor = edgeLength / (Math.sqrt(5.0) - 1.0); Vector3d[] cubePoints = new Vector3d[8]; for (int i = 0; i < 8; i++) { Vector3d vcube = new Vector3d(); vcube.z = (i & 1) == 1 ? -1.0 : 1.0; vcube.x = ((i >> 1) & 1) == 1 ? -1.0 : 1.0; vcube.y = ((i >> 2) & 1) == 1 ? -1.0 : 1.0; vcube.scale(edgeScaleFactor); cubePoints[i] = vcube; } Vector3d[] greenVertices = new Vector3d[4]; Vector3d[] pinkVertices = new Vector3d[4]; Vector3d[] blueVertices = new Vector3d[4]; for (int i = 0; i < 4; i++) { Vector3d vgreen = new Vector3d(); vgreen.x = (i & 1) == 1 ? -goldenRatio : goldenRatio; vgreen.y = ((i >> 1) & 1) == 1 ? -goldenRatioInv : goldenRatioInv; vgreen.scale(edgeScaleFactor); greenVertices[i] = vgreen; Vector3d vpink = new Vector3d(); vpink.z = (i & 1) == 1 ? -goldenRatio : goldenRatio; vpink.x = ((i >> 1) & 1) == 1 ? -goldenRatioInv : goldenRatioInv; vpink.scale(edgeScaleFactor); pinkVertices[i] = vpink; Vector3d vblue = new Vector3d(); vblue.y = (i & 1) == 1 ? -goldenRatio : goldenRatio; vblue.z = ((i >> 1) & 1) == 1 ? -goldenRatioInv : goldenRatioInv; vblue.scale(edgeScaleFactor); blueVertices[i] = vblue; } // Cube points: 0-7, green: 8-11, pink: 12-15, blue: 16-19 addVertexPositions(cubePoints); addVertexPositions(greenVertices); addVertexPositions(pinkVertices); addVertexPositions(blueVertices); Face[] faces = new Face[12]; for (int i = 0; i < faces.length; i++) { faces[i] = new Face(5); } // Construct faces faces[0].setAllVertexIndices(0, 16, 2, 14, 12); faces[1].setAllVertexIndices(1, 13, 15, 3, 18); faces[2].setAllVertexIndices(4, 12, 14, 6, 17); faces[3].setAllVertexIndices(5, 19, 7, 15, 13); faces[4].setAllVertexIndices(0, 12, 4, 10, 8); faces[5].setAllVertexIndices(2, 9, 11, 6, 14); faces[6].setAllVertexIndices(1, 8, 10, 5, 13); faces[7].setAllVertexIndices(3, 15, 7, 11, 9); faces[8].setAllVertexIndices(0, 8, 1, 18, 16); faces[9].setAllVertexIndices(4, 17, 19, 5, 10); faces[10].setAllVertexIndices(2, 16, 18, 3, 9); faces[11].setAllVertexIndices(6, 11, 7, 19, 17); addFaces(faces); setVertexNormalsToFaceNormals(); } /** * Construct a dodecahedron mesh with the specified circumradius. * * @param circumradius * The circumradius this polyhedron will have. * @param dummy * A dummy variable. */ public Dodecahedron(double circumradius, boolean dummy) { this(circumradius / RADIUS_FACTOR); } public Dodecahedron(Vector3d[] vertices) { super(PlatonicSolid.edgeLength(vertices)); addVertexPositions(vertices); Face[] faces = new Face[12]; for (int i = 0; i < faces.length; i++) { faces[i] = new Face(5); } @SuppressWarnings("unused") int[] v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; @SuppressWarnings("unused") int[][][] faceMap = { { { 0, 1, 2 }, { 2, 1, 5 }, { 2, 5, 6 } }, { { 0, 3, 7 }, { 0, 7, 1 }, { 1, 7, 4 } }, { { 0, 2, 8 }, { 0, 8, 9 }, { 0, 9, 3 } }, { { 1, 4, 10 }, { 1, 10, 5 }, { 5, 10, 11 } }, { { 2, 6, 8 }, { 6, 14, 8 }, { 6, 12, 14 } }, { { 3, 9, 7 }, { 7, 9, 13 }, { 13, 9, 15 } }, { { 4, 7, 10 }, { 10, 7, 16 }, { 16, 7, 13 } }, { { 5, 11, 17 }, { 5, 17, 12 }, { 5, 12, 6 } }, { { 8, 14, 18 }, { 8, 18, 15 }, { 8, 15, 9 } }, { { 10, 16, 19 }, { 10, 19, 11 }, { 11, 19, 17 } }, { { 12, 17, 19 }, { 12, 19, 18 }, { 12, 18, 14 } }, { { 13, 15, 18 }, { 13, 18, 19 }, { 13, 19, 16 } } }; // Construct faces faces[0].setAllVertexIndices(0, 1, 6, 5, 2); faces[1].setAllVertexIndices(0, 3, 7, 1, 4); faces[2].setAllVertexIndices(0, 2, 8, 9, 3); faces[3].setAllVertexIndices(1, 4, 10, 5, 11); faces[4].setAllVertexIndices(2, 6, 8, 14, 12); faces[5].setAllVertexIndices(3, 9, 7, 13, 15); faces[6].setAllVertexIndices(4, 7, 10, 16, 13); faces[7].setAllVertexIndices(5, 11, 17, 12, 6); faces[8].setAllVertexIndices(8, 14, 18, 15, 9); faces[9].setAllVertexIndices(10, 16, 19, 11, 17); faces[10].setAllVertexIndices(12, 17, 19, 18, 14); faces[11].setAllVertexIndices(13, 15, 18, 19, 16); addFaces(faces); setVertexNormalsToFaceNormals(); } }
9236e27f262aad58da970795744018fa849604a4
8,413
java
Java
src/main/java/youtube/data/UploadThumbnail.java
TELECOMNancy/pcd-2016-martynique
afab886adb1f0fec5e349d10ec8435edb98e49cc
[ "Apache-2.0" ]
null
null
null
src/main/java/youtube/data/UploadThumbnail.java
TELECOMNancy/pcd-2016-martynique
afab886adb1f0fec5e349d10ec8435edb98e49cc
[ "Apache-2.0" ]
null
null
null
src/main/java/youtube/data/UploadThumbnail.java
TELECOMNancy/pcd-2016-martynique
afab886adb1f0fec5e349d10ec8435edb98e49cc
[ "Apache-2.0" ]
null
null
null
42.705584
113
0.608939
997,862
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package youtube.data; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.media.MediaHttpUploader; import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener; import com.google.api.client.http.InputStreamContent; import youtube.Auth; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.YouTube.Thumbnails.Set; import com.google.api.services.youtube.model.ThumbnailSetResponse; import com.google.common.collect.Lists; import java.io.*; import java.util.List; /** * This sample uses MediaHttpUploader to upload an image and then calls the * API's youtube.thumbnails.set method to set the image as the custom thumbnail * for a video. * * @author Ibrahim Ulukaya */ public class UploadThumbnail { /** * Define a global instance of a Youtube object, which will be used * to make YouTube Data API requests. */ private static YouTube youtube; /** * Define a global variable that specifies the MIME type of the image * being uploaded. */ private static final String IMAGE_FILE_FORMAT = "image/png"; /** * Prompt the user to specify a video ID and the path for a thumbnail * image. Then call the API to set the image as the thumbnail for the video. * * @param args command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "uploadthumbnail"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName( "youtube-cmdline-uploadthumbnail-sample").build(); // Prompt the user to enter the video ID of the video being updated. String videoId = getVideoIdFromUser(); System.out.println("You chose " + videoId + " to upload a thumbnail."); // Prompt the user to specify the location of the thumbnail image. File imageFile = getImageFromUser(); System.out.println("You chose " + imageFile + " to upload."); // Create an object that contains the thumbnail image file's // contents. InputStreamContent mediaContent = new InputStreamContent( IMAGE_FILE_FORMAT, new BufferedInputStream(new FileInputStream(imageFile))); mediaContent.setLength(imageFile.length()); // Create an API request that specifies that the mediaContent // object is the thumbnail of the specified video. Set thumbnailSet = youtube.thumbnails().set(videoId, mediaContent); // Set the upload type and add an event listener. MediaHttpUploader uploader = thumbnailSet.getMediaHttpUploader(); // Indicate whether direct media upload is enabled. A value of // "True" indicates that direct media upload is enabled and that // the entire media content will be uploaded in a single request. // A value of "False," which is the default, indicates that the // request will use the resumable media upload protocol, which // supports the ability to resume an upload operation after a // network interruption or other transmission failure, saving // time and bandwidth in the event of network failures. uploader.setDirectUploadEnabled(false); // Set the upload state for the thumbnail image. MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() { //@Override public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { // This value is set before the initiation request is // sent. case INITIATION_STARTED: System.out.println("Initiation Started"); break; // This value is set after the initiation request // completes. case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; // This value is set after a media file chunk is // uploaded. case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; // This value is set after the entire media file has // been successfully uploaded. case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; // This value indicates that the upload process has // not started yet. case NOT_STARTED: System.out.println("Upload Not Started!"); break; } } }; uploader.setProgressListener(progressListener); // Upload the image and set it as the specified video's thumbnail. ThumbnailSetResponse setResponse = thumbnailSet.execute(); // Print the URL for the updated video's thumbnail image. System.out.println("\n================== Uploaded Thumbnail ==================\n"); System.out.println(" - Url: " + setResponse.getItems().get(0).getDefault().getUrl()); } catch (GoogleJsonResponseException e) { System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(); } } /* * Prompts the user to enter a YouTube video ID and return the user input. */ private static String getVideoIdFromUser() throws IOException { String inputVideoId = ""; System.out.print("Please enter a video Id to update: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); inputVideoId = bReader.readLine(); if (inputVideoId.length() < 1) { // Exit if the user does not specify a video ID. System.out.print("Video Id can't be empty!"); System.exit(1); } return inputVideoId; } /* * Prompt the user to enter the path for the thumbnail image being uploaded. */ private static File getImageFromUser() throws IOException { String path = ""; System.out.print("Please enter the path of the image file to upload: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); path = bReader.readLine(); if (path.length() < 1) { // Exit if the user does not provide a path to the image file. System.out.print("Path can not be empty!"); System.exit(1); } return new File(path); } }
9236e2ed4fa2c420d38b896a8e5e68c0c3d356b2
2,653
java
Java
cosmo-core/src/main/java/org/unitedinternet/cosmo/acegisecurity/userdetails/CosmoUserDetailsService.java
k-oliver/cosmo
a5c8ccd1df53517785bc92df04867fccf7828bc7
[ "Apache-2.0" ]
67
2015-05-20T14:37:10.000Z
2022-02-11T22:23:05.000Z
cosmo-core/src/main/java/org/unitedinternet/cosmo/acegisecurity/userdetails/CosmoUserDetailsService.java
k-oliver/cosmo
a5c8ccd1df53517785bc92df04867fccf7828bc7
[ "Apache-2.0" ]
47
2015-12-16T07:45:56.000Z
2022-01-25T18:38:20.000Z
cosmo-core/src/main/java/org/unitedinternet/cosmo/acegisecurity/userdetails/CosmoUserDetailsService.java
k-oliver/cosmo
a5c8ccd1df53517785bc92df04867fccf7828bc7
[ "Apache-2.0" ]
37
2015-06-03T11:00:59.000Z
2022-03-29T07:14:13.000Z
34.012821
84
0.71617
997,863
/* * Copyright 2005-2006 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.unitedinternet.cosmo.acegisecurity.userdetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.unitedinternet.cosmo.dao.UserDao; import org.unitedinternet.cosmo.model.User; /** * Implements Acegi Security's <code>UserDetailsService</code> * interface by retrieving user details with a <code>UserDao</code>. * * @see UserDetailsService * @see UserDao */ @Component public class CosmoUserDetailsService implements UserDetailsService { @Autowired private UserDao userDao; /** * Locates the user with the given username by retrieving it * with this service's <code>UserDao</code> and returns a * <code>UserDetails</code> representing the user. * * @param username the username to look up * @return a fully populated <code>UserDetails</code> (never * <code>null</code>) * @throws UsernameNotFoundException if the user could not be * found * @see UserDetails * @throws DataAccessException - if something is wrong this exception is thrown. */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { User user = userDao.getUser(username); if (user == null) { throw new UsernameNotFoundException("user " + username + " not found"); } return new CosmoUserDetails(userDao.getUser(username)); } /** * Gets user dao. * @return The user. */ public UserDao getUserDao() { return userDao; } /** * Sets user dao. * @param userDao The user dao. */ public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
9236e30a56f37dbc72e9014e09c013b042e4a86c
1,842
java
Java
android/VotoEletronico/VotoEletronicoApp/src/main/java/br/com/renanfretta/votoeletronico/uis/SplashScreenActivity.java
frettarenan/voto-eletronico-microservices-spring-java-e-android
53679636f6d7181dd3afd989ad50544a8fd159f4
[ "Apache-2.0" ]
2
2021-05-12T13:46:16.000Z
2021-05-12T23:47:43.000Z
android/VotoEletronico/VotoEletronicoApp/src/main/java/br/com/renanfretta/votoeletronico/uis/SplashScreenActivity.java
frettarenan/voto-eletronico-microservices-spring-java-e-android
53679636f6d7181dd3afd989ad50544a8fd159f4
[ "Apache-2.0" ]
null
null
null
android/VotoEletronico/VotoEletronicoApp/src/main/java/br/com/renanfretta/votoeletronico/uis/SplashScreenActivity.java
frettarenan/voto-eletronico-microservices-spring-java-e-android
53679636f6d7181dd3afd989ad50544a8fd159f4
[ "Apache-2.0" ]
null
null
null
32.315789
158
0.676439
997,864
package br.com.renanfretta.votoeletronico.uis; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.StrictMode; import androidx.appcompat.app.AppCompatActivity; import br.com.renanfretta.votoeletronico.R; import br.com.renanfretta.votoeletronico.utils.SessaoUsuarioUtil; import br.com.renanfretta.votoeletronico.utils.SharedPreferencesUtil; public class SplashScreenActivity extends AppCompatActivity { private final int SPLASH_DISPLAY_LENGTH = 2000; private SplashScreenActivity currentActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen_activity); currentActivity = this; new Handler().postDelayed(new Runnable() { @Override public void run() { mostrarMainActivity(); finish(); } }, SPLASH_DISPLAY_LENGTH); } private void mostrarMainActivity() { try { if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } boolean isPermanecerConectado = SharedPreferencesUtil.getInstance(getApplicationContext()).getBoolean(SharedPreferencesUtil.PERMANECER_CONECTADO); boolean isUsuarioLogado = SessaoUsuarioUtil.getInstance(currentActivity).isUsuarioLogado(); if (isPermanecerConectado && isUsuarioLogado) { startActivity(new Intent(this, PrincipalActivity.class)); return; } startActivity(new Intent(this, LoginActivity.class)); } finally { finish(); } } }
9236e3690f87878a377133748ee8181b8b2781a7
3,756
java
Java
tis-manage-pojo/src/main/java/com/qlangtech/tis/manage/biz/dal/pojo/Application.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
1
2019-09-26T03:08:34.000Z
2019-09-26T03:08:34.000Z
tis-manage-pojo/src/main/java/com/qlangtech/tis/manage/biz/dal/pojo/Application.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
tis-manage-pojo/src/main/java/com/qlangtech/tis/manage/biz/dal/pojo/Application.java
jhonyang/tis-solr
ab1dfe0bc4a4d2ab78709b2d271f153988285d30
[ "MIT" ]
null
null
null
22.094118
80
0.711129
997,865
/* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.qlangtech.tis.manage.biz.dal.pojo; import java.io.Serializable; import java.util.Date; /* * * @author 百岁(baisui@qlangtech.com) * @date 2019年1月17日 */ public class Application implements Serializable { private Integer appId; private String projectName; private String recept; private String manager; private Date createTime; private Date updateTime; private String isDeleted; /** * prop:dpt_id */ private Integer dptId; // private String indexsetName; /** * prop:dpt_name */ private String dptName; // private String yuntiPath; // <result column="nobel_app_id" property="nobleAppId" jdbcType="INTEGER" /> // <result column="nobel_app_name" property="nobleAppName" // jdbcType="VARCHAR" /> //private Integer nobleAppId; //private String nobleAppName; // public Integer getNobleAppId() { // return nobleAppId; // } // // public void setNobleAppId(Integer nobleAppId) { // this.nobleAppId = nobleAppId; // } // // public String getNobleAppName() { // return nobleAppName; // } // // public void setNobleAppName(String nobleAppName) { // this.nobleAppName = nobleAppName; // } private static final long serialVersionUID = 1L; public Integer getAppId() { return appId; } public void setAppId(Integer appId) { this.appId = appId; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName == null ? null : projectName.trim(); } public String getRecept() { return recept; } public void setRecept(String recept) { this.recept = recept == null ? null : recept.trim(); } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager == null ? null : manager.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getIsDeleted() { return isDeleted; } public void setIsDeleted(String isDeleted) { this.isDeleted = isDeleted == null ? null : isDeleted.trim(); } /** * get:dpt_id */ public Integer getDptId() { return dptId; } /** * set:dpt_id */ public void setDptId(Integer dptId) { this.dptId = dptId; } /** * get:dpt_name */ public String getDptName() { return dptName; } /** * set:dpt_name */ public void setDptName(String dptName) { this.dptName = dptName == null ? null : dptName.trim(); } }
9236e3dfaefa7bf029ae0311fbb5a58e2b460c90
1,025
java
Java
core/src/main/java/com/amazon/opendistroforelasticsearch/sql/expression/function/FunctionImplementation.java
chyun/sql
0bb88d0595a6076dff4883b546d9aed90355ce75
[ "Apache-2.0" ]
574
2019-03-11T16:02:24.000Z
2022-03-30T13:21:59.000Z
core/src/main/java/com/amazon/opendistroforelasticsearch/sql/expression/function/FunctionImplementation.java
chyun/sql
0bb88d0595a6076dff4883b546d9aed90355ce75
[ "Apache-2.0" ]
802
2019-03-11T14:43:20.000Z
2022-03-17T07:46:03.000Z
core/src/main/java/com/amazon/opendistroforelasticsearch/sql/expression/function/FunctionImplementation.java
chyun/sql
0bb88d0595a6076dff4883b546d9aed90355ce75
[ "Apache-2.0" ]
197
2019-03-11T20:52:28.000Z
2022-03-30T12:59:05.000Z
28.472222
78
0.722927
997,866
/* * Copyright 2019 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://www.apache.org/licenses/LICENSE-2.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.amazon.opendistroforelasticsearch.sql.expression.function; import com.amazon.opendistroforelasticsearch.sql.expression.Expression; import java.util.List; /** * The definition of Function Implementation. */ public interface FunctionImplementation { /** * Get Function Name. */ FunctionName getFunctionName(); /** * Get Function Arguments. */ List<Expression> getArguments(); }
9236e40faf0a09a24bcdc4a864f18609b00ecc53
4,454
java
Java
citizen-intelligence-agency/src/main/java/com/hack23/cia/web/impl/ui/application/views/user/party/pagemode/PartyOverviewPageModContentFactoryImpl.java
TrisA/cia
c67d638ec50b47afb9a033eae6e350fa514a0469
[ "Apache-2.0" ]
75
2015-08-01T15:31:54.000Z
2022-03-19T12:07:06.000Z
citizen-intelligence-agency/src/main/java/com/hack23/cia/web/impl/ui/application/views/user/party/pagemode/PartyOverviewPageModContentFactoryImpl.java
TrisA/cia
c67d638ec50b47afb9a033eae6e350fa514a0469
[ "Apache-2.0" ]
2,662
2016-12-16T17:27:08.000Z
2022-03-28T09:32:36.000Z
citizen-intelligence-agency/src/main/java/com/hack23/cia/web/impl/ui/application/views/user/party/pagemode/PartyOverviewPageModContentFactoryImpl.java
TrisA/cia
c67d638ec50b47afb9a033eae6e350fa514a0469
[ "Apache-2.0" ]
38
2017-03-03T23:15:18.000Z
2021-12-31T19:07:13.000Z
37.745763
114
0.792546
997,867
/* * Copyright 2010-2021 James Pether Sörling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.web.impl.ui.application.views.user.party.pagemode; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Component; import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenParty; import com.hack23.cia.model.internal.application.data.party.impl.ViewRiksdagenPartySummary; import com.hack23.cia.service.api.DataContainer; import com.hack23.cia.web.impl.ui.application.views.common.labelfactory.LabelFactory; import com.hack23.cia.web.impl.ui.application.views.common.sizing.ContentRatio; import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode; import com.vaadin.ui.Layout; import com.vaadin.ui.Link; import com.vaadin.ui.MenuBar; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; /** * The Class OverviewPageModContentFactoryImpl. */ @Component public final class PartyOverviewPageModContentFactoryImpl extends AbstractPartyPageModContentFactoryImpl { private static final List<String> AS_LIST = Arrays.asList("partyName", "partyId", "headCount", "partyNumber", "registeredDate", "website"); private static final List<String> AS_LIST2 = Arrays.asList("active", "firstAssignmentDate", "lastAssignmentDate", "currentAssignments", "totalAssignments", "totalDaysServed", "activeEu", "totalActiveEu", "totalDaysServedEu", "activeGovernment", "totalActiveGovernment", "totalDaysServedGovernment", "activeCommittee", "totalActiveCommittee", "totalDaysServedCommittee", "activeParliament", "totalActiveParliament", "totalDaysServedParliament"); /** The Constant OVERVIEW. */ private static final String OVERVIEW = "overview"; /** * Instantiates a new party overview page mod content factory impl. */ public PartyOverviewPageModContentFactoryImpl() { super(); } @Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" }) @Override public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) { final VerticalLayout panelContent = createPanelContent(); final String pageId = getPageId(parameters); final ViewRiksdagenParty viewRiksdagenParty = getItem(parameters); getPartyMenuItemFactory().createPartyMenuBar(menuBar, pageId); LabelFactory.createHeader2Label(panelContent, OVERVIEW); final Link addPartyPageLink = getPageLinkFactory().addPartyPageLink(viewRiksdagenParty); panelContent.addComponent(addPartyPageLink); panelContent.setExpandRatio(addPartyPageLink, ContentRatio.SMALL); getFormFactory().addFormPanelTextFields(panelContent, viewRiksdagenParty, ViewRiksdagenParty.class, AS_LIST); final DataContainer<ViewRiksdagenPartySummary, String> partySummarydataContainer = getApplicationManager() .getDataContainer(ViewRiksdagenPartySummary.class); final ViewRiksdagenPartySummary viewRiksdagenPartySummary = partySummarydataContainer.load(pageId); if (viewRiksdagenPartySummary != null) { getFormFactory().addFormPanelTextFields(panelContent, viewRiksdagenPartySummary, ViewRiksdagenPartySummary.class, AS_LIST2); } final VerticalLayout overviewLayout = new VerticalLayout(); overviewLayout.setSizeFull(); panelContent.addComponent(overviewLayout); panelContent.setExpandRatio(overviewLayout, ContentRatio.LARGE_FORM); getPartyMenuItemFactory().createOverviewPage(overviewLayout, pageId); pageCompleted(parameters, panel, pageId, viewRiksdagenParty); return panelContent; } @Override public boolean matches(final String page, final String parameters) { final String pageId = getPageId(parameters); return NAME.equals(page) && (StringUtils.isEmpty(parameters) || parameters.equals(pageId) || parameters.contains(PageMode.OVERVIEW.toString())); } }
9236e5061ab186baa1fa7e5a6a9286cd952bfa78
170
java
Java
src/main/java/fi/hh/jsonresume/domain/ResumeRepository.java
VierasTalo/JSONR
613f1dcc088b1233a3ab36401a84f249541a1230
[ "MIT" ]
null
null
null
src/main/java/fi/hh/jsonresume/domain/ResumeRepository.java
VierasTalo/JSONR
613f1dcc088b1233a3ab36401a84f249541a1230
[ "MIT" ]
null
null
null
src/main/java/fi/hh/jsonresume/domain/ResumeRepository.java
VierasTalo/JSONR
613f1dcc088b1233a3ab36401a84f249541a1230
[ "MIT" ]
null
null
null
21.25
72
0.829412
997,868
package fi.hh.jsonresume.domain; import org.springframework.data.repository.CrudRepository; public interface ResumeRepository extends CrudRepository<Resume, Long> { }
9236e5dfc58534286bddb21943fd89f2891d7ec4
2,388
java
Java
app/src/main/java/marcosambrosi/mmovies/network/ServiceController.java
mambrosi/MaterialMovies
abcc26c424d8443599c9aa829965b4c5fa29c301
[ "MIT" ]
9
2015-11-10T00:36:55.000Z
2021-09-13T12:15:59.000Z
app/src/main/java/marcosambrosi/mmovies/network/ServiceController.java
mambrosi/MaterialMovies
abcc26c424d8443599c9aa829965b4c5fa29c301
[ "MIT" ]
null
null
null
app/src/main/java/marcosambrosi/mmovies/network/ServiceController.java
mambrosi/MaterialMovies
abcc26c424d8443599c9aa829965b4c5fa29c301
[ "MIT" ]
3
2015-10-30T15:28:17.000Z
2018-10-10T08:39:00.000Z
29.195122
92
0.691312
997,869
/* * * * * * * * Copyright (C) 2015 Marcos Ambrosi upchh@example.com * * * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * * you may not use this file except in compliance with the License. * * * You may obtain a copy of the License at * * * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * * * Unless required by applicable law or agreed to in writing, software * * * distributed under the License is distributed on an "AS IS" BASIS, * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * * See the License for the specific language governing permissions and * * * limitations under the License. * * * */ package marcosambrosi.mmovies.network; import marcosambrosi.mmovies.model.Configuration; import marcosambrosi.mmovies.model.response.MovieResponse; import marcosambrosi.mmovies.model.response.ReviewResponse; import marcosambrosi.mmovies.util.Constants; import retrofit.Callback; import retrofit.RestAdapter; /** * Created by marcosambrosi on 5/6/15. */ public class ServiceController { private static ServiceController sInstance; private static MoviesService sService; private static String sAuthToken; static { initializeService(); } private ServiceController() { } private static void initializeService() { RestAdapter.Builder restAdapter = new RestAdapter.Builder() .setEndpoint(Constants.BASE_URL) .setLogLevel(RestAdapter.LogLevel.FULL); sService = restAdapter.build().create(MoviesService.class); } public static ServiceController getInstance() { if (sInstance == null) { sInstance = new ServiceController(); } return sInstance; } public void discoverMovies(Callback<MovieResponse> callback) { sService.discoverMovie(Constants.API_KEY, callback); } public void nowPlaying(Callback<MovieResponse> callback) { sService.nowPlaying(Constants.API_KEY, callback); } public void configuration(Callback<Configuration> callback) { sService.configuration(Constants.API_KEY, callback); } public void getMovieReviews(String movieId, Callback<ReviewResponse> responseCallback) { sService.getMovieReviews(Constants.API_KEY, movieId, responseCallback); } }
9236e667bb16843d9bef789633e874eb68050f05
3,085
java
Java
src/main/java/com/mfg/InterviewApplication.java
yunguzi/InterviewMFG
34f16ad1b250fd94c29d236aaf65f8e1348e0ce7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mfg/InterviewApplication.java
yunguzi/InterviewMFG
34f16ad1b250fd94c29d236aaf65f8e1348e0ce7
[ "Apache-2.0" ]
null
null
null
src/main/java/com/mfg/InterviewApplication.java
yunguzi/InterviewMFG
34f16ad1b250fd94c29d236aaf65f8e1348e0ce7
[ "Apache-2.0" ]
null
null
null
34.277778
90
0.731929
997,870
package com.mfg; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.date.GoodRepository; import com.model.Good; @SpringBootApplication @RestController public class InterviewApplication { @Autowired GoodRepository goodRepository; //查前十条 @RequestMapping(value = "/api/good/{pageNumber}", method = RequestMethod.GET) public List<Good> getGoodList(@PathVariable int pageNumber) { //构建分页信息 PageRequest pageRequest = buildPageRequest(pageNumber,10,"productionDate"); //查询指定分页的内容 Iterator<Good> goods = goodRepository.findAll(pageRequest).iterator(); List<Good> goodList = new ArrayList<Good>(); while(goods.hasNext()){ goodList.add(goods.next()); } return goodList; } //按name查找 @RequestMapping(value = "/api/getGoodByName/{name}", method = RequestMethod.GET) public Good getGoodByName(@PathVariable String name) { return goodRepository.findByName(name); } //增加Good对象 @RequestMapping(value = "/api/addGood", method = RequestMethod.POST) public Good addGood(@RequestParam("Good") Good good) { return goodRepository.insert(good); } //根据name删除 @RequestMapping(value = "/api/deleteGoodByName/{name}", method = RequestMethod.DELETE) public boolean deleteCustomerById(@PathVariable String name) { goodRepository.delete(name); return true; } //修改Good对象 @RequestMapping(value = "/api/updateGood", method = RequestMethod.PUT) public String updateGood(@RequestParam("Good") Good good) { if(goodRepository.exists(good.getName())){ goodRepository.save(good); return "update success!"; } return "update fail, the Good name not exists!"; } public static void main(String[] args) { SpringApplication.run(InterviewApplication.class, args); } /** * 创建分页请求. */ private PageRequest buildPageRequest(int pageNumber, int pageSize,String sortType) { Sort sort = new Sort(Sort.Direction.DESC, sortType); //参数1表示当前第几页,参数2表示每页的大小,参数3表示排序 return new PageRequest(pageNumber-1,pageSize,sort); } }
9236e699032fd7d934d35158329f3c280f2136d7
1,180
java
Java
src/main/java/org/balumba/sagademo/business/order/OrderService.java
wallner/saga-demo
56e48f4015b5f4b29e0bb96f8735fa187c3065f7
[ "Apache-2.0" ]
null
null
null
src/main/java/org/balumba/sagademo/business/order/OrderService.java
wallner/saga-demo
56e48f4015b5f4b29e0bb96f8735fa187c3065f7
[ "Apache-2.0" ]
null
null
null
src/main/java/org/balumba/sagademo/business/order/OrderService.java
wallner/saga-demo
56e48f4015b5f4b29e0bb96f8735fa187c3065f7
[ "Apache-2.0" ]
null
null
null
26.818182
84
0.687288
997,871
package org.balumba.sagademo.business.order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class OrderService { public static final Logger logger = LoggerFactory.getLogger(OrderService.class); private final OrderRepository repository; public OrderService(OrderRepository repository) { this.repository = repository; } public Long createOrder(Order order) { logger.info("creating initial order"); return repository.save(order).getId(); } public Optional<Order> findOrderById(Long orderId) { return repository.findById(orderId); } public Order approveOrder(Long orderId) { var order = repository.findById(orderId).orElseThrow(); order.approve(); logger.info("Approving order {}", order.getId()); return repository.save(order); } public Order refuseOrder(Long orderId) { var order = repository.findById(orderId).orElseThrow(); order.cancel(); logger.info("Canceling order {}", order.getId()); return repository.save(order); } }
9236e7a268440d185f60ea2c43fa9a793f5eae32
1,370
java
Java
src/java/ge/mziuri/model/Card.java
getsadzeg/tickets
3346de3440edba9c679b63480f9a3ab80802d149
[ "MIT" ]
null
null
null
src/java/ge/mziuri/model/Card.java
getsadzeg/tickets
3346de3440edba9c679b63480f9a3ab80802d149
[ "MIT" ]
5
2017-03-18T08:48:59.000Z
2017-06-04T19:59:04.000Z
src/java/ge/mziuri/model/Card.java
getsadzeg/tickets
3346de3440edba9c679b63480f9a3ab80802d149
[ "MIT" ]
null
null
null
17.792208
142
0.546715
997,872
package ge.mziuri.model; import java.util.Date; public class Card { private int id; private double money; private String code; private String passcode; private Date expDate; public Card() { } public Card(int id, double money, String code, String passcode, Date expDate) { this.id = id; this.money = money; this.code = code; this.passcode = passcode; this.expDate = expDate; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getPasscode() { return passcode; } public void setPasscode(String passcode) { this.passcode = passcode; } public Date getExpDate() { return expDate; } public void setExpDate(Date expDate) { this.expDate = expDate; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "id: " + id + ", money: " + money + ", code: " + code + ", password: " + passcode + ", expiration date: " + expDate.toString(); } }
9236e7ad1b3fe95f940510cb802e8391e0266f0d
985
java
Java
modules/desktop-awt/desktop-awt-hacking/src/main/java/consulo/awt/hacking/AWTAutoShutdownHacking.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
634
2015-01-01T19:14:25.000Z
2022-03-22T11:42:50.000Z
modules/desktop-awt/desktop-awt-hacking/src/main/java/consulo/awt/hacking/AWTAutoShutdownHacking.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
410
2015-01-19T09:57:51.000Z
2022-03-22T16:24:59.000Z
modules/desktop-awt/desktop-awt-hacking/src/main/java/consulo/awt/hacking/AWTAutoShutdownHacking.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
50
2015-03-10T04:14:49.000Z
2022-03-22T07:08:45.000Z
29.848485
75
0.747208
997,873
/* * Copyright 2013-2020 consulo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.awt.hacking; import sun.awt.AWTAutoShutdown; /** * @author VISTALL * @since 2020-10-18 */ public class AWTAutoShutdownHacking { public static void notifyThreadBusy(Thread thread) { AWTAutoShutdown.getInstance().notifyThreadBusy(thread); } public static void notifyThreadFree(Thread thread) { AWTAutoShutdown.getInstance().notifyThreadFree(thread); } }
9236e8090187f968ed19ccf21373412c0976c64a
4,386
java
Java
examples/eclipse-tut-carddav/src/main/java/com/mycontacts/resource/ContactManager.java
zlp1992/micro-milton
235db615e09d8251aca1c2d064c40668568ffd4b
[ "Apache-2.0" ]
null
null
null
examples/eclipse-tut-carddav/src/main/java/com/mycontacts/resource/ContactManager.java
zlp1992/micro-milton
235db615e09d8251aca1c2d064c40668568ffd4b
[ "Apache-2.0" ]
null
null
null
examples/eclipse-tut-carddav/src/main/java/com/mycontacts/resource/ContactManager.java
zlp1992/micro-milton
235db615e09d8251aca1c2d064c40668568ffd4b
[ "Apache-2.0" ]
null
null
null
33.738462
115
0.654811
997,874
/* * Copyright (C) 2012 McEvoy Software Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycontacts.resource; import com.mycontacts.model.ContactsDao; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import java.util.UUID; import net.sourceforge.cardme.engine.VCardEngine; import net.sourceforge.cardme.io.VCardWriter; import net.sourceforge.cardme.vcard.VCard; import net.sourceforge.cardme.vcard.features.EmailFeature; import net.sourceforge.cardme.vcard.features.TelephoneFeature; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author brad */ public class ContactManager { private static final Logger log = LoggerFactory.getLogger(ContactManager.class); private final ContactsDao contactsDao; public ContactManager(ContactsDao contactsDao) { this.contactsDao = contactsDao; } public ContactsDao.Contact createContact(String newName, String icalData) throws UnsupportedEncodingException { ContactsDao.Contact e = contactsDao.addContact(newName); update(e, icalData); return e; } public void update(ContactsDao.Contact contact, String data) { log.info("update: " + data); VCard vcard = parse(data); if (vcard.getUID() != null && vcard.getUID().hasUID()) { contact.setUid(vcard.getUID().getUID()); } else { log.warn("NO UID FOUND, making up our own"); contact.setUid(UUID.randomUUID().toString()); } if (vcard.getName() != null) { contact.setGivenName(vcard.getName().getGivenName()); contact.setSurName(vcard.getName().getFamilyName()); log.info("parsed name: " + contact.getGivenName() + " " + contact.getSurName()); } else { log.warn("No name component found!"); } contact.setMail(""); // reset in case none given Iterator<EmailFeature> it = vcard.getEmails(); while (it.hasNext()) { contact.setMail(it.next().getEmail()); } log.info("email: " + contact.getMail()); if (vcard.getOrganizations() != null) { // contact.setOrganizationName(""); // Iterator<String> itOrg = vcard.getOrganizations().getOrganizations(); // while (itOrg.hasNext()) { // contact.setOrganizationName(itOrg.next()); // } } String ph = getPhone(vcard); contact.setTelephonenumber(ph); log.info("phone: " + contact.getTelephonenumber()); contact.setIcalData(data); contactsDao.incrementContactsVersion(); } public VCard parse(String data) { VCardEngine cardEngine = new VCardEngine(); try { return cardEngine.parse(data); } catch (IOException ex) { throw new RuntimeException(ex); } } private String getPhone(VCard vcard) { Iterator<TelephoneFeature> itPhone = vcard.getTelephoneNumbers(); while (itPhone.hasNext()) { return itPhone.next().getTelephone(); } return null; } public List<VCard> parseMultiple(InputStream inputStream) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(inputStream, bout); String vcardText = bout.toString("UTF-8"); VCardEngine cardEngine = new VCardEngine(); List<VCard> vcards = cardEngine.parseMultiple(vcardText); return vcards; } public ContactsDao getContactsDao() { return contactsDao; } }
9236e88a63ad80167aed01862d9ee1b09d27f09f
1,268
java
Java
guns-admin/src/main/java/com/stylefeng/guns/modular/system/dao/BrushMapper.java
JingDecre/guns-bigcoffee
e7e943062d11ede81320d625b2184f4b02a7d517
[ "Apache-2.0" ]
null
null
null
guns-admin/src/main/java/com/stylefeng/guns/modular/system/dao/BrushMapper.java
JingDecre/guns-bigcoffee
e7e943062d11ede81320d625b2184f4b02a7d517
[ "Apache-2.0" ]
null
null
null
guns-admin/src/main/java/com/stylefeng/guns/modular/system/dao/BrushMapper.java
JingDecre/guns-bigcoffee
e7e943062d11ede81320d625b2184f4b02a7d517
[ "Apache-2.0" ]
null
null
null
27.565217
257
0.686909
997,875
package com.stylefeng.guns.modular.system.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.plugins.Page; import com.stylefeng.guns.modular.brushmanage.vo.BrushVo; import com.stylefeng.guns.modular.system.model.Brush; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * <p> * 刷单管理表 Mapper 接口 * </p> * * @author decre123 * @since 2018-08-31 */ public interface BrushMapper extends BaseMapper<Brush> { /** * 根据条件查询刷单列表 * @param page * @param name * @param beginTime * @param endTime * @return */ List<Map<String, Object>> selectBrushList(@Param("page") Page<Brush> page, @Param("name") String name, @Param("beginTime") String beginTime, @Param("endTime") String endTime, @Param("createUserId") Integer createUserId); /** * 根据条件获取刷单导出对象列表 * * @param beginTime * @param endTime * @param startPage * @param pageSize * @return */ List<BrushVo> selectBrushVoList(@Param("name") String name, @Param("beginTime") String beginTime, @Param("endTime") String endTime, @Param("createUserId") Integer createUserId, @Param("startPage") Integer startPage, @Param("pageSize") Integer pageSize); }
9236e943bcbf806cc3612786708db3d83e502b02
1,183
java
Java
data/src/main/java/edu/harvard/hms/dbmi/avillach/cliniscope/repositories/GroupValidationRepository.java
hms-dbmi/adept
8d4a3f6ca7baa2781c1d4a7d8bf868754b238169
[ "Apache-2.0" ]
null
null
null
data/src/main/java/edu/harvard/hms/dbmi/avillach/cliniscope/repositories/GroupValidationRepository.java
hms-dbmi/adept
8d4a3f6ca7baa2781c1d4a7d8bf868754b238169
[ "Apache-2.0" ]
null
null
null
data/src/main/java/edu/harvard/hms/dbmi/avillach/cliniscope/repositories/GroupValidationRepository.java
hms-dbmi/adept
8d4a3f6ca7baa2781c1d4a7d8bf868754b238169
[ "Apache-2.0" ]
null
null
null
31.131579
102
0.810651
997,876
package edu.harvard.hms.dbmi.avillach.cliniscope.repositories; import java.util.List; import javax.persistence.StoredProcedureQuery; import javax.transaction.Transactional; import org.springframework.stereotype.Repository; import edu.harvard.hms.dbmi.avillach.cliniscope.entities.GroupValidation; @Repository @Transactional public class GroupValidationRepository extends BaseRepository<GroupValidation>{ private static final String VALIDATIONS_FOR_NOTE = "VALIDATIONS_FOR_NOTE"; public GroupValidationRepository(){ super(new GroupValidation()); } public boolean setScoreForGroup(int groupId, int score) { GroupValidation validation = new GroupValidation().setGroupId(groupId).setUserId(0).setScore(score); em.merge(validation); return true; } @SuppressWarnings("unchecked") public List<GroupValidation> getValidationsForPatient(String noteId) { StoredProcedureQuery validationsQuery = createQueryFor(VALIDATIONS_FOR_NOTE, GroupValidation.class, inParam(String.class).name("clinicalNoteId").value(noteId)); validationsQuery.execute(); List<GroupValidation> groupValidations = validationsQuery.getResultList(); return groupValidations; } }
9236e9560b8998336b6dcca9171d15b440e4cb18
165
java
Java
Sistemas_inform.java
KlopeDarkWolf/Personal
d1da8f7bc10a6ec7d638ad486d646e3079a88e63
[ "MIT" ]
null
null
null
Sistemas_inform.java
KlopeDarkWolf/Personal
d1da8f7bc10a6ec7d638ad486d646e3079a88e63
[ "MIT" ]
null
null
null
Sistemas_inform.java
KlopeDarkWolf/Personal
d1da8f7bc10a6ec7d638ad486d646e3079a88e63
[ "MIT" ]
null
null
null
12.692308
44
0.630303
997,877
package sistemas_inform; public class Sistemas_inform { public static void main(String[] args) { System.out.println("Hello World"); } }
9236eb6efd8ccee37ff3a80e9e0deb7c90c24eae
13,279
java
Java
cellbase-app/src/main/java/org/opencb/cellbase/app/transform/clinical/variant/DOCMIndexer.java
babelomics/cellbase
23699a2049205bac2eb7c72d804c8a540181ee38
[ "Apache-2.0" ]
null
null
null
cellbase-app/src/main/java/org/opencb/cellbase/app/transform/clinical/variant/DOCMIndexer.java
babelomics/cellbase
23699a2049205bac2eb7c72d804c8a540181ee38
[ "Apache-2.0" ]
1
2019-06-14T08:35:10.000Z
2019-06-14T08:35:10.000Z
cellbase-app/src/main/java/org/opencb/cellbase/app/transform/clinical/variant/DOCMIndexer.java
babelomics/cellbase
23699a2049205bac2eb7c72d804c8a540181ee38
[ "Apache-2.0" ]
1
2020-01-23T06:52:17.000Z
2020-01-23T06:52:17.000Z
46.268293
129
0.593569
997,878
package org.opencb.cellbase.app.transform.clinical.variant; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections.map.HashedMap; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.avro.*; import org.opencb.cellbase.app.cli.EtlCommons; import org.opencb.commons.utils.FileUtils; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Path; import java.util.*; import java.util.stream.Collectors; import static org.opencb.biodata.models.variant.protobuf.EvidenceEntryProto.FeatureTypes.gene; /** * Created by fjlopez on 29/03/17. */ public class DOCMIndexer extends ClinicalIndexer { private static final String REFERENCE_VERSION = "reference_version"; private static final String CHROMOSOME = "chromosome"; private static final String START = "start"; private static final String REFERENCE = "reference"; private static final String VARIANT = "variant"; private static final String DISEASES = "diseases"; private static final String DISEASE = "disease"; private static final String SOURCE_PUBMED_ID = "source_pubmed_id"; private static final String PMID = "PMID:"; private static final String URL_PREFIX = "http://docm.genome.wustl.edu/variants/"; private static final String HGVS = "hgvs"; private static final String GENE = "gene"; private static final String TRANSCRIPT = "transcript"; private static final String ENST = "ENST"; private static final String SYMBOL = "symbol"; private static final String TAGS = "tags"; private static final String TAGS_IN_SOURCE_FILE = "tags_in_source_file"; private static final String META = "meta"; private static final String DRUG_INTERACTION_DATA = "Drug Interaction Data"; private static final String FIELDS = "fields"; private static final String ROWS = "rows"; private static final String THERAPEUTIC_CONTEXT = "Therapeutic Context"; private static final String PATHWAY = "Pathway"; private static final String EFFECT = "Effect"; private static final String ASSOCIATION = "Association"; private static final String STATUS = "Status"; private static final String EVIDENCE = "Evidence"; private static final String SOURCE = "Source"; private static final String NAME = "name"; private final Path docmFile; private final String assembly; public DOCMIndexer(Path docmFile, boolean normalize, Path genomeSequenceFilePath, String assembly, RocksDB rdb) throws IOException { super(genomeSequenceFilePath); this.rdb = rdb; this.assembly = assembly; this.docmFile = docmFile; this.normalize = normalize; } public void index() throws RocksDBException { logger.info("Parsing DOCM file ..."); try { BufferedReader bufferedReader = FileUtils.newBufferedReader(docmFile); String line = bufferedReader.readLine(); while (line != null) { Variant variant = parseVariant(line); if (variant != null) { boolean success = updateRocksDB(variant); // updateRocksDB may fail (false) if normalisation process fails if (success) { numberIndexedRecords++; } } line = bufferedReader.readLine(); } totalNumberRecords++; if (totalNumberRecords % 1000 == 0) { logger.info("{} records parsed", totalNumberRecords); } } catch (RocksDBException e) { logger.error("Error reading/writing from/to the RocksDB index while indexing Cosmic"); throw e; } catch (IOException ex) { ex.printStackTrace(); } finally { logger.info("Done"); // this.printSummary(); } } private boolean updateRocksDB(Variant variant) throws RocksDBException, IOException { // More than one variant being returned from the normalisation process would mean it's and MNV which has been // decomposed List<String> normalisedVariantStringList = getNormalisedVariantString(variant.getChromosome(), variant.getStart(), variant.getReference(), variant.getAlternate()); if (normalisedVariantStringList != null) { for (String normalisedVariantString : normalisedVariantStringList) { VariantAnnotation variantAnnotation = getVariantAnnotation(normalisedVariantString.getBytes()); // Add haplotype property to all EvidenceEntry objects in variant if there are more than 1 variants in // normalisedVariantStringList, i.e. if this variant is part of an MNV (haplotype) addHaplotypeProperty(variant.getAnnotation().getTraitAssociation(), normalisedVariantStringList); // Add EvidenceEntry objects variantAnnotation.getTraitAssociation().addAll(variant.getAnnotation().getTraitAssociation()); // Check if drug info is available if (variant.getAnnotation().getDrugs() != null && !variant.getAnnotation().getDrugs().isEmpty()) { // Drug info is stored at the VariantAnnotation root if (variantAnnotation.getDrugs() == null) { variantAnnotation.setDrugs(variant.getAnnotation().getDrugs()); } else { variantAnnotation.getDrugs().addAll(variant.getAnnotation().getDrugs()); } } rdb.put(normalisedVariantString.getBytes(), jsonObjectWriter.writeValueAsBytes(variantAnnotation)); } return true; } return false; } private Variant parseVariant(String line) throws IOException { Map<String, Object> map = (HashMap<String, Object>) new ObjectMapper().readValue(line, HashMap.class); if (assembly.equalsIgnoreCase((String) map.get(REFERENCE_VERSION))) { Variant variant = new Variant((String) map.get(CHROMOSOME), (Integer) map.get(START), (String) map.get(REFERENCE), (String) map.get(VARIANT)); VariantAnnotation variantAnnotation = parseVariantAnnotation(map); variant.setAnnotation(variantAnnotation); return variant; } else { return null; } } private VariantAnnotation parseVariantAnnotation(Map<String, Object> map) { // The list diseases in map.get(DISEASES) may contain multiple elements for the same disease but with different // pubmed ids Map<String, EvidenceEntry> evidenceEntryMap = new HashedMap(((List) map.get(DISEASES)).size()); for (Map diseaseMap : ((List<Map>) map.get(DISEASES))) { EvidenceEntry evidenceEntry; // An object with current disease string has already been parsed for this variant if (evidenceEntryMap.containsKey(diseaseMap.get(DISEASE)) && diseaseMap.containsKey(SOURCE_PUBMED_ID)) { evidenceEntry = evidenceEntryMap.get(diseaseMap.get(DISEASE)); List<String> bibliography = getBibliography(evidenceEntry); bibliography.add(PMID + diseaseMap.get(SOURCE_PUBMED_ID)); } else { EvidenceSource evidenceSource = new EvidenceSource(EtlCommons.DOCM_DATA, null, null); HeritableTrait heritableTrait = new HeritableTrait((String) diseaseMap.get(DISEASE), null); List<GenomicFeature> genomicFeatureList = getGenomicFeature(map); VariantClassification variantClassification = getVariantClassification((List<String>) diseaseMap.get(TAGS)); Property property = new Property(null, TAGS_IN_SOURCE_FILE, String.join(",", (List<String>) diseaseMap.get(TAGS))); List<Property> additionalProperties = new ArrayList<>(); additionalProperties.add(property); List<String> bibliography = new ArrayList<>(); bibliography.add(PMID + String.valueOf(diseaseMap.get(SOURCE_PUBMED_ID))); evidenceEntry = new EvidenceEntry(evidenceSource, null, null, URL_PREFIX + (String) map.get(HGVS), null, null, null, Collections.singletonList(heritableTrait), genomicFeatureList, variantClassification, null, null, null, null, null, null, null, additionalProperties, bibliography); evidenceEntryMap.put((String) diseaseMap.get(DISEASE), evidenceEntry); } } List<Drug> drugList = null; if (map.containsKey(META)) { drugList = new ArrayList<>(((List<Map>) map.get(META)).size()); for (Map metaMap : ((List<Map>) map.get(META))) { if (metaMap.containsKey(DRUG_INTERACTION_DATA) && ((Map) metaMap.get(DRUG_INTERACTION_DATA)).containsKey(FIELDS) && ((Map) metaMap.get(DRUG_INTERACTION_DATA)).containsKey(ROWS)) { List<String> fields = (List<String>) ((Map) metaMap.get(DRUG_INTERACTION_DATA)).get(FIELDS); if (fields.size() > 7) { logger.warn("More fields than expected found within Drug Interaction info. Please, check:"); for (String field : fields) { logger.warn("{}", field); } } for (List<String> drugInfoList : (List<List<String>>) ((Map) metaMap.get(DRUG_INTERACTION_DATA)).get(ROWS)) { Drug drug = new Drug(); int idx = fields.indexOf(THERAPEUTIC_CONTEXT); if (idx > -1) { drug.setTherapeuticContext(drugInfoList.get(idx)); } idx = fields.indexOf(PATHWAY); if (idx > -1) { drug.setPathway(drugInfoList.get(idx)); } idx = fields.indexOf(EFFECT); if (idx > -1) { drug.setEffect(drugInfoList.get(idx)); } idx = fields.indexOf(ASSOCIATION); if (idx > -1) { drug.setAssociation(drugInfoList.get(idx)); } idx = fields.indexOf(STATUS); if (idx > -1) { drug.setStatus(drugInfoList.get(idx)); } idx = fields.indexOf(EVIDENCE); if (idx > -1) { drug.setEvidence(drugInfoList.get(idx)); } idx = fields.indexOf(SOURCE); if (idx > -1) { drug.setBibliography(Collections.singletonList(PMID + drugInfoList.get(idx))); } drugList.add(drug); } } else { logger.warn("Meta field found but no drug interaction data"); logger.warn("Variant: {}:{}:{}:{}", map.get("chromosome"), map.get("start"), map.get("reference"), map.get("alternate")); } } } VariantAnnotation variantAnnotation = new VariantAnnotation(); variantAnnotation.setDrugs(drugList); variantAnnotation.setTraitAssociation(evidenceEntryMap .keySet() .stream() .map((diseaseName) -> evidenceEntryMap.get(diseaseName)) .collect(Collectors.toList())); return variantAnnotation; } private List<String> getBibliography(EvidenceEntry evidenceEntry) { if (evidenceEntry.getBibliography() == null) { List<String> bibliography = new ArrayList<>(1); evidenceEntry.setBibliography(bibliography); } return evidenceEntry.getBibliography(); } private List<GenomicFeature> getGenomicFeature(Map<String, Object> map) { List<GenomicFeature> genomicFeatureList = new ArrayList<>(); if (map.containsKey(GENE)) { genomicFeatureList.add(createGeneGenomicFeature((String) map.get(GENE))); } if (map.containsKey(TRANSCRIPT)) { String symbol = (String) ((Map) map.get(TRANSCRIPT)).get(NAME); if (symbol.startsWith(ENST)) { genomicFeatureList.add(new GenomicFeature(FeatureTypes.transcript, symbol, null)); } else { Map<String, String> transcriptMap = new HashMap<>(1); map.put(SYMBOL, gene); genomicFeatureList.add(new GenomicFeature(FeatureTypes.transcript, null, transcriptMap)); } } return genomicFeatureList; } }
9236eb7c9ec3b8dbad253d41f67f0581fd50aad9
4,240
java
Java
bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/StartGamePacket.java
lt-name/Protocol
587fe15c3da158729badb1a93819f0317860ffa5
[ "Apache-2.0" ]
1
2021-03-30T18:10:27.000Z
2021-03-30T18:10:27.000Z
bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/StartGamePacket.java
lt-name/Protocol
587fe15c3da158729badb1a93819f0317860ffa5
[ "Apache-2.0" ]
null
null
null
bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/StartGamePacket.java
lt-name/Protocol
587fe15c3da158729badb1a93819f0317860ffa5
[ "Apache-2.0" ]
null
null
null
35.333333
103
0.757783
997,879
package com.nukkitx.protocol.bedrock.packet; import com.nukkitx.math.vector.Vector2f; import com.nukkitx.math.vector.Vector3f; import com.nukkitx.math.vector.Vector3i; import com.nukkitx.nbt.NbtList; import com.nukkitx.nbt.NbtMap; import com.nukkitx.protocol.bedrock.BedrockPacket; import com.nukkitx.protocol.bedrock.BedrockPacketType; import com.nukkitx.protocol.bedrock.data.*; import com.nukkitx.protocol.bedrock.handler.BedrockPacketHandler; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import lombok.*; import java.util.List; @Data @EqualsAndHashCode(doNotUseGetters = true, callSuper = false) @ToString(exclude = {"itemEntries", "blockPalette"}) public class StartGamePacket extends BedrockPacket { private static final InternalLogger log = InternalLoggerFactory.getInstance(StartGamePacket.class); private final List<GameRuleData<?>> gamerules = new ObjectArrayList<>(); private long uniqueEntityId; private long runtimeEntityId; private GameType playerGameType; private Vector3f playerPosition; private Vector2f rotation; // Level settings start private int seed; private SpawnBiomeType spawnBiomeType = SpawnBiomeType.DEFAULT; private String customBiomeName = ""; private int dimensionId; private int generatorId; private GameType levelGameType; private int difficulty; private Vector3i defaultSpawn; private boolean achievementsDisabled; private int dayCycleStopTime; private int eduEditionOffers; private boolean eduFeaturesEnabled; private String educationProductionId = ""; private float rainLevel; private float lightningLevel; private boolean platformLockedContentConfirmed; private boolean multiplayerGame; private boolean broadcastingToLan; private GamePublishSetting xblBroadcastMode; private GamePublishSetting platformBroadcastMode; private boolean commandsEnabled; private boolean texturePacksRequired; private final List<ExperimentData> experiments = new ObjectArrayList<>(); private boolean experimentsPreviouslyToggled; private boolean bonusChestEnabled; private boolean startingWithMap; private boolean trustingPlayers; private PlayerPermission defaultPlayerPermission; private int serverChunkTickRange; private boolean behaviorPackLocked; private boolean resourcePackLocked; private boolean fromLockedWorldTemplate; private boolean usingMsaGamertagsOnly; private boolean fromWorldTemplate; private boolean worldTemplateOptionLocked; private boolean onlySpawningV1Villagers; private String vanillaVersion; private int limitedWorldWidth; private int limitedWorldHeight; private boolean netherType; private boolean forceExperimentalGameplay; // Level settings end private String levelId; private String levelName; private String premiumWorldTemplateId; private boolean trial; /** * @deprecated as of v428 */ private AuthoritativeMovementMode authoritativeMovementMode; /** * @since v428 */ private SyncedPlayerMovementSettings playerMovementSettings; private long currentTick; private int enchantmentSeed; private NbtList<NbtMap> blockPalette; private final List<BlockPropertyData> blockProperties = new ObjectArrayList<>(); private List<ItemEntry> itemEntries = new ObjectArrayList<>(); private String multiplayerCorrelationId; /** * @since v407 */ private boolean inventoriesServerAuthoritative; @Override public final boolean handle(BedrockPacketHandler handler) { return handler.handle(this); } public BedrockPacketType getPacketType() { return BedrockPacketType.START_GAME; } @Value @AllArgsConstructor public static class ItemEntry { private final String identifier; private final short id; private final boolean componentBased; public ItemEntry(String identifier, short id) { this.identifier = identifier; this.id = id; this.componentBased = false; } } }
9236eb921f6093abb94d43d2aaa15deca097ee8c
1,214
java
Java
LeanLauncher/src/main/java/com/android/leanlauncher/LauncherFiles.java
krajeswaran/LeanLauncher
9ef53ee6821be37c890b77dbc233edb24f47d7f8
[ "Apache-2.0" ]
13
2015-11-13T07:35:32.000Z
2021-04-06T13:21:53.000Z
LeanLauncher/src/main/java/com/android/leanlauncher/LauncherFiles.java
krajeswaran/LeanLauncher
9ef53ee6821be37c890b77dbc233edb24f47d7f8
[ "Apache-2.0" ]
null
null
null
LeanLauncher/src/main/java/com/android/leanlauncher/LauncherFiles.java
krajeswaran/LeanLauncher
9ef53ee6821be37c890b77dbc233edb24f47d7f8
[ "Apache-2.0" ]
10
2016-05-03T07:27:02.000Z
2022-03-05T13:53:14.000Z
37.9375
96
0.738056
997,880
/* * Copyright (C) 2015. Kumaresan Rajeswaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.leanlauncher; /** * Central list of files the Launcher writes to the application data directory. * * To add a new Launcher file, create a String constant referring to the filename, and add it to * ALL_FILES, as shown below. */ public class LauncherFiles { public static final String LAUNCHER_DB = "launcher.db"; public static final String LAUNCHER_PREFERENCES = "launcher.preferences"; public static final String SHARED_PREFERENCES_KEY = "com.android.leanlauncher.prefs"; public static final String WIDGET_PREVIEWS_DB = "widgetpreviews.db"; }
9236ebc7d210440761fb6b86215601a6215404b4
1,105
java
Java
src/com/docuware/dev/schema/_public/services/platform/StampSignatureType.java
DocuWare/PlatformJavaClient
249901433d3e0b08329775157d3fbd402c92c950
[ "MIT" ]
2
2017-03-13T12:39:07.000Z
2019-10-29T10:16:15.000Z
src/com/docuware/dev/schema/_public/services/platform/StampSignatureType.java
DocuWare/PlatformJavaClient
249901433d3e0b08329775157d3fbd402c92c950
[ "MIT" ]
10
2017-03-13T12:39:51.000Z
2019-03-13T09:39:37.000Z
src/com/docuware/dev/schema/_public/services/platform/StampSignatureType.java
DocuWare/PlatformJavaClient
249901433d3e0b08329775157d3fbd402c92c950
[ "MIT" ]
9
2016-09-26T12:52:01.000Z
2020-11-13T14:35:20.000Z
21.666667
66
0.647059
997,881
package com.docuware.dev.schema._public.services.platform; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.net.URI; import com.docuware.dev.Extensions.*; import java.util.concurrent.CompletableFuture; import java.util.*; import com.docuware.dev.schema._public.services.Link; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; @XmlType(name = "StampSignatureType") @XmlEnum public enum StampSignatureType { @XmlEnumValue("No") NO("No"), @XmlEnumValue("Simple") SIMPLE("Simple"), XMLDSIG("XMLDSIG"); private final String value; StampSignatureType(String v) { value = v; } public String value() { return value; } public static StampSignatureType fromValue(String v) { for (StampSignatureType c: StampSignatureType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
9236ec4608ec50a326aac69b8d365000d000573e
1,166
java
Java
subprojects/groovy-xml/src/main/java/groovy/xml/markupsupport/DoubleQuoteFilter.java
T45K/groovy
21122ce43fe6f983d40e7c3c9632e1314047873b
[ "Apache-2.0" ]
1
2021-11-23T22:51:20.000Z
2021-11-23T22:51:20.000Z
subprojects/groovy-xml/src/main/java/groovy/xml/markupsupport/DoubleQuoteFilter.java
BlazeOS-dev/groovy
9e420c1a3a90c737891abff9d1e84b7493d18bd0
[ "Apache-2.0" ]
1
2020-12-19T22:31:27.000Z
2020-12-19T22:32:25.000Z
subprojects/groovy-xml/src/main/java/groovy/xml/markupsupport/DoubleQuoteFilter.java
BlazeOS-dev/groovy
9e420c1a3a90c737891abff9d1e84b7493d18bd0
[ "Apache-2.0" ]
1
2022-02-05T05:58:12.000Z
2022-02-05T05:58:12.000Z
37.612903
81
0.727273
997,882
/* * 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 groovy.xml.markupsupport; import java.util.Optional; import java.util.function.Function; public class DoubleQuoteFilter implements Function<Character, Optional<String>> { @Override public Optional<String> apply(Character ch) { if (ch == '"') return Optional.of("&quot;"); else return Optional.empty(); } }
9236ec63ffd715d8a4935c6b92a2866861d5da8e
1,173
java
Java
src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal/Solution.java
IvanMenov/LeetCode-in-Java
7eb9ead69339e29ac0acf597f061a4cf7e578531
[ "MIT" ]
null
null
null
src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal/Solution.java
IvanMenov/LeetCode-in-Java
7eb9ead69339e29ac0acf597f061a4cf7e578531
[ "MIT" ]
null
null
null
src/main/java/g0001_0100/s0094_binary_tree_inorder_traversal/Solution.java
IvanMenov/LeetCode-in-Java
7eb9ead69339e29ac0acf597f061a4cf7e578531
[ "MIT" ]
null
null
null
25.5
71
0.57971
997,883
package g0001_0100.s0094_binary_tree_inorder_traversal; import com_github_leetcode.TreeNode; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { if (root == null) { return Collections.emptyList(); } List<Integer> answer = new ArrayList<>(); inorderTraversal(root, answer); return answer; } public void inorderTraversal(TreeNode root, List<Integer> answer) { if (root == null) { return; } if (root.left != null) { inorderTraversal(root.left, answer); } answer.add(root.val); if (root.right != null) { inorderTraversal(root.right, answer); } } }
9236ec7544bdda34ae6ad22277e7686ee1033c4c
380
java
Java
src/main/java/edu/xautjzd/dao/CustomHibernateDaoSupport.java
xautjzd/HibernateSpringDemo
775906e93fd5c922f195f0f6002e3eca331bcd86
[ "MIT" ]
null
null
null
src/main/java/edu/xautjzd/dao/CustomHibernateDaoSupport.java
xautjzd/HibernateSpringDemo
775906e93fd5c922f195f0f6002e3eca331bcd86
[ "MIT" ]
null
null
null
src/main/java/edu/xautjzd/dao/CustomHibernateDaoSupport.java
xautjzd/HibernateSpringDemo
775906e93fd5c922f195f0f6002e3eca331bcd86
[ "MIT" ]
null
null
null
27.142857
70
0.842105
997,884
package edu.xautjzd.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; public class CustomHibernateDaoSupport extends HibernateDaoSupport { @Autowired public void setFactory(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } }
9236ec8f88e36e7614b6dce7b356bc78f8311cb0
11,111
java
Java
litho-processor/src/main/java/com/facebook/litho/specmodels/model/StateValidation.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
7,886
2017-04-18T19:27:19.000Z
2022-03-29T13:18:19.000Z
litho-processor/src/main/java/com/facebook/litho/specmodels/model/StateValidation.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
667
2017-04-18T20:43:18.000Z
2022-03-28T15:21:43.000Z
litho-processor/src/main/java/com/facebook/litho/specmodels/model/StateValidation.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
824
2017-04-18T19:56:51.000Z
2022-03-25T07:17:34.000Z
43.572549
118
0.649986
997,885
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.specmodels.model; import static com.facebook.litho.specmodels.model.ClassNames.STATE_VALUE; import com.facebook.litho.annotations.InjectProp; import com.facebook.litho.annotations.OnUpdateState; import com.facebook.litho.annotations.Param; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.State; import com.facebook.litho.annotations.TreeProp; import com.facebook.litho.specmodels.internal.ImmutableList; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.WildcardTypeName; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** Class for validating that the state models within a {@link SpecModel} are well-formed. */ public class StateValidation { static List<SpecModelValidationError> validate(SpecModel specModel) { final List<SpecModelValidationError> validationErrors = new ArrayList<>(); validationErrors.addAll(validateStateValues(specModel)); validationErrors.addAll(validateOnUpdateStateMethods(specModel)); return validationErrors; } static List<SpecModelValidationError> validateStateValues(SpecModel specModel) { final List<SpecModelValidationError> validationErrors = new ArrayList<>(); final ImmutableList<StateParamModel> stateValues = specModel.getStateValues(); for (int i = 0, size = stateValues.size(); i < size - 1; i++) { final StateParamModel thisStateValue = stateValues.get(i); for (int j = i + 1; j < size; j++) { final StateParamModel thatStateValue = stateValues.get(j); if (thisStateValue.getName().equals(thatStateValue.getName())) { if (!thisStateValue.getTypeName().box().equals(thatStateValue.getTypeName().box())) { validationErrors.add( new SpecModelValidationError( thatStateValue.getRepresentedObject(), "State values with the same name must have the same type.")); } if (thisStateValue.canUpdateLazily() != thatStateValue.canUpdateLazily()) { validationErrors.add( new SpecModelValidationError( thatStateValue.getRepresentedObject(), "State values with the same name must have the same annotated value for " + "canUpdateLazily().")); } } } } final Set<String> stateNameSet = stateValues.stream().map(StateParamModel::getName).collect(Collectors.toSet()); validateDuplicateName(stateNameSet, specModel.getProps(), validationErrors); validateDuplicateName(stateNameSet, specModel.getInjectProps(), validationErrors); validateDuplicateName(stateNameSet, specModel.getTreeProps(), validationErrors); validateInterStagePropsDuplicateName( stateNameSet, specModel.getInterStageInputs(), validationErrors); validatePrepareInterStagePropsDuplicateName( stateNameSet, specModel.getPrepareInterStageInputs(), validationErrors); return validationErrors; } static List<SpecModelValidationError> validateOnUpdateStateMethods(SpecModel specModel) { final List<SpecModelValidationError> validationErrors = new ArrayList<>(); for (SpecMethodModel<UpdateStateMethod, Void> updateStateMethodModel : specModel.getUpdateStateMethods()) { validationErrors.addAll(validateOnUpdateStateMethod(specModel, updateStateMethodModel)); } return validationErrors; } /** * Validate that the declaration of a method annotated with {@link OnUpdateState} is correct: * * <ul> * <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters * annotated with {@link State} or {@link Prop}. * <li>2. Method parameters not annotated with {@link Param} must be of type * com.facebook.litho.StateValue. * <li>3. Names of method parameters not annotated with {@link Param} must match the name and * type of a parameter annotated with {@link State}. * </ul> * * @return a list of validation errors. If the list is empty, the method is well-formed. */ static List<SpecModelValidationError> validateOnUpdateStateMethod( SpecModel specModel, SpecMethodModel<UpdateStateMethod, Void> updateStateMethodModel) { final List<SpecModelValidationError> validationErrors = new ArrayList<>(); validationErrors.addAll( SpecMethodModelValidation.validateMethodIsStatic(specModel, updateStateMethodModel)); for (MethodParamModel methodParam : updateStateMethodModel.methodParams) { if (MethodParamModelUtils.isAnnotatedWith(methodParam, Param.class)) { // Check #1 for (PropModel prop : specModel.getProps()) { if (methodParam.getName().equals(prop.getName())) { validationErrors.add( new SpecModelValidationError( methodParam.getRepresentedObject(), "Parameters annotated with @Param should not have the same name as a @Prop.")); } } for (StateParamModel stateValue : specModel.getStateValues()) { if (methodParam.getName().equals(stateValue.getName())) { validationErrors.add( new SpecModelValidationError( methodParam.getRepresentedObject(), "Parameters annotated with @Param should not have the same name as a @State " + "value.")); } } } else { // Check #2 if (!(methodParam.getTypeName() instanceof ParameterizedTypeName) || !(((ParameterizedTypeName) methodParam.getTypeName()).rawType.equals(STATE_VALUE))) { validationErrors.add( new SpecModelValidationError( methodParam.getRepresentedObject(), "Only state parameters and parameters annotated with @Param are permitted in " + "@OnUpdateState method, and all state parameters must be of type " + "com.facebook.litho.StateValue, but " + methodParam.getName() + " is of type " + methodParam.getTypeName() + ".")); } else if (((ParameterizedTypeName) methodParam.getTypeName()).typeArguments.size() != 1 || ((ParameterizedTypeName) methodParam.getTypeName()).typeArguments.get(0) instanceof WildcardTypeName) { validationErrors.add( new SpecModelValidationError( methodParam.getRepresentedObject(), "All parameters of type com.facebook.litho.StateValue must define a type " + "argument, " + methodParam.getName() + " in method " + updateStateMethodModel.name + " does not.")); } else if (!definesStateValue( specModel, methodParam.getName(), ((ParameterizedTypeName) methodParam.getTypeName()).typeArguments.get(0))) { // Check #3 validationErrors.add( new SpecModelValidationError( methodParam.getRepresentedObject(), "Names of parameters of type StateValue must match the name and type of a " + "parameter annotated with @State.")); } } } return validationErrors; } private static boolean definesStateValue(SpecModel specModel, String name, TypeName type) { for (StateParamModel stateValue : specModel.getStateValues()) { if (stateValue.getName().equals(name) && stateValue.getTypeName().box().equals(type.box())) { return true; } } return false; } private static void validateDuplicateName( Set<String> stateNameSet, List<? extends MethodParamModel> propModelList, List<SpecModelValidationError> validationErrors) { for (int i = 0, size = propModelList.size(); i < size; i++) { final MethodParamModel model = propModelList.get(i); if (stateNameSet.contains(model.getName())) { final Annotation paramAnnotation = model.getAnnotations().stream() .filter( it -> it instanceof Prop || it instanceof InjectProp || it instanceof TreeProp) .findFirst() .get(); validationErrors.add( new SpecModelValidationError( model.getRepresentedObject(), "The parameter name of @" + paramAnnotation.annotationType().getSimpleName() + " \"" + model.getName() + "\" and @State \"" + model.getName() + "\" collide!")); } } } private static void validateInterStagePropsDuplicateName( Set<String> stateNameSet, List<InterStageInputParamModel> interStageInputParamModels, List<SpecModelValidationError> validationErrors) { for (int i = 0, size = interStageInputParamModels.size(); i < size; i++) { final MethodParamModel model = interStageInputParamModels.get(i); if (stateNameSet.contains(model.getName())) { validationErrors.add( new SpecModelValidationError( model.getRepresentedObject(), "The parameter with name " + model.getName() + " annotated with @State is colliding with another inter-stage prop param with the same name.")); } } } private static void validatePrepareInterStagePropsDuplicateName( Set<String> stateNameSet, List<PrepareInterStageInputParamModel> interStageInputParamModels, List<SpecModelValidationError> validationErrors) { for (int i = 0, size = interStageInputParamModels.size(); i < size; i++) { final MethodParamModel model = interStageInputParamModels.get(i); if (stateNameSet.contains(model.getName())) { validationErrors.add( new SpecModelValidationError( model.getRepresentedObject(), "The parameter with name " + model.getName() + " annotated with @State is colliding with another inter-stage prop param with the same name.")); } } } }
9236ed028ac79a646076a66d32ec1a34b1bef8dc
347
java
Java
IFSPEC/Aliasing-StrongUpdate-secure/program/Main.java
HarvardPL/Co-InflowPrototype
d1c7f3bed6bed734268bf36bdcb9cf5f89af78d7
[ "MIT" ]
2
2021-12-14T10:55:25.000Z
2021-12-14T11:22:29.000Z
IFSPEC/Aliasing-StrongUpdate-secure/program/Main.java
HarvardPL/Co-InflowPrototype
d1c7f3bed6bed734268bf36bdcb9cf5f89af78d7
[ "MIT" ]
null
null
null
IFSPEC/Aliasing-StrongUpdate-secure/program/Main.java
HarvardPL/Co-InflowPrototype
d1c7f3bed6bed734268bf36bdcb9cf5f89af78d7
[ "MIT" ]
null
null
null
13.88
43
0.417867
997,886
public class Main { static class A { int val; A(int val) { this.val = val; } } static int secret=42; public static void main(String[] arg) { A a = new A(secret); A b = new A(5); A c = b; b = a; a.val = 2; System.out.println(c.val); } }
9236edb29cb234ea03c9a63c7a690efb3ca8467f
1,350
java
Java
src/main/test/com/java/utils/test/TestDoubleUtils.java
albertocerqueira/java-utils
ac5d1c5faeb33cf72f427da8a304f01d24098104
[ "Apache-2.0" ]
null
null
null
src/main/test/com/java/utils/test/TestDoubleUtils.java
albertocerqueira/java-utils
ac5d1c5faeb33cf72f427da8a304f01d24098104
[ "Apache-2.0" ]
null
null
null
src/main/test/com/java/utils/test/TestDoubleUtils.java
albertocerqueira/java-utils
ac5d1c5faeb33cf72f427da8a304f01d24098104
[ "Apache-2.0" ]
null
null
null
29.347826
79
0.74
997,887
package com.java.utils.test; import org.junit.Assert; import org.junit.Test; import com.java.utils.DoubleUtils; public class TestDoubleUtils { @Test public void test_isBlank() { Assert.assertEquals(DoubleUtils.isBlank(""), true); Assert.assertEquals(DoubleUtils.isBlank("albertocerqueira"), false); Assert.assertEquals(DoubleUtils.isBlank("1990"), false); Assert.assertEquals(DoubleUtils.isBlank("0.00001"), false); Assert.assertEquals(DoubleUtils.isBlank(null), true); } @Test public void test_isOnlyNumber() { Assert.assertEquals(DoubleUtils.isOnlyNumber("albertocerqueira"), false); Assert.assertEquals(DoubleUtils.isOnlyNumber("albertocerqueira1990"), false); Assert.assertEquals(DoubleUtils.isOnlyNumber("1990"), true); Assert.assertEquals(DoubleUtils.isOnlyNumber("0.00001"), true); Assert.assertEquals(DoubleUtils.isOnlyNumber(null), false); } @Test public void test_isZero() { Assert.assertEquals(DoubleUtils.isZero("0"), true); try { Assert.assertEquals(DoubleUtils.isZero("albertocerqueira1990"), false); Assert.fail(); } catch (Exception e) { } Assert.assertEquals(DoubleUtils.isZero("1990"), false); Assert.assertEquals(DoubleUtils.isZero("0.00001"), false); try { Assert.assertEquals(DoubleUtils.isZero(null), false); Assert.fail(); } catch (Exception e) { } } }
9236ee27baaca61198b6538781c8c9c09a7e2fa5
8,616
java
Java
components/studio-platform/plugins/org.wso2.integrationstudio.artifact.registry/src/org/wso2/integrationstudio/artifact/registry/validators/RegistryArtifactFieldController.java
chanikag/integration-studio
860542074068146e95960889e281d9dbdeeaeaba
[ "Apache-2.0" ]
23
2020-12-09T09:52:23.000Z
2022-03-23T03:59:39.000Z
components/studio-platform/plugins/org.wso2.integrationstudio.artifact.registry/src/org/wso2/integrationstudio/artifact/registry/validators/RegistryArtifactFieldController.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "Apache-2.0" ]
751
2020-12-16T12:30:50.000Z
2022-03-31T07:53:21.000Z
components/studio-platform/plugins/org.wso2.integrationstudio.artifact.registry/src/org/wso2/integrationstudio/artifact/registry/validators/RegistryArtifactFieldController.java
sajithaliyanage/integration-studio
3329da9fa47e75028edf51f79264b6816bc4e333
[ "Apache-2.0" ]
25
2020-12-09T09:52:29.000Z
2022-03-16T06:18:08.000Z
39.522936
163
0.735956
997,888
/* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) 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.wso2.integrationstudio.artifact.registry.validators; import java.io.File; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Path; import org.wso2.integrationstudio.artifact.registry.model.RegistryArtifactModel; import org.wso2.integrationstudio.artifact.registry.utils.RegistryArtifactConstants; import org.wso2.integrationstudio.artifact.registry.utils.RegistryTemplate; import org.wso2.integrationstudio.general.project.artifact.GeneralProjectArtifact; import org.wso2.integrationstudio.general.project.artifact.RegistryArtifact; import org.wso2.integrationstudio.registry.base.model.RegistryResourceNode; import org.wso2.integrationstudio.platform.core.exception.FieldValidationException; import org.wso2.integrationstudio.platform.core.model.AbstractFieldController; import org.wso2.integrationstudio.platform.core.project.model.ProjectDataModel; import org.wso2.integrationstudio.platform.ui.validator.CommonFieldValidator; import org.wso2.integrationstudio.utils.file.FileUtils; import org.wso2.integrationstudio.utils.project.ProjectUtils; public class RegistryArtifactFieldController extends AbstractFieldController { public void validate(String modelProperty, Object value, ProjectDataModel model) throws FieldValidationException { if (modelProperty.equals(RegistryArtifactConstants.DATA_REG_LOCATION)) { if (value == null) { throw new FieldValidationException("Registry path cannot be empty"); } String regPath = value.toString(); if (regPath.trim().equals("")) { throw new FieldValidationException("Registry path cannot be empty"); } } else if (modelProperty.equals(RegistryArtifactConstants.DATA_RESOURCE_NAME)) { if (value == null) { throw new FieldValidationException("Resource name cannot be empty"); } String resource = value.toString(); if (resource.trim().equals("")) { throw new FieldValidationException("Resource name cannot be empty"); }else{ if(!CommonFieldValidator.isValidArtifactName(resource)){ throw new FieldValidationException("Resource name cannot contain invalid characters (/:@%\\^+;,=*#[{]}$?\"<> +)"); } } }else if (modelProperty.equals("artifact.name")) { CommonFieldValidator.validateArtifactName(value); if (value != null) { String resource = value.toString(); RegistryArtifactModel regModel = (RegistryArtifactModel) model; if (regModel != null) { IContainer resLocation = regModel.getResourceSaveLocation(); if (resLocation != null) { IProject project = resLocation.getProject(); GeneralProjectArtifact generalProjectArtifact = new GeneralProjectArtifact(); try { generalProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile()); List<RegistryArtifact> allArtifacts = generalProjectArtifact.getAllArtifacts(); for (RegistryArtifact registryArtifact : allArtifacts) { if (resource.equals(registryArtifact.getName())) { throw new FieldValidationException(""); } } } catch (Exception e) { throw new FieldValidationException("Artifact name already exists"); } } } if (regModel != null) { IContainer resLocation = regModel.getResourceSaveLocation(); if (resLocation != null) { RegistryTemplate selectedTemplate = regModel.getSelectedTemplate(); String file = regModel.getResourceName() + "." + selectedTemplate.getTemplateFileName().substring(selectedTemplate.getTemplateFileName().lastIndexOf(".")+1); IResource findMember = resLocation.findMember(file); if(findMember != null){ throw new FieldValidationException("A Resource already exist in the same location with same name."); } } } } }else if (modelProperty.equals(RegistryArtifactConstants.DATA_IMPORT_FILE)) { if (value == null) { throw new FieldValidationException("Specified resource location is invalid"); } File resource = (File) value; if (resource==null || !resource.exists()) { throw new FieldValidationException("Specified resource doesn't exist"); } RegistryArtifactModel regModel = (RegistryArtifactModel) model; IContainer resLocation = regModel.getResourceSaveLocation(); if (resLocation != null) { IResource findMember = resLocation.findMember(resource.getName()); if(findMember != null){ throw new FieldValidationException("A Resource already exist in the same location with same name."); } } } else if (modelProperty.equals("save.file")) { IResource resource = (IResource)value; if(resource==null || !resource.exists()) throw new FieldValidationException("Specified project or path doesn't exist"); } else if (modelProperty.equals(RegistryArtifactConstants.DATA_CHECKOUT_PATH)) { if (value == null) { throw new FieldValidationException("Registry path cannot be empty"); } else{ if(value instanceof RegistryResourceNode){ RegistryResourceNode node =(RegistryResourceNode)value; } else{ throw new FieldValidationException("Registry path cannot be empty"); } } } } public boolean isEnableField(String modelProperty, ProjectDataModel model) { boolean enableField = super.isEnableField(modelProperty, model); if (modelProperty.equals(RegistryArtifactConstants.DATA_COPY_CONTENT)) { File file = (File) model.getModelPropertyValue(RegistryArtifactConstants.DATA_IMPORT_FILE); if(file!=null) { if(file.isDirectory()){ enableField=true; } else{ enableField=false; } } else{ enableField=false; } } return enableField; } public boolean isReadOnlyField(String modelProperty, ProjectDataModel model) { boolean isReadOnly = super.isReadOnlyField(modelProperty, model); if (modelProperty.equals(RegistryArtifactConstants.DATA_CHECKOUT_PATH)) { isReadOnly=true; } return isReadOnly; } public List<String> getUpdateFields(String modelProperty, ProjectDataModel model) { List<String> updateFields = super.getUpdateFields(modelProperty, model); if (modelProperty.equals(RegistryArtifactConstants.DATA_IMPORT_FILE)) { updateFields.add(RegistryArtifactConstants.DATA_COPY_CONTENT); } else if (modelProperty.equals("create.prj")) { updateFields.add("save.file"); } else if (modelProperty.equals(RegistryArtifactConstants.DATA_RESOURCE_TYPE)) { updateFields.add(RegistryArtifactConstants.DATA_REG_LOCATION); } if (("resource.name".equals(modelProperty)) || ("import.file".equals(modelProperty)) || ("registry.browser".equals(modelProperty))) { RegistryArtifactModel tempmodel = (RegistryArtifactModel) model; if (("resource.name".equals(modelProperty))) { String resourcesName = tempmodel.getResourceName(); String oldresourcesName = ""; if (resourcesName.length() >= 1) { oldresourcesName = resourcesName.substring(0, resourcesName.length() - 1); } String artifactName = tempmodel.getArtifactName(); String oldArtifactName = ""; if (artifactName.length() >= 1) { oldArtifactName = artifactName.substring(0, artifactName.length() - 1); } if (oldresourcesName.equals(tempmodel.getArtifactName()) || (resourcesName.equals(oldArtifactName))) { tempmodel.setArtifactName(resourcesName); updateFields.add("artifact.name"); } } else if("import.file".equals(modelProperty)){ if (tempmodel.getImportFile()!=null) { String fileNameWithExtension = ProjectUtils.fileNameWithExtension(tempmodel.getImportFile().getName()); tempmodel.setArtifactName(fileNameWithExtension); updateFields.add("artifact.name"); } }else { if (tempmodel.getResourceName()!=null) { tempmodel.setArtifactName(tempmodel.getResourceName()); updateFields.add("artifact.name"); } } } return updateFields; } }
9236eee28ad6917271134279722dab457a4aecc2
5,717
java
Java
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/MetricSchemaRecordQuery.java
lpadia2/Argus
dbfdf57de7441f9a27de0b0335cd14b2f0cb52b8
[ "BSD-3-Clause" ]
1
2016-05-20T22:02:49.000Z
2016-05-20T22:02:49.000Z
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/MetricSchemaRecordQuery.java
lpadia2/Argus
dbfdf57de7441f9a27de0b0335cd14b2f0cb52b8
[ "BSD-3-Clause" ]
1
2016-12-13T16:38:44.000Z
2016-12-13T16:38:44.000Z
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/MetricSchemaRecordQuery.java
lpadia2/Argus
dbfdf57de7441f9a27de0b0335cd14b2f0cb52b8
[ "BSD-3-Clause" ]
2
2016-12-07T13:12:16.000Z
2022-03-26T09:05:44.000Z
33.267442
150
0.606606
997,889
/* * Copyright (c) 2016, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.entity; import com.salesforce.dva.argus.system.SystemAssert; import java.text.MessageFormat; /** * Represents a query against the metric schema data. This is used for the discovery service and to expand wildcards. * * @author Tom Valine (upchh@example.com) */ public class MetricSchemaRecordQuery { //~ Instance fields ****************************************************************************************************************************** private String namespace; private String scope; private String metric; private String tagKey; private String tagValue; //~ Constructors ********************************************************************************************************************************* /** * Creates a new MetricSchemaRecordQuery object. * * @param namespace The namespace. Can be null. * @param scope The scope. Cannot be null or empty. * @param metric The metric. Cannot be null or empty. * @param tagKey The tag key. Can be null. * @param tagValue The tag value. Can be null. */ public MetricSchemaRecordQuery(String namespace, String scope, String metric, String tagKey, String tagValue) { setNamespace(namespace); setScope(scope); setMetric(metric); setTagKey(tagKey); setTagValue(tagValue); } //~ Methods ************************************************************************************************************************************** /** * Indicates the namespace of the query. * * @return The namespace. Can be null. */ public String getNamespace() { return namespace; } /** * Specifies the namespace for the query. * * @param namespace The namespace. Can be null. */ public void setNamespace(String namespace) { this.namespace = namespace; } /** * Indicates the scope of the query. * * @return The scope of the query. Will never return null. */ public String getScope() { return scope; } /** * Specifies the scope of the query. * * @param scope The scope of the query. Cannot be null or empty. */ public void setScope(String scope) { SystemAssert.requireArgument(scope != null && !scope.isEmpty(), "Scope cannot be null or empty."); this.scope = scope; } /** * Indicates the metric name of the query. * * @return The metric name of the query. Will never return null. */ public String getMetric() { return metric; } /** * Specifies the metric name of the query. * * @param metric The metric name of the query. Cannot be null or empty. */ public void setMetric(String metric) { SystemAssert.requireArgument(metric != null && !metric.isEmpty(), "Metric cannot be null or empty."); this.metric = metric; } /** * Indicates the tag key of the query. * * @return The tag key of the query. Can be null. */ public String getTagKey() { return tagKey; } /** * Specifies the tag key of the query. * * @param tagKey The tag key of the query. Can be null. */ public void setTagKey(String tagKey) { this.tagKey = tagKey; } /** * Indicates the tag value of the query. * * @return The tag value of the query. Can be null. */ public String getTagValue() { return tagValue; } /** * Specifies the tag value of the query. * * @param tagValue The tag value of the query. Can be null. */ public void setTagValue(String tagValue) { this.tagValue = tagValue; } @Override public String toString() { return MessageFormat.format("MetricSchemaRecordQuery = (Namespace = {0}, Scope = {1}, Metric = {2}, TagKey = {3}, TagValue = {4})", namespace, scope, metric, tagKey, tagValue); } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
9236ef7a25c2e66e2ecdb67aae16cfac619007c2
12,569
java
Java
code/Tests/Multiverse/multiverse-core/src/test/java/org/multiverse/TestUtils.java
Felorati/Thesis
96741cffdbf14bfa5ca0664ad96c1834f8bf9d07
[ "MIT" ]
161
2015-01-19T11:57:08.000Z
2022-03-19T13:03:29.000Z
multiverse-core/src/test/java/org/multiverse/TestUtils.java
zyjwall/Multiverse
b73cd3ceb17d0a5122216f2cacc86c4f864ee957
[ "Apache-2.0" ]
3
2015-07-22T11:43:57.000Z
2017-09-22T03:44:54.000Z
multiverse-core/src/test/java/org/multiverse/TestUtils.java
zyjwall/Multiverse
b73cd3ceb17d0a5122216f2cacc86c4f864ee957
[ "Apache-2.0" ]
32
2015-02-16T13:01:52.000Z
2021-08-24T13:09:26.000Z
32.731771
136
0.581112
997,890
package org.multiverse; import org.multiverse.api.Txn; import org.multiverse.api.TxnStatus; import org.multiverse.api.blocking.RetryLatch; import org.multiverse.stms.gamma.GammaConstants; import org.multiverse.stms.gamma.transactionalobjects.AbstractGammaObject; import org.multiverse.utils.Bugshaker; import org.multiverse.utils.ThreadLocalRandom; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static java.lang.String.format; import static org.junit.Assert.*; /** * @author Peter Veentjer */ public class TestUtils implements MultiverseConstants { public static void assertOrecValue(AbstractGammaObject object, long expected) { assertEquals(expected, object.orec); } public static void assertFailure(int value) { assertEquals(GammaConstants.FAILURE, value); } public static void assertHasMasks(int value, int... masks) { for (int mask : masks) { assertTrue((value & mask) > 0); } } public static void assertNotHasMasks(int value, int... masks) { for (int mask : masks) { assertTrue((value & mask) == 0); } } public static void clearCurrentThreadInterruptedStatus() { Thread.interrupted(); } public static void assertEqualsDouble(String msg, double expected, double found) { assertEquals(msg, Double.doubleToLongBits(expected), Double.doubleToLongBits(found)); } public static void assertEqualsDouble(double expected, double found) { assertEqualsDouble(format("expected %s found %s", expected, found), expected, found); } public static int processorCount() { return Runtime.getRuntime().availableProcessors(); } public static void assertEra(RetryLatch latch, long era) { assertEquals(era, latch.getEra()); } public static void assertOpen(RetryLatch latch) { assertTrue(latch.isOpen()); } public static void assertClosed(RetryLatch latch) { assertFalse(latch.isOpen()); } public static void assertEqualByteArray(byte[] array1, byte[] array2) { if (array1 == array2) { return; } if (array1 == null) { fail(); } int length = array1.length; assertEquals(length, array2.length); for (int k = 0; k < array1.length; k++) { assertEquals(array1[k], array2[k]); } } public static Object getField(Object o, String fieldname) { if (o == null || fieldname == null) { throw new NullPointerException(); } try { Field field = findField(o.getClass(), fieldname); if (field == null) { fail(format("field '%s' is not found on class '%s' or on one of its super classes", fieldname, o.getClass().getName())); } field.setAccessible(true); return field.get(o); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static Field findField(Class clazz, String fieldname) { try { return clazz.getDeclaredField(fieldname); } catch (NoSuchFieldException e) { if (clazz.equals(Object.class)) { return null; } return findField(clazz.getSuperclass(), fieldname); } } public static void assertNotEquals(long l1, long l2) { assertFalse(format("both values are %s, but should not be equal", l2), l1 == l2); } public static void assertIsPrepared(Txn... txns) { for (Txn tx : txns) { assertEquals(TxnStatus.Prepared, tx.getStatus()); } } public static void assertIsAborted(Txn... txns) { for (Txn tx : txns) { assertEquals(TxnStatus.Aborted, tx.getStatus()); } } public static void assertIsCommitted(Txn... txns) { for (Txn tx : txns) { assertEquals(TxnStatus.Committed, tx.getStatus()); } } public static void assertIsActive(Txn... txns) { for (Txn tx : txns) { assertEquals(TxnStatus.Active, tx.getStatus()); } } public static int randomInt(int max) { if (max <= 0) { return 0; } return ThreadLocalRandom.current().nextInt(max); } public static void sleepRandomMs(int maxMs) { Bugshaker.sleepUs((long) randomInt((int) TimeUnit.MILLISECONDS.toMicros(maxMs))); } public static void sleepMs(long ms) { long us = TimeUnit.MILLISECONDS.toMicros(ms); Bugshaker.sleepUs(us); } public static boolean randomBoolean() { return randomInt(10) % 2 == 0; } public static boolean randomOneOf(int chance) { return randomInt(Integer.MAX_VALUE) % chance == 0; } public static long getStressTestDurationMs(long defaultDuration) { String value = System.getProperty("org.multiverse.integrationtest.durationMs", String.valueOf(defaultDuration)); return Long.parseLong(value); } public static void assertIsInterrupted(Thread t) { assertTrue(t.isInterrupted()); } public static void assertAlive(Thread... threads) { for (Thread thread : threads) { assertTrue(thread.getName(), thread.isAlive()); } } public static boolean isAlive(Thread... threads) { for (Thread thread : threads) { if (!thread.isAlive()) { return false; } } return true; } public static void assertNothingThrown(TestThread... threads){ for(TestThread t: threads){ Throwable throwable = t.getThrowable(); if(throwable != null){ fail(String.format("TestThread [%s] failed with the following exception\n%s", t.getName(),getStackTrace(throwable))); } } } public static String getStackTrace(Throwable aThrowable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); aThrowable.printStackTrace(printWriter); return result.toString(); } public static void assertNotAlive(Thread... threads) { for (Thread thread : threads) { assertFalse(thread.isAlive()); } } public static void assertEventuallyNotAlive(Thread... threads){ assertEventuallyNotAlive(60 * 1000, threads); } public static void assertEventuallyNotAlive(long timeoutMs, Thread... threads) { for (Thread thread : threads) { if(timeoutMs <=0){ fail("There is no remaining timeout"); } long startMs = System.currentTimeMillis(); try { thread.join(timeoutMs); } catch (InterruptedException e) { fail("Failed to join thread: " + thread.getName()); } long elapsed = System.currentTimeMillis() - startMs; if (thread.isAlive()) { fail(format("Thread [%s] is still alive after a timeout of [%s] ms", thread, timeoutMs)); } assertFalse(thread.isAlive()); timeoutMs -= elapsed; } } public static void startAll(TestThread... threads) { for (Thread thread : threads) { thread.start(); } } public static void assertEventuallyFalse(Callable<Boolean> f) { assertEventually(f, false); } public static void assertEventuallyFalse(Callable<Boolean> f, long timeoutMs) { assertEventually(f, false, timeoutMs); } public static void assertEventually(Callable<Boolean> f, boolean value) { assertEventually(f, value, 60 * 1000); } public static void assertEventuallyTrue(Callable<Boolean> f) { assertEventually(f, true); } public static void assertEventuallyTrue(Callable<Boolean> f, long timeoutMs) { assertEventually(f, true, timeoutMs); } public static void assertEventually(Callable<Boolean> f, boolean value, long timeoutMs) { long endTime = System.currentTimeMillis() + timeoutMs; for (; ; ) { try { if (f.call() == value) { return; } } catch (Exception e) { throw new RuntimeException(e); } sleepMs(100); if (endTime > System.currentTimeMillis()) { fail("Failed to become true in the given timeout"); } } } public static void sleepRandomUs(int maxUs) { Bugshaker.sleepUs((long) randomInt(maxUs)); } public static void assertInstanceof(Class expected, Object o) { assertTrue(o.getClass().getName(), expected.isAssignableFrom(o.getClass())); } /** * Joins all threads. If this can't be done within 5 minutes, an assertion failure is thrown. * * @param threads the threads to join. * @return the total duration of all threads (so the sum of the time each thread has been running. * @see #joinAll(long, TestThread...) for more specifics. */ public static long joinAll(TestThread... threads) { return joinAll(5 * 60, threads); } /** * Joins all threads. If one of the thread throws a throwable, the join will fail as well. * * @param timeoutSec the timeout in seconds. If the join doesn't complete within that time, the * join fails. * @param threads the threads to join. * @return the total duration of all threads (so the sum of the time each thread has been running. */ @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) public static long joinAll(long timeoutSec, TestThread... threads) { if (timeoutSec < 0) { throw new IllegalArgumentException(); } List<TestThread> uncompleted = new LinkedList<TestThread>(Arrays.asList(threads)); long maxTimeMs = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSec); long durationMs = 0; while (!uncompleted.isEmpty()) { for (Iterator<TestThread> it = uncompleted.iterator(); it.hasNext(); ) { TestThread thread = it.next(); try { if (System.currentTimeMillis() > maxTimeMs) { fail(String.format( "Failed to join all threads in %s seconds, remaining threads %s.\n%s", timeoutSec, uncompleted, getStacks(uncompleted))); } thread.join(100); if (!thread.isAlive()) { it.remove(); durationMs += thread.getDurationMs(); if (thread.getThrowable() == null) { System.out.printf("Multiverse > %s completed successfully\n", thread.getName()); } else { System.out.printf("Multiverse > %s encountered the following error\n", thread.getName()); thread.getThrowable().printStackTrace(); fail(String.format("Multiverse > %s completed with failure", thread.getName())); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(String.format("Joining %s was interrupted", thread), e); } } } return durationMs; } private static String getStacks(List<TestThread> uncompleted) { StringBuffer sb = new StringBuffer(); sb.append("Uncompleted threads:\n"); for (TestThread thread : uncompleted) { sb.append("-------------------------------------------------------------------\n"); sb.append(thread.getName() + "\n"); for (StackTraceElement element : thread.getStackTrace()) { sb.append("\tat " + element + "\n"); } } sb.append("-------------------------------------------------------------------\n"); return sb.toString(); } }
9236efa6d7c93aac0081ae6f7e7b2a09c787a46b
13,642
java
Java
hedera-node/src/main/java/com/hedera/services/state/exports/SignedStateBalancesExporter.java
gizatupu/hedera-services
09a572c3f5bb6e341370ef1f1e9bdc0ed2b658c9
[ "Apache-2.0" ]
null
null
null
hedera-node/src/main/java/com/hedera/services/state/exports/SignedStateBalancesExporter.java
gizatupu/hedera-services
09a572c3f5bb6e341370ef1f1e9bdc0ed2b658c9
[ "Apache-2.0" ]
null
null
null
hedera-node/src/main/java/com/hedera/services/state/exports/SignedStateBalancesExporter.java
gizatupu/hedera-services
09a572c3f5bb6e341370ef1f1e9bdc0ed2b658c9
[ "Apache-2.0" ]
null
null
null
36.770889
128
0.761032
997,891
package com.hedera.services.state.exports; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.ServicesState; import com.hedera.services.context.properties.GlobalDynamicProperties; import com.hedera.services.context.properties.PropertySource; import com.hedera.services.state.merkle.MerkleAccount; import com.hedera.services.state.merkle.MerkleEntityAssociation; import com.hedera.services.state.merkle.MerkleEntityId; import com.hedera.services.state.merkle.MerkleToken; import com.hedera.services.state.merkle.MerkleTokenRelStatus; import com.hedera.services.stream.proto.AllAccountBalances; import com.hedera.services.stream.proto.SingleAccountBalances; import com.hedera.services.stream.proto.TokenUnitBalance; import com.hedera.services.utils.MiscUtils; import com.hederahashgraph.api.proto.java.AccountID; import com.hederahashgraph.api.proto.java.Timestamp; import com.hederahashgraph.api.proto.java.TokenBalance; import com.hederahashgraph.api.proto.java.TokenBalances; import com.hederahashgraph.api.proto.java.TokenID; import com.swirlds.fcmap.FCMap; import org.apache.commons.lang3.time.StopWatch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.UnaryOperator; import static com.hedera.services.ledger.HederaLedger.ACCOUNT_ID_COMPARATOR; import static com.hedera.services.state.merkle.MerkleEntityAssociation.fromAccountTokenRel; import static com.hedera.services.state.merkle.MerkleEntityId.fromTokenId; import static com.hedera.services.utils.EntityIdUtils.readableId; public class SignedStateBalancesExporter implements BalancesExporter { private static final Logger log = LogManager.getLogger(SignedStateBalancesExporter.class); private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String UNKNOWN_EXPORT_DIR = ""; private static final String BAD_EXPORT_ATTEMPT_ERROR_MSG_TPL = "Could not export to '{}'!"; private static final String BAD_SIGNING_ATTEMPT_ERROR_MSG_TPL = "Could not sign balance file '{}'!"; static final String BAD_EXPORT_DIR_ERROR_MSG_TPL = "Cannot ensure existence of export dir '{}'!"; static final String LOW_NODE_BALANCE_WARN_MSG_TPL = "Node '{}' has unacceptably low balance {}!"; static final String GOOD_SIGNING_ATTEMPT_DEBUG_MSG_TPL = "Created balance signature file '{}'."; static final String CURRENT_VERSION = "version:2"; private static final String PROTO_FILE_EXTENSION = ".pb"; private static final String CSV_FILE_EXTENSION = ".csv"; private static final Instant NEVER = null; private static final int ALLOWED_EXPORT_TIME_SKEW = 1; private static final Base64.Encoder encoder = Base64.getEncoder(); final long expectedFloat; private final UnaryOperator<byte[]> signer; private final GlobalDynamicProperties dynamicProperties; /* Used to toggle output for testing. */ boolean exportCsv = true, exportProto = true; SigFileWriter sigFileWriter = new StandardSigFileWriter(); FileHashReader hashReader = new Sha384HashReader(); DirectoryAssurance directories = loc -> Files.createDirectories(Paths.get(loc)); private String lastUsedExportDir = UNKNOWN_EXPORT_DIR; private BalancesSummary summary; Instant periodBegin = NEVER; static final Comparator<SingleAccountBalances> SINGLE_ACCOUNT_BALANCES_COMPARATOR = Comparator.comparing(SingleAccountBalances::getAccountID, ACCOUNT_ID_COMPARATOR); public SignedStateBalancesExporter( PropertySource properties, UnaryOperator<byte[]> signer, GlobalDynamicProperties dynamicProperties ) { this.signer = signer; this.expectedFloat = properties.getLongProperty("ledger.totalTinyBarFloat"); this.dynamicProperties = dynamicProperties; } @Override public boolean isTimeToExport(Instant now) { final int exportPeriod = dynamicProperties.balancesExportPeriodSecs(); if ( periodBegin != NEVER && now.getEpochSecond() % exportPeriod <= ALLOWED_EXPORT_TIME_SKEW && now.getEpochSecond() / exportPeriod != periodBegin.getEpochSecond() / exportPeriod) { periodBegin = now; return true; } periodBegin = now; if(log.isDebugEnabled()) { log.debug("Now {} is NOT time to export.", now); } return false; } @Override public void exportBalancesFrom(ServicesState signedState, Instant when) { if (!ensureExportDir(signedState.getNodeAccountId())) { return; } var watch = StopWatch.createStarted(); summary = summarized(signedState); var expected = BigInteger.valueOf(expectedFloat); if (!expected.equals(summary.getTotalFloat())) { throw new IllegalStateException(String.format( "Signed state @ %s had total balance %d not %d!", when, summary.getTotalFloat(), expectedFloat)); } log.info("Took {}ms to summarize signed state balances", watch.getTime(TimeUnit.MILLISECONDS)); // .pb account balances file is our focus, process it first to let its timestamp to stay close to // epoch export period boundary if (exportProto) { toProtoFile(when); } if (exportCsv) { toCsvFile(when); } } private void toCsvFile(Instant exportTimeStamp) { var watch = StopWatch.createStarted(); var csvLoc = lastUsedExportDir + exportTimeStamp.toString().replace(":", "_") + "_Balances" + CSV_FILE_EXTENSION; boolean exportSucceeded = exportBalancesFile(summary, csvLoc, exportTimeStamp); if (exportSucceeded) { tryToSign(csvLoc); } log.info(" -> Took {}ms to export and sign CSV balances file at {}", watch.getTime(TimeUnit.MILLISECONDS), exportTimeStamp); } private void toProtoFile(Instant exportTimeStamp) { var watch = StopWatch.createStarted(); var builder = AllAccountBalances.newBuilder(); summarizeAsProto(exportTimeStamp, builder); var protoLoc = lastUsedExportDir + exportTimeStamp.toString().replace(":", "_") + "_Balances" + PROTO_FILE_EXTENSION; boolean exportSucceeded = exportBalancesProtoFile(builder, protoLoc); if (exportSucceeded) { tryToSign(protoLoc); } log.info(" -> Took {}ms to export and sign proto balances file at {}", watch.getTime(TimeUnit.MILLISECONDS), exportTimeStamp); } private void tryToSign(String csvLoc) { try { var hash = hashReader.readHash(csvLoc); var sig = signer.apply(hash); var sigFileLoc = sigFileWriter.writeSigFile(csvLoc, sig, hash); if (log.isDebugEnabled()) { log.debug(GOOD_SIGNING_ATTEMPT_DEBUG_MSG_TPL, sigFileLoc); } } catch (Exception e) { log.error(BAD_SIGNING_ATTEMPT_ERROR_MSG_TPL, csvLoc, e); } } private boolean exportBalancesFile(BalancesSummary summary, String csvLoc, Instant when) { try (BufferedWriter fout = Files.newBufferedWriter(Paths.get(csvLoc))) { if (dynamicProperties.shouldExportTokenBalances()) { addRelease090Header(fout, when); } else { addLegacyHeader(fout, when); } for (SingleAccountBalances singleAccountBalances : summary.getOrderedBalances()) { fout.write(Long.toString(singleAccountBalances.getAccountID().getShardNum())); fout.write(","); fout.write(Long.toString(singleAccountBalances.getAccountID().getRealmNum())); fout.write(","); fout.write(Long.toString(singleAccountBalances.getAccountID().getAccountNum())); fout.write(","); fout.write(Long.toString(singleAccountBalances.getHbarBalance())); if (dynamicProperties.shouldExportTokenBalances()) { if (singleAccountBalances.getTokenUnitBalancesList().size() > 0) { fout.write(","); fout.write(b64Encode(singleAccountBalances)); } else { fout.write(","); } } fout.write(LINE_SEPARATOR); } } catch (IOException e) { log.error(BAD_EXPORT_ATTEMPT_ERROR_MSG_TPL, csvLoc, e); return false; } return true; } private void summarizeAsProto(Instant exportTimeStamp, AllAccountBalances.Builder builder) { builder.setConsensusTimestamp(Timestamp.newBuilder() .setSeconds(exportTimeStamp.getEpochSecond()) .setNanos(exportTimeStamp.getNano())); builder.addAllAllAccounts(summary.getOrderedBalances()); } private boolean exportBalancesProtoFile(AllAccountBalances.Builder allAccountsBuilder, String protoLoc) { try (FileOutputStream fout = new FileOutputStream(protoLoc)) { allAccountsBuilder.build().writeTo(fout); } catch (IOException e) { log.error(BAD_EXPORT_ATTEMPT_ERROR_MSG_TPL, protoLoc, e); return false; } return true; } private void addLegacyHeader(Writer writer, Instant at) throws IOException { writer.write("TimeStamp:"); writer.write(at.toString()); writer.write(LINE_SEPARATOR); writer.write("shardNum,realmNum,accountNum,balance"); writer.write(LINE_SEPARATOR); } private void addRelease090Header(Writer writer, Instant at) throws IOException { writer.write("# "); writer.write(CURRENT_VERSION); writer.write(LINE_SEPARATOR); writer.write("# TimeStamp:"); writer.write(at.toString()); writer.write(LINE_SEPARATOR); writer.write("shardNum,realmNum,accountNum,balance,tokenBalances"); writer.write(LINE_SEPARATOR); } BalancesSummary summarized(ServicesState signedState) { long nodeBalanceWarnThreshold = dynamicProperties.nodeBalanceWarningThreshold(); BigInteger totalFloat = BigInteger.valueOf(0L); List<SingleAccountBalances> accountBalances = new ArrayList<>(); var nodeIds = MiscUtils.getNodeAccounts(signedState.addressBook()); var tokens = signedState.tokens(); var accounts = signedState.accounts(); var tokenAssociations = signedState.tokenAssociations(); for (var entry : accounts.entrySet()) { var id = entry.getKey(); var account = entry.getValue(); if (!account.isDeleted()) { var accountId = id.toAccountId(); var balance = account.getBalance(); if (nodeIds.contains(accountId) && balance < nodeBalanceWarnThreshold) { log.warn(LOW_NODE_BALANCE_WARN_MSG_TPL, readableId(accountId), balance); } totalFloat = totalFloat.add(BigInteger.valueOf(account.getBalance())); SingleAccountBalances.Builder sabBuilder = SingleAccountBalances.newBuilder(); sabBuilder.setHbarBalance(balance) .setAccountID(accountId); if (dynamicProperties.shouldExportTokenBalances()) { addTokenBalances(accountId, account, sabBuilder, tokens, tokenAssociations); } accountBalances.add(sabBuilder.build()); } } accountBalances.sort(SINGLE_ACCOUNT_BALANCES_COMPARATOR); return new BalancesSummary(totalFloat, accountBalances); } private void addTokenBalances( AccountID id, MerkleAccount account, SingleAccountBalances.Builder sabBuilder, FCMap<MerkleEntityId, MerkleToken> tokens, FCMap<MerkleEntityAssociation, MerkleTokenRelStatus> tokenAssociations ) { var accountTokens = account.tokens(); for (TokenID tokenId : accountTokens.asTokenIds()) { var token = tokens.get(fromTokenId(tokenId)); if (token != null && !token.isDeleted()) { var relationship = tokenAssociations.get(fromAccountTokenRel(id, tokenId)); sabBuilder.addTokenUnitBalances(tb(tokenId, relationship.getBalance())); } } } private TokenUnitBalance tb(TokenID id, long balance) { return TokenUnitBalance.newBuilder().setTokenId(id).setBalance(balance).build(); } static String b64Encode(SingleAccountBalances accountBalances) { var wrapper = TokenBalances.newBuilder(); for (TokenUnitBalance tokenUnitBalance : accountBalances.getTokenUnitBalancesList()) { wrapper.addTokenBalances(TokenBalance.newBuilder() .setTokenId(tokenUnitBalance.getTokenId()) .setBalance(tokenUnitBalance.getBalance())); } return encoder.encodeToString(wrapper.build().toByteArray()); } private boolean ensureExportDir(AccountID node) { var correctDir = dynamicProperties.pathToBalancesExportDir(); if (!lastUsedExportDir.startsWith(correctDir)) { var sb = new StringBuilder(correctDir); if (!correctDir.endsWith(File.separator)) { sb.append(File.separator); } sb.append("balance").append(readableId(node)).append(File.separator); var candidateDir = sb.toString(); try { directories.ensureExistenceOf(candidateDir); lastUsedExportDir = candidateDir; } catch (IOException e) { log.error(BAD_EXPORT_DIR_ERROR_MSG_TPL, candidateDir); return false; } } return true; } static class BalancesSummary { private final BigInteger totalFloat; private final List<SingleAccountBalances> orderedBalances; BalancesSummary( BigInteger totalFloat, List<SingleAccountBalances> orderedBalances ) { this.totalFloat = totalFloat; this.orderedBalances = orderedBalances; } public BigInteger getTotalFloat() { return totalFloat; } public List<SingleAccountBalances> getOrderedBalances() { return orderedBalances; } } }
9236efec7c28fad4f6a9c8ab357d9d3c8912e3bf
10,539
java
Java
src/main/java/zes/openworks/web/webCommunity/user/cmUserPlan/CmUserPlanController.java
tenbirds/OPENWORKS-3.0
d9ea72589854380d7ad95a1df7e5397ad6d726a6
[ "Apache-2.0" ]
null
null
null
src/main/java/zes/openworks/web/webCommunity/user/cmUserPlan/CmUserPlanController.java
tenbirds/OPENWORKS-3.0
d9ea72589854380d7ad95a1df7e5397ad6d726a6
[ "Apache-2.0" ]
null
null
null
src/main/java/zes/openworks/web/webCommunity/user/cmUserPlan/CmUserPlanController.java
tenbirds/OPENWORKS-3.0
d9ea72589854380d7ad95a1df7e5397ad6d726a6
[ "Apache-2.0" ]
null
null
null
37.505338
139
0.656039
997,892
/* * Copyright (c) 2012 OMP Inc. All rights reserved. * This software is the confidential and proprietary information of OMP Inc. * You shall not disclose such Confidential Information and shall use it * only in accordance with the terms of the license agreement you entered into * with OMP Inc. */ package zes.openworks.web.webCommunity.user.cmUserPlan; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import zes.base.support.OpHelper; import zes.openworks.common.Messages; import zes.openworks.common.controller.WebController; import zes.openworks.intra.cmMgmt.cmManage.CmManageService; import zes.openworks.intra.cmMgmt.cmManage.CmManageVO; import zes.openworks.intra.cms.support.CmsUtil; import zes.openworks.web.common.CommonDutyConstant; import zes.openworks.web.common.CommonDutyService; import zes.openworks.web.login.UserLoginVO; import zes.openworks.web.webCommunity.user.cmUserMenu.CmUserMenuService; /** * * * @version 1.0 * @since OpenMarketPlace 프로젝트. (After JDK 1.6) * @author 오픈마켓플레이스 *<pre> *<< 개정이력(Modification Information) >> * * 수정일 수정자 수정내용 *-------------- ---------- ------------------------------- * 2014. 11. 28. boseok 신규 *</pre> * @see */ @Controller @RequestMapping(value = "/**/cm/user/cmUserPlan") public class CmUserPlanController extends WebController { @Autowired CmUserPlanService cmUserPlanService; @Autowired CommonDutyService commonDutyService; @Autowired CmManageService cmManageService; @Autowired CmUserMenuService cmUserMenuService; /** * 커뮤니티 사용자 일정 게시판 */ @RequestMapping(value = "BD_cmUserPlanList.do") public void cmUserPlanList(HttpServletRequest request, ModelMap model, CmManageVO cmv){ OpHelper.bindSearchMap(cmv, request); // CmManageVO cmv = new CmManageVO(); UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; // String strOptUserId = ""; String strCmmntyMenuCode = request.getParameter("cmmntyMenuCode") != null ? request.getParameter("cmmntyMenuCode").toString() : ""; // vo.setCmmntyMenuCode(strCmmntyMenuCode); // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); cmv.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); cmv.setCmmntyId(strCmmntyId); cmv.setCmmntyMenuCode(strCmmntyMenuCode); if(userLoginVo != null){ cmv.setCmmntyMberId(userLoginVo.getUserId()); cmv.setUserId(userLoginVo.getUserId()); } model.addAttribute("cmInfo", cmManageService.openCmManageView(cmv)); // 기본정보 model.addAttribute("cmMberInfo", cmUserMenuService.cmUserMberInfo(cmv)); // 회원기본정보 model.addAttribute("cmUserMenuView", cmUserMenuService.cmUserMenuView(cmv)); // model.addAttribute(GlobalConfig.KEY_PAGER, cmUserPlanService.cmUserPlanCalList(vo)); } /** * 커뮤니티 사용자 일정 게시판 달력 */ @RequestMapping(value = "ND_cmUserPlanCalList.do") public String cmCalList(HttpServletRequest request, ModelMap model, CmUserPlanVO vo) { UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; String strCmmntyMenuCode = request.getParameter("cmmntyMenuCode") != null ? request.getParameter("cmmntyMenuCode").toString() : ""; vo.setCmmntyMenuCode(strCmmntyMenuCode); vo.setCmmntyId(strCmmntyId); // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); vo.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); vo.setCmmntyId(strCmmntyId); Calendar cal = Calendar.getInstance(); if(userLoginVo != null){ vo.setRegistId(userLoginVo.getUserId()); } int a = cal.get(Calendar.YEAR); int b = vo.getStartYear(); int c = cal.get(Calendar.MONTH); int d = vo.getStartMonth(); // 현재 년도와 이동년도의 차이를 구해 세팅 vo.setStartY(b - a); // 현재 년도와 이동달의 차이를 구해세팅 vo.setStartM(d - c); return responseJson(model, cmUserPlanService.cmUserPlanCalList(vo)); } /** * 커뮤니티 사용자 일정 등록/수정 폼 */ @RequestMapping(value = {"BD_cmUserPlanForm.do","BD_cmUserPlanView.do"}) public void cmUserPlanForm(HttpServletRequest request, ModelMap model, CmUserPlanVO vo, CmManageVO cmv){ OpHelper.bindSearchMap(vo, request); OpHelper.bindSearchMap(cmv, request); UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; String strCmmntyMenuCode = request.getParameter("cmmntyMenuCode") != null ? request.getParameter("cmmntyMenuCode").toString() : ""; vo.setCmmntyMenuCode(strCmmntyMenuCode); cmv.setCmmntyMenuCode(strCmmntyMenuCode); // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); vo.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); cmv.setLangCode(vo.getLangCode()); cmv.setCmmntyId(strCmmntyId); vo.setCmmntyId(strCmmntyId); if(userLoginVo != null){ cmv.setCmmntyMberId(userLoginVo.getUserId()); vo.setRegistId(userLoginVo.getUserId()); } model.addAttribute("cmInfo", cmManageService.openCmManageView(cmv)); // 기본정보 model.addAttribute("cmMberInfo", cmUserMenuService.cmUserMberInfo(cmv)); // 회원기본정보 model.addAttribute("cmUserMenuView", cmUserMenuService.cmUserMenuView(cmv)); // 메뉴 기본정보 model.addAttribute("cmUserPlanView", cmUserPlanService.cmUserPlanCalView(vo)); // 달력 상세 페이지 } /** * 커뮤니티 사용자 일정관리 등록 * */ @RequestMapping(value = "INC_cmUserPlanInsert.do") public String cmUserPlanInsert( HttpServletRequest request, ModelMap model, CmUserPlanVO vo) { String StrResult1 = ""; UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; String strCmmntyMenuCode = request.getParameter("cmmntyMenuCode") != null ? request.getParameter("cmmntyMenuCode").toString() : ""; vo.setCmmntyMenuCode(strCmmntyMenuCode); // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); vo.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); vo.setCmmntyId(strCmmntyId); vo.setLangCode(vo.getLangCode()); if(userLoginVo != null){ vo.setRegistId(userLoginVo.getUserId()); } StrResult1 = cmUserPlanService.cmUserPlanCalInsert(request, vo); if("Y".equals(StrResult1)){ return responseText(model, Messages.TRUE ); }else{ return responseText(model,Messages.FALSE ); } } /** * 커뮤니티 사용자 일정관리 수정 * */ @RequestMapping(value = "INC_cmUserPlanUpdate.do") public String cmUserPlanUpdate( HttpServletRequest request, ModelMap model ,CmUserPlanVO vo ) { String StrResult1 = ""; UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); vo.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); vo.setCmmntyId(strCmmntyId); vo.setLangCode(vo.getLangCode()); if(userLoginVo != null){ vo.setRegistId(userLoginVo.getUserId()); vo.setUpdtId(userLoginVo.getUserId()); } StrResult1 = cmUserPlanService.cmUserPlanCalUpdate(request, vo); if("Y".equals(StrResult1)){ return responseText(model, Messages.TRUE ); }else{ return responseText(model,Messages.FALSE ); } } /** * 커뮤니티 사용자 일정관리 삭제 * */ @RequestMapping(value = "INC_cmUserPlanDelete.do") public String cmUserPlanDelete( HttpServletRequest request, ModelMap model, CmUserPlanVO vo ) { String StrResult1 = ""; UserLoginVO userLoginVo = OpHelper.getUserSession(request); String strCmmntyId = request.getParameter("cmmntyId") != null ? request.getParameter("cmmntyId").toString() : ""; String strCmmntyMenuCode = request.getParameter("cmmntyMenuCode") != null ? request.getParameter("cmmntyMenuCode").toString() : ""; // 도메인코드 String hostNm = CmsUtil.getHostName(request.getServerName()); String domainCode = new CommonDutyConstant().getDomainCode(hostNm); vo.setLangCode(commonDutyService.getLangCd(Integer.parseInt(domainCode))); vo.setCmmntyMenuCode(strCmmntyMenuCode); vo.setCmmntyId(strCmmntyId); vo.setLangCode(vo.getLangCode()); if(userLoginVo != null){ vo.setRegistId(userLoginVo.getUserId()); vo.setUpdtId(userLoginVo.getUserId()); } StrResult1 = cmUserPlanService.cmUserPlanCalDelete(request, vo); if("Y".equals(StrResult1)){ return responseText(model, Messages.TRUE ); }else{ return responseText(model,Messages.FALSE ); } } }
9236effb3ea8249b471b3d412638de618161510a
6,413
java
Java
app/src/main/java/com/argent/aiyunzan/MINE/mvp/ui/activity/Mine_SrmxActivity.java
DNDHades/AI-
56296e502cca25be16e7cf828fd2d4a3cc4e3c3f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/argent/aiyunzan/MINE/mvp/ui/activity/Mine_SrmxActivity.java
DNDHades/AI-
56296e502cca25be16e7cf828fd2d4a3cc4e3c3f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/argent/aiyunzan/MINE/mvp/ui/activity/Mine_SrmxActivity.java
DNDHades/AI-
56296e502cca25be16e7cf828fd2d4a3cc4e3c3f
[ "Apache-2.0" ]
null
null
null
33.442708
107
0.645071
997,893
package com.argent.aiyunzan.MINE.mvp.ui.activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import android.widget.TextView; import com.argent.aiyunzan.R; import com.argent.aiyunzan.common.model.bean.response.MineSrmxRsp; import com.argent.aiyunzan.common.model.constant.SPConstants; import com.argent.aiyunzan.common.utils.WeiboDialogUtils; import com.blankj.utilcode.util.SPUtils; import com.jess.arms.base.BaseActivity; import com.jess.arms.di.component.AppComponent; import com.jess.arms.utils.ArmsUtils; import com.argent.aiyunzan.MINE.di.component.DaggerMine_SrmxComponent; import com.argent.aiyunzan.MINE.mvp.contract.Mine_SrmxContract; import com.argent.aiyunzan.MINE.mvp.presenter.Mine_SrmxPresenter; import butterknife.BindView; import butterknife.OnClick; import static com.jess.arms.utils.Preconditions.checkNotNull; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 03/31/2020 17:00 * <a href="mailto:ychag@example.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ public class Mine_SrmxActivity extends BaseActivity<Mine_SrmxPresenter> implements Mine_SrmxContract.View { @BindView(R.id.toolbar_title) TextView toolbar_title; @BindView(R.id.tv_time1) TextView tv_time1; @BindView(R.id.tv_time2) TextView tv_time2; @BindView(R.id.tv_time3) TextView tv_time3; @BindView(R.id.tv_time4) TextView tv_time4; @BindView(R.id.tv_time5) TextView tv_time5; @BindView(R.id.tv_click) TextView tv_click; @BindView(R.id.tv_share) TextView tv_share; @BindView(R.id.tv_team) TextView tv_team; @BindView(R.id.tv_luck) TextView tv_luck; @BindView(R.id.tv_other) TextView tv_other; @BindView(R.id.tv_all_profit) TextView tv_all_profit; @BindView(R.id.tv_myprofit) TextView tv_myprofit; @BindView(R.id.tv_werden) TextView tv_werden; @BindView(R.id.tv_1) TextView tv_1; @BindView(R.id.tv_2) TextView tv_2; @BindView(R.id.tv_3) TextView tv_3; @BindView(R.id.tv_4) TextView tv_4; @BindView(R.id.tv_5) TextView tv_5; private Dialog mWeiboDialog; @OnClick({R.id.rl_click1, R.id.rl_click2, R.id.rl_click3, R.id.rl_click4, R.id.rl_click5}) void onClick(View view) { switch (view.getId()) { case R.id.rl_click1: SPUtils.getInstance().put(SPConstants.TDTYPE, "1"); SPUtils.getInstance().put(SPConstants.SYMXNAME, getText(tv_1)+""); launchActivity(new Intent(this,Mine_SrmxClickActivity.class)); break; case R.id.rl_click2: SPUtils.getInstance().put(SPConstants.TDTYPE, "2"); SPUtils.getInstance().put(SPConstants.SYMXNAME, getText(tv_2)+""); launchActivity(new Intent(this,Mine_SrmxClickActivity.class)); break; case R.id.rl_click3: SPUtils.getInstance().put(SPConstants.TDTYPE, "3"); SPUtils.getInstance().put(SPConstants.SYMXNAME, getText(tv_3)+""); launchActivity(new Intent(this,Mine_SrmxClickActivity.class)); break; case R.id.rl_click4: SPUtils.getInstance().put(SPConstants.TDTYPE, "5"); SPUtils.getInstance().put(SPConstants.SYMXNAME, getText(tv_4)+""); launchActivity(new Intent(this,Mine_SrmxClickActivity.class)); break; case R.id.rl_click5: SPUtils.getInstance().put(SPConstants.TDTYPE, "4"); SPUtils.getInstance().put(SPConstants.SYMXNAME, getText(tv_5)+""); launchActivity(new Intent(this,Mine_SrmxClickActivity.class)); break; } } @Override protected void onResume() { super.onResume(); toolbar_title.setText("收入明细"); } @Override public void setupActivityComponent(@NonNull AppComponent appComponent) { DaggerMine_SrmxComponent //如找不到该类,请编译一下项目 .builder() .appComponent(appComponent) .view(this) .build() .inject(this); } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.activity_mine__srmx; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0 } @Override public void initData(@Nullable Bundle savedInstanceState) { mPresenter.loadData(); } @Override public void showLoading() { mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this, "加载中..."); } @Override public void hideLoading() { WeiboDialogUtils.closeDialog(mWeiboDialog); } @Override public void showMessage(@NonNull String message) { checkNotNull(message); ArmsUtils.snackbarText(message); } @Override public void launchActivity(@NonNull Intent intent) { checkNotNull(intent); ArmsUtils.startActivity(intent); } @Override public void killMyself() { finish(); } @Override public void loadHomeSuccess(MineSrmxRsp datas) { MineSrmxRsp.DataBean data = datas.getData(); tv_time1.setText(datas.getTime() + ""); tv_time2.setText(datas.getTime() + ""); tv_time3.setText(datas.getTime() + ""); tv_time4.setText(datas.getTime() + ""); tv_time5.setText(datas.getTime() + ""); tv_share.setText(data.getShare() + "元"); tv_team.setText(data.getTeam() + "元"); tv_click.setText(data.getClick() + "元"); tv_luck.setText(data.getLuck() + "元"); tv_other.setText(data.getOther() + "元"); tv_all_profit.setText(data.getAll_profit() + ""); tv_myprofit.setText(data.getMyprofit() + ""); tv_werden.setText(data.getWerden() + ""); } private String getText(TextView textView) { return textView.getText().toString().trim(); } }
9236f122538ec5c28b5c0bc340111e17ae184241
17,400
java
Java
ruoyi-activiti/src/main/java/com/ruoyi/activiti/service/impl/ProcessCustomService.java
qwersm/ruoyi
5119e5578072918acafaa82d49b20b826cc00f70
[ "MIT" ]
2
2020-04-28T02:50:38.000Z
2020-12-02T06:33:42.000Z
ruoyi-activiti/src/main/java/com/ruoyi/activiti/service/impl/ProcessCustomService.java
qwersm/ruoyi
5119e5578072918acafaa82d49b20b826cc00f70
[ "MIT" ]
4
2021-04-22T16:59:15.000Z
2022-02-01T00:53:38.000Z
ruoyi-activiti/src/main/java/com/ruoyi/activiti/service/impl/ProcessCustomService.java
qwersm/ruoyi
5119e5578072918acafaa82d49b20b826cc00f70
[ "MIT" ]
3
2020-04-28T02:50:40.000Z
2021-11-22T01:53:12.000Z
22.985469
121
0.582989
997,894
package com.ruoyi.activiti.service.impl; import org.activiti.engine.*; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.impl.RepositoryServiceImpl; import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.activiti.engine.impl.pvm.PvmTransition; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl; import org.activiti.engine.impl.pvm.process.TransitionImpl; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.apache.commons.lang3.StringUtils; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 流程操作核心类<br> * <p> * 此核心类主要处理:流程通过、驳回、转办、中止、挂起等核心操作<br> */ public class ProcessCustomService { @Resource private static RepositoryService repositoryService; @Resource private static RuntimeService runtimeService; @Resource private static TaskService taskService; @Resource private static FormService formService; @Resource private static HistoryService historyService; /** * 退回流程 * * @param taskId 当前任务ID * @param activityId 退回节点ID * @param variables 流程存储参数 * @throws Exception */ public static void backProcess(String taskId, String activityId, Map<String, Object> variables) throws Exception { if (StringUtils.isEmpty(activityId)) { throw new Exception("退回目标节点ID为空!"); } // 查找所有并行任务节点,同时驳回 List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId( taskId).getId(), findTaskById(taskId).getTaskDefinitionKey()); for (Task task : taskList) { commitProcess(task.getId(), variables, activityId); } } /** * 取回流程 * * @param taskId 当前任务ID * @param activityId 取回节点ID * @throws Exception */ public static void callBackProcess(String taskId, String activityId) throws Exception { if (StringUtils.isEmpty(activityId)) { throw new Exception("退回目标节点ID为空!"); } // 查找所有并行任务节点,同时取回 List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId( taskId).getId(), findTaskById(taskId).getTaskDefinitionKey()); for (Task task : taskList) { commitProcess(task.getId(), null, activityId); } } /** * 清空指定活动节点流向 * * @param activityImpl 活动节点 * @return 节点流向集合 */ private static List<PvmTransition> clearTransition(ActivityImpl activityImpl) { // 存储当前节点所有流向临时变量 List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>(); // 获取当前节点所有流向,存储到临时变量,然后清空 List<PvmTransition> pvmTransitionList = activityImpl .getOutgoingTransitions(); for (PvmTransition pvmTransition : pvmTransitionList) { oriPvmTransitionList.add(pvmTransition); } pvmTransitionList.clear(); return oriPvmTransitionList; } /** * @param taskId 当前任务ID * @param variables 流程变量 * @param activityId 流程转向执行任务节点ID<br> * <p> * 此参数为空,默认为提交操作 * @throws Exception */ private static void commitProcess(String taskId, Map<String, Object> variables, String activityId) throws Exception { if (variables == null) { variables = new HashMap<String, Object>(); } // 跳转节点为空,默认提交操作 if (StringUtils.isEmpty(activityId)) { taskService.complete(taskId, variables); } else {// 流程转向操作 turnTransition(taskId, activityId, variables); } } /** * 中止流程(特权人直接审批通过等) * * @param taskId */ public static void endProcess(String taskId) throws Exception { ActivityImpl endActivity = findActivitiImpl(taskId, "end"); commitProcess(taskId, null, endActivity.getId()); } /** * 根据流入任务集合,查询最近一次的流入任务节点 * * @param processInstance 流程实例 * @param tempList 流入任务集合 * @return */ private static ActivityImpl filterNewestActivity(ProcessInstance processInstance, List<ActivityImpl> tempList) { while (tempList.size() > 0) { ActivityImpl activity_1 = tempList.get(0); HistoricActivityInstance activityInstance_1 = findHistoricUserTask( processInstance, activity_1.getId()); if (activityInstance_1 == null) { tempList.remove(activity_1); continue; } if (tempList.size() > 1) { ActivityImpl activity_2 = tempList.get(1); HistoricActivityInstance activityInstance_2 = findHistoricUserTask( processInstance, activity_2.getId()); if (activityInstance_2 == null) { tempList.remove(activity_2); continue; } if (activityInstance_1.getEndTime().before( activityInstance_2.getEndTime())) { tempList.remove(activity_1); } else { tempList.remove(activity_2); } } else { break; } } if (tempList.size() > 0) { return tempList.get(0); } return null; } /** * 根据任务ID和节点ID获取活动节点 <br> * * @param taskId 任务ID * @param activityId 活动节点ID <br> * <p> * 如果为null或"",则默认查询当前活动节点 <br> * <p> * 如果为"end",则查询结束节点 <br> * @return * @throws Exception */ private static ActivityImpl findActivitiImpl(String taskId, String activityId) throws Exception { // 取得流程定义 ProcessDefinitionEntity processDefinition = findProcessDefinitionEntityByTaskId(taskId); // 获取当前活动节点ID if (StringUtils.isEmpty(activityId)) { activityId = findTaskById(taskId).getTaskDefinitionKey(); } // 根据流程定义,获取该流程实例的结束节点 if (activityId.toUpperCase().equals("END")) { for (ActivityImpl activityImpl : processDefinition.getActivities()) { List<PvmTransition> pvmTransitionList = activityImpl .getOutgoingTransitions(); if (pvmTransitionList.isEmpty()) { return activityImpl; } } } // 根据节点ID,获取对应的活动节点 ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition) .findActivity(activityId); return activityImpl; } /** * 根据当前任务ID,查询可以驳回的任务节点 * * @param taskId 当前任务ID */ public static List<ActivityImpl> findBackAvtivity(String taskId) throws Exception { List<ActivityImpl> rtnList = iteratorBackActivity(taskId, findActivitiImpl(taskId, null), new ArrayList<ActivityImpl>(), new ArrayList<ActivityImpl>()); return reverList(rtnList); } /** * 查询指定任务节点的最新记录 * * @param processInstance 流程实例 * @param activityId * @return */ private static HistoricActivityInstance findHistoricUserTask( ProcessInstance processInstance, String activityId) { HistoricActivityInstance rtnVal = null; // 查询当前流程实例审批结束的历史节点 List<HistoricActivityInstance> historicActivityInstances = historyService .createHistoricActivityInstanceQuery().activityType("userTask") .processInstanceId(processInstance.getId()).activityId( activityId).finished() .orderByHistoricActivityInstanceEndTime().desc().list(); if (historicActivityInstances.size() > 0) { rtnVal = historicActivityInstances.get(0); } return rtnVal; } /** * 根据当前节点,查询输出流向是否为并行终点,如果为并行终点,则拼装对应的并行起点ID * * @param activityImpl 当前节点 * @return */ private static String findParallelGatewayId(ActivityImpl activityImpl) { List<PvmTransition> incomingTransitions = activityImpl .getOutgoingTransitions(); for (PvmTransition pvmTransition : incomingTransitions) { TransitionImpl transitionImpl = (TransitionImpl) pvmTransition; activityImpl = transitionImpl.getDestination(); String type = (String) activityImpl.getProperty("type"); if ("parallelGateway".equals(type)) {// 并行路线 String gatewayId = activityImpl.getId(); String gatewayType = gatewayId.substring(gatewayId .lastIndexOf("_") + 1); if ("END".equals(gatewayType.toUpperCase())) { return gatewayId.substring(0, gatewayId.lastIndexOf("_")) + "_start"; } } } return null; } /** * 根据任务ID获取流程定义 * * @param taskId 任务ID * @return * @throws Exception */ public static ProcessDefinitionEntity findProcessDefinitionEntityByTaskId( String taskId) throws Exception { // 取得流程定义 ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService) .getDeployedProcessDefinition(findTaskById(taskId) .getProcessDefinitionId()); if (processDefinition == null) { throw new Exception("流程定义未找到!"); } return processDefinition; } /** * 根据任务ID获取对应的流程实例 * * @param taskId 任务ID * @return * @throws Exception */ public static ProcessInstance findProcessInstanceByTaskId(String taskId) throws Exception { // 找到流程实例 ProcessInstance processInstance = runtimeService .createProcessInstanceQuery().processInstanceId( findTaskById(taskId).getProcessInstanceId()) .singleResult(); if (processInstance == null) { throw new Exception("流程实例未找到!"); } return processInstance; } /** * 根据任务ID获得任务实例 * * @param taskId 任务ID * @return * @throws Exception */ private static TaskEntity findTaskById(String taskId) throws Exception { TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId( taskId).singleResult(); if (task == null) { throw new Exception("任务实例未找到!"); } return task; } /** * 根据流程实例ID和任务key值查询所有同级任务集合 * * @param processInstanceId * @param key * @return */ private static List<Task> findTaskListByKey(String processInstanceId, String key) { return taskService.createTaskQuery().processInstanceId( processInstanceId).taskDefinitionKey(key).list(); } /** * 迭代循环流程树结构,查询当前节点可驳回的任务节点 * * @param taskId 当前任务ID * @param currActivity 当前活动节点 * @param rtnList 存储回退节点集合 * @param tempList 临时存储节点集合(存储一次迭代过程中的同级userTask节点) * @return 回退节点集合 */ private static List<ActivityImpl> iteratorBackActivity(String taskId, ActivityImpl currActivity, List<ActivityImpl> rtnList, List<ActivityImpl> tempList) throws Exception { // 查询流程定义,生成流程树结构 ProcessInstance processInstance = findProcessInstanceByTaskId(taskId); // 当前节点的流入来源 List<PvmTransition> incomingTransitions = currActivity .getIncomingTransitions(); // 条件分支节点集合,userTask节点遍历完毕,迭代遍历此集合,查询条件分支对应的userTask节点 List<ActivityImpl> exclusiveGateways = new ArrayList<ActivityImpl>(); // 并行节点集合,userTask节点遍历完毕,迭代遍历此集合,查询并行节点对应的userTask节点 List<ActivityImpl> parallelGateways = new ArrayList<ActivityImpl>(); // 遍历当前节点所有流入路径 for (PvmTransition pvmTransition : incomingTransitions) { TransitionImpl transitionImpl = (TransitionImpl) pvmTransition; ActivityImpl activityImpl = transitionImpl.getSource(); String type = (String) activityImpl.getProperty("type"); /** * 并行节点配置要求:<br> * 必须成对出现,且要求分别配置节点ID为:XXX_start(开始),XXX_end(结束) */ if ("parallelGateway".equals(type)) {// 并行路线 String gatewayId = activityImpl.getId(); String gatewayType = gatewayId.substring(gatewayId .lastIndexOf("_") + 1); if ("START".equals(gatewayType.toUpperCase())) {// 并行起点,停止递归 return rtnList; } else {// 并行终点,临时存储此节点,本次循环结束,迭代集合,查询对应的userTask节点 parallelGateways.add(activityImpl); } } else if ("startEvent".equals(type)) {// 开始节点,停止递归 return rtnList; } else if ("userTask".equals(type)) {// 用户任务 tempList.add(activityImpl); } else if ("exclusiveGateway".equals(type)) {// 分支路线,临时存储此节点,本次循环结束,迭代集合,查询对应的userTask节点 currActivity = transitionImpl.getSource(); exclusiveGateways.add(currActivity); } } /** * 迭代条件分支集合,查询对应的userTask节点 */ for (ActivityImpl activityImpl : exclusiveGateways) { iteratorBackActivity(taskId, activityImpl, rtnList, tempList); } /** * 迭代并行集合,查询对应的userTask节点 */ for (ActivityImpl activityImpl : parallelGateways) { iteratorBackActivity(taskId, activityImpl, rtnList, tempList); } /** * 根据同级userTask集合,过滤最近发生的节点 */ currActivity = filterNewestActivity(processInstance, tempList); if (currActivity != null) { // 查询当前节点的流向是否为并行终点,并获取并行起点ID String id = findParallelGatewayId(currActivity); if (StringUtils.isEmpty(id)) {// 并行起点ID为空,此节点流向不是并行终点,符合驳回条件,存储此节点 rtnList.add(currActivity); } else {// 根据并行起点ID查询当前节点,然后迭代查询其对应的userTask任务节点 currActivity = findActivitiImpl(taskId, id); } // 清空本次迭代临时集合 tempList.clear(); // 执行下次迭代 iteratorBackActivity(taskId, currActivity, rtnList, tempList); } return rtnList; } /** * 还原指定活动节点流向 * * @param activityImpl 活动节点 * @param oriPvmTransitionList 原有节点流向集合 */ private static void restoreTransition(ActivityImpl activityImpl, List<PvmTransition> oriPvmTransitionList) { // 清空现有流向 List<PvmTransition> pvmTransitionList = activityImpl .getOutgoingTransitions(); pvmTransitionList.clear(); // 还原以前流向 for (PvmTransition pvmTransition : oriPvmTransitionList) { pvmTransitionList.add(pvmTransition); } } /** * 反向排序list集合,便于驳回节点按顺序显示 * * @param list * @return */ private static List<ActivityImpl> reverList(List<ActivityImpl> list) { List<ActivityImpl> rtnList = new ArrayList<ActivityImpl>(); // 由于迭代出现重复数据,排除重复 for (int i = list.size(); i > 0; i--) { if (!rtnList.contains(list.get(i - 1))) rtnList.add(list.get(i - 1)); } return rtnList; } /** * 转办流程 * * @param taskId 当前任务节点ID * @param userCode 被转办人Code */ public static void transferAssignee(String taskId, String userCode) { taskService.setAssignee(taskId, userCode); } /** * 流程转向操作 * * @param taskId 当前任务ID * @param activityId 目标节点任务ID * @param variables 流程变量 * @throws Exception */ private static void turnTransition(String taskId, String activityId, Map<String, Object> variables) throws Exception { // 当前节点 ActivityImpl currActivity = findActivitiImpl(taskId, null); // 清空当前流向 List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity); // 创建新流向 TransitionImpl newTransition = currActivity.createOutgoingTransition(); // 目标节点 ActivityImpl pointActivity = findActivitiImpl(taskId, activityId); // 设置新流向的目标节点 newTransition.setDestination(pointActivity); // 执行转向任务 taskService.complete(taskId, variables); // 删除目标节点新流入 pointActivity.getIncomingTransitions().remove(newTransition); // 还原以前流向 restoreTransition(currActivity, oriPvmTransitionList); } }
9236f142064260c72d52a9e6b344df812f43d6a5
262
java
Java
src/main/java/alexandre/thiellin/pathfinder/repository/CharacterItemRepository.java
alexandre-thiellin/Pathfinder_API
8f9b7130c6cb387e074ec3eb3d046f15a16effcc
[ "MIT" ]
null
null
null
src/main/java/alexandre/thiellin/pathfinder/repository/CharacterItemRepository.java
alexandre-thiellin/Pathfinder_API
8f9b7130c6cb387e074ec3eb3d046f15a16effcc
[ "MIT" ]
null
null
null
src/main/java/alexandre/thiellin/pathfinder/repository/CharacterItemRepository.java
alexandre-thiellin/Pathfinder_API
8f9b7130c6cb387e074ec3eb3d046f15a16effcc
[ "MIT" ]
null
null
null
32.75
86
0.862595
997,895
package alexandre.thiellin.pathfinder.repository; import alexandre.thiellin.pathfinder.model.Character_Item; import org.springframework.data.jpa.repository.JpaRepository; public interface CharacterItemRepository extends JpaRepository<Character_Item, Long> { }
9236f1c6a8699e217588189517c4836906572435
4,512
java
Java
luckymall-admin/src/main/java/com/ruoyi/project/controller/SysProductTypeController.java
Threadalive/LuckyMall
ab5fc67a1983617ad1c472057d482e8a00dbf525
[ "MIT" ]
1
2020-05-15T12:35:21.000Z
2020-05-15T12:35:21.000Z
luckymall-admin/src/main/java/com/ruoyi/project/controller/SysProductTypeController.java
Threadalive/LuckyMall
ab5fc67a1983617ad1c472057d482e8a00dbf525
[ "MIT" ]
1
2020-12-03T11:01:06.000Z
2020-12-03T11:01:06.000Z
luckymall-admin/src/main/java/com/ruoyi/project/controller/SysProductTypeController.java
Threadalive/LuckyMall
ab5fc67a1983617ad1c472057d482e8a00dbf525
[ "MIT" ]
null
null
null
32.695652
118
0.708555
997,896
package com.ruoyi.project.controller; import java.util.List; import com.alibaba.fastjson.JSON; import com.ruoyi.project.domain.SysProductType; import com.ruoyi.project.service.ISysLogAnalyseService; import com.ruoyi.project.service.ISysProductTypeService; import com.ruoyi.system.utils.Constant; import com.ruoyi.system.utils.Result; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.utils.poi.ExcelUtil; /** * 【请填写功能名称】Controller * * @author ruoyi * @date 2020-05-04 */ @Controller @RequestMapping("/productType") public class SysProductTypeController extends BaseController { private String prefix = "system/type"; private static final Logger LOGGER = LoggerFactory.getLogger(SysProductTypeController.class); @Autowired private ISysProductTypeService sysProductTypeService; @Autowired private ISysLogAnalyseService logAnalyseService; @RequiresPermissions("system:type:view") @GetMapping() public String type() { return prefix + "/type"; } /** * 查询【请填写功能名称】列表 */ @RequiresPermissions("system:type:list") @PostMapping("/listType") @ResponseBody public Result<List<SysProductType>> list() { //频繁日志记录 logAnalyseService.logCommon(Constant.CURRENCY_LOG, "get product's type", Constant.INFO, Constant.LOG_TIMEOUT); Result<List<SysProductType>> result = new Result<>(); SysProductType sysProductType = new SysProductType(); List<SysProductType> list = sysProductTypeService.selectSysProductTypeList(sysProductType); if (list == null) { result.setMsg(Constant.ERROR_MSG); } else { result.setMsg(Constant.SUCCESS_MSG); result.setData(list); } LOGGER.info("商品种类列表:" + JSON.toJSONString(result)); return result; } /** * 导出【请填写功能名称】列表 */ @RequiresPermissions("system:type:export") @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT) @PostMapping("/export") @ResponseBody public AjaxResult export(SysProductType sysProductType) { List<SysProductType> list = sysProductTypeService.selectSysProductTypeList(sysProductType); ExcelUtil<SysProductType> util = new ExcelUtil<SysProductType>(SysProductType.class); return util.exportExcel(list, "type"); } /** * 新增【请填写功能名称】 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存【请填写功能名称】 */ @RequiresPermissions("system:type:add") @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(SysProductType sysProductType) { return toAjax(sysProductTypeService.insertSysProductType(sysProductType)); } /** * 修改【请填写功能名称】 */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") Long id, ModelMap mmap) { SysProductType sysProductType = sysProductTypeService.selectSysProductTypeById(id); mmap.put("sysProductType", sysProductType); return prefix + "/edit"; } /** * 修改保存【请填写功能名称】 */ @RequiresPermissions("system:type:edit") @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(SysProductType sysProductType) { return toAjax(sysProductTypeService.updateSysProductType(sysProductType)); } /** * 删除【请填写功能名称】 */ @RequiresPermissions("system:type:remove") @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE) @PostMapping("/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(sysProductTypeService.deleteSysProductTypeByIds(ids)); } }
9236f28c65c8d9e68850bc7573f09549e8b78140
2,080
java
Java
AudioSeparate/src/com/audioseparate/SingleWaveformPanel.java
siracoj/BluetoothRecord
d02f29cce04c5b0f2ba88885f184bc5a6e7a9c1d
[ "Apache-2.0" ]
3
2016-12-13T03:32:30.000Z
2021-06-03T14:13:44.000Z
AudioSeparate/src/com/audioseparate/SingleWaveformPanel.java
siracoj/BluetoothRecord
d02f29cce04c5b0f2ba88885f184bc5a6e7a9c1d
[ "Apache-2.0" ]
null
null
null
AudioSeparate/src/com/audioseparate/SingleWaveformPanel.java
siracoj/BluetoothRecord
d02f29cce04c5b0f2ba88885f184bc5a6e7a9c1d
[ "Apache-2.0" ]
1
2019-07-23T16:27:14.000Z
2019-07-23T16:27:14.000Z
28.108108
81
0.583173
997,897
package com.audioseparate; import javax.swing.*; import java.awt.*; /** * Created by IntelliJ IDEA. * User: Jonathan Simon * Date: Mar 6, 2005 * Time: 9:16:15 PM * To change this template use File | Settings | File Templates. */ public class SingleWaveformPanel extends JPanel { /** * */ private static final long serialVersionUID = -133514436822003255L; protected static final Color BACKGROUND_COLOR = Color.WHITE; protected static final Color REFERENCE_LINE_COLOR = Color.BLACK; protected static final Color WAVEFORM_COLOR = Color.RED; private AudioSep helper; private int channelIndex; public SingleWaveformPanel(AudioSep helper, int channelIndex) { this.helper = helper; this.channelIndex = channelIndex; setBackground(BACKGROUND_COLOR); } protected void paintComponent(Graphics g) { super.paintComponent(g); int lineHeight = getHeight() / 2; g.setColor(REFERENCE_LINE_COLOR); g.drawLine(0, lineHeight, (int)getWidth(), lineHeight); drawWaveform(g, helper.getAudio(channelIndex)); } protected void drawWaveform(Graphics g, int[] samples) { if (samples == null) { return; } int oldX = 0; int oldY = (int) (getHeight() / 2); int xIndex = 0; int increment = helper.getIncrement(helper.getXScaleFactor(getWidth())); g.setColor(WAVEFORM_COLOR); int t = 0; for (t = 0; t < increment; t += increment) { g.drawLine(oldX, oldY, xIndex, oldY); xIndex++; oldX = xIndex; } for (; t < samples.length; t += increment) { double scaleFactor = helper.getYScaleFactor(getHeight()); double scaledSample = samples[t] * scaleFactor; int y = (int) ((getHeight() / 2) - (scaledSample)); g.drawLine(oldX, oldY, xIndex, y); xIndex++; oldX = xIndex; oldY = y; } } }
9236f581d23d94391db810227823d94544746588
1,007
java
Java
com.yzd.hazelcast-lean/04-hazelcast-listener-v2/src/test/java/com/yzd/transfer/TransferClientManagerTest.java
yaozd/com.yzd.hazelcast-lean
64370268f7660c3fe8007c11d15e9c4448456680
[ "MIT" ]
null
null
null
com.yzd.hazelcast-lean/04-hazelcast-listener-v2/src/test/java/com/yzd/transfer/TransferClientManagerTest.java
yaozd/com.yzd.hazelcast-lean
64370268f7660c3fe8007c11d15e9c4448456680
[ "MIT" ]
null
null
null
com.yzd.hazelcast-lean/04-hazelcast-listener-v2/src/test/java/com/yzd/transfer/TransferClientManagerTest.java
yaozd/com.yzd.hazelcast-lean
64370268f7660c3fe8007c11d15e9c4448456680
[ "MIT" ]
null
null
null
27.216216
87
0.688183
997,898
package com.yzd.transfer; import com.yzd.hazelcast.NodeInfo; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * @Author: yaozh * @Description: */ public class TransferClientManagerTest { TransferClientManager transferClientManager = new TransferClientManager(); private String memberId = "192.168.56.1|5701|dfd2f365-9805-4589-9f46-07af0aabaab8"; @Before public void init() { List<NodeInfo> memberInfos = new ArrayList<>(); NodeInfo member = new NodeInfo(); member.setGrpcPort(1001); member.setIp("127.0.0.1"); member.setMemberId(memberId); memberInfos.add(member); transferClientManager.updateClient(memberInfos); } @Test public void getClient() { TransferClient client = transferClientManager.getClient(memberId); String uuid = "fd23d4f6-dbbe-474b-925f-16bae912dc70"; client.call(uuid, 200, uuid + System.currentTimeMillis()); } }
9236f5f36696d2efbab299b67053f6d22358962f
181
java
Java
lip/src/main/java/com/archinamon/libinstantparcelable/parcel/engine/AjcIParcelableBridge.java
Archinamon/LibInstantParcelable
e62ac18e81bb2319a9bea08458f4c5b62c520792
[ "Apache-2.0" ]
null
null
null
lip/src/main/java/com/archinamon/libinstantparcelable/parcel/engine/AjcIParcelableBridge.java
Archinamon/LibInstantParcelable
e62ac18e81bb2319a9bea08458f4c5b62c520792
[ "Apache-2.0" ]
null
null
null
lip/src/main/java/com/archinamon/libinstantparcelable/parcel/engine/AjcIParcelableBridge.java
Archinamon/LibInstantParcelable
e62ac18e81bb2319a9bea08458f4c5b62c520792
[ "Apache-2.0" ]
null
null
null
25.857143
58
0.81768
997,899
package com.archinamon.libinstantparcelable.parcel.engine; interface AjcIParcelableBridge extends IParcelableBridge { Creator CREATOR = new InterParcelableCreatorImpl(); }
9236f77344f7e0e8b29b6725be4d504730c8df77
200
java
Java
book-spring-in-action-5-insight/taco-cloud-jpa/src/main/java/tacocloud/data/OrderRepository.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
1
2021-09-29T07:24:56.000Z
2021-09-29T07:24:56.000Z
book-spring-in-action-5-insight/taco-cloud-jpa/src/main/java/tacocloud/data/OrderRepository.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
null
null
null
book-spring-in-action-5-insight/taco-cloud-jpa/src/main/java/tacocloud/data/OrderRepository.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
1
2021-09-17T15:05:17.000Z
2021-09-17T15:05:17.000Z
20
58
0.79
997,900
package tacocloud.data; import org.springframework.data.repository.CrudRepository; import tacocloud.entity.Order; public interface OrderRepository extends CrudRepository<Order, Long> { }
9236f815498985a75dbe0926fcc766bd0a6d4f89
570
java
Java
sb-feign/src/main/java/com/mrcoder/sbfeign/controller/TestController.java
WilliamSESE/SpringBootDemo
a7f346af498d5e8664c79e160779ea6fbc6df429
[ "Apache-2.0" ]
389
2019-03-19T08:16:38.000Z
2022-02-24T07:28:04.000Z
sb-feign/src/main/java/com/mrcoder/sbfeign/controller/TestController.java
FrCoderBlog/SpringBootDemo
64bcb1050e49d337a71d3fe9ca538ff6b4a4ee31
[ "Apache-2.0" ]
1
2019-09-10T06:16:01.000Z
2019-10-24T08:09:27.000Z
sb-feign/src/main/java/com/mrcoder/sbfeign/controller/TestController.java
FrCoderBlog/SpringBootDemo
64bcb1050e49d337a71d3fe9ca538ff6b4a4ee31
[ "Apache-2.0" ]
88
2019-04-26T03:59:43.000Z
2022-02-24T07:29:13.000Z
25.909091
70
0.785965
997,901
package com.mrcoder.sbfeign.controller; import com.mrcoder.sbfeign.feign.ExampleControllerFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @CrossOrigin @RestController public class TestController { @Autowired private ExampleControllerFeignClient exampleControllerFeignClient; @RequestMapping(value = "getInfoById", method = RequestMethod.GET) public String test(@RequestParam(value = "id") Long Id) { return exampleControllerFeignClient.getInfoById(Id); } }
9236f8cae062a64e62f2d60d2cb3e48fd4a82b16
45,062
java
Java
r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
kumarerubandi/cqf-ruler
251264772fe814f4337f3be95ad0476657aed2aa
[ "Apache-2.0" ]
null
null
null
r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
kumarerubandi/cqf-ruler
251264772fe814f4337f3be95ad0476657aed2aa
[ "Apache-2.0" ]
null
null
null
r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
kumarerubandi/cqf-ruler
251264772fe814f4337f3be95ad0476657aed2aa
[ "Apache-2.0" ]
null
null
null
47.836518
120
0.641561
997,902
package org.opencds.cqf.r4.providers; import java.io.ByteArrayInputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.hl7.fhir.r4.model.Attachment; import org.hl7.fhir.r4.model.BaseReference; import org.hl7.fhir.r4.model.Binary; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Claim; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Coding; import org.hl7.fhir.r4.model.Composition; import org.hl7.fhir.r4.model.DetectedIssue; import org.hl7.fhir.r4.model.DeviceRequest; import org.hl7.fhir.r4.model.Extension; import org.hl7.fhir.r4.model.Group; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.ListResource; import org.hl7.fhir.r4.model.Measure; import org.hl7.fhir.r4.model.MeasureReport; import org.hl7.fhir.r4.model.Meta; import org.hl7.fhir.r4.model.Narrative; import org.hl7.fhir.r4.model.Parameters; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.Quantity; import org.hl7.fhir.r4.model.Reference; import org.hl7.fhir.r4.model.RelatedArtifact; import org.hl7.fhir.r4.model.Resource; import org.hl7.fhir.r4.model.ServiceRequest; import org.hl7.fhir.r4.model.StringType; import org.hl7.fhir.r4.model.Group.GroupMemberComponent; import org.hl7.fhir.r4.model.ListResource.ListEntryComponent; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.cqframework.cql.cql2elm.LibraryManager; import org.cqframework.cql.cql2elm.ModelManager; import org.cqframework.cql.elm.execution.Library; import org.hl7.fhir.MeasureScoring; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.instance.model.api.IAnyResource; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.utilities.xhtml.XhtmlNode; import org.opencds.cqf.common.evaluation.EvaluationProviderFactory; import org.opencds.cqf.common.helpers.TranslatorHelper; import org.opencds.cqf.common.providers.LibraryResolutionProvider; import org.opencds.cqf.common.retrieve.InMemoryRetrieveProvider; import org.opencds.cqf.common.retrieve.JpaFhirRetrieveProvider; import org.opencds.cqf.common.retrieve.RemoteRetrieveProvider; import org.opencds.cqf.cql.engine.execution.Context; import org.opencds.cqf.common.evaluation.LibraryLoader; import org.opencds.cqf.library.r4.NarrativeProvider; import org.opencds.cqf.cql.engine.data.DataProvider; import org.opencds.cqf.measure.r4.CqfMeasure; import org.opencds.cqf.r4.evaluation.MeasureEvaluation; import org.opencds.cqf.r4.evaluation.MeasureEvaluationSeed; import org.opencds.cqf.r4.helpers.LibraryHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ca.uhn.fhir.context.BaseRuntimeChildDefinition; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.api.dao.DaoRegistry; import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.rp.r4.LibraryResourceProvider; import ca.uhn.fhir.jpa.rp.r4.MeasureResourceProvider; import ca.uhn.fhir.jpa.searchparam.SearchParameterMap; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Operation; import ca.uhn.fhir.rest.annotation.OperationParam; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.RequiredParam; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.server.IBundleProvider; import ca.uhn.fhir.rest.api.server.RequestDetails; import ca.uhn.fhir.rest.param.ReferenceParam; import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.param.TokenParamModifier; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; public class MeasureOperationsProvider { private NarrativeProvider narrativeProvider; private HQMFProvider hqmfProvider; private DataRequirementsProvider dataRequirementsProvider; private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider; private MeasureResourceProvider measureResourceProvider; private DaoRegistry registry; private EvaluationProviderFactory factory; private LibraryResourceProvider defaultLibraryResourceProvider; private HashMap<String, Object> nonLocal; private Boolean local; private String retrieverType; private static final Logger logger = LoggerFactory.getLogger(MeasureOperationsProvider.class); public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider, LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider, MeasureResourceProvider measureResourceProvider) { this.registry = registry; this.factory = factory; this.libraryResolutionProvider = libraryResolutionProvider; this.narrativeProvider = narrativeProvider; this.hqmfProvider = hqmfProvider; this.dataRequirementsProvider = new DataRequirementsProvider(); this.measureResourceProvider = measureResourceProvider; this.nonLocal = new HashMap<>(); this.local = true; this.retrieverType = MeasureEvaluationSeed.LOCAL_RETRIEVER; } public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory, NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider, LibraryResourceProvider libraryResourceProvider, MeasureResourceProvider measureResourceProvider) { this(registry, factory, narrativeProvider, hqmfProvider, new LibraryOperationsProvider(libraryResourceProvider, narrativeProvider), measureResourceProvider); this.defaultLibraryResourceProvider = libraryResourceProvider; } @Operation(name = "$hqmf", idempotent = true, type = Measure.class) public Parameters hqmf(@IdParam IdType theId) { Measure theResource = this.measureResourceProvider.getDao().read(theId); String hqmf = this.generateHQMF(theResource); Parameters p = new Parameters(); p.addParameter().setValue(new StringType(hqmf)); return p; } @Operation(name = "$refresh-generated-content", type = Measure.class) public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails, @IdParam IdType theId) { Measure theResource = this.measureResourceProvider.getDao().read(theId); theResource.getRelatedArtifact().removeIf( relatedArtifact -> relatedArtifact.getType().equals(RelatedArtifact.RelatedArtifactType.DEPENDSON)); CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider); // Ensure All Related Artifacts for all referenced Libraries if (!cqfMeasure.getRelatedArtifact().isEmpty()) { for (RelatedArtifact relatedArtifact : cqfMeasure.getRelatedArtifact()) { boolean artifactExists = false; // logger.info("Related Artifact: " + relatedArtifact.getUrl()); for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) { if (resourceArtifact.equalsDeep(relatedArtifact)) { // logger.info("Equals deep true"); artifactExists = true; break; } } if (!artifactExists) { theResource.addRelatedArtifact(relatedArtifact.copy()); } } } try { Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure); theResource.setText(n.copy()); } catch (Exception e) { // Ignore the exception so the resource still gets updated } return this.measureResourceProvider.update(theRequest, theResource, theId, theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails); } @Operation(name = "$get-narrative", idempotent = true, type = Measure.class) public Parameters getNarrative(@IdParam IdType theId) { Measure theResource = this.measureResourceProvider.getDao().read(theId); CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider); Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure); Parameters p = new Parameters(); p.addParameter().setValue(new StringType(n.getDivAsString())); return p; } private String generateHQMF(Measure theResource) { CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource, this.libraryResolutionProvider); return this.hqmfProvider.generateHQMF(cqfMeasure); } /* * * NOTE that the source, user, and pass parameters are not standard parameters * for the FHIR $evaluate-measure operation * */ @Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class) public MeasureReport evaluateMeasure(@IdParam IdType theId, @OperationParam(name = "periodStart") String periodStart, @OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "measure") String measureRef, @OperationParam(name = "reportType") String reportType, @OperationParam(name = "subject") String patientRef, @OperationParam(name = "productLine") String productLine, @OperationParam(name = "practitioner") String practitionerRef, @OperationParam(name = "lastReceivedOn") String lastReceivedOn, @OperationParam(name = "patientServerUrl") String patientServerUrl, @OperationParam(name = "patientServerToken") String patientServerToken, @OperationParam(name = "dataBundle", min = 1, max = 1, type = Bundle.class) Bundle dataBundle, @OperationParam(name = "source") String source, @OperationParam(name = "user") String user, @OperationParam(name = "pass") String pass) throws InternalErrorException, FHIRException { this.retrieverType = MeasureEvaluationSeed.LOCAL_RETRIEVER; LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider); MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider); // logger.info("get measure dao"); Measure measure = this.measureResourceProvider.getDao().read(theId); logger.info("patientserverurl: " + patientServerUrl); if (measure == null) { throw new RuntimeException("Could not find Measure/" + theId.getIdPart()); } if (patientServerUrl != null) { if (patientServerUrl != "") { nonLocal.put("patient_server_url", patientServerUrl); this.local = false; this.retrieverType = MeasureEvaluationSeed.REMOTE_RETRIEVER; } } if (patientServerToken != null) { if (patientServerToken != "") { this.nonLocal.put("patient_server_token", patientServerToken); } } if (dataBundle != null) { this.retrieverType = MeasureEvaluationSeed.INMEMORY_RETRIEVER; this.nonLocal.put("dataBundle", dataBundle); InMemoryRetrieveProvider.patient_fhir.set(nonLocal); } if (!local) { RemoteRetrieveProvider.patient_fhir.set(this.nonLocal); } seed.setRetrieverType(this.retrieverType); seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass); if ((patientRef != null) && (patientRef.startsWith("Patient/"))) { patientRef = patientRef.replace("Patient/", ""); } MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod()); if (reportType != null) { switch (reportType) { case "patient": return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef); case "patient-list": return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef); case "population": return evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext()); default: throw new IllegalArgumentException("Invalid report type: " + reportType); } } // default report type is patient MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef); if (productLine != null) { Extension ext = new Extension(); ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine"); ext.setValue(new StringType(productLine)); report.addExtension(ext); } // logger.info("Stopping evaluate"); return report; } @Operation(name = "$lib-evaluate", idempotent = true, type = Measure.class) public Parameters libraryEvaluate(@OperationParam(name = "libraryId") String libraryId, @OperationParam(name = "criteria") String criteria, @OperationParam(name = "subject") String patientRef, @OperationParam(name = "periodStart") String periodStart, @OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "source") String source, @OperationParam(name = "patientServerUrl") String patientServerUrl, @OperationParam(name = "patientServerToken") String patientServerToken, @OperationParam(name = "libraryServerUrl") String libraryServerUrl, @OperationParam(name = "libraryServerToken") String libraryServerToken, @OperationParam(name = "criteriaList") String criteriaList, @OperationParam(name = "valueSetsBundle", min = 1, max = 1, type = Bundle.class) Bundle valueSetsBundle, @OperationParam(name = "dataBundle", min = 1, max = 1, type = Bundle.class) Bundle dataBundle, @OperationParam(name = "libBundle", min = 1, max = 1, type = Bundle.class) Bundle libBundle, @OperationParam(name = "user") String user, @OperationParam(name = "parameters") Parameters parameters, @OperationParam(name = "pass") String pass) throws InternalErrorException, FHIRException { ArrayList<String> evalCriterias = new ArrayList<>(); this.retrieverType = MeasureEvaluationSeed.LOCAL_RETRIEVER; if (criteria == null && criteriaList == null) { throw new RuntimeException("Either Criteria or Criteria List should be given"); } if (criteria != null) { evalCriterias.add(criteria); } else { String[] cList = criteriaList.split(","); for (String crit : cList) { evalCriterias.add(crit); } } if (libraryId == null) { throw new RuntimeException(" LibraryId cannot be null"); } if (patientServerUrl != null) { if (patientServerUrl != "") { this.nonLocal.put("patient_server_url", patientServerUrl); this.local = false; this.retrieverType = MeasureEvaluationSeed.REMOTE_RETRIEVER; } if (patientServerToken != null) { if (patientServerToken != "") { this.nonLocal.put("patient_server_token", patientServerToken); } } } if (dataBundle != null) { this.retrieverType = MeasureEvaluationSeed.INMEMORY_RETRIEVER; nonLocal.put("dataBundle", dataBundle); InMemoryRetrieveProvider.patient_fhir.set(nonLocal); } if (!local) { RemoteRetrieveProvider.patient_fhir.set(this.nonLocal); } LibraryResourceProvider rp = new LibraryResourceProvider(); rp.setDao(defaultLibraryResourceProvider.getDao()); if ((libraryServerUrl != null) && (libraryServerUrl != "")) { if ((libraryServerToken != null) && (libraryServerToken != "")) { rp.setDao(new RemoteLibraryBundleDao(libraryServerUrl,libraryServerToken)); } else { rp.setDao(new RemoteLibraryBundleDao(libraryServerUrl,null)); } } if (libBundle != null) { rp.setDao(new LibraryBundleDao(libBundle)); } LibraryOperationsProvider libOpsProvider = new LibraryOperationsProvider(rp, this.narrativeProvider); LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(libOpsProvider); MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, libOpsProvider); seed.setRetrieverType(this.retrieverType); if (valueSetsBundle != null) { seed.setValueSetsBundle(valueSetsBundle); } seed.setupLibrary(libraryId, periodStart, periodEnd, null, source, user, pass); MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod()); Context context = null; Library library = null; context = seed.getContext(); library = seed.getLibrary(); if (parameters != null) { for (Parameters.ParametersParameterComponent pc : parameters.getParameter()) { context.setParameter(null, pc.getName(), pc.getResource()); } } Parameters result = new Parameters(); try { result = evaluator.cqlEvaluate(context, patientRef, evalCriterias, library); } catch (RuntimeException re) { re.printStackTrace(); String message = re.getMessage() != null ? re.getMessage() : re.getClass().getName(); result.addParameter().setName("error").setValue(new StringType(message)); } return result; } @Operation(name = "$care-gaps", idempotent = true, type = Measure.class) public Resource careGapsReport(@OperationParam(name = "periodStart") String periodStart, @OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "topic") String topic, @OperationParam(name = "subject") String patientRef, @OperationParam(name = "program") String program, @OperationParam(name = "measure") String measureparam, @OperationParam(name = "practitioner") String practitionerRef, @OperationParam(name = "patientServerUrl") String patientServerUrl, @OperationParam(name = "patientServerToken") String patientServerToken, @OperationParam(name = "dataBundle", min = 1, max = 1, type = Bundle.class) Bundle dataBundle, @OperationParam(name = "status") String status) { Parameters parameters = new Parameters(); this.retrieverType = MeasureEvaluationSeed.LOCAL_RETRIEVER; List<String> patients = new ArrayList<>(); List<Measure> measures = new ArrayList<>(); boolean patientSearch = false; boolean groupSearch = false; if ((patientRef == null) & (practitionerRef == null)) { throw new RuntimeException("Subject and Practitioner both cannot be null!"); } if (patientRef != null) { if (patientRef.startsWith("Patient/")) { patientSearch = true; } else if (patientRef.startsWith("Group/")) { groupSearch = true; } else { throw new RuntimeException("Subject should start with either Patient or Group"); } } System.out.println("Patient server url: " + patientServerUrl); boolean topicgiven = false; boolean measuregiven = false; if (patientServerUrl != null) { if (patientServerUrl != "") { nonLocal.put("patient_server_url", patientServerUrl); this.local = false; this.retrieverType = MeasureEvaluationSeed.REMOTE_RETRIEVER; } } if (patientServerToken != null) { if (patientServerToken != "") { this.nonLocal.put("patient_server_token", patientServerToken); } } if (dataBundle != null) { this.retrieverType = MeasureEvaluationSeed.INMEMORY_RETRIEVER; this.nonLocal.put("dataBundle", dataBundle); InMemoryRetrieveProvider.patient_fhir.set(nonLocal); } if (!local) { RemoteRetrieveProvider.patient_fhir.set(this.nonLocal); } // This is temporary fix to get the topics for searching with texts Hashtable<String, String> topic_codes = new Hashtable<String, String>(); topic_codes.put("75484-6", "Preventive Care"); topic_codes.put("91393-9", "Management of Chronic Conditions"); topic_codes.put("44943-9", "Prevention and Treatment of Opioid and Substance Use Disorders"); if (topic != null) { boolean valueCodingSearch = false; String valueCode = ""; SearchParameterMap topicSearch; // if topic in known code use codesearch else text search if (topic_codes.containsKey(topic)) { valueCodingSearch = false; valueCode = topic; } if (valueCodingSearch) { topicSearch = new SearchParameterMap().add("topic", new TokenParam().setModifier(TokenParamModifier.valueOf("coding")).setValue(valueCode)); // logger.info("code search : "+ // topicSearch.toNormalizedQueryString(FhirContext.forR4())); } else { topicSearch = new SearchParameterMap().add("topic", new TokenParam().setModifier(TokenParamModifier.TEXT).setValue(topic)); } topicSearch.add("status", new TokenParam().setValue("active")); IBundleProvider bundleProvider = this.measureResourceProvider.getDao().search(topicSearch); List<IBaseResource> resources = bundleProvider.getResources(0, 10000); for (Iterator iterator = resources.iterator(); iterator.hasNext();) { Measure res = (Measure) (iterator.next()); measures.add(res); } } if (measureparam != null) { IBundleProvider bundleProvider = this.measureResourceProvider.getDao().search(new SearchParameterMap() .add("_id", new TokenParam().setModifier(TokenParamModifier.TEXT).setValue(measureparam))); List<IBaseResource> resources = bundleProvider.getResources(0, 10000); for (Iterator iterator = resources.iterator(); iterator.hasNext();) { Measure res = (Measure) (iterator.next()); measures.add(res); } } if (measures.size() == 0) { throw new RuntimeException( "Neither topic nor measure parameter resolves to available Measure for running care gap report"); } LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider); MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader, this.libraryResolutionProvider); seed.setRetrieverType(this.retrieverType); // Hack solution for getting Provider -- Needed for getting patients data seed.setup(measures.get(0), periodStart, periodEnd, null, null, null, null); if (practitionerRef != null) { List<String> practitionerPatients = getPractitionerPatients(practitionerRef, seed.getDataProvider()); patients.addAll(practitionerPatients); } if (patientRef != null) { if (patientSearch) { patients.addAll(getPatients(patientRef, seed.getDataProvider())); } if (groupSearch) { patients.addAll(getGroupPatients(patientRef, seed.getDataProvider())); } } if (patients.size() > 1) { for (String patient : patients) { Bundle careGapBundle = getCareGapReport(patient, measures, status, periodStart, periodEnd, seed); parameters.addParameter( new Parameters.ParametersParameterComponent().setName("return").setResource(careGapBundle)); } return parameters; } else if (patients.size() == 1) { return getCareGapReport(patients.get(0), measures, status, periodStart, periodEnd, seed); } else { throw new RuntimeException("Subject not found for running care gap report"); } } private Bundle getCareGapReport(String patientRef, List<Measure> measures, String status, String periodStart, String periodEnd, MeasureEvaluationSeed seed) { Bundle careGapReport = new Bundle(); careGapReport.setType(Bundle.BundleType.DOCUMENT); careGapReport.setTimestamp(new Date()); Composition composition = new Composition(); if (patientRef.startsWith("Patient/")) { patientRef = patientRef.replace("Patient/", ""); } CodeableConcept typeCode = new CodeableConcept(); typeCode.addCoding(new Coding().setCode("gaps-doc") .setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/gaps-doc-type") .setDisplay("Gaps in Care Report")); composition.setStatus(Composition.CompositionStatus.FINAL).setType(typeCode); composition.setSubject(new Reference("Patient/" + patientRef)) .setTitle("Care Gap Report for Patient:" + patientRef); List<MeasureReport> reports = new ArrayList<>(); List<DetectedIssue> detectedIssues = new ArrayList<DetectedIssue>(); MeasureReport report = new MeasureReport(); for (Measure measure : measures) { Composition.SectionComponent section = new Composition.SectionComponent(); if (measure.hasTitle()) { section.setTitle(measure.getTitle()); } seed.setup(measure, periodStart, periodEnd, null, null, null, null); MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry, seed.getMeasurementPeriod()); report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef); report.setId(UUID.randomUUID().toString()); report.setDate(new Date()); report.setMeta(new Meta() .addProfile("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/indv-measurereport-deqm")); section.setFocus(new Reference("MeasureReport/" + report.getId())); // Check for detected issue DetectedIssue detected = checkDetectedIssue(report, patientRef); if (detected != null) { detectedIssues.add(detected); section.addEntry(new Reference("DetectedIssue/" + detected.getIdElement().getIdPart())); } reports.add(report); composition.addSection(section); } careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition)); // Add the reports based on status parameter boolean addreport; for (MeasureReport rep : reports) { if (getMeasureScore(rep) != null) { boolean openGap = checkOpenGap(rep); if (status == null || status == "") { addreport = true; } else if (status.equals("open-gap") && openGap) { addreport = true; } else if (status.equals("closed-gap") && !openGap) { addreport = true; } else { addreport = false; } if (addreport) { Parameters parameters = addEvaluatedResources(rep); careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep)); for (DetectedIssue detectedIssue : detectedIssues) { careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(detectedIssue)); } for (Parameters.ParametersParameterComponent parameter : parameters.getParameter()) { careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(parameter.getResource())); } } } } return careGapReport; } private Parameters addEvaluatedResources(MeasureReport rep) { Parameters parameters = new Parameters(); if (rep.hasContained()) { for (Resource contained : rep.getContained()) { if (contained instanceof Bundle) { addEvaluatedResourcesToParameters((Bundle) contained, parameters, null); List<Reference> listRef = populateListReferences((Bundle) contained); rep.setEvaluatedResource(listRef); } } } return parameters; } private List<Reference> populateListReferences(Bundle bundle) { List<Reference> listRef = new ArrayList<>(); if (bundle.hasEntry()) { for (Bundle.BundleEntryComponent entry : bundle.getEntry()) { if ((entry.getResource() instanceof ListResource)) { ListResource listResource = (ListResource) entry.getResource(); String popType = listResource.getTitle(); String displayPop = WordUtils.capitalize(popType.replace("-", " ")); for (ListEntryComponent listComponent : listResource.getEntry()) { List<Extension> evalResourceExt = new ArrayList<>(); evalResourceExt.add(new Extension( "http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/extension-populationReference", new CodeableConcept() .addCoding(new Coding("http://teminology.hl7.org/CodeSystem/measure-population", popType, displayPop)))); Reference evaluateRef = listComponent.getItem(); evaluateRef.setExtension(evalResourceExt); listRef.add(evaluateRef); } } } } return listRef; } private DetectedIssue checkDetectedIssue(MeasureReport report, String patientRef) { boolean isOpenGap = checkOpenGap(report); if (isOpenGap) { return createDetectedIssue(report, patientRef); } else { return null; } } private boolean checkOpenGap(MeasureReport report) { boolean openGap = false; String improvementNotation = report.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase(); BigDecimal measureScore = getMeasureScore(report); if (measureScore != null) { if (((improvementNotation.equals("increase")) && (measureScore.compareTo(new BigDecimal(0))) <= 0)) { openGap = true; } else if (((improvementNotation.equals("decrease")) && (measureScore.compareTo(new BigDecimal(1))) >= 0)) { openGap = true; } } return openGap; } private DetectedIssue createDetectedIssue(MeasureReport report, String patientRef) { DetectedIssue detectedIssue = new DetectedIssue(); detectedIssue.setId(UUID.randomUUID().toString()); detectedIssue.setStatus(DetectedIssue.DetectedIssueStatus.FINAL); detectedIssue.setPatient(new Reference("Patient/" + patientRef)); detectedIssue.getEvidence().add(new DetectedIssue.DetectedIssueEvidenceComponent() .addDetail(new Reference("MeasureReport/" + report.getId()))); CodeableConcept code = new CodeableConcept().addCoding( new Coding().setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/detectedissue-category") .setCode("care-gap").setDisplay("Gap in Care Detected")); detectedIssue.setCode(code); return detectedIssue; } private BigDecimal getMeasureScore(MeasureReport report) { BigDecimal scorevalue = null; for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) { if (group.hasMeasureScore()) { scorevalue = group.getMeasureScore().getValue(); } } return scorevalue; } private List<String> getGroupPatients(String groupRef, DataProvider provider) { if (groupRef.startsWith("Group/")) { groupRef = groupRef.replace("Group/", ""); } List<String> patients = new ArrayList<>(); System.out.println("Search for patients in the group: " + groupRef); Iterable<Object> groupRetrieve = provider.retrieve("Group", "id", groupRef, "Group", null, null, null, null, null, null, null, null); for (Iterator iterator = groupRetrieve.iterator(); iterator.hasNext();) { Group group = (Group) iterator.next(); if (group.getIdElement().getIdPart().equals(groupRef)) { List<GroupMemberComponent> memberList = group.getMember(); for (GroupMemberComponent member : memberList) { patients.add(member.getEntity().getReference()); } } } // logger.info("patients available!!" + patients.size()); return patients; } private List<String> getPractitionerPatients(String practitionerRef, DataProvider provider) { SearchParameterMap map = new SearchParameterMap(); map.add("general-practitioner", new ReferenceParam( practitionerRef.startsWith("Practitioner/") ? practitionerRef : "Practitioner/" + practitionerRef)); List<String> patients = new ArrayList<>(); IBundleProvider patientProvider = registry.getResourceDao("Patient").search(map); List<IBaseResource> patientList = patientProvider.getResources(0, patientProvider.size()); patientList.forEach(x -> patients.add((String) x.getIdElement().getIdPart())); return patients; } private List<String> getPatients(String patientRef, DataProvider provider) { if (patientRef.startsWith("Patient/")) { patientRef = patientRef.replace("Patient/", ""); } List<String> patients = new ArrayList<>(); Iterable<Object> patientRetrieve = provider.retrieve("Patient", "id", patientRef, "Patient", null, null, null, null, null, null, null, null); for (Iterator iterator = patientRetrieve.iterator(); iterator.hasNext();) { Patient patient = (Patient) iterator.next(); patients.add(patient.getIdElement().getIdPart()); } // logger.info("patients available!!" + patients.size()); return patients; } @Operation(name = "$collect-data", idempotent = true, type = Measure.class) public Parameters collectData(@IdParam IdType theId, @OperationParam(name = "periodStart") String periodStart, @OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "subject") String patientRef, @OperationParam(name = "practitioner") String practitionerRef, @OperationParam(name = "patientServerUrl") String patientServerUrl, @OperationParam(name = "patientServerToken") String patientServerToken, @OperationParam(name = "dataBundle", min = 1, max = 1, type = Bundle.class) Bundle dataBundle, @OperationParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException { // TODO: Spec says that the periods are not required, but I am not sure what to // do when they aren't supplied so I made them required MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null, practitionerRef, lastReceivedOn, patientServerUrl, patientServerToken, dataBundle, null, null, null); report.setGroup(null); Parameters parameters = new Parameters(); parameters.addParameter( new Parameters.ParametersParameterComponent().setName("measureReport").setResource(report)); if (report.hasContained()) { for (Resource contained : report.getContained()) { if (contained instanceof Bundle) { addEvaluatedResourcesToParameters((Bundle) contained, parameters, dataBundle); } } } // TODO: need a way to resolve referenced resources within the evaluated // resources // Should be able to use _include search with * wildcard, but HAPI doesn't // support that return parameters; } private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters, Bundle dataBundle) { Map<String, Resource> resourceMap = new HashMap<>(); if (contained.hasEntry()) { for (Bundle.BundleEntryComponent entry : contained.getEntry()) { if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) { if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) { parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource") .setResource(entry.getResource())); resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource()); // Commenting for now to resolve bug for remotefhir care-gap // resolveReferences(entry.getResource(), parameters, resourceMap, dataBundle); } } } } } private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap, Bundle dataBundle) { List<IBase> values; for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext() .getResourceDefinition(resource).getChildren()) { values = child.getAccessor().getValues(resource); if (values == null || values.isEmpty()) { continue; } else if (values.get(0) instanceof Reference && ((Reference) values.get(0)).getReferenceElement().hasResourceType() && ((Reference) values.get(0)).getReferenceElement().hasIdPart()) { Resource fetchedResource; if (dataBundle != null) { fetchedResource = (Resource) getRelatedResource( ((Reference) values.get(0)).getReferenceElement().getResourceType(), ((Reference) values.get(0)).getReferenceElement().getIdPart(), dataBundle); } else { fetchedResource = (Resource) registry .getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType()) .read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart())); } if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) { parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource") .setResource(fetchedResource)); resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource); } } } } private Resource getRelatedResource(String resourceType, String idPart, Bundle dataBundle) { logger.info("Resource type :" + resourceType); logger.info("idPart :" + idPart); for (Bundle.BundleEntryComponent entry : dataBundle.getEntry()) { if (entry.getResource().getResourceType().toString().equals(resourceType)) { if (entry.getResource().getIdElement().getIdPart().equals(idPart)) { return entry.getResource(); } } } throw new RuntimeException("Resource " + idPart + " not found"); } // TODO - this needs a lot of work @Operation(name = "$data-requirements", idempotent = true, type = Measure.class) public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId, @OperationParam(name = "startPeriod") String startPeriod, @OperationParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException { Measure measure = this.measureResourceProvider.getDao().read(theId); return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider); } @Operation(name = "$submit-data", idempotent = true, type = Measure.class) public Resource submitData(RequestDetails details, @IdParam IdType theId, @OperationParam(name = "measureReport", min = 1, max = 1, type = MeasureReport.class) MeasureReport report, @OperationParam(name = "resource") List<IAnyResource> resources) { Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION); /* * TODO - resource validation using $data-requirements operation (params are the * provided id and the measurement period from the MeasureReport) * * TODO - profile validation ... not sure how that would work ... (get * StructureDefinition from URL or must it be stored in Ruler?) */ transactionBundle.addEntry(createTransactionEntry(report)); for (IAnyResource resource : resources) { Resource res = (Resource) resource; if (res instanceof Bundle) { for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) { transactionBundle.addEntry(entry); } } else { // Build transaction bundle transactionBundle.addEntry(createTransactionEntry(res)); } } System.out.println(FhirContext.forR4().newJsonParser().encodeResourceToString(transactionBundle)); return (Resource) this.registry.getSystemDao().transaction(details, transactionBundle); } private Bundle createTransactionBundle(Bundle bundle) { Bundle transactionBundle; if (bundle != null) { if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) { transactionBundle = bundle; } else { transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION); if (bundle.hasEntry()) { for (Bundle.BundleEntryComponent entry : bundle.getEntry()) { if (entry.hasResource()) { transactionBundle.addEntry(createTransactionEntry(entry.getResource())); } } } } } else { transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>()); } return transactionBundle; } private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) { Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource); if (resource.hasId()) { transactionEntry.setRequest( new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl(resource.getId())); } else { transactionEntry.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST) .setUrl(resource.fhirType())); } return transactionEntry; } }
9236f8ea27e9aa7551e246de1824ef7f32cb2d38
3,417
java
Java
modules/galen/src/main/java/io/wcm/qa/glnm/galen/specs/imagecomparison/IcsFactory.java
wcm-io-qa/wcm-io-qa-galenium
50cbf757a251901c0fa27b21539a0cc36c2c141b
[ "Apache-2.0" ]
8
2017-02-10T06:19:30.000Z
2020-12-05T22:44:01.000Z
modules/galen/src/main/java/io/wcm/qa/glnm/galen/specs/imagecomparison/IcsFactory.java
wcm-io-qa/wcm-io-qa-galenium
50cbf757a251901c0fa27b21539a0cc36c2c141b
[ "Apache-2.0" ]
2
2018-12-14T16:55:33.000Z
2019-02-04T15:13:36.000Z
modules/galen/src/main/java/io/wcm/qa/glnm/galen/specs/imagecomparison/IcsFactory.java
wcm-io-qa/wcm-io-qa-galenium
50cbf757a251901c0fa27b21539a0cc36c2c141b
[ "Apache-2.0" ]
9
2017-03-02T08:22:46.000Z
2020-05-17T12:29:52.000Z
30.783784
106
0.716711
997,903
/* * #%L * wcm.io * %% * Copyright (C) 2019 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.qa.glnm.galen.specs.imagecomparison; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.galenframework.specs.Spec; import com.galenframework.specs.page.CorrectionsRect; import com.galenframework.specs.page.Locator; import com.galenframework.specs.page.ObjectSpecs; import com.galenframework.specs.page.PageSection; import com.galenframework.specs.page.PageSpec; import io.wcm.qa.glnm.configuration.GaleniumConfiguration; import io.wcm.qa.glnm.exceptions.GaleniumException; import io.wcm.qa.glnm.selectors.base.Selector; /** * Factory class to get image comparing Galen specs. * * @since 2.0.0 */ final class IcsFactory { private IcsFactory() { } /** * <p>getPageSpec.</p> * * @param def parameters for spec generation * @return a parsed Galen page spec */ static PageSpec getPageSpec(IcsDefinition def) { checkSanity(def); // specs Spec spec = IcUtil.getSpecForText(IcUtil.getImageComparisonSpecText(def)); ObjectSpecs objectSpecs = new ObjectSpecs(def.getElementName()); Spec insideViewportSpec = IcUtil.getSpecForText("inside viewport"); objectSpecs.addSpec(insideViewportSpec); objectSpecs.addSpec(spec); if (GaleniumConfiguration.isSamplingVerificationIgnore()) { spec.setOnlyWarn(true); insideViewportSpec.setOnlyWarn(true); } if (def.isZeroToleranceWarning()) { Spec zeroToleranceSpec = IcUtil.getSpecForText(IcUtil.getZeroToleranceImageComparisonSpecText(def)); zeroToleranceSpec.setOnlyWarn(true); objectSpecs.addSpec(zeroToleranceSpec); } // page section PageSection pageSection = new PageSection(def.getSectionName()); pageSection.addObjects(objectSpecs); // page spec PageSpec pageSpec = new PageSpec(); pageSpec.addObject(def.getElementName(), def.getSelector().asLocator()); List<Selector> objectsToIgnore = def.getObjectsToIgnore(); if (!objectsToIgnore.isEmpty()) { CorrectionsRect corrections = def.getCorrections().getCorrectionsRect(); for (Selector objectToIgnore : objectsToIgnore) { Locator asLocator = objectToIgnore.asLocator(); if (corrections != null) { asLocator.withCorrections(corrections); } pageSpec.addObject(objectToIgnore.elementName(), asLocator); } } pageSpec.addSection(pageSection); return pageSpec; } private static void checkSanity(IcsDefinition def) { if (def == null) { throw new GaleniumException("Definition is null."); } if (def.getSelector() == null) { throw new GaleniumException("Definition has null Selector."); } if (StringUtils.isBlank(def.getFilename())) { throw new GaleniumException("Definition has empty filename."); } } }
9236f9e824ec2ddee6f97093f1f2cd673fc7a13f
702
java
Java
gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillDetailEntity.java
layman-809/gmall
1bde59e1428ca9c775b930f9e0947f8a4c6dcda9
[ "Apache-2.0" ]
null
null
null
gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillDetailEntity.java
layman-809/gmall
1bde59e1428ca9c775b930f9e0947f8a4c6dcda9
[ "Apache-2.0" ]
null
null
null
gmall-wms-interface/src/main/java/com/atguigu/gmall/wms/entity/WareOrderBillDetailEntity.java
layman-809/gmall
1bde59e1428ca9c775b930f9e0947f8a4c6dcda9
[ "Apache-2.0" ]
null
null
null
15.6
64
0.69943
997,904
package com.atguigu.gmall.wms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 库存工作单 * * @author layman * @email upchh@example.com * @date 2021-08-28 23:57:05 */ @Data @TableName("wms_ware_order_bill_detail") public class WareOrderBillDetailEntity implements Serializable { private static final long serialVersionUID = 1L; /** * id */ @TableId private Long id; /** * sku_id */ private Long skuId; /** * sku_name */ private String skuName; /** * 购买个数 */ private Integer skuNum; /** * 工作单id */ private Long taskId; }
9236fddcaf4d2ddaa77d027d9681d4605191bd4e
1,776
java
Java
translator/src/main/java/com/google/devtools/j2objc/jdt/JdtPrimitiveType.java
nidhinmahesh/j2objc
fc48513f4beb1113c9e7449c200e9f41f852a7eb
[ "Apache-2.0" ]
null
null
null
translator/src/main/java/com/google/devtools/j2objc/jdt/JdtPrimitiveType.java
nidhinmahesh/j2objc
fc48513f4beb1113c9e7449c200e9f41f852a7eb
[ "Apache-2.0" ]
null
null
null
translator/src/main/java/com/google/devtools/j2objc/jdt/JdtPrimitiveType.java
nidhinmahesh/j2objc
fc48513f4beb1113c9e7449c200e9f41f852a7eb
[ "Apache-2.0" ]
null
null
null
32.290909
82
0.689752
997,905
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc.jdt; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeVisitor; import org.eclipse.jdt.core.dom.ITypeBinding; class JdtPrimitiveType extends JdtTypeMirror implements PrimitiveType { JdtPrimitiveType(ITypeBinding binding) { super(binding); assert binding.isPrimitive(); } @Override public TypeKind getKind() { String binaryName = ((ITypeBinding) binding).getBinaryName(); if (binaryName.length() == 1) { switch (binaryName.charAt(0)) { case 'B': return TypeKind.BYTE; case 'C': return TypeKind.CHAR; case 'D': return TypeKind.DOUBLE; case 'F': return TypeKind.FLOAT; case 'I': return TypeKind.INT; case 'J': return TypeKind.LONG; case 'S': return TypeKind.SHORT; case 'V': return TypeKind.VOID; case 'Z': return TypeKind.BOOLEAN; default: // Fall through and throw assertion error. } } throw new AssertionError("unknown primitive type binary name: " + binaryName); } @Override public <R, P> R accept(TypeVisitor<R, P> v, P p) { return v.visitPrimitive(this, p); } }
9236ff18e35d86ec273305611f3247d0675c52e6
726
java
Java
gmall-pms/src/main/java/com/atguigu/gmall/pms/service/AttrGroupService.java
H-HowTime/gmall
bc186b5cd89da498136604eb13416055eab864f7
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/service/AttrGroupService.java
H-HowTime/gmall
bc186b5cd89da498136604eb13416055eab864f7
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/service/AttrGroupService.java
H-HowTime/gmall
bc186b5cd89da498136604eb13416055eab864f7
[ "Apache-2.0" ]
null
null
null
25.857143
104
0.785912
997,906
package com.atguigu.gmall.pms.service; import com.atguigu.gmall.pms.vo.ItemGroupVo; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.gmall.common.bean.PageResultVo; import com.atguigu.gmall.common.bean.PageParamVo; import com.atguigu.gmall.pms.entity.AttrGroupEntity; import java.util.List; import java.util.Map; /** * 属性分组 * * @author hehao * @email dycjh@example.com * @date 2021-01-18 18:30:53 */ public interface AttrGroupService extends IService<AttrGroupEntity> { PageResultVo queryPage(PageParamVo paramVo); List<AttrGroupEntity> queryWithAttrsByCid(long cid); List<ItemGroupVo> queryAttrGroupValueByCidAndSpuIdAndSkuId(Long categoryId, Long spuId, Long skuId); }
9236ff19cfee4c35d76260a0d93c47188bb13c5b
2,885
java
Java
sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/implementation/OperationOperationsImpl.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
1,350
2015-01-17T05:22:05.000Z
2022-03-29T21:00:37.000Z
sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/implementation/OperationOperationsImpl.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
16,834
2015-01-07T02:19:09.000Z
2022-03-31T23:29:10.000Z
sdk/recoveryservicesbackup/azure-resourcemanager-recoveryservicesbackup/src/main/java/com/azure/resourcemanager/recoveryservicesbackup/implementation/OperationOperationsImpl.java
liukun2634/azure-sdk-for-java
a42ba097eef284333c9befba180eea3cfed41312
[ "MIT" ]
1,586
2015-01-02T01:50:28.000Z
2022-03-31T11:25:34.000Z
44.384615
120
0.759099
997,907
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.recoveryservicesbackup.implementation; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.recoveryservicesbackup.fluent.OperationOperationsClient; import com.azure.resourcemanager.recoveryservicesbackup.fluent.models.ValidateOperationsResponseInner; import com.azure.resourcemanager.recoveryservicesbackup.models.OperationOperations; import com.azure.resourcemanager.recoveryservicesbackup.models.ValidateOperationRequest; import com.azure.resourcemanager.recoveryservicesbackup.models.ValidateOperationsResponse; import com.fasterxml.jackson.annotation.JsonIgnore; public final class OperationOperationsImpl implements OperationOperations { @JsonIgnore private final ClientLogger logger = new ClientLogger(OperationOperationsImpl.class); private final OperationOperationsClient innerClient; private final com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager serviceManager; public OperationOperationsImpl( OperationOperationsClient innerClient, com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager serviceManager) { this.innerClient = innerClient; this.serviceManager = serviceManager; } public ValidateOperationsResponse validate( String vaultName, String resourceGroupName, ValidateOperationRequest parameters) { ValidateOperationsResponseInner inner = this.serviceClient().validate(vaultName, resourceGroupName, parameters); if (inner != null) { return new ValidateOperationsResponseImpl(inner, this.manager()); } else { return null; } } public Response<ValidateOperationsResponse> validateWithResponse( String vaultName, String resourceGroupName, ValidateOperationRequest parameters, Context context) { Response<ValidateOperationsResponseInner> inner = this.serviceClient().validateWithResponse(vaultName, resourceGroupName, parameters, context); if (inner != null) { return new SimpleResponse<>( inner.getRequest(), inner.getStatusCode(), inner.getHeaders(), new ValidateOperationsResponseImpl(inner.getValue(), this.manager())); } else { return null; } } private OperationOperationsClient serviceClient() { return this.innerClient; } private com.azure.resourcemanager.recoveryservicesbackup.RecoveryServicesBackupManager manager() { return this.serviceManager; } }
9236ff1c35179709c276989bf1f2719e10ba398b
13,621
java
Java
compiler/src/main/java/dyvilx/tools/compiler/ast/generic/TypeParameter.java
Dyvil/Dyvil
5837abf9ff5ec5af339d0ed0501555f3618c6d47
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
48
2015-07-28T22:29:00.000Z
2021-12-16T19:10:20.000Z
compiler/src/main/java/dyvilx/tools/compiler/ast/generic/TypeParameter.java
Dyvil/Dyvil
5837abf9ff5ec5af339d0ed0501555f3618c6d47
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
436
2015-07-20T15:54:45.000Z
2020-10-06T10:59:04.000Z
compiler/src/main/java/dyvilx/tools/compiler/ast/generic/TypeParameter.java
Dyvil/Dyvil
5837abf9ff5ec5af339d0ed0501555f3618c6d47
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-09-27T19:37:41.000Z
2017-04-09T02:56:45.000Z
23.729965
107
0.692827
997,908
package dyvilx.tools.compiler.ast.generic; import dyvil.annotation.Reified; import dyvil.annotation.internal.NonNull; import dyvil.annotation.internal.Nullable; import dyvil.lang.Name; import dyvilx.tools.asm.TypeAnnotatableVisitor; import dyvilx.tools.asm.TypeReference; import dyvilx.tools.compiler.ast.attribute.AttributeList; import dyvilx.tools.compiler.ast.attribute.annotation.Annotation; import dyvilx.tools.compiler.ast.classes.IClass; import dyvilx.tools.compiler.ast.expression.IValue; import dyvilx.tools.compiler.ast.expression.constant.EnumValue; import dyvilx.tools.compiler.ast.field.IDataMember; import dyvilx.tools.compiler.ast.method.IMethod; import dyvilx.tools.compiler.ast.method.MatchList; import dyvilx.tools.compiler.ast.parameter.ArgumentList; import dyvilx.tools.compiler.ast.parameter.IParameter; import dyvilx.tools.compiler.ast.type.IType; import dyvilx.tools.compiler.ast.type.builtin.Types; import dyvilx.tools.compiler.ast.type.compound.IntersectionType; import dyvilx.tools.compiler.ast.type.typevar.CovariantTypeVarType; import dyvilx.tools.compiler.backend.exception.BytecodeException; import dyvilx.tools.compiler.backend.method.MethodWriter; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.annotation.ElementType; import java.util.ArrayList; import java.util.List; import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperClass; import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperType; public abstract class TypeParameter implements ITypeParameter { // =============== Fields =============== // --------------- Accompanying Member --------------- protected ITypeParametric generic; // --------------- Declaration --------------- protected @NonNull AttributeList attributes = new AttributeList(); protected Variance variance = Variance.INVARIANT; protected Name name; private @NonNull IType upperBound = Types.NULLABLE_ANY; protected @Nullable IType lowerBound; // --------------- Metadata --------------- private IType safeUpperBound; private IType[] upperBounds; protected Reified.Type reifiedKind; // defaults to null (not reified) protected IParameter reifyParameter; private final IType covariantType = new CovariantTypeVarType(this); // =============== Constructors =============== public TypeParameter(ITypeParametric generic) { this.generic = generic; } public TypeParameter(ITypeParametric generic, Name name) { this.name = name; this.generic = generic; } public TypeParameter(ITypeParametric generic, Name name, Variance variance) { this.name = name; this.generic = generic; this.variance = variance; } // =============== Properties =============== // --------------- Accompanying Member --------------- @Override public ITypeParametric getGeneric() { return this.generic; } @Override public void setGeneric(ITypeParametric generic) { this.generic = generic; } // --------------- Attributes --------------- @Override public ElementType getElementType() { return ElementType.TYPE_PARAMETER; } @Override public AttributeList getAttributes() { return this.attributes; } @Override public void setAttributes(AttributeList attributes) { this.attributes = attributes; } @Override public final Annotation getAnnotation(IClass type) { return this.attributes.getAnnotation(type); } @Override public boolean skipAnnotation(String type, Annotation annotation) { switch (type) { case "dyvil/annotation/internal/Covariant": this.variance = Variance.COVARIANT; return true; case "dyvil/annotation/internal/Contravariant": this.variance = Variance.CONTRAVARIANT; return true; } return false; } // --------------- Reification --------------- protected void computeReifiedKind() { if (this.reifiedKind != null) { return; } final Annotation reifiedAnnotation = this.getAnnotation(Types.REIFIED_CLASS); if (reifiedAnnotation != null) { final IParameter parameter = Types.REIFIED_CLASS.getParameters().get(0); this.reifiedKind = EnumValue .eval(reifiedAnnotation.getArguments().getOrDefault(parameter), Reified.Type.class); } } @Override public Reified.Type getReifiedKind() { return this.reifiedKind; } @Override public IParameter getReifyParameter() { return this.reifyParameter; } @Override public void setReifyParameter(IParameter parameter) { this.reifyParameter = parameter; } // --------------- Variance --------------- @Override public Variance getVariance() { return this.variance; } @Override public void setVariance(Variance variance) { this.variance = variance; } // --------------- Name --------------- @Override public Name getName() { return this.name; } @Override public void setName(Name name) { this.name = name; } // --------------- Upper Bound --------------- @Override public IType getUpperBound() { if (this.upperBound != null) { return this.upperBound; } final IType[] upperBounds = this.getUpperBounds(); if (upperBounds != null) { return this.upperBound = getUpperBound(upperBounds, 0, upperBounds.length); } return null; } @Override public void setUpperBound(IType bound) { this.upperBound = bound; this.upperBounds = null; this.safeUpperBound = null; } public IType[] getUpperBounds() { if (this.upperBounds != null) { return this.upperBounds; } final IType upperBound = this.getUpperBound(); if (upperBound != null) { // Flatten the tree-like upperBound structure into a list final List<IType> list = new ArrayList<>(); getUpperBounds(list, upperBound); return this.upperBounds = list.toArray(new IType[0]); } return null; } public void setUpperBounds(IType[] upperBounds) { this.upperBounds = upperBounds; this.upperBound = null; this.safeUpperBound = null; } /** * Creates a balanced tree for the slice of the given array * * @param upperBounds * the upper bounds array * @param start * the start index * @param count * the number of elements * * @return a balanced tree of {@link IntersectionType}s */ private static IType getUpperBound(IType[] upperBounds, int start, int count) { if (count == 1) { return upperBounds[start]; } final int halfCount = count / 2; return new IntersectionType(getUpperBound(upperBounds, start, halfCount), getUpperBound(upperBounds, start + halfCount, count - halfCount)); } private static void getUpperBounds(List<IType> list, IType upperBound) { if (upperBound.typeTag() != IType.INTERSECTION) { list.add(upperBound); return; } final IntersectionType intersection = (IntersectionType) upperBound; getUpperBounds(list, intersection.getLeft()); getUpperBounds(list, intersection.getRight()); } // --------------- Safe Upper Bound --------------- private IType getSafeUpperBound() { if (this.safeUpperBound != null) { return this.safeUpperBound; } return (this.safeUpperBound = this.getUpperBound().getConcreteType(this::replaceBackRefs)); } private @Nullable IType replaceBackRefs(ITypeParameter typeParameter) { if (typeParameter.getGeneric() == this.getGeneric() && typeParameter.getIndex() >= this.getIndex()) { return new CovariantTypeVarType(this, true); } return null; } // --------------- Lower Bound --------------- @Override public IType getLowerBound() { return this.lowerBound; } @Override public void setLowerBound(IType bound) { this.lowerBound = bound; } // --------------- Other Types --------------- @Override public IType getErasure() { return this.getUpperBounds()[0]; } @Override public IType getCovariantType() { return this.covariantType; } @Override public IClass getTheClass() { return this.getSafeUpperBound().getTheClass(); } // =============== Methods =============== // --------------- Subtyping --------------- @Override public boolean isAssignableFrom(IType type, ITypeContext typeContext) { if (!Types.isSuperType(this.getSafeUpperBound().getConcreteType(typeContext), type)) { return false; } final IType lowerBound = this.getLowerBound(); return lowerBound == null || Types.isSuperType(type, lowerBound.getConcreteType(typeContext)); } @Override public boolean isSameType(IType type) { return Types.isSameType(type, this.getSafeUpperBound()); } @Override public boolean isSameClass(IType type) { return Types.isSameClass(type, this.getSafeUpperBound()); } @Override public boolean isSuperTypeOf(IType subType) { return isSuperType(this.getSafeUpperBound(), subType); } @Override public boolean isSuperClassOf(IType subType) { return isSuperClass(this.getSafeUpperBound(), subType); } @Override public boolean isSubTypeOf(IType superType) { return isSuperType(superType, this.getSafeUpperBound()); } @Override public boolean isSubClassOf(IType superType) { return isSuperClass(superType, this.getSafeUpperBound()); } // --------------- Field and Method Resolution --------------- @Override public IDataMember resolveField(Name name) { return this.getSafeUpperBound().resolveField(name); } @Override public void getMethodMatches(MatchList<IMethod> list, IValue instance, Name name, ArgumentList arguments) { this.getSafeUpperBound().getMethodMatches(list, instance, name, arguments); } @Override public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType) { this.getSafeUpperBound().getImplicitMatches(list, value, targetType); } // --------------- Descriptor and Signature --------------- @Override public void appendSignature(StringBuilder buffer) { buffer.append(this.name).append(':'); final IType[] upperBounds = this.getUpperBounds(); if (upperBounds == null || upperBounds.length == 0) { buffer.append("Ljava/lang/Object;"); return; } final IClass theClass = upperBounds[0].getTheClass(); if (theClass != null && theClass.isInterface()) { // If the first type is an interface, we append two colons // T::Lmy/Interface; buffer.append(':'); } upperBounds[0].appendSignature(buffer, false); for (int i = 1, count = upperBounds.length; i < count; i++) { buffer.append(':'); upperBounds[i].appendSignature(buffer, false); } } @Override public void appendParameterDescriptor(StringBuilder buffer) { if (this.reifiedKind == Reified.Type.TYPE) { buffer.append("Ldyvil/reflect/types/Type;"); } else if (this.reifiedKind != null) // OBJECT_CLASS or ANY_CLASS { buffer.append("Ljava/lang/Class;"); } } @Override public void appendParameterSignature(StringBuilder buffer) { this.appendParameterDescriptor(buffer); } // --------------- Compilation --------------- @Override public void writeArgument(MethodWriter writer, IType type) throws BytecodeException { if (this.reifiedKind == Reified.Type.ANY_CLASS) { type.writeClassExpression(writer, false); } else if (this.reifiedKind == Reified.Type.OBJECT_CLASS) { // Convert primitive types to their reference counterpart type.writeClassExpression(writer, true); } else if (this.reifiedKind == Reified.Type.TYPE) { type.writeTypeExpression(writer); } } @Override public void write(TypeAnnotatableVisitor visitor) { boolean method = this.generic instanceof IMethod; final int index = this.getIndex(); int typeRef = TypeReference.newTypeParameterReference( method ? TypeReference.METHOD_TYPE_PARAMETER : TypeReference.CLASS_TYPE_PARAMETER, index); if (this.variance != Variance.INVARIANT) { String type = this.variance == Variance.CONTRAVARIANT ? "Ldyvil/annotation/internal/Contravariant;" : "Ldyvil/annotation/internal/Covariant;"; visitor.visitTypeAnnotation(typeRef, null, type, true).visitEnd(); } this.attributes.write(visitor, typeRef, null); final IType[] upperBounds = this.getUpperBounds(); for (int i = 0, size = upperBounds.length; i < size; i++) { final int boundTypeRef = TypeReference.newTypeParameterBoundReference( method ? TypeReference.METHOD_TYPE_PARAMETER_BOUND : TypeReference.CLASS_TYPE_PARAMETER_BOUND, index, i); IType.writeAnnotations(upperBounds[i], visitor, boundTypeRef, ""); } } // --------------- Serialization --------------- @Override public void write(DataOutput out) throws IOException { this.name.write(out); Variance.write(this.variance, out); IType.writeType(this.lowerBound, out); IType.writeType(this.getUpperBound(), out); } @Override public void read(DataInput in) throws IOException { this.name = Name.read(in); this.variance = Variance.read(in); this.lowerBound = IType.readType(in); this.setUpperBound(IType.readType(in)); } // --------------- Formatting --------------- @Override public String toString() { StringBuilder builder = new StringBuilder(); this.toString("", builder); return builder.toString(); } @Override public void toString(@NonNull String indent, @NonNull StringBuilder buffer) { this.attributes.toInlineString(indent, buffer); buffer.append("type "); this.variance.appendPrefix(buffer); buffer.append(this.name); final IType upperBound = this.getSafeUpperBound(); if (upperBound != null) { buffer.append(": "); upperBound.toString(indent, buffer); } final IType lowerBound = this.getLowerBound(); if (lowerBound != null) { buffer.append(" super "); lowerBound.toString(indent, buffer); } } }
9237004b7274465bb6f1c9aaceccad1fa342f81c
4,943
java
Java
api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java
aleskxyz/cloudstack
2700beb4fb1206f93829b8c4085479a8f416833d
[ "Apache-2.0" ]
1,131
2015-01-08T18:59:06.000Z
2022-03-29T11:31:10.000Z
api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java
aleskxyz/cloudstack
2700beb4fb1206f93829b8c4085479a8f416833d
[ "Apache-2.0" ]
5,908
2015-01-13T15:28:37.000Z
2022-03-31T20:31:07.000Z
api/src/main/java/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java
Rostov1991/cloudstack
4abe8385e0721793d5dae8f195303d010c8ff8d2
[ "Apache-2.0" ]
1,083
2015-01-05T01:16:52.000Z
2022-03-31T12:14:10.000Z
38.023077
161
0.645357
997,909
// 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.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; import org.apache.cloudstack.acl.SecurityChecker.AccessType; import org.apache.cloudstack.api.ACL; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandJobType; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.SystemVmResponse; import org.apache.cloudstack.context.CallContext; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.vm.VirtualMachine; @APICommand(name = "stopSystemVm", description = "Stops a system VM.", responseObject = SystemVmResponse.class, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class StopSystemVmCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); private static final String s_name = "stopsystemvmresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @ACL(accessType = AccessType.OperateEntry) @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = SystemVmResponse.class, required = true, description = "The ID of the system virtual machine") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM. The caller knows the VM is stopped.") private Boolean forced; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { Account account = CallContext.current().getCallingAccount(); if (account != null) { return account.getId(); } return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } @Override public String getEventType() { VirtualMachine.Type type = _mgr.findSystemVMTypeById(getId()); if (type == VirtualMachine.Type.ConsoleProxy) { return EventTypes.EVENT_PROXY_STOP; } else { return EventTypes.EVENT_SSVM_STOP; } } @Override public String getEventDescription() { return "stopping system vm: " + this._uuidMgr.getUuid(VirtualMachine.class, getId()); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.SystemVm; } @Override public Long getInstanceId() { return getId(); } public boolean isForced() { return (forced != null) ? forced : false; } @Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { CallContext.current().setEventDetails("Vm Id: " + this._uuidMgr.getUuid(VirtualMachine.class, getId())); VirtualMachine result = _mgr.stopSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Fail to stop system vm"); } } }
92370304ebdb30a0140c970bf3bb9de574420695
1,446
java
Java
core/src/main/java/org/teavm/model/classes/VirtualTableEntry.java
frankbauer/teavm
0465b908ca1fd14c530735d795c888b12c26fce5
[ "Apache-2.0" ]
1
2019-02-24T17:29:16.000Z
2019-02-24T17:29:16.000Z
core/src/main/java/org/teavm/model/classes/VirtualTableEntry.java
xuxq126/teavm
a8f1940df33f79285eb5cf143cc77fa98d5961b5
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/teavm/model/classes/VirtualTableEntry.java
xuxq126/teavm
a8f1940df33f79285eb5cf143cc77fa98d5961b5
[ "Apache-2.0" ]
null
null
null
28.92
115
0.706777
997,910
/* * Copyright 2016 Alexey Andreev. * * 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.teavm.model.classes; import org.teavm.model.MethodDescriptor; import org.teavm.model.MethodReference; public class VirtualTableEntry { private VirtualTable virtualTable; private MethodDescriptor method; MethodReference implementor; private int index; VirtualTableEntry(VirtualTable virtualTable, MethodDescriptor method, MethodReference implementor, int index) { this.virtualTable = virtualTable; this.method = method; this.implementor = implementor; this.index = index; } public VirtualTable getVirtualTable() { return virtualTable; } public MethodDescriptor getMethod() { return method; } public MethodReference getImplementor() { return implementor; } public int getIndex() { return index; } }
9237033e0520b7576cb49b9eeb00b66163ed4791
160,505
java
Java
src/main/java/com/flagstone/translate/ASNode.java
juancata/translate-swf
ef68b1d2100a822da5d5154f50bc35c5feee2df3
[ "BSD-3-Clause" ]
5
2015-09-30T11:52:48.000Z
2022-03-07T10:09:13.000Z
src/main/java/com/flagstone/translate/ASNode.java
juancata/translate-swf
ef68b1d2100a822da5d5154f50bc35c5feee2df3
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/flagstone/translate/ASNode.java
juancata/translate-swf
ef68b1d2100a822da5d5154f50bc35c5feee2df3
[ "BSD-3-Clause" ]
4
2015-03-14T23:17:33.000Z
2021-03-21T19:50:08.000Z
40.006231
96
0.511822
997,911
/* * ASNode.java * Translate * * Copyright (c) 2003-2010 Flagstone Software Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Flagstone Software Ltd. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.flagstone.translate; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.flagstone.transform.action.Action; import com.flagstone.transform.action.ActionObject; import com.flagstone.transform.action.ActionTypes; import com.flagstone.transform.action.BasicAction; import com.flagstone.transform.action.Call; import com.flagstone.transform.action.ExceptionHandler; import com.flagstone.transform.action.GetUrl; import com.flagstone.transform.action.GetUrl2; import com.flagstone.transform.action.GotoFrame; import com.flagstone.transform.action.GotoFrame2; import com.flagstone.transform.action.GotoLabel; import com.flagstone.transform.action.If; import com.flagstone.transform.action.Jump; import com.flagstone.transform.action.NewFunction; import com.flagstone.transform.action.Null; import com.flagstone.transform.action.Property; import com.flagstone.transform.action.Push; import com.flagstone.transform.action.RegisterCopy; import com.flagstone.transform.action.RegisterIndex; import com.flagstone.transform.action.SetTarget; import com.flagstone.transform.action.Table; import com.flagstone.transform.action.TableIndex; import com.flagstone.transform.action.Void; import com.flagstone.transform.action.WaitForFrame2; import com.flagstone.transform.action.With; import com.flagstone.transform.coder.Context; import com.flagstone.transform.coder.SWFEncodeable; import com.flagstone.translate.as.ParseException; import com.flagstone.translate.as.Token; /** * ASNode is the class used by the parser to construct a tree representation of * an ActionScript file based on the parser grammar. * * Node trees can also be constructed 'manually' and then encoded to give the * binary representation of the byte-codes and actions that will be executed by * the Flash Player. * * For example, the node tree for the ActionScript statement: * * <pre> * c = a + b; * </pre> * * Can be represented using the following code to build the tree. * * <pre> * ASNode a = new ASNode(ASNode.Identifier, &quot;a&quot;); * ASNode b = new ASNode(ASNode.Identifier, &quot;b&quot;); * ASNode c = new ASNode(ASNode.Identifier, &quot;c&quot;); * * ASNode add = new ASNode(ASNode.Add, a, b); * ASNode assign = new ASNode(a, add); * </pre> * * The ASNode class defines a full range of node types ranging from specifying * literals through to complex structures such as iterative and conditional * constructs such as for loops and if/else blocks. * * The simplest method for determining the structure of the trees that represent * different structure in ActionScript is to use the Interpreter class provided * in the framework and dump out the structure of the parsed code. * */ public class ASNode extends Object { /** * Array nodes are used to represent any list of ActionScript statements. * Use this type of node when constructing trees to represent sequences of * actions for FSDoAction, FSClipEvent or FSButtonEvent objects. */ public static final int Array = 1; /** * Button nodes are used to represent the on() block statement in * ActionScript. Use this type of node when constructing trees that will be * encoded and added to FSDefineButton2 objects. */ public static final int Button = 2; /** * MovieClip nodes are used to represent the onClipEvent() block statement * in ActionScript. Use this type of node when constructing trees that will * be encoded and added to FSPlaceObject2 objects. */ public static final int MovieClip = 3; /** * List nodes are used to represent groups of one or more statements. They * are used to represent statements included in any block structure such as * an if statement or for loop. * * Lists are also used to simplify the construction of complex statements * such as for loops. Using Lists, a for loop contains a maximum of four * child nodes with lists used to group the statements forming the * initialisation and iteration part of the for statement and body of the * loop. */ public static final int StatementList = 4; public static final int List = 5; /** * NoOp is used as a place-holder for child nodes with resorting to using * null. No actions will be generated when the node is translated. */ public static final int NoOp = 6; /** Use to represent if statements */ public static final int If = 7; /** Use to represent for loops */ public static final int For = 8; /** Use to represent for..in statements */ public static final int ForIn = 9; /** Use to represent while loops */ public static final int While = 10; /** Use to represent do..while loops */ public static final int Do = 11; /** Use to represent with statements */ public static final int With = 12; /** Use to represent onClipEvent statements */ public static final int OnClipEvent = 13; /** Use to represent on statements */ public static final int On = 14; /** Use to represent break statements */ public static final int Break = 15; /** Use to represent return statements */ public static final int Return = 16; /** < Use to represent continue statements */ public static final int Continue = 17; /** * Value is an abstract node type used to group together nodes that will * result in a value being generated such as subscripting an array variable * or dereferencing an object's attribute. */ public static final int Value = 18; /** Use to represent a boolean value */ public static final int BooleanLiteral = 20; /** Use to represent an integer value */ public static final int IntegerLiteral = 21; /** Use to represent an double-precision floating point value */ public static final int DoubleLiteral = 22; /** Use to represent a string value */ public static final int StringLiteral = 23; /** Use to represent a null literal */ public static final int NullLiteral = 24; /** Use to represent a variable */ public static final int Identifier = 30; /** Use to represent an attribute of an object */ public static final int Attribute = 31; /** Use to represent the name of a method */ public static final int Method = 32; /** Use to represent the name of one of ActionScript's built-in functions. */ public static final int Function = 33; /** Use to represent new statements for creating instances of objects. */ public static final int NewObject = 34; /** * Use to represent subscript operation when accessing the elements of an * array. */ public static final int Subscript = 35; /** Use to represent a user defined function. */ public static final int DefineFunction = 36; /** Use to represent an anonyomus array. */ public static final int DefineArray = 37; /** Use to represent a user defined object. */ public static final int DefineObject = 38; /** Use to represent a method on a user defined object. */ public static final int DefineMethod = 39; /** Use to represent an attribute on a user defined object. */ public static final int DefineAttribute = 40; /** Use to represent a var statement */ public static final int DefineVariable = 41; /** Add operation */ public static final int Add = 42; /** Subtract operation */ public static final int Sub = 43; /** Multiply operation */ public static final int Mul = 44; /** Divide operation */ public static final int Div = 45; /** Modulo operation */ public static final int Mod = 46; /** Logical Shift Left operation */ public static final int LSL = 47; /** Arithmetic Shift Right operation */ public static final int ASR = 48; /** Logical Shift Right operation */ public static final int LSR = 49; /** Bitwise AND operation */ public static final int BitAnd = 50; /** Bitwise OR operation */ public static final int BitOr = 51; /** Bitwise Exclusive-OR operation */ public static final int BitXOr = 52; /** Logical AND operation */ public static final int LogicalAnd = 53; /** Logical OR operation */ public static final int LogicalOr = 54; /** Equal comparison */ public static final int Equal = 55; /** Not Equal comparison */ public static final int NotEqual = 56; /** Greater Than comparison */ public static final int GreaterThan = 57; /** Less Than comparison */ public static final int LessThan = 58; /** Greater Than or Equal comparison */ public static final int GreaterThanEqual = 59; /** Less Than or Equal comparison */ public static final int LessThanEqual = 60; /** ternary operator. */ public static final int Select = 61; /** Unary not */ public static final int Not = 62; /** Unary bit-not */ public static final int BitNot = 63; /** Unary plus */ public static final int Plus = 64; /** Unary minus */ public static final int Minus = 65; /** Pre-increment */ public static final int PreInc = 66; /** Pre-decrement */ public static final int PreDec = 67; /** Post-increment */ public static final int PostInc = 68; /** Post-decrement */ public static final int PostDec = 69; /** Assign, = */ public static final int Assign = 70; /** Assign add, += */ public static final int AssignAdd = 71; /** Assign subtract, -= */ public static final int AssignSub = 72; /** Assign multiply, *= */ public static final int AssignMul = 73; /** Assign divide, /= */ public static final int AssignDiv = 74; /** Assign modulo, %= */ public static final int AssignMod = 75; /** Assign logical shift left, <<= */ public static final int AssignLSL = 76; /** Assign arithmetic shift right, >>= */ public static final int AssignASR = 77; /** Assign logical shift right, >>>= */ public static final int AssignLSR = 78; /** Assign bitwise-AND, &= */ public static final int AssignBitAnd = 79; /** Assign bitwise-OR, |= */ public static final int AssignBitOr = 80; /** Assign bitwise-exclusive-OR, ^= */ public static final int AssignBitXOr = 81; /** Object identity */ public static final int InstanceOf = 82; /** Object reclamation */ public static final int Delete = 83; /** Strict Equal comparison */ public static final int StrictEqual = 84; /** Strict Not Equal comparison */ public static final int StrictNotEqual = 85; /** Strict Not Equal comparison */ public static final int StringAdd = 86; public static final int StringEqual = 87; public static final int StringNotEqual = 88; public static final int StringLessThanEqual = 89; public static final int StringGreaterThan = 90; public static final int StringGreaterThanEqual = 91; public static final int Exception = 92; public static final int Try = 93; public static final int Catch = 94; public static final int Finally = 95; public static final int Switch = 96; public static final int Throw = 97; public static final int Label = 98; public static final int InitClip = 99; public static final int EndInitClip = 100; public static final int And = 101; public static final int Or = 102; /* * Names for each of the different types of node. Names are used in the * toString() method. */ private static String[] nodeNames = { "", "Frame", "Button", "MovieClip", "Statements", "List", "NoOp", "if", "for", "for..in", "while", "do..while", "With", "OnClipEvent", "On", "Break", "Return", "Continue", "Value", "", "Boolean", "Integer", "Double", "String", "Null", "", "", "", "", "", "Identifier", "Attribute", "Method", "Function", "NewObject", "Subscript", "Define Function", "Define Array", "Define Object", "Define Method", "Define Attribute", "Define Variable", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "==", "!=", ">", "<", ">=", "<=", "?", "!", "~", "+x", "-x", "++x", "--x", "x++", "x--", "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "intanceof", "delete", "===", "!==", "add", "eq", "ne", "le", "gt", "ge", "exception", "try", "catch", "finally", "switch", "throw", "label", "#initclip", "#endinitclip", "and", "or", }; /* * Table for the different types of events that buttons respond to. The * table is accessible in the package as it is used in the ASParser to * convert the identifiers representing the different events into the codes * indicating which flags are set. */ static Map<String, Integer> buttonEvents = new HashMap<String, Integer>(); /* * Table for the different types of events that movie clips respond to. The * table is package accessible as it is used in the ASParser to convert the * identifiers representing the different events into the codes indicating * which flags are set. */ static Map<String, Integer> clipEvents = new HashMap<String, Integer>(); // Table for constants defined in Flash. private static Map<String, Object> constants = new HashMap<String, Object>(); // Table for properties defined in Flash. private static Map<String, Integer> propertyNames = new HashMap<String, Integer>(); // Table for properties defined in Flash 4 or earlier. private static Map<String, Integer> earlyPropertyNames = new HashMap<String, Integer>(); // Table for the functions built into Flash. private static Map<String, Boolean> functions = new HashMap<String, Boolean>(); // Table for the functions built into Flash that return a value. private static Map<String, Object> valueFunctions = new HashMap<String, Object>(); // Table for the classes built into Flash that return a value. private static Map<String, Object> classes = new HashMap<String, Object>(); static { /* * Button events identifies the values that represents the bit flags * that are set in the encoded event field as well as code values for * special keyboard keys. */ buttonEvents.put("rollOver", new Integer(1)); buttonEvents.put("rollOut", new Integer(2)); buttonEvents.put("press", new Integer(4)); buttonEvents.put("release", new Integer(8)); buttonEvents.put("dragOut", new Integer(16)); buttonEvents.put("dragOver", new Integer(160)); buttonEvents.put("releaseOutside", new Integer(64)); buttonEvents.put("menuDragOver", new Integer(160)); buttonEvents.put("menuDragOut", new Integer(256)); buttonEvents.put("<left>", new Integer(512)); buttonEvents.put("<right>", new Integer(1024)); buttonEvents.put("<home>", new Integer(1536)); buttonEvents.put("<end>", new Integer(2048)); buttonEvents.put("<insert>", new Integer(2560)); buttonEvents.put("<delete>", new Integer(3072)); buttonEvents.put("<backspace>", new Integer(4096)); buttonEvents.put("<enter>", new Integer(6656)); buttonEvents.put("<up>", new Integer(7168)); buttonEvents.put("<down>", new Integer(7680)); buttonEvents.put("<pageUp>", new Integer(8192)); buttonEvents.put("<pageDown>", new Integer(8704)); buttonEvents.put("<tab>", new Integer(9216)); buttonEvents.put("<escape>", new Integer(9728)); buttonEvents.put("<space>", new Integer(16384)); /* * Button events identifies the values that represents the bit flags * that are set in the encoded event field. */ clipEvents.put("load", new Integer(1)); clipEvents.put("enterFrame", new Integer(2)); clipEvents.put("unload", new Integer(4)); clipEvents.put("mouseMove", new Integer(8)); clipEvents.put("mouseDown", new Integer(16)); clipEvents.put("mouseUp", new Integer(32)); clipEvents.put("keyDown", new Integer(64)); clipEvents.put("keyUp", new Integer(128)); clipEvents.put("data", new Integer(256)); constants.put("Math.E", new Double(Math.E)); constants.put("Math.LN2", new Double(Math.log(2))); constants.put("Math.LOG2E", new Double(Math.log(Math.E) / Math.log(2))); constants.put("Math.LN10", new Double(Math.log(10))); constants.put("Math.LOG10E", new Double(Math.log(Math.E) / Math.log(10))); constants.put("Math.PI", new Double(Math.PI)); constants.put("Math.SQRT1_2", new Double(Math.sqrt(0.5))); constants.put("Math.SQRT2", new Double(Math.sqrt(2))); constants.put("Number.MAX_VALUE", new Double(Double.MAX_VALUE)); constants.put("Number.MIN_VALUE", new Double(Double.MIN_VALUE)); constants.put("Number.NaN", new Double(Double.NaN)); constants.put("Number.NEGATIVE_INFINITY", new Double( Double.NEGATIVE_INFINITY)); constants.put("Number.POSITIVE_INFINITY", new Double( Double.POSITIVE_INFINITY)); constants.put("Key.BACKSPACE", new Integer(8)); constants.put("Key.CAPSLOCK", new Integer(20)); constants.put("Key.CONTROL", new Integer(17)); constants.put("Key.DELETEKEY", new Integer(46)); constants.put("Key.DOWN", new Integer(40)); constants.put("Key.END", new Integer(35)); constants.put("Key.ENTER", new Integer(13)); constants.put("Key.ESCAPE", new Integer(27)); constants.put("Key.HOME", new Integer(36)); constants.put("Key.INSERT", new Integer(45)); constants.put("Key.LEFT", new Integer(37)); constants.put("Key.PGDN", new Integer(34)); constants.put("Key.PGUP", new Integer(33)); constants.put("Key.RIGHT", new Integer(39)); constants.put("Key.SHIFT", new Integer(16)); constants.put("Key.SPACE", new Integer(32)); constants.put("Key.TAB", new Integer(9)); constants.put("Key.UP", new Integer(38)); constants.put("newline", new String("\n")); constants.put("undefined", null); earlyPropertyNames.put("_x", new Integer(0)); earlyPropertyNames.put("_y", new Integer(0x3f800000)); earlyPropertyNames.put("_xscale", new Integer(0x40000000)); earlyPropertyNames.put("_yscale", new Integer(0x40400000)); earlyPropertyNames.put("_currentframe", new Integer(0x40800000)); earlyPropertyNames.put("_totalframes", new Integer(0x40a00000)); earlyPropertyNames.put("_alpha", new Integer(0x40c00000)); earlyPropertyNames.put("_visible", new Integer(0x40e00000)); earlyPropertyNames.put("_width", new Integer(0x41000000)); earlyPropertyNames.put("_height", new Integer(0x41100000)); earlyPropertyNames.put("_rotation", new Integer(0x41200000)); earlyPropertyNames.put("_target", new Integer(0x41300000)); earlyPropertyNames.put("_framesloaded", new Integer(0x41400000)); earlyPropertyNames.put("_name", new Integer(0x41500000)); earlyPropertyNames.put("_droptarget", new Integer(0x41600000)); earlyPropertyNames.put("_url", new Integer(0x41700000)); earlyPropertyNames.put("_highquality", new Integer(16)); earlyPropertyNames.put("_focusrect", new Integer(17)); earlyPropertyNames.put("_soundbuftime", new Integer(18)); earlyPropertyNames.put("_quality", new Integer(19)); earlyPropertyNames.put("_xmouse", new Integer(20)); earlyPropertyNames.put("_ymouse", new Integer(21)); propertyNames.put("_x", new Integer(0)); propertyNames.put("_y", new Integer(1)); propertyNames.put("_xscale", new Integer(2)); propertyNames.put("_yscale", new Integer(3)); propertyNames.put("_currentframe", new Integer(4)); propertyNames.put("_totalframes", new Integer(5)); propertyNames.put("_alpha", new Integer(6)); propertyNames.put("_visible", new Integer(7)); propertyNames.put("_width", new Integer(8)); propertyNames.put("_height", new Integer(9)); propertyNames.put("_rotation", new Integer(10)); propertyNames.put("_target", new Integer(11)); propertyNames.put("_framesloaded", new Integer(12)); propertyNames.put("_name", new Integer(13)); propertyNames.put("_droptarget", new Integer(14)); propertyNames.put("_url", new Integer(15)); propertyNames.put("_highquality", new Integer(16)); propertyNames.put("_focusrect", new Integer(17)); propertyNames.put("_soundbuftime", new Integer(18)); propertyNames.put("_quality", new Integer(19)); propertyNames.put("_xmouse", new Integer(20)); propertyNames.put("_ymouse", new Integer(21)); /* * The functions table is only used to identify built-in functions so no * value is associated with each name. */ functions.put("call", new Boolean(false)); functions.put("chr", new Boolean(true)); functions.put("delete", new Boolean(false)); functions.put("duplicatemovieclip", new Boolean(false)); functions.put("eval", new Boolean(true)); functions.put("fscommand", new Boolean(false)); functions.put("getproperty", new Boolean(true)); functions.put("gettimer", new Boolean(true)); functions.put("geturl", new Boolean(false)); functions.put("getversion", new Boolean(true)); functions.put("gotoandplay", new Boolean(false)); functions.put("gotoandstop", new Boolean(false)); functions.put("ifframeloaded", new Boolean(false)); functions.put("int", new Boolean(true)); functions.put("loadmovie", new Boolean(false)); functions.put("loadmovienum", new Boolean(false)); functions.put("loadvariables", new Boolean(false)); functions.put("length", new Boolean(true)); functions.put("mbchr", new Boolean(true)); functions.put("mbord", new Boolean(true)); functions.put("mbsubstring", new Boolean(true)); functions.put("nextframe", new Boolean(false)); functions.put("nextscene", new Boolean(false)); functions.put("number", new Boolean(false)); functions.put("ord", new Boolean(true)); functions.put("play", new Boolean(false)); functions.put("prevframe", new Boolean(false)); functions.put("prevscene", new Boolean(false)); functions.put("print", new Boolean(false)); functions.put("printnum", new Boolean(false)); functions.put("printasbitmap", new Boolean(false)); functions.put("printasbitmapnum", new Boolean(false)); functions.put("random", new Boolean(true)); functions.put("removemovieclip", new Boolean(false)); functions.put("set", new Boolean(false)); functions.put("setproperty", new Boolean(false)); functions.put("startdrag", new Boolean(false)); functions.put("stop", new Boolean(false)); functions.put("stopallsounds", new Boolean(false)); functions.put("stopdrag", new Boolean(false)); functions.put("string", new Boolean(false)); functions.put("substring", new Boolean(true)); functions.put("targetpath", new Boolean(false)); functions.put("telltarget", new Boolean(false)); functions.put("togglehighquality", new Boolean(false)); functions.put("trace", new Boolean(false)); functions.put("typeof", new Boolean(true)); functions.put("unloadmovie", new Boolean(false)); functions.put("unloadmovienum", new Boolean(false)); functions.put("void", new Boolean(true)); /* * The functions table is only used to identify built-in functions that * return a value to determine whether a pop action should be generated * if the value returned by the function is not assigned to a variable. */ valueFunctions.put("attachaudio", null); valueFunctions.put("attachmovie", null); valueFunctions.put("escape", null); valueFunctions.put("getbounds", null); valueFunctions.put("getbytesloaded", null); valueFunctions.put("getbytestotal", null); valueFunctions.put("getversion", null); valueFunctions.put("globaltolocal", null); valueFunctions.put("hittest", null); valueFunctions.put("isfinite", null); valueFunctions.put("isnan", null); valueFunctions.put("localtoglobal", null); valueFunctions.put("parsefloat", null); valueFunctions.put("parseint", null); valueFunctions.put("swapdepths", null); valueFunctions.put("targetpath", null); valueFunctions.put("unescape", null); valueFunctions.put("updateafterevent", null); classes.put("Math", null); classes.put("Clip", null); } private int type = 0; /* * Nodes may store integer, floating-point literals or the names of * functions, identifiers or string literals. Separate attributes are used * rather than an Object to avoid repeated class casting, improve * readability of code and increase performance. */ private int iValue = 0; private double dValue = Double.NaN; private String sValue = null; private boolean bValue = false; /* * the discardValue flag is used to signal to a node that the value it * returns is not used by the parent and so a pop action should be added * when the node is translated into action objects. The discardValue flag is * set by the parent node through the discardValues() method. */ private boolean discardValue = false; /* * insertIndex is used when reordering nodes so that function definitions * defined within a block are placed at the start - mirroring the behaviour * of the Flash authoring application. The index is used to preserve the * order in which functions are defined making regression testing easier * when comparing the code generated by a node against the code generated by * the Flash authoring application. */ private int insertIndex = 0; private ASNode parent = null; private ASNode[] children = null; /* * The number attribute is used either to store the line number in a script * where the node was generated or an identifier for the node if a node tree * was created manually. The number is used when reporting errors while * validating the nodes. */ private int number = 0; /** * Constructs an ASNode with the specified type. * * @param nodeType * the type of node being constructed. */ public ASNode(int nodeType) { type = nodeType; } /** * Constructs an ASNode with the specified type and integer value. This * constructor is primarily used to create nodes representing integer * literals. * * @param nodeType * the type of node being constructed. * @param value * the integer value assigned to the node. */ public ASNode(int nodeType, int value) { type = nodeType; iValue = value; } /** * Constructs an ASNode with the specified type and floating-point value. * This constructor is primarily used to create nodes representing literals. * * @param nodeType * the type of node being constructed. * @param value * the floating-point value assigned to the node. */ public ASNode(int nodeType, double value) { type = nodeType; dValue = value; } /** * Constructs an ASNode with the specified type and string value. This * constructor is primarily used to create string literals and identifiers. * * @param nodeType * the type of node being constructed. * @param value * the string assigned to the node. */ public ASNode(int nodeType, String value) { type = nodeType; sValue = value; } /** * Constructs an ASNode with the specified type and adds the child node. * * @param nodeType * the type of node being constructed. * @param node * a child node which will be added to the new node. */ public ASNode(int nodeType, ASNode node) { type = nodeType; add(node); } /** * Constructs an ASNode with the specified type and adds the child nodes. * * @param nodeType * the type of node being constructed. * @param node1 * a child node which will be added to the new node. * @param node2 * a child node which will be added to the new node. */ public ASNode(int nodeType, ASNode node1, ASNode node2) { type = nodeType; add(node1); add(node2); } /** * Gets the type of the node. * * @return the type assigned to the node. */ public int getType() { return type; } /** * Sets the type of the node. * * @param type * the type assigned to the node. */ public void setType(int type) { this.type = type; } /** * Get the boolean value assigned to a node. * * @return the boolean value assigned to a node. */ public boolean getBoolValue() { return bValue; } /** * Set the boolean value assigned to a node. * * @param value * a value that will be assigned to the node. */ public void setBoolValue(boolean value) { bValue = value; iValue = 0; dValue = Double.NaN; sValue = null; } /** * Get the integer value assigned to a node. * * @return the integer value assigned to a node. */ public int getIntValue() { return iValue; } /** * Set the integer value assigned to a node. * * @param value * a value that will be assigned to the node. */ public void setIntValue(int value) { bValue = false; iValue = value; dValue = Double.NaN; sValue = null; } /** * Get the floating-point value assigned to a node. * * @return the floating-point value assigned to a node. */ public double getDoubleValue() { return dValue; } /** * Set the floating-point value assigned to a node. * * @param value * a floating-point value that will be assigned to the node. */ public void setDoubleValue(double value) { bValue = false; iValue = 0; dValue = value; sValue = null; } /** * Get the string value assigned to a node. * * @return the string value assigned to a node. */ public String getStringValue() { return sValue; } /** * Set the number assigned to a node. * * @param value * a unique number that will be assigned to the node. */ public void setNumber(int value) { number = value; } /** * Get the number assigned to a node. * * @return the number assigned to a node. */ public int getNumber() { return number; } /** * Set the string value assigned to a node. * * @param value * a string that will be assigned to the node. */ public void setStringValue(String value) { bValue = false; iValue = 0; dValue = Double.NaN; sValue = value; } /** * Returns the node at the specified index from the array of child nodes. If * the index is outside the range of the array then an ArrayIndexOutOfBounds * exception is thrown. * * @param index * the index of the child node to return. * @return the ith node in the array of children. * @throws ArrayIndexOutOfBoundsException * if (index < 0 || index >= length). */ public ASNode get(int index) { if (children == null || index < 0 || index >= children.length) throw new ArrayIndexOutOfBoundsException(index); return children[index]; } /** * Replaces the node at position i in the array of children. If the position * is outside the range of the array (i< 0 || i >= length) then an * ArrayIndexOutOfBoundsException is thrown. * * @param i * the index of the child node to replace. * @param aNode * the node to replace the ith node. * @throws ArrayIndexOutOfBoundsException * if (index < 0 || index >= length). */ public void set(int i, ASNode aNode) { if (aNode != null && children != null) { if (i < 0 || i >= children.length) throw new ArrayIndexOutOfBoundsException(i); aNode.parent = this; children[i] = aNode; } } /** * Adds a node to the array of children. If the node is null then it is * ignored. * * @param aNode * the node to be added. */ public void add(ASNode aNode) { if (aNode != null) { aNode.parent = this; if (children == null) { children = new ASNode[1]; } else { ASNode c[] = new ASNode[children.length + 1]; System.arraycopy(children, 0, c, 0, children.length); children = c; } children[children.length - 1] = aNode; } } /** * Inserts a node at position i in the array of children. The size of the * array is increased by one and the nodes from the insertion point onwards * are moved to the right. * * If the position is outside the range of the array (i< 0 || i >= length) * then an ArrayIndexOutOfBoundsException is thrown. * * @param index * the index of the child node to replace. * @param aNode * the node to replace the ith node. * @throws ArrayIndexOutOfBoundsException * if (index < 0 || index >= length). */ public void insert(int index, ASNode aNode) { if (children == null || index < 0 || index >= children.length) throw new ArrayIndexOutOfBoundsException(index); aNode.parent = this; ASNode c[] = new ASNode[children.length + 1]; for (int i = 0; i < index; i++) c[i] = children[i]; c[index] = aNode; for (int i = index; i < children.length; i++) c[i + 1] = children[i]; children = c; } /** * Removes the node at position i in the array of children. The size of the * array is decreased by one and the nodes from the insertion point onwards * are moved to the left. * * If the position is outside the range of the array (i< 0 || i >= length) * then an ArrayIndexOutOfBoundsException is thrown. * * @param index * the index of the child node to remove. * @throws ArrayIndexOutOfBoundsException * if (index < 0 || index >= length). */ public void remove(int index) { if (children == null || index < 0 || index >= children.length) throw new ArrayIndexOutOfBoundsException(index); children[index].parent = null; children[index] = null; ASNode c[] = new ASNode[children.length - 1]; for (int i = 0, j = 0; i < children.length; i++) { if (children[i] != null) c[j++] = children[i]; } children = c; } /** * Returns the index position of a node in the array of child nodes. If the * node is not one of the current nodes children then -1 is returned. * * @param aNode * the node to search the array of children for. * * @return the index of the node in the array of children, -1 if the node is * not a child of this node. */ public int indexOf(ASNode aNode) { int index = -1; for (int i = 0; i < children.length; i++) if (children[i].equals(aNode)) index = i; return index; } /** * Gets the parent node of this one. If no parent is define then null is * returned. * * @return the parent node of this one. */ public ASNode getParent() { return parent; } /** * Return the number of child nodes contained by this node. * * @return the number of child nodes. */ public int count() { return (children == null) ? 0 : children.length; } /** * Returns a string containing the type of node, any associated value and * the number of children. * * @return the string representation of the node. */ @Override public String toString() { String str = nodeNames[type]; if (type == BooleanLiteral) { str = str + " = " + (bValue ? "true" : "false") + "; "; } else if (type == IntegerLiteral) { str = str + " = " + iValue + "; "; } else if (type == DoubleLiteral) { str = str + " = " + dValue + "; "; } else if (type == StringLiteral) { str = str + " = " + sValue + "; "; } else if (type == NullLiteral) { str = str + " = null; "; } else if (sValue != null) { str = str + " = " + sValue + "; "; } return str; } /** * displayTree is used to display the structure of the node tree, with the * root starting at the current node. The prefix argument is used to indent * the text displayed. The level of indent is increased by appending the * string " " before calling the displayTree method on each child node. * This illustrates the tree structure with nodes at the same level in the * tree displayed with the same level of indent. * * @param prefix * the string prepended to the text representation for this node. */ public void displayTree(String prefix) { int count = count(); System.out.println(prefix + toString()); for (int i = 0; i < count; i++) children[i].displayTree(prefix + " "); } /* * Translates the array of nodes into the actions that will be executed by * the Flash Player. The version of Flash for which the actions are * generated is specified to ensure compatibility with future release of * Flash. IMPORTANT: The programming model changed with Flash version 5 to * support stack-based actions. Earlier versions of Flash are not support. * An IllegalArgumentException will be thrown if the version is earlier than * 5. * @param version the version of Flash that control the actions that are * generated. * @param encoding the character set used to represent the strings parsed in * the script. */ public List<Action> compile(ASContext info) { ArrayList<Action> array = new ArrayList<Action>(); reorder(info); findStrings(info); if (type == Array || type == Button || type == MovieClip) { generateScript(info, array); } return array; } private void generateScript(ASContext info, List<Action> list) { int count = count(); switch (type) { case Array: if (type == Array && info.useStrings) list.add(new Table(info.strings)); for (int i = 0; i < count; i++) children[i].discardValues(); for (int i = 0; i < count; i++) children[i].generate(info, list); list.add(BasicAction.END); break; case Button: case MovieClip: for (int i = 0; i < count; i++) ((ASEventNode)children[i]).generateEvent(info, list); break; default: break; } } /* * reorder is used to restructure the node tree and individual nodes to * simplify the generation of the action objects that represent the * 'compiled' version of an ActionScript program. */ private void reorder(ASContext info) { switch (type) { case Array: case Button: case MovieClip: info.nodes.push(this); break; case Identifier: if (constants.containsKey(sValue)) { type = Identifier; Object value = constants.get(sValue); if (value != null && value instanceof String) { type = StringLiteral; sValue = value.toString(); } } break; case Value: if (children[0].type == Identifier && children[1].type == Attribute) { String name = children[0].sValue + "." + children[1].sValue; if (constants.containsKey(name)) { type = Identifier; sValue = name; remove(0); remove(0); } } break; case Assign: if (parent != null && parent.type == List && parent.count() > 0) { if (parent.children[0].count() > 0) { if (parent.children[0].children[0].type == DefineVariable) { if (parent.indexOf(this) != 0) children[0].type = DefineVariable; } } } break; case DefineFunction: ASNode node = info.nodes.peek(); node.insert(node.insertIndex++, this); int index = parent.indexOf(this); if (index != -1) parent.remove(index); info.nodes.push(this); break; case Function: if (sValue.equals("fscommand")) { if (children[0].type == StringLiteral) children[0].sValue = "FSCommand:" + children[0].sValue; } else if (sValue.equals("print")) { ASNode c0 = children[0]; ASNode c1 = children[1]; if (children[1].sValue.equals("bmovie")) children[1].sValue = "print:"; else children[1].sValue = "print:#" + children[1].sValue; children[0] = c1; children[1] = c0; } else if (sValue.equals("printNum")) { if (children[0].type == IntegerLiteral) { children[0].type = StringLiteral; children[0].setStringValue("_level" + children[0].iValue); } if (children[1].sValue.equals("bmovie")) { children[1].sValue = "print:"; } else { children[1].sValue = "print:#" + children[1].sValue; } } else if (sValue.equals("printAsBitmap")) { ASNode c0 = children[0]; ASNode c1 = children[1]; if (children[1].sValue.equals("bmovie")) children[1].sValue = "printasbitmap:"; else children[1].sValue = "printasbitmap:#" + children[1].sValue; children[0] = c1; children[1] = c0; } else if (sValue.equals("printAsBitmapNum")) { if (children[0].type == IntegerLiteral) { children[0].type = StringLiteral; children[0].setStringValue("_level" + children[0].iValue); } if (children[1].sValue.equals("bmovie")) children[1].sValue = "printasbitmap:"; else children[1].sValue = "printasbitmap:#" + children[1].sValue; } break; } /* * reorder any child nodes before reordering any binary operators to * ensure any interger literals are evaluated first. */ int count = count(); for (int i = 0; i < count; i++) children[i].reorder(info); switch (type) { case Array: case Add: case Sub: case Mul: case Div: case Mod: if (count() == 2) { if (children[0].getType() == IntegerLiteral && children[1].getType() == IntegerLiteral) { switch (type) { case Add: type = IntegerLiteral; iValue = children[0].iValue + children[1].iValue; break; case Sub: type = IntegerLiteral; iValue = children[0].iValue - children[1].iValue; break; case Mul: type = IntegerLiteral; iValue = children[0].iValue * children[1].iValue; break; case Div: if (children[0].iValue / children[1].iValue == 0) { type = DoubleLiteral; dValue = ((double) children[0].iValue) / ((double) children[1].iValue); } else if (children[0].iValue % children[1].iValue != 0) { type = DoubleLiteral; dValue = ((double) children[0].iValue) / ((double) children[1].iValue); } else { type = IntegerLiteral; iValue = children[0].iValue / children[1].iValue; } break; case Mod: type = IntegerLiteral; iValue = children[0].iValue % children[1].iValue; break; } remove(0); remove(0); } else if (children[0].getType() == DoubleLiteral && children[1].getType() == IntegerLiteral) { switch (type) { case Add: dValue = children[0].dValue + children[1].iValue; break; case Sub: dValue = children[0].dValue - children[1].iValue; break; case Mul: dValue = children[0].dValue * children[1].iValue; break; case Div: dValue = children[0].dValue / children[1].iValue; break; case Mod: dValue = children[0].dValue % children[1].iValue; break; } type = DoubleLiteral; remove(0); remove(0); } else if (children[0].getType() == IntegerLiteral && children[1].getType() == DoubleLiteral) { switch (type) { case Add: dValue = children[0].iValue + children[1].dValue; break; case Sub: dValue = children[0].iValue - children[1].dValue; break; case Mul: dValue = children[0].iValue * children[1].dValue; break; case Div: dValue = children[0].iValue / children[1].dValue; break; case Mod: dValue = children[0].iValue % children[1].dValue; break; } type = DoubleLiteral; remove(0); remove(0); } else if (children[0].getType() == DoubleLiteral && children[1].getType() == DoubleLiteral) { switch (type) { case Add: dValue = children[0].dValue + children[1].dValue; break; case Sub: dValue = children[0].dValue - children[1].dValue; break; case Mul: dValue = children[0].dValue * children[1].dValue; break; case Div: dValue = children[0].dValue / children[1].dValue; break; case Mod: dValue = children[0].dValue % children[1].dValue; break; } type = DoubleLiteral; remove(0); remove(0); } else if (children[0].getType() == StringLiteral || children[1].getType() == StringLiteral) { String aValue = null; String bValue = null; switch (type) { case Add: if (children[0].getType() == StringLiteral) { aValue = children[0].sValue; } else if (children[0].getType() == IntegerLiteral) { aValue = String.valueOf(children[0].iValue); } if (children[1].getType() == StringLiteral) { bValue = children[1].sValue; } else if (children[1].getType() == IntegerLiteral) { bValue = String.valueOf(children[1].iValue); } break; } if (aValue != null && bValue != null) { sValue = aValue + bValue; type = StringLiteral; remove(0); remove(0); } } } break; case ASR: case LSL: case LSR: case BitAnd: case BitOr: case BitXOr: if (count() == 2) { if (children[0].getType() == IntegerLiteral && children[1].getType() == IntegerLiteral) { switch (type) { case ASR: iValue = children[0].iValue >> children[1].iValue; break; case LSL: iValue = children[0].iValue << children[1].iValue; break; case LSR: iValue = children[0].iValue >>> children[1].iValue; break; case BitAnd: iValue = children[0].iValue & children[1].iValue; break; case BitOr: iValue = children[0].iValue | children[1].iValue; break; case BitXOr: iValue = children[0].iValue ^ children[1].iValue; break; } type = IntegerLiteral; remove(0); remove(0); } } break; case And: case LogicalAnd: if (count() == 2) { // if (children[0].getType() == IntegerLiteral) { // children[0].type = BooleanLiteral; // children[0].bValue = children[0].iValue != 0; // children[0].iValue = 0; // } // if (children[1].getType() == IntegerLiteral) { // children[1].type = BooleanLiteral; // children[1].bValue = children[1].iValue != 0; // children[1].iValue = 0; // } // if (children[0].getType() == DoubleLiteral) { // children[0].type = BooleanLiteral; // children[0].bValue = children[0].dValue != 0.0; // children[0].dValue = 0.0; // } // if (children[1].getType() == DoubleLiteral) { // children[1].type = BooleanLiteral; // children[1].bValue = children[1].dValue != 0; // children[1].dValue = 0.0; // } if (children[0].getType() == BooleanLiteral && children[1].getType() == BooleanLiteral) { switch (type) { case LogicalAnd: case And: type = BooleanLiteral; bValue = children[0].bValue && children[1].bValue; break; } remove(0); remove(0); } else if (children[0].getType() == BooleanLiteral && children[1].getType() == IntegerLiteral) { switch (type) { case And: case LogicalAnd: type = BooleanLiteral; bValue = children[0].bValue && (children[1].iValue != 0); break; } remove(0); remove(0); } else if (children[0].getType() == IntegerLiteral && children[1].getType() == BooleanLiteral) { switch (type) { case LogicalAnd: case And: type = BooleanLiteral; bValue = (children[0].iValue != 0) && children[1].bValue; break; } remove(0); remove(0); } else if (children[0].getType() == IntegerLiteral && children[1].getType() == IntegerLiteral) { boolean a = children[0].iValue != 0; boolean b = children[1].iValue != 0; switch (type) { case LogicalAnd: case And: type = IntegerLiteral; iValue = a ? children[1].iValue : 0; break; } remove(0); remove(0); } } break; case Or: case LogicalOr: if (count() == 2) { if (children[0].getType() == BooleanLiteral && children[1].getType() == BooleanLiteral) { switch (type) { case LogicalOr: case Or: type = BooleanLiteral; bValue = children[0].bValue || children[1].bValue; break; } remove(0); remove(0); } else if (children[0].getType() == BooleanLiteral && children[1].getType() == IntegerLiteral) { switch (type) { case LogicalOr: case Or: type = IntegerLiteral; iValue = children[1].iValue; break; } remove(0); remove(0); } else if (children[0].getType() == IntegerLiteral && children[1].getType() == BooleanLiteral) { switch (type) { case LogicalOr: case Or: type = IntegerLiteral; iValue = ((children[0].iValue != 0) || children[1].bValue) ? 1 : 0; break; } remove(0); remove(0); } else if (children[0].getType() == IntegerLiteral && children[1].getType() == IntegerLiteral) { boolean a = children[0].iValue != 0; boolean b = children[1].iValue != 0; switch (type) { case LogicalOr: case Or: type = IntegerLiteral; iValue = a || b ? 1 : 0; break; } remove(0); remove(0); } } break; case Not: if (count() == 1) { if (children[0].getType() == BooleanLiteral) { type = BooleanLiteral; bValue = !children[0].bValue; remove(0); } else if (children[0].getType() == IntegerLiteral) { type = BooleanLiteral; bValue = children[0].iValue == 0; remove(0); } } break; case BitNot: if (count() == 1) { if (children[0].getType() == IntegerLiteral) { type = IntegerLiteral; iValue = ~children[0].iValue; remove(0); } } break; default: break; } switch (type) { case Array: case Button: case MovieClip: case DefineFunction: info.nodes.pop(); break; default: break; } } /* * findStrings is used to generate a table of string literals so rather than * pushing a string directly onto the Flash Player's stack an index into the * table is used instead. This reduces the encoded file size if the string * is used more than once. * @param info is an ASContext object that passes context information between * nodes. */ private void findStrings(ASContext info) { int count = count(); if (type == Function) info.context.push(sValue); else info.context.push(nodeNames[type]); switch (type) { // case On: // case OnClipEvent: // info.clearStrings(); // for (int i = 0; i < count; i++) // children[i].findStrings(info); // break; case StringLiteral: sValue = sValue.replaceAll("\\\\n", "\n"); sValue = sValue.replaceAll("\\\\t", "\t"); sValue = sValue.replaceAll("\\\\b", "\b"); sValue = sValue.replaceAll("\\\\r", "\r"); sValue = sValue.replaceAll("\\\\f", "\f"); info.addString(sValue); break; case Identifier: if (constants.containsKey(sValue)) break; else if (propertyNames.containsKey(sValue)) { if (info.context.contains("getProperty")) break; else if (info.context.contains("setProperty")) break; else if (info.context.contains("With")) info.addString(sValue); else if (info.context.contains("Define Object")) info.addString(sValue); else info.addString(""); break; } info.addString(sValue); break; case DefineVariable: info.addString(sValue); break; case Attribute: case Method: case NewObject: for (int i = count - 1; i >= 0; i--) children[i].findStrings(info); if (sValue.length() > 0) info.addString(sValue); break; case Function: if (sValue != null && functions.containsKey(sValue.toLowerCase()) == false) { for (int i = 0; i < count; i++) children[i].findStrings(info); if (sValue.length() > 0) info.addString(sValue); } else { if (sValue != null && sValue.toLowerCase().equals("fscommand")) { info.addString("FSCommand:"); for (int i = 0; i < count; i++) children[i].findStrings(info); } else if (sValue != null && sValue.toLowerCase().equals("getURL")) { if (count > 0) children[0].findStrings(info); if (count > 1) children[1].findStrings(info); if (count == 1 && children[0].type != StringLiteral) info.addString(""); break; } else if (sValue != null && sValue.toLowerCase().equals("gotoAndPlay")) { if (count == 1) children[0].findStrings(info); else if (count == 2) children[1].findStrings(info); break; } else if (sValue != null && sValue.toLowerCase().equals("gotoAndStop")) { if (count == 1) children[0].findStrings(info); else if (count == 2) children[1].findStrings(info); break; } else if (sValue != null && sValue.toLowerCase().equals("loadMovie")) { if (count > 0) children[0].findStrings(info); if (count > 1) children[1].findStrings(info); if (count == 1) info.addString(""); break; } else if (sValue != null && sValue.toLowerCase().equals("loadVariables")) { if (count > 0) children[0].findStrings(info); if (count > 1) children[1].findStrings(info); if (count == 1) info.addString(""); break; } else if (sValue != null && sValue.toLowerCase().equals("printNum")) { children[1].findStrings(info); if (children[0].type == Identifier) info.addString("_level"); children[0].findStrings(info); } else if (sValue != null && sValue.toLowerCase().equals("printAsBitmapNum")) { children[1].findStrings(info); if (children[0].type == Identifier) info.addString("_level"); children[0].findStrings(info); } else { for (int i = 0; i < count; i++) children[i].findStrings(info); } } break; case DefineMethod: children[count - 1].findStrings(info); break; case DefineFunction: if (sValue != null && sValue.equals("ifFrameLoaded")) { if (children[0].count() == 0) { children[0].findStrings(info); } else if (children[0].count() == 2) { children[0].children[1].findStrings(info); } } children[count - 1].findStrings(info); break; case DefineArray: for (int i = count - 1; i >= 0; i--) children[i].findStrings(info); break; case Value: if (count > 0) { if (children[0].sValue != null && classes.containsKey(children[0].sValue)) { boolean containsClass = false; for (Iterator<String> i = info.strings.iterator(); i .hasNext();) { if (i.next().toString().equals(children[0].sValue)) { containsClass = true; break; } } // Swap the name of the function and the class to // simplify verification during testing. if (containsClass == false) { int index = info.strings.size(); for (int i = 0; i < count; i++) children[i].findStrings(info); info.strings.set(index, info.strings.get(index + 1)); info.strings.set(index + 1, children[0].sValue); } else { for (int i = 0; i < count; i++) children[i].findStrings(info); } } else { for (int i = 0; i < count; i++) children[i].findStrings(info); } } break; default: for (int i = 0; i < count; i++) children[i].findStrings(info); break; } info.context.pop(); } /* * generate 'compiles' ActionScript statements that this node and all child * nodes represent into the set of actions that will be executed by the * Flash Player. * @param info an ASContext object that is used to pass context and context * information between nodes. This should be the same object used when * preprocessing modes. * @param actions an array that the compiled actions will be added to. */ protected void generate(ASContext info, List<Action> actions) { if (type == Function) info.context.push(sValue); else info.context.push(nodeNames[type]); switch (type) { case Array: case Button: case MovieClip: //generateScript(info, actions); break; case StatementList: case List: generateList(info, actions); break; case If: generateIf(info, actions); break; case Do: generateDo(info, actions); break; case While: generateWhile(info, actions); break; case For: generateFor(info, actions); break; case ForIn: generateForIn(info, actions); break; case With: generateWith(info, actions); break; case Switch: generateSwitch(info, actions); break; case Label: generateLabel(info, actions); break; case Exception: generateException(info, actions); break; case Try: case Catch: case Finally: generateClauses(info, actions); break; // case OnClipEvent: // generateOnClipEvent(info, actions); // break; // case On: // generateOn(info, actions); // break; case Break: case Continue: case Return: generateReturn(info, actions); break; case Value: case BooleanLiteral: case IntegerLiteral: case DoubleLiteral: case StringLiteral: case NullLiteral: case Identifier: case Attribute: case Method: case NewObject: case Subscript: generateValue(info, actions); break; case Function: generateFunction(actions, info, sValue); break; case DefineArray: case DefineObject: case DefineFunction: case DefineMethod: case DefineAttribute: case DefineVariable: generateDefinition(info, actions); break; case PreInc: case PreDec: case PostInc: case PostDec: case Plus: case Minus: case Not: case BitNot: case Delete: case Throw: generateUnary(info, actions); break; case StringAdd: case Add: case Sub: case Mul: case Div: case Mod: case BitAnd: case BitOr: case BitXOr: case LSL: case LSR: case ASR: case Equal: case NotEqual: case LessThan: case GreaterThan: case LessThanEqual: case GreaterThanEqual: case StringEqual: case StringNotEqual: case StringGreaterThan: case StringLessThanEqual: case StringGreaterThanEqual: case And: case Or: case LogicalAnd: case LogicalOr: case InstanceOf: case StrictEqual: case StrictNotEqual: generateBinary(info, actions); break; case Select: generateSelect(info, actions); break; case Assign: case AssignAdd: case AssignSub: case AssignMul: case AssignDiv: case AssignMod: case AssignBitAnd: case AssignBitOr: case AssignBitXOr: case AssignLSL: case AssignLSR: case AssignASR: generateAssignment(info, actions); break; default: break; } info.context.pop(); } private void generateList(ASContext info, List<Action> actions) { int count = count(); for (int i = 0; i < count; i++) children[i].generate(info, actions); } private void generateIf(ASContext info, List<Action> actions) { int count = count(); boolean addJump = false; List<Action> trueActions = new ArrayList<Action>(); int offsetToNext = 0; List<Action> falseActions = new ArrayList<Action>(); int offsetToEnd = 0; if (count > 1) { children[1].discardValues(); children[1].generate(info, trueActions); offsetToNext = actionLength(trueActions, info); } if (count == 3) { children[2].discardValues(); children[2].generate(info, falseActions); offsetToEnd = actionLength(falseActions, info); addJump = offsetToEnd != 0; } if (trueActions.size() > 0) { SWFEncodeable action = (trueActions.get(trueActions.size() - 1)); if (action instanceof ActionObject) { ActionObject actionObj = (ActionObject) action; if (actionObj.getType() == 256 || actionObj.getType() == 257) { addJump = true; if (falseActions.size() == 0) offsetToNext -= 5; } } } // Special case if (count == 3 && trueActions.isEmpty() && falseActions.isEmpty()) { trueActions.add(new Jump(0)); offsetToNext = 0; addJump = true; } if (addJump) offsetToNext += 5; // Length of jump tag children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); actions.add(new If(offsetToNext)); actions.addAll(trueActions); if (addJump == true && offsetToEnd > 0) actions.add(new Jump(offsetToEnd)); actions.addAll(falseActions); } private void generateDo(ASContext info, List<Action> actions) { ArrayList<Action> blockActions = new ArrayList<Action>(); int blockLength = 0; ArrayList<Action> conditionActions = new ArrayList<Action>(); int conditionLength = 0; children[0].discardValues(); children[0].generate(info, blockActions); children[1].generate(info, conditionActions); blockLength = actionLength(blockActions, info); conditionLength = actionLength(conditionActions, info); conditionLength += 5; // include following if statement conditionActions.add(new If(-(blockLength + conditionLength))); // includes // if int currentLength = 0; // Replace any break and continue place holders with jump statements. for (int i = 0; i < blockActions.size(); i++) { Action currentAction = blockActions.get(i); currentLength += currentAction.prepareToEncode(info); if (currentAction instanceof ActionObject) { ActionObject actionObj = (ActionObject) currentAction; if (actionObj.getType() == 256) { blockActions.set(i, new Jump(blockLength - currentLength + conditionLength)); } if (actionObj.getType() == 257) { blockActions.set(i, new Jump(blockLength - currentLength)); } } } actions.addAll(blockActions); actions.addAll(conditionActions); } private void generateWhile(ASContext info, List<Action> actions) { int count = (children != null) ? children.length : 0; ArrayList<Action> blockActions = new ArrayList<Action>(); int blockLength = 0; ArrayList<Action> conditionActions = new ArrayList<Action>(); int conditionLength = 0; if (count == 2) { children[1].discardValues(); children[1].generate(info, blockActions); } blockLength = actionLength(blockActions, info); children[0].generate(info, conditionActions); conditionActions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); conditionActions.add(new If(blockLength + 5)); // includes loop jump conditionLength = actionLength(conditionActions, info); blockActions.add(new Jump(-(conditionLength + blockLength + 5))); blockLength += 5; int currentLength = conditionLength; // Replace any break and continue place holders with jump statements. for (int i = 0; i < blockActions.size(); i++) { Action currentAction = blockActions.get(i); currentLength += currentAction.prepareToEncode(info); if (currentAction instanceof ActionObject) { ActionObject actionObject = (ActionObject) currentAction; if (actionObject.getType() == 256) blockActions.set(i, new Jump( (blockLength + conditionLength) - currentLength)); if (actionObject.getType() == 257) blockActions.set(i, new Jump(-currentLength)); } } actions.addAll(conditionActions); actions.addAll(blockActions); } private void generateFor(ASContext info, List<Action> actions) { ArrayList<Action> initializeActions = new ArrayList<Action>(); ArrayList<Action> conditionActions = new ArrayList<Action>(); ArrayList<Action> iteratorActions = new ArrayList<Action>(); ArrayList<Action> blockActions = new ArrayList<Action>(); //int initializeLength = 0; int conditionLength = 0; int blockLength = 0; int iteratorLength = 0; if (children[0].type != NoOp) { children[0].generate(info, initializeActions); //initializeLength = actionLength(initializeActions, info); } if (children[1].type != NoOp) { children[1].generate(info, conditionActions); conditionLength = actionLength(conditionActions, info); } if (children[2].type != NoOp) { children[2].discardValues(); children[2].generate(info, iteratorActions); iteratorLength = actionLength(iteratorActions, info); } if (children[3].type != NoOp) { children[3].discardValues(); children[3].generate(info, blockActions); blockLength = actionLength(blockActions, info); } // Add the if test with jump to end if false. Jump include block and // iterator actions plus a jump at the end to go back to the condition // actions if (conditionActions.size() > 0) { Action lastAction = conditionActions .get(conditionActions.size() - 1); if (lastAction instanceof Push) { List<Object> values = ((Push) lastAction).getValues(); int lastIndex = values.size() - 1; Object lastValue = values.get(lastIndex); if (lastValue instanceof Boolean) { if (((Boolean) lastValue).booleanValue()) { values.set(lastIndex, new Boolean(false)); conditionActions.add(new If(blockLength + iteratorLength + 5)); conditionLength += 5; } } else if (lastValue instanceof Integer) { if (((Integer) lastValue).intValue() > 0) { values.set(lastIndex, new Integer(0)); conditionActions.add(new If(blockLength + iteratorLength + 5)); conditionLength += 5; } } else if (lastValue instanceof Double) { if (((Double) lastValue).doubleValue() > 0.0) { values.set(lastIndex, new Double(0)); conditionActions.add(new If(blockLength + iteratorLength + 5)); conditionLength += 5; } } else if (lastValue instanceof String) { if (((String) lastValue).equals("0") == false) { values.set(lastIndex, "0"); conditionActions.add(new If(blockLength + iteratorLength + 5)); conditionLength += 5; } } conditionActions.set(lastIndex, new Push(values)); } else { conditionActions.add(BasicAction .fromInt(ActionTypes.LOGICAL_NOT)); conditionActions.add(new If(blockLength + iteratorLength + 5)); conditionLength += 6; } } // Add the jump to the start of the condition block iteratorLength += 5; iteratorActions.add(new Jump( -(conditionLength + blockLength + iteratorLength))); // Replace any break and continue place holders with jump statements. int currentLength = conditionLength; for (int i = 0; i < blockActions.size(); i++) { Action currentAction = blockActions.get(i); currentLength += currentAction.prepareToEncode(info); if (currentAction instanceof ActionObject) { ActionObject actionObject = (ActionObject) currentAction; if (actionObject.getType() == 256) blockActions.set(i, new Jump( (blockLength + conditionLength) - currentLength + iteratorLength)); if (actionObject.getType() == 257) blockActions.set(i, new Jump( (blockLength + conditionLength) - currentLength)); } } actions.addAll(initializeActions); actions.addAll(conditionActions); actions.addAll(blockActions); actions.addAll(iteratorActions); } private void generateForIn(ASContext info, List<Action> actions) { int count = count(); ArrayList<Action> conditionActions = new ArrayList<Action>(); ArrayList<Action> blockActions = new ArrayList<Action>(); int conditionLength = 0; int blockLength = 0; // Push all the attributes of the specified object onto the stack switch (info.get(Context.VERSION)) { case 5: children[1].generate(info, actions); actions.remove(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.ENUMERATE)); break; case 6: case 7: children[1].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.ENUMERATE_OBJECT)); break; } // Set the enumerator variable with the current attribute addReference(blockActions, info, children[0].sValue); addLiteral(blockActions, new RegisterIndex(0)); blockActions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); // Translate the body of the for..in statement if (count == 3) { children[2].discardValues(); children[2].generate(info, blockActions); } // Calculate the length of the block in bytes blockLength = actionLength(blockActions, info); // Translate the clause of the for..in statement conditionActions.add(new RegisterCopy(0)); addLiteral(conditionActions, Null.getInstance()); conditionActions.add(BasicAction.fromInt(ActionTypes.EQUALS)); conditionActions.add(new If(blockLength + 5)); // includes loop jump // Calculate the length of the condition actions in bytes conditionLength = actionLength(conditionActions, info); // Add the jump to the start of the condition block blockActions.add(new Jump(-(conditionLength + blockLength + 5))); blockLength += 5; // Replace any break and continue place holders with jump statements. int currentLength = conditionLength; for (int i = 0; i < blockActions.size(); i++) { Action currentAction = blockActions.get(i); currentLength += currentAction.prepareToEncode(info); if (currentAction instanceof ActionObject) { ActionObject actionObject = (ActionObject) currentAction; if (actionObject.getType() == 256) blockActions.set(i, new Jump(blockLength - currentLength)); if (actionObject.getType() == 257) blockActions.set(i, new Jump( -(conditionLength + currentLength))); } } actions.addAll(conditionActions); actions.addAll(blockActions); } private void generateWith(ASContext info, List<Action> actions) { ArrayList<Action> array = new ArrayList<Action>(); int count = count(); for (int i = 1; i < count; i++) children[i].discardValues(); for (int i = 1; i < count; i++) children[i].generate(info, array); children[0].generate(info, actions); actions.add(new With(array)); } @SuppressWarnings("unchecked") private void generateSwitch(ASContext info, List<Action> actions) { int count = count(); int listCount = 0; int labelCount = 0; int defaultIndex = -1; int defaultTarget = -1; for (int i = 0; i < count; i++) { if (children[i].type == ASNode.List) { listCount += 1; } else if (children[i].type == ASNode.Label) { if (children[i].children == null) { defaultIndex = labelCount; defaultTarget = listCount; } labelCount += 1; } } ArrayList<Action> labelArray[] = new ArrayList[labelCount]; int labelLength[] = new int[labelCount]; int labelTarget[] = new int[labelCount]; ArrayList<Action> listArray[] = new ArrayList[listCount]; int listLength[] = new int[listCount]; int offsetToEnd[] = new int[listCount]; int offsetFromStart[] = new int[listCount]; for (int i = 0; i < labelCount; i++) { labelArray[i] = new ArrayList<Action>(); } for (int i = 0; i < listCount; i++) { listArray[i] = new ArrayList<Action>(); offsetToEnd[i] = 0; offsetFromStart[i] = 0; } int listIndex = 0; int labelIndex = 0; for (int i = 0; i < count; i++) { if (children[i].type == ASNode.Label) { if (children[i].children != null) { if (labelIndex == 0) labelArray[labelIndex].add(new RegisterCopy(0)); else addLiteral(labelArray[labelIndex], new RegisterIndex(0)); } children[i].generate(info, labelArray[labelIndex]); labelLength[labelIndex] = actionLength(labelArray[labelIndex], info); labelTarget[labelIndex] = listIndex; labelIndex += 1; } else if (children[i].type == ASNode.List) { children[i].generate(info, listArray[listIndex]); listLength[listIndex] = actionLength(listArray[listIndex], info); listIndex += 1; } } for (int i = listCount - 2; i >= 0; i--) { offsetToEnd[i] = offsetToEnd[i + 1] + listLength[i + 1]; } for (int i = 1; i < listCount; i++) { offsetFromStart[i] = offsetFromStart[i - 1] + listLength[i - 1]; } for (int i = 0; i < labelCount; i++) { labelLength[i] += (i == defaultIndex) ? 0 : 6; } if (defaultIndex != -1) labelLength[defaultIndex] = 5; int index = 0; children[0].generate(info, actions); for (int i = 1; i < count; i++) { if (children[i].type == ASNode.Label) { if (children[i].children != null) { int offset = 0; for (int j = index + 1; j < labelCount; j++) offset += labelLength[j]; actions.addAll(labelArray[index]); actions.add(BasicAction.fromInt(ActionTypes.STRICT_EQUALS)); actions.add(new If(offsetFromStart[labelTarget[index]] + offset)); } else { actions.add(new Jump(offsetFromStart[defaultTarget])); } index += 1; } } for (int i = 0; i < listCount; i++) { Action action = (listArray[i].get(listArray[i].size() - 1)); if (action instanceof ActionObject) { if (((ActionObject) action).getType() == 256) { listArray[i].remove(listArray[i].size() - 1); listArray[i].add(new Jump(offsetToEnd[i])); } } actions.addAll(listArray[i]); } } private void generateLabel(ASContext info, List<Action> actions) { int count = count(); for (int i = 0; i < count; i++) { children[i].generate(info, actions); } } @SuppressWarnings("unchecked") private void generateException(ASContext info, List<Action> actions) { int count = count(); ArrayList<Action> actionArray[] = new ArrayList[count]; for (int i = 0; i < count; i++) children[i].discardValues(); for (int i = 0; i < count; i++) { actionArray[i] = new ArrayList<Action>(); children[i].generate(info, actionArray[i]); } actions.add(new ExceptionHandler(101, actionArray[0], actionArray[1], actionArray[2])); } private void generateClauses(ASContext info, List<Action> actions) { int count = count(); for (int i = 0; i < count; i++) children[i].discardValues(); for (int i = 0; i < count; i++) { children[i].generate(info, actions); } } private void generateReturn(ASContext info, List<Action> actions) { int count = count(); switch (type) { case Break: actions.add(new ActionObject(256, new byte[2])); break; case Continue: actions.add(new ActionObject(257, new byte[2])); break; case Return: if (count == 0) { addLiteral(actions, Void.getInstance()); } else { for (int i = 0; i < count; i++) children[i].generate(info, actions); } actions.add(BasicAction.fromInt(ActionTypes.RETURN)); break; default: break; } } private void generateValue(ASContext info, List<Action> actions) { int count = count(); switch (type) { case Value: /* * If any of the children is a method call then generate the actions * for the method arguments. This ensures that the arguments will be * popped off the stack in the correct order. */ for (int i = count - 1; i >= 0; i--) { if (children[i].type == Function || children[i].type == Method) { ASNode[] grandChildren = children[i].children; if (grandChildren != null) { int numGrandChildren = grandChildren.length; for (int j = numGrandChildren - 1; j >= 0; j--) grandChildren[j].generate(info, actions); addLiteral(actions, numGrandChildren); } else { addLiteral(actions, 0); } } } /* * Now generate the actions for each node that returns a value. Note * that below methods do not generate actions for their children * since the parent node is always a Value. Functions only do so if * the parent node is not a Value. */ children[0].generate(info, actions); for (int i = 1; i < count; i++) { if (children[i].type == Function) { Action last = actions.get(actions.size() - 1); if (last == BasicAction.GET_ATTRIBUTE) { actions.remove(actions.size() - 1); actions.add(BasicAction .fromInt(ActionTypes.EXECUTE_METHOD)); } else { actions.add(BasicAction .fromInt(ActionTypes.EXECUTE_FUNCTION)); } } else children[i].generate(info, actions); } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case BooleanLiteral: addLiteral(actions, new Boolean(bValue)); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case IntegerLiteral: addLiteral(actions, iValue); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case DoubleLiteral: int val = (int) dValue; if (dValue == -0.0) { addLiteral(actions, new Double(dValue)); } else if (val == dValue) { addLiteral(actions, new Integer(val)); } else { addLiteral(actions, new Double(dValue)); } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case StringLiteral: addReference(actions, info, sValue); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case NullLiteral: addLiteral(actions, Null.getInstance()); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Identifier: if (constants.containsKey(sValue)) { if (sValue.equals("undefined")) addLiteral(actions, Void.getInstance()); else addLiteral(actions, constants.get(sValue)); } else if (propertyNames.containsKey(sValue)) { if (info.context.contains("With")) { addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); } else if (info.context.contains("Define Object")) { addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); } else if (info.context.contains("setProperty")) { int pVal = (propertyNames.get(sValue)).intValue(); if (pVal >= 16 && pVal <= 21) addLiteral(actions, new Integer(pVal)); else addLiteral(actions, new Property((earlyPropertyNames .get(sValue)).intValue())); } else { int pVal = (propertyNames.get(sValue)).intValue(); addReference(actions, info, ""); if (pVal >= 0 && pVal <= 21) addLiteral(actions, new Integer(pVal)); else addLiteral(actions, new Property(pVal)); actions.add(BasicAction.fromInt(ActionTypes.GET_PROPERTY)); } } else { addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Attribute: addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_ATTRIBUTE)); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Method: addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_METHOD)); break; case NewObject: for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.NAMED_OBJECT)); break; case Subscript: children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GET_ATTRIBUTE)); break; default: break; } } private void generateDefinition(ASContext info, List<Action> actions) { int count = count(); int last = count - 1; switch (type) { case DefineArray: for (int i = last; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); actions.add(BasicAction.fromInt(ActionTypes.NEW_ARRAY)); break; case DefineObject: for (int i = 0; i < count; i++) children[i].generate(info, actions); addLiteral(actions, count); actions.add(BasicAction.fromInt(ActionTypes.NEW_OBJECT)); break; case DefineFunction: if (sValue.equals("ifFrameLoaded")) { List<Action> array = new ArrayList<Action>(); children[count - 1].discardValues(); children[count - 1].generate(info, array); if (children[0].count() == 0) { children[0].generate(info, actions); } else if (children[0].count() == 2) { children[0].children[1].generate(info, actions); } addLiteral(actions, 0); actions.add(BasicAction.fromInt(ActionTypes.ADD)); actions.add(new WaitForFrame2(array.size())); actions.addAll(array); } else if (sValue.equals("tellTarget")) { actions.add(new SetTarget(children[0].sValue)); children[1].generate(info, actions); actions.add(new SetTarget("")); } else { List<String> functionArguments = new ArrayList<String>(); List<Action> functionActions = new ArrayList<Action>(); if (count() == 2) { if (children[0].type == List) { count = children[0].count(); for (int i = 0; i < count; i++) functionArguments .add(children[0].children[i].sValue); } else { functionArguments.add(children[0].sValue); } } children[last].discardValues(); children[last].generate(info, functionActions); actions.add(new NewFunction(sValue, functionArguments, functionActions)); } break; case DefineMethod: List<String> methodArguments = new ArrayList<String>(); List<Action> methodActions = new ArrayList<Action>(); if (count() == 2) { if (children[0].type == List) { count = children[0].count(); for (int i = 0; i < count; i++) methodArguments.add(children[0].children[i].sValue); } else { methodArguments.add(children[0].sValue); } } children[last].discardValues(); children[last].generate(info, methodActions); actions.add(new NewFunction("", methodArguments, methodActions)); break; case DefineAttribute: children[0].generate(info, actions); actions.remove(actions.size() - 1); children[1].generate(info, actions); break; case DefineVariable: addReference(actions, info, sValue); actions.add(BasicAction.fromInt(ActionTypes.INIT_VARIABLE)); break; default: break; } } private void generateUnary(ASContext info, List<Action> actions) { Action lastAction = null; switch (type) { case PreInc: children[0].generate(info, actions); actions.remove(actions.size() - 1); children[0].generate(info, actions); lastAction = actions.get(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.INCREMENT)); if (discardValue == false) actions.add(new RegisterCopy(0)); if (lastAction == BasicAction.GET_ATTRIBUTE) actions.add(BasicAction.fromInt(ActionTypes.SET_ATTRIBUTE)); else actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); if (discardValue == false) addLiteral(actions, new RegisterIndex(0)); break; case PreDec: children[0].generate(info, actions); actions.remove(actions.size() - 1); children[0].generate(info, actions); lastAction = actions.get(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.DECREMENT)); if (discardValue == false) actions.add(new RegisterCopy(0)); if (lastAction == BasicAction.GET_ATTRIBUTE) actions.add(BasicAction.fromInt(ActionTypes.SET_ATTRIBUTE)); else actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); if (discardValue == false) addLiteral(actions, new RegisterIndex(0)); break; case PostInc: if (discardValue == false) children[0].generate(info, actions); children[0].generate(info, actions); actions.remove(actions.size() - 1); children[0].generate(info, actions); lastAction = actions.get(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.INCREMENT)); if (lastAction == BasicAction.GET_ATTRIBUTE) actions.add(BasicAction.fromInt(ActionTypes.SET_ATTRIBUTE)); else actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); break; case PostDec: if (discardValue == false) children[0].generate(info, actions); children[0].generate(info, actions); actions.remove(actions.size() - 1); children[0].generate(info, actions); lastAction = actions.get(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.DECREMENT)); if (lastAction == BasicAction.GET_ATTRIBUTE) actions.add(BasicAction.fromInt(ActionTypes.SET_ATTRIBUTE)); else actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); break; case Plus: if (children[0].type == BooleanLiteral) { children[0].generate(info, actions); addLiteral(actions, 0); actions.add(BasicAction.fromInt(ActionTypes.ADD)); } else if (children[0].type == IntegerLiteral) { addLiteral(actions, children[0].iValue); } else if (children[0].type == StringLiteral) { children[0].generate(info, actions); addLiteral(actions, 0); actions.add(BasicAction.fromInt(ActionTypes.ADD)); } else if (children[0].type == NullLiteral) { children[0].generate(info, actions); addLiteral(actions, 0); actions.add(BasicAction.fromInt(ActionTypes.ADD)); } else { children[0].generate(info, actions); } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Minus: if (children[0].type == BooleanLiteral) { addLiteral(actions, 0); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); } else if (children[0].type == IntegerLiteral) { if (children[0].iValue == 0) { addLiteral(actions, -0.0); } else { addLiteral(actions, -children[0].iValue); } } else if (children[0].type == StringLiteral) { addLiteral(actions, 0); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); } else if (children[0].type == NullLiteral) { addLiteral(actions, 0); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); } else { addLiteral(actions, 0); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case BitNot: children[0].generate(info, actions); addLiteral(actions, new Double(Double .longBitsToDouble(0x41EFFFFFFFE00000L))); actions.add(BasicAction.fromInt(ActionTypes.BITWISE_XOR)); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Not: children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Delete: children[0].generate(info, actions); actions.remove(actions.size() - 1); if (children[0].type == Value) actions.add(BasicAction.fromInt(ActionTypes.DELETE_VARIABLE)); else actions.add(BasicAction.fromInt(ActionTypes.DELETE)); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); break; case Throw: children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.THROW)); break; default: break; } } private void generateBinary(ASContext info, List<Action> actions) { List<Action> array = new ArrayList<Action>(); int count = count(); int offset = 0; /* * For most node types we want to generate the actions for the child * nodes (if any) before adding the actions for node type. */ switch (type) { // > and <= are synthesised using < and !, see below. case LessThanEqual: case StringLessThanEqual: case StringGreaterThan: for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); break; // Code Logical And/Or generated using if actions, see below. case LogicalAnd: case LogicalOr: case StrictEqual: case StrictNotEqual: case GreaterThan: break; default: for (int i = 0; i < count; i++) children[i].generate(info, actions); break; } switch (type) { case StringAdd: actions.add(BasicAction.fromInt(ActionTypes.STRING_ADD)); break; case StringLessThanEqual: case StringGreaterThanEqual: actions.add(BasicAction.fromInt(ActionTypes.STRING_LESS)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case StringGreaterThan: actions.add(BasicAction.fromInt(ActionTypes.STRING_LESS)); break; case Add: actions.add(BasicAction.fromInt(ActionTypes.ADD)); break; case Sub: actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); break; case Mul: actions.add(BasicAction.fromInt(ActionTypes.MULTIPLY)); break; case Div: actions.add(BasicAction.fromInt(ActionTypes.DIVIDE)); break; case Mod: actions.add(BasicAction.fromInt(ActionTypes.MODULO)); break; case BitAnd: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_AND)); break; case BitOr: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_OR)); break; case BitXOr: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_XOR)); break; case LSL: actions.add(BasicAction.fromInt(ActionTypes.SHIFT_LEFT)); break; case LSR: actions.add(BasicAction.fromInt(ActionTypes.SHIFT_RIGHT)); break; case ASR: actions.add(BasicAction.fromInt(ActionTypes.ARITH_SHIFT_RIGHT)); break; case Equal: actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); break; case NotEqual: actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case LessThan: actions.add(BasicAction.fromInt(ActionTypes.LESS)); break; case GreaterThan: switch (info.get(Context.VERSION)) { case 5: children[1].generate(info, actions); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.LESS)); // // if (parent.type != If) // actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case 6: case 7: children[0].generate(info, actions); children[1].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GREATER)); break; } break; case LessThanEqual: actions.add(BasicAction.fromInt(ActionTypes.LESS)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case GreaterThanEqual: actions.add(BasicAction.fromInt(ActionTypes.LESS)); if (parent.type != If) actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case And: actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_AND)); break; case Or: actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_OR)); break; case LogicalAnd: array.add(BasicAction.fromInt(ActionTypes.POP)); children[1].generate(info, array); offset = actionLength(array, info); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.DUPLICATE)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); actions.add(new If(offset)); actions.addAll(array); break; case LogicalOr: array.add(BasicAction.fromInt(ActionTypes.POP)); children[1].generate(info, array); offset = actionLength(array, info); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.DUPLICATE)); actions.add(new If(offset)); actions.addAll(array); break; case InstanceOf: actions.add(BasicAction.fromInt(ActionTypes.INSTANCEOF)); break; case StrictEqual: switch (info.get(Context.VERSION)) { case 5: children[0].generate(info, actions); actions.add(new RegisterCopy(1)); actions.add(BasicAction.fromInt(ActionTypes.GET_TYPE)); children[1].generate(info, actions); actions.add(new RegisterCopy(2)); actions.add(BasicAction.fromInt(ActionTypes.GET_TYPE)); actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); actions.add(new If(10)); addLiteral(actions, new Boolean(true)); actions.add(new Jump(8)); addLiteral(actions, new RegisterIndex(1)); addLiteral(actions, new RegisterIndex(2)); actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); break; case 6: actions.add(BasicAction.fromInt(ActionTypes.STRICT_EQUALS)); break; } break; case StrictNotEqual: switch (info.get(Context.VERSION)) { case 5: children[0].generate(info, actions); actions.add(new RegisterCopy(1)); actions.add(BasicAction.fromInt(ActionTypes.GET_TYPE)); children[1].generate(info, actions); actions.add(new RegisterCopy(2)); actions.add(BasicAction.fromInt(ActionTypes.GET_TYPE)); actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); actions.add(new If(10)); addLiteral(actions, new Boolean(true)); actions.add(new Jump(8)); addLiteral(actions, new RegisterIndex(1)); addLiteral(actions, new RegisterIndex(2)); actions.add(BasicAction.fromInt(ActionTypes.EQUALS)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; case 6: actions.add(BasicAction.fromInt(ActionTypes.STRICT_EQUALS)); actions.add(BasicAction.fromInt(ActionTypes.LOGICAL_NOT)); break; } break; default: break; } if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); } private void generateSelect(ASContext info, List<Action> actions) { List<Action> trueActions = new ArrayList<Action>(); int offsetToNext = 0; List<Action> falseActions = new ArrayList<Action>(); int offsetToEnd = 0; children[2].generate(info, falseActions); offsetToNext = actionLength(falseActions, info); offsetToNext += 5; // Length of jump tag children[1].generate(info, trueActions); offsetToEnd = actionLength(trueActions, info); children[0].generate(info, actions); actions.add(new If(offsetToNext)); actions.addAll(falseActions); actions.add(new Jump(offsetToEnd)); actions.addAll(trueActions); if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); } private void generateAssignment(ASContext info, List<Action> actions) { children[0].generate(info, actions); Action lastAction = actions.get(actions.size() - 1); if (lastAction == BasicAction.GET_VARIABLE) actions.remove(actions.size() - 1); else if (lastAction == BasicAction.GET_ATTRIBUTE) actions.remove(actions.size() - 1); else if (lastAction == BasicAction.GET_PROPERTY) actions.remove(actions.size() - 1); else if (lastAction == BasicAction.INIT_VARIABLE) actions.remove(actions.size() - 1); if (type != Assign) children[0].generate(info, actions); children[1].generate(info, actions); switch (type) { case AssignAdd: actions.add(BasicAction.fromInt(ActionTypes.ADD)); break; case AssignSub: actions.add(BasicAction.fromInt(ActionTypes.SUBTRACT)); break; case AssignMul: actions.add(BasicAction.fromInt(ActionTypes.MULTIPLY)); break; case AssignDiv: actions.add(BasicAction.fromInt(ActionTypes.DIVIDE)); break; case AssignMod: actions.add(BasicAction.fromInt(ActionTypes.MODULO)); break; case AssignBitAnd: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_AND)); break; case AssignBitOr: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_OR)); break; case AssignBitXOr: actions.add(BasicAction.fromInt(ActionTypes.BITWISE_XOR)); break; case AssignLSL: actions.add(BasicAction.fromInt(ActionTypes.SHIFT_LEFT)); break; case AssignLSR: actions.add(BasicAction.fromInt(ActionTypes.SHIFT_RIGHT)); break; case AssignASR: actions.add(BasicAction.fromInt(ActionTypes.ARITH_SHIFT_RIGHT)); break; default: break; } if (type == Assign && parent != null && (parent.type == List || parent.type == Assign)) { if (children[0].type != DefineVariable) { actions.add(new RegisterCopy(0)); } } if (lastAction == BasicAction.GET_PROPERTY) actions.add(BasicAction.fromInt(ActionTypes.SET_PROPERTY)); else if (lastAction == BasicAction.GET_ATTRIBUTE) actions.add(BasicAction.fromInt(ActionTypes.SET_ATTRIBUTE)); else if (lastAction == BasicAction.GET_VARIABLE) actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); else if (lastAction == BasicAction.INIT_VARIABLE) actions.add(BasicAction.fromInt(ActionTypes.INIT_VARIABLE)); if (type == Assign && parent != null && (parent.type == List || parent.type == Assign)) { if (children[0].type != DefineVariable) { addLiteral(actions, new RegisterIndex(0)); if (parent.type == List) actions.add(BasicAction.fromInt(ActionTypes.POP)); } } } /* * generateFunction is used to add either a predefined action if the * function call is to one of Flash's built-in functions. A separate method * is used to make the code in the generate method more readable. */ private void generateFunction(List<Action> actions, ASContext info, Object value) { String name = (value == null) ? "" : (String) value; int count = count(); if (functions.containsKey(name.toLowerCase())) { if (sValue.toLowerCase().equals("call")) { children[0].generate(info, actions); Action lastAction = actions.get(actions.size() - 1); if (lastAction == BasicAction.GET_VARIABLE) actions.remove(actions.size() - 1); actions.add(Call.getInstance()); } else if (sValue.toLowerCase().equals("chr")) { children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.ASCII_TO_CHAR)); } else if (sValue.toLowerCase().equals("delete")) { children[0].generate(info, actions); Action lastAction = actions.get(actions.size() - 1); if (lastAction == BasicAction.GET_VARIABLE) actions.remove(actions.size() - 1); actions.add(BasicAction.fromInt(ActionTypes.DELETE)); } else if (sValue.toLowerCase().equals("duplicatemovieclip")) { children[0].generate(info, actions); children[1].generate(info, actions); if (children[2].type == IntegerLiteral && children[2].sValue == null) { int level = 16384; level += children[2].iValue; addLiteral(actions, level); } else { addLiteral(actions, 16384); children[2].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.ADD)); } actions.add(BasicAction.fromInt(ActionTypes.CLONE_SPRITE)); } else if (sValue.toLowerCase().equals("eval")) { children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); } else if (sValue.toLowerCase().equals("fscommand")) { boolean isCommandString = children[0].type == StringLiteral && children[0].sValue != null; boolean isArgumentString = false; if (count == 1) { isArgumentString = true; } if (count > 1) { isArgumentString = children[1].type == StringLiteral && children[1].sValue != null; } if (isCommandString && isArgumentString) { String url = children[0].sValue; String target; if (count == 1) { target = ""; } else { target = children[1].sValue; } actions.add(new GetUrl(url, target)); } else { if (isCommandString) { addReference(actions, info, children[0].sValue); } else { addReference(actions, info, "FSCommand:"); children[0].generate(info, actions); actions .add(BasicAction .fromInt(ActionTypes.STRING_ADD)); } if (count > 1) { children[1].generate(info, actions); } actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } } else if (sValue.toLowerCase().equals("getproperty")) { String propertyName = children[1].sValue; int pVal = (propertyNames.get(propertyName)).intValue(); children[0].generate(info, actions); if (pVal >= 1 && pVal <= 21) addLiteral(actions, new Integer(pVal)); else if (pVal == 0) addLiteral(actions, new Double(pVal)); else addLiteral(actions, new Property(pVal)); actions.add(BasicAction.fromInt(ActionTypes.GET_PROPERTY)); } else if (sValue.toLowerCase().equals("gettimer")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GET_TIME)); } else if (sValue.toLowerCase().equals("geturl")) { switch (count) { case 1: if (children[0].type == StringLiteral && children[0].sValue != null) { actions.add(new GetUrl(children[0].sValue, "")); } else { children[0].generate(info, actions); addReference(actions, info, ""); actions .add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } break; case 2: if (children[0].type == StringLiteral && children[0].sValue != null && children[1].type == StringLiteral && children[1].sValue != null) { actions.add(new GetUrl(children[0].sValue, children[1].sValue)); } else { children[0].generate(info, actions); children[1].generate(info, actions); actions .add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } break; case 3: children[0].generate(info, actions); children[1].generate(info, actions); if (children[2].sValue.toLowerCase().equals("get")) actions.add(new GetUrl2( GetUrl2.Request.MOVIE_TO_LEVEL_WITH_GET)); else if (children[2].sValue.toLowerCase().equals("post")) actions.add(new GetUrl2( GetUrl2.Request.MOVIE_TO_LEVEL_WITH_POST)); else actions .add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); break; default: break; } } else if (sValue.toLowerCase().equals("getversion")) { addLiteral(actions, "/:$version"); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); } else if (sValue.toLowerCase().equals("gotoandplay")) { int index = count - 1; if (info.context.firstElement().toString().equals("MovieClip")) { if (children[index].sValue == null) { int frameNumber = children[index].iValue - 1; actions.add(new GotoFrame(frameNumber)); } else { actions.add(new GotoLabel(children[index].sValue)); } actions.add(BasicAction.fromInt(ActionTypes.PLAY)); } else { if (children[index].sValue == null) { int frameNumber = children[index].iValue - 1; actions.add(new GotoFrame(frameNumber)); actions.add(BasicAction.fromInt(ActionTypes.PLAY)); } else if (children[index].sValue.toLowerCase().startsWith( "frame ")) { String frame = children[index].sValue.substring(6); int frameNumber = 0; try { frameNumber = Integer.valueOf(frame).intValue() - 1; } catch (NumberFormatException e) { } if (frameNumber == 1) { children[index].generate(info, actions); actions.add(new GotoFrame2(0, true)); } else { actions.add(new GotoLabel(children[index].sValue)); actions.add(BasicAction.fromInt(ActionTypes.PLAY)); } } else { children[index].generate(info, actions); actions.add(new GotoFrame2(0, true)); } } } else if (sValue.toLowerCase().equals("gotoandstop")) { int index = count - 1; if (info.context.firstElement().toString().equals("MovieClip")) { if (children[index].sValue == null) { int frameNumber = children[index].iValue - 1; actions.add(new GotoFrame(frameNumber)); } else { actions.add(new GotoLabel(children[index].sValue)); } } else { if (children[index].sValue == null) { int frameNumber = children[index].iValue - 1; actions.add(new GotoFrame(frameNumber)); } else if (children[index].sValue.toLowerCase().startsWith( "frame ")) { String frame = children[index].sValue.substring(6); int frameNumber = 0; try { frameNumber = Integer.valueOf(frame).intValue() - 1; } catch (NumberFormatException e) { } if (frameNumber == 1) { children[index].generate(info, actions); actions.add(new GotoFrame2(0, false)); } else { actions.add(new GotoLabel(children[index].sValue)); } } else { children[index].generate(info, actions); actions.add(new GotoFrame2(0, false)); } } } else if (sValue.toLowerCase().equals("int")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.TO_INTEGER)); } else if (sValue.toLowerCase().equals("length")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.STRING_LENGTH)); } else if (sValue.toLowerCase().equals("loadmovie")) { switch (count) { case 2: if (children[0].sValue != null && children[1].sValue == null) { String url = children[0].sValue; String target = "_level" + children[1].iValue; actions.add(new GetUrl(url, target)); } else { children[0].generate(info, actions); children[1].generate(info, actions); actions .add(new GetUrl2( GetUrl2.Request.MOVIE_TO_TARGET)); } break; case 3: children[0].generate(info, actions); children[1].generate(info, actions); if (children[2].sValue.toLowerCase().equals("get")) actions.add(new GetUrl2( GetUrl2.Request.MOVIE_TO_TARGET_WITH_GET)); else actions.add(new GetUrl2( GetUrl2.Request.MOVIE_TO_TARGET_WITH_POST)); break; default: break; } } else if (sValue.toLowerCase().equals("loadvariables")) { switch (count) { case 2: children[0].generate(info, actions); children[1].generate(info, actions); actions .add(new GetUrl2( GetUrl2.Request.VARIABLES_TO_TARGET)); break; case 3: children[0].generate(info, actions); children[1].generate(info, actions); if (children[2].sValue.toLowerCase().equals("get")) actions.add(new GetUrl2( GetUrl2.Request.VARIABLES_TO_TARGET_WITH_GET)); else actions.add(new GetUrl2( GetUrl2.Request.VARIABLES_TO_TARGET_WITH_POST)); break; default: break; } } else if (sValue.toLowerCase().equals("mbchr")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.MB_ASCII_TO_CHAR)); } else if (sValue.toLowerCase().equals("mbord")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.MB_CHAR_TO_ASCII)); } else if (sValue.toLowerCase().equals("mbsubstring")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.MB_STRING_EXTRACT)); } else if (sValue.toLowerCase().equals("nextframe")) { actions.add(BasicAction.fromInt(ActionTypes.NEXT_FRAME)); } else if (sValue.toLowerCase().equals("nextscene")) { actions.add(new GotoFrame(0)); } else if (sValue.toLowerCase().equals("number")) { children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.TO_NUMBER)); } else if (sValue.toLowerCase().equals("ord")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.CHAR_TO_ASCII)); } else if (sValue.toLowerCase().equals("parseint")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); addReference(actions, info, name); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_FUNCTION)); } else if (sValue.toLowerCase().equals("play")) { actions.add(BasicAction.fromInt(ActionTypes.PLAY)); } else if (sValue.toLowerCase().equals("prevframe")) { actions.add(BasicAction.fromInt(ActionTypes.PREV_FRAME)); } else if (sValue.toLowerCase().equals("prevscene")) { actions.add(new GotoFrame(0)); } else if (sValue.toLowerCase().equals("print")) { children[0].generate(info, actions); addReference(actions, info, children[1].sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } else if (sValue.toLowerCase().equals("printnum")) { addReference(actions, info, children[1].sValue); if (children[0].type == Identifier) { addReference(actions, info, "_level"); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.STRING_ADD)); } else { children[0].generate(info, actions); } actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } else if (sValue.toLowerCase().equals("printasbitmap")) { children[0].generate(info, actions); addReference(actions, info, children[1].sValue); actions.add(BasicAction.fromInt(ActionTypes.GET_VARIABLE)); actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } else if (sValue.toLowerCase().equals("printasbitmapnum")) { addReference(actions, info, children[1].sValue); if (children[0].type == Identifier) { addReference(actions, info, "_level"); children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.STRING_ADD)); } else { children[0].generate(info, actions); } actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_LEVEL)); } else if (sValue.toLowerCase().equals("random")) { children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.RANDOM_NUMBER)); } else if (sValue.toLowerCase().equals("removemovieclip")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.REMOVE_SPRITE)); } else if (sValue.toLowerCase().equals("set")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SET_VARIABLE)); } else if (sValue.toLowerCase().equals("setproperty")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.SET_PROPERTY)); } else if (sValue.toLowerCase().equals("startdrag")) { if (count > 2) { children[2].generate(info, actions); children[3].generate(info, actions); children[4].generate(info, actions); children[5].generate(info, actions); addLiteral(actions, 1); if (children[1].getType() == BooleanLiteral) { addLiteral(actions, children[1].bValue ? 1 : 0); } else { children[1].generate(info, actions); } } else if (count == 2) { addLiteral(actions, 0); if (children[1].getType() == BooleanLiteral) { addLiteral(actions, children[1].bValue ? 1 : 0); } else { children[1].generate(info, actions); } } else { addLiteral(actions, 0); addLiteral(actions, 0); } children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.START_DRAG)); } else if (sValue.toLowerCase().equals("stop")) { actions.add(BasicAction.fromInt(ActionTypes.STOP)); } else if (sValue.toLowerCase().equals("stopallsounds")) { actions.add(BasicAction.fromInt(ActionTypes.STOP_SOUNDS)); } else if (sValue.toLowerCase().equals("stopdrag")) { actions.add(BasicAction.fromInt(ActionTypes.END_DRAG)); } else if (sValue.toLowerCase().equals("string")) { children[0].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.TO_STRING)); } else if (sValue.toLowerCase().equals("substring")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.STRING_EXTRACT)); } else if (sValue.toLowerCase().equals("targetpath")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GET_TARGET)); } else if (sValue.toLowerCase().equals("togglehighquality")) { actions.add(BasicAction.fromInt(ActionTypes.TOGGLE_QUALITY)); } else if (sValue.toLowerCase().equals("trace")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.TRACE)); } else if (sValue.toLowerCase().equals("typeof")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.GET_TYPE)); } else if (sValue.toLowerCase().equals("unloadmovie")) { if (children[0].sValue == null) { actions.add(new GetUrl("", "_level" + children[0].iValue)); } else { addLiteral(actions, ""); children[0].generate(info, actions); actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_TARGET)); } } else if (sValue.toLowerCase().equals("unloadmovienum")) { if (children[0].sValue == null) { actions.add(new GetUrl("", "_level" + children[0].iValue)); } else { addLiteral(actions, ""); children[0].generate(info, actions); actions.add(new GetUrl2(GetUrl2.Request.MOVIE_TO_TARGET)); } } else if (sValue.toLowerCase().equals("void")) { for (int i = 0; i < count; i++) children[i].generate(info, actions); actions.add(BasicAction.fromInt(ActionTypes.POP)); addLiteral(actions, Void.getInstance()); } else { for (int i = 0; i < count; i++) children[i].generate(info, actions); addReference(actions, info, name); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_FUNCTION)); } if ((functions.get(name.toLowerCase())).booleanValue()) { if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); } } else { if (sValue.toLowerCase().equals("parseint")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); addReference(actions, info, name); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_FUNCTION)); } else if (sValue.toLowerCase().equals("updateafterevent")) { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); addReference(actions, info, name); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_FUNCTION)); } else { for (int i = count - 1; i >= 0; i--) children[i].generate(info, actions); addLiteral(actions, count); addReference(actions, info, name); actions.add(BasicAction.fromInt(ActionTypes.EXECUTE_FUNCTION)); if (valueFunctions.containsKey(name.toLowerCase()) == false) { if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); } } } if (valueFunctions.containsKey(name.toLowerCase())) { if (discardValue) actions.add(BasicAction.fromInt(ActionTypes.POP)); } } private void addReference(List<Action> actions, ASContext info, Object literal) { if (info.useStrings && info.strings.contains(literal)) literal = new TableIndex(info.strings.indexOf(literal)); if (literal instanceof Integer) { int value = ((Integer) literal).intValue(); if (value == 0) literal = new Double(0.0); } if (actions.size() > 0) { int index = actions.size() - 1; Action action = actions.get(index); if (action instanceof Push) { List<Object>values = ((Push) action).getValues(); values.add(literal); actions.set(index, new Push(values)); } else { actions.add(new Push.Builder().add(literal).build()); } } else { actions.add(new Push.Builder().add(literal).build()); } } private void addLiteral(List<Action> actions, int value) { Object number = null; if (value == 0) number = new Double(0.0); else number = new Integer(value); if (actions.size() > 0) { int index = actions.size() - 1; Action action = actions.get(index); if (action instanceof Push) { List<Object>values = ((Push) action).getValues(); values.add(number); actions.set(index, new Push(values)); } else { actions.add(new Push.Builder().add(number).build()); } } else { actions.add(new Push.Builder().add(number).build()); } } private void addLiteral(List<Action> actions, Object literal) { Action action = null; int index = actions.size() - 1; if (literal instanceof Integer) { int value = ((Integer) literal).intValue(); if (value == 0) literal = new Double(0.0); } if (actions.size() > 0) { action = actions.get(index); } if (action instanceof Push) { List<Object>values = ((Push) action).getValues(); values.add(literal); actions.set(index, new Push(values)); } else { actions.add(new Push.Builder().add(literal).build()); } } private int actionLength(List<Action> array, ASContext info) { int length = 0; for (Iterator<Action> i = array.iterator(); i.hasNext();) { Action action = i.next(); length += action.prepareToEncode(info); } return length; } protected void discardValues() { discardValue = true; if (type == List || type == StatementList) { int count = count(); for (int i = 0; i < count; i++) children[i].discardValues(); } } /* * validate is used to provide additional error checking not covered in the * parser grammar. */ public void validate() throws ParseException { boolean reportError = false; int count = count(); ASNode node = this; switch (type) { case Button: /* * Check scripts for button only contain on() statements. */ for (int i = 0; i < count; i++) { if (children[i].type != On) reportError = true; } if (reportError) reportError("OnOnly", number); break; case MovieClip: /* * Check scripts for movie clips only contain onClipEvent() * statements. */ for (int i = 0; i < count; i++) { if (children[i].getType() != OnClipEvent) reportError = true; } if (reportError) reportError("OnClipEventOnly", number); break; case Break: reportError = true; while (node != null) { if (node.type == For || node.type == ForIn || node.type == Do || node.type == While || node.type == Switch) reportError = false; node = node.parent; } if (reportError) reportError("CannotUseBreak", number); break; case Continue: reportError = true; while (node != null) { if (node.type == For || node.type == ForIn || node.type == Do || node.type == While) reportError = false; node = node.parent; } if (reportError) reportError("CannotUseContinue", number); break; case Return: reportError = true; while (node != null) { if (node.type == DefineFunction || node.type == DefineMethod) reportError = false; node = node.parent; } if (reportError) reportError("CannotUseReturn", number); break; case Function: /* * Check the number of arguments are supplied to built in Flash * functions. Some addition checking of attributes is also carried * out on a per function basis. */ if (sValue.toLowerCase().equals("delete")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("duplicatemovieclip")) { if (count != 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("escape")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("eval")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("fscommand")) { if (count < 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("getproperty")) { if (count != 2) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("geturl")) { if (count < 1 || count > 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("getversion")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("gotoandplay")) { if (count < 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("gotoandstop")) { if (count < 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("hittest")) { if (count < 1 || count > 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("isfinite")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("isnan")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("loadmovie")) { if (count < 1 || count > 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("loadvariables")) { if (count < 1 || count > 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("nextframe")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("nextscene")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("number")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("parseint")) { if (count < 1 || count > 2) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("parsefloat")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("play")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("prevframe")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("prevscene")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("print")) { if (count != 2) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("printasbitmap")) { if (count != 2) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("removemovieclip")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("set")) { if (count != 2) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("setproperty")) { if (count != 3) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("startdrag")) { if ((count == 1 || count == 2 || count == 6) == false) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("stop")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("stopallsounds")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("stopdrag")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("string")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("targetpath")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("togglehighquality")) { if (count != 0) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("trace")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("typeof")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("unescape")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("unloadmovie")) { if (count != 1) reportError("IncorrectArgumentCount", number); } else if (sValue.toLowerCase().equals("void")) { if (count != 1) reportError("IncorrectArgumentCount", number); } break; } for (int i = 0; i < count; i++) children[i].validate(); } private void reportError(String errorKey, int number) throws ParseException { ParseException parseError = new ParseException(errorKey); parseError.currentToken = new Token(); parseError.currentToken.beginLine = number; throw parseError; } }
9237036b27ccadffa659f15f8b8a6d389404fb21
140
java
Java
src/main/java/com/slyak/spring/jpa/QueryTemplate.java
SLYAK/spring-data-jpa-extra
34829f0309893873c67fcf1ab5856cc767d55c06
[ "Apache-2.0" ]
418
2016-05-17T00:51:24.000Z
2022-03-30T12:52:06.000Z
src/main/java/com/slyak/spring/jpa/QueryTemplate.java
SLYAK/spring-data-jpa-extra
34829f0309893873c67fcf1ab5856cc767d55c06
[ "Apache-2.0" ]
56
2016-05-19T01:36:04.000Z
2021-12-09T10:23:30.000Z
src/main/java/com/slyak/spring/jpa/QueryTemplate.java
SLYAK/spring-data-jpa-extra
34829f0309893873c67fcf1ab5856cc767d55c06
[ "Apache-2.0" ]
124
2016-05-19T07:27:38.000Z
2022-03-25T03:36:01.000Z
12.727273
32
0.664286
997,912
package com.slyak.spring.jpa; /** * . * * @author stormning on 16/6/5. */ public interface QueryTemplate { String getQueryString(); }
92370378fb5e09a73fd54ec76b6cbf3017196231
1,040
java
Java
impl/src/main/java/fr/brouillard/oss/ee/fault/tolerance/impl/Chains.java
McFoggy/portable-mpft-jee
ddf6d783294bb1ebcc32ab99822447a620a7c45b
[ "Apache-2.0" ]
null
null
null
impl/src/main/java/fr/brouillard/oss/ee/fault/tolerance/impl/Chains.java
McFoggy/portable-mpft-jee
ddf6d783294bb1ebcc32ab99822447a620a7c45b
[ "Apache-2.0" ]
6
2017-11-07T10:01:46.000Z
2017-11-16T08:44:55.000Z
impl/src/main/java/fr/brouillard/oss/ee/fault/tolerance/impl/Chains.java
McFoggy/portable-mpft-jee
ddf6d783294bb1ebcc32ab99822447a620a7c45b
[ "Apache-2.0" ]
null
null
null
36.034483
99
0.732057
997,913
/** * Copyright © 2017 Matthieu Brouillard [http://oss.brouillard.fr/GuardEE] (nnheo@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.brouillard.oss.ee.fault.tolerance.impl; import fr.brouillard.oss.ee.fault.tolerance.timeout.TimeoutInvoker; public class Chains { public static InvokerChain end() { return context -> context.proceed(); } public static InvokerChain decorate(Invoker invoker, InvokerChain chain) { return context -> invoker.invoke(context, chain); } }
92370394246a047c7c19a0283db3c2d502b0059e
441
java
Java
codebase/server/yadaserver/src/main/java/yada/coach/group/Group.java
modianshu/yada
ffb0f5391b245f853b506191ffea859221e7a46c
[ "MIT" ]
1
2016-02-16T12:10:36.000Z
2016-02-16T12:10:36.000Z
codebase/server/yadaserver/src/main/java/yada/coach/group/Group.java
modianshu/yada
ffb0f5391b245f853b506191ffea859221e7a46c
[ "MIT" ]
null
null
null
codebase/server/yadaserver/src/main/java/yada/coach/group/Group.java
modianshu/yada
ffb0f5391b245f853b506191ffea859221e7a46c
[ "MIT" ]
null
null
null
15.206897
49
0.739229
997,914
package yada.coach.group; import org.mongodb.morphia.annotations.Entity; import yada.BaseEntity; @Entity public class Group extends BaseEntity{ private String name, description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
923704ca21c864daa541d1e7c4de066673810a8a
186
java
Java
jacob-core/src/main/java/com/guujiang/jacob/Stub.java
nicerloop/Jacob
df7f4bf4f1fbbcff00f3f98932b85f5ea4a7613c
[ "BSD-3-Clause" ]
null
null
null
jacob-core/src/main/java/com/guujiang/jacob/Stub.java
nicerloop/Jacob
df7f4bf4f1fbbcff00f3f98932b85f5ea4a7613c
[ "BSD-3-Clause" ]
null
null
null
jacob-core/src/main/java/com/guujiang/jacob/Stub.java
nicerloop/Jacob
df7f4bf4f1fbbcff00f3f98932b85f5ea4a7613c
[ "BSD-3-Clause" ]
null
null
null
23.25
86
0.72043
997,915
package com.guujiang.jacob; public class Stub { public static <T> void yield(T val) { throw new IllegalStateException("The generator should be instrumented with agent"); } }
9237050e9fb77aed595d45e4e431213ec6914986
2,774
java
Java
src/edu/rutgers/MOST/presentation/NodeInformationDialog.java
desmondlun/MOST
536b98cb9c8ec5f2f5e5c4682eab025e648a04cf
[ "Unlicense" ]
5
2015-07-16T07:49:58.000Z
2021-05-27T20:27:21.000Z
src/edu/rutgers/MOST/presentation/NodeInformationDialog.java
desmondlun/MOST
536b98cb9c8ec5f2f5e5c4682eab025e648a04cf
[ "Unlicense" ]
3
2015-05-08T22:31:17.000Z
2015-07-17T00:24:27.000Z
src/edu/rutgers/MOST/presentation/NodeInformationDialog.java
desmondlun/MOST
536b98cb9c8ec5f2f5e5c4682eab025e648a04cf
[ "Unlicense" ]
13
2015-05-02T15:42:08.000Z
2021-05-27T20:27:24.000Z
30.822222
105
0.751983
997,916
package edu.rutgers.MOST.presentation; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; public class NodeInformationDialog extends JDialog { private static final long serialVersionUID = 1L; //http://stackoverflow.com/questions/14737810/jlabel-show-longer-text-as-multiple-lines // html can be used to make multi line label. public static JLabel messageLabel = new JLabel(); public static JButton okButton = new JButton("OK"); public JButton copyNodeInfoButton = new JButton("Copy Node Information to Clipboard"); public NodeInformationDialog(String info) { // need to set up box layout setTitle(PathwaysFrameConstants.NODE_INFORMATION_TITLE); //box layout Box vb = Box.createVerticalBox(); Box hbMessageLabel = Box.createHorizontalBox(); Box hbButton = Box.createHorizontalBox(); messageLabel.setText(info); //messageLabel.setSize(new Dimension(150, 10)); //top, left, bottom. right messageLabel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); messageLabel.setAlignmentX(CENTER_ALIGNMENT); JPanel messageLabelPanel = new JPanel(); messageLabelPanel.setLayout(new BoxLayout(messageLabelPanel, BoxLayout.X_AXIS)); messageLabelPanel.add(messageLabel); messageLabelPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); hbMessageLabel.add(messageLabelPanel); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); buttonPanel.add(okButton); JLabel label = new JLabel(" "); buttonPanel.add(label); buttonPanel.add(copyNodeInfoButton); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0,20,20,20)); hbButton.add(buttonPanel); vb.add(hbMessageLabel); vb.add(hbButton); add(vb); ActionListener okButtonActionListener = new ActionListener() { public void actionPerformed(ActionEvent prodActionEvent) { setVisible(false); dispose(); } }; okButton.addActionListener(okButtonActionListener); } public static void main(String[] args) { //based on code from http:stackoverflow.com/questions/6403821/how-to-add-an-image-to-a-jframe-title-bar final ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon("etc/most16.jpg").getImage()); icons.add(new ImageIcon("etc/most32.jpg").getImage()); NodeInformationDialog d = new NodeInformationDialog("test"); d.setIconImages(icons); //d.setSize(360, 180); d.pack(); d.setVisible(true); } }
923706d4ef208f7460a0982c6df5a85466c670c6
2,199
java
Java
app/src/main/java/cc/zkteam/juediqiusheng/api/ZKApi.java
ZhuoKeTeam/JueDiQiuSheng
11b265d7636abc1cd0d66fecdbfa5bb01d231442
[ "BSD-3-Clause" ]
7
2017-11-02T15:01:16.000Z
2019-06-20T12:48:59.000Z
app/src/main/java/cc/zkteam/juediqiusheng/api/ZKApi.java
ZhuoKeTeam/JueDiQiuSheng
11b265d7636abc1cd0d66fecdbfa5bb01d231442
[ "BSD-3-Clause" ]
null
null
null
app/src/main/java/cc/zkteam/juediqiusheng/api/ZKApi.java
ZhuoKeTeam/JueDiQiuSheng
11b265d7636abc1cd0d66fecdbfa5bb01d231442
[ "BSD-3-Clause" ]
8
2017-10-24T12:58:26.000Z
2019-02-11T16:20:19.000Z
26.493976
136
0.671669
997,917
package cc.zkteam.juediqiusheng.api; import java.util.List; import cc.zkteam.juediqiusheng.bean.BannerBean; import cc.zkteam.juediqiusheng.bean.BaseBean; import cc.zkteam.juediqiusheng.bean.CategoryBean; import cc.zkteam.juediqiusheng.bean.PicBean; import cc.zkteam.juediqiusheng.bean.PicCategoryBean; import cc.zkteam.juediqiusheng.bean.RecommendedBean; import cc.zkteam.juediqiusheng.bean.SortDetailBean; import cc.zkteam.juediqiusheng.bean.UpdateBean; import cc.zkteam.juediqiusheng.module.waterfall.ItemBean; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * ZKService retrofit2 * Created by WangQing on 2017/10/27. */ public interface ZKApi { /** * 请求分类接口 * * @return 分类的数据 */ @GET("JueDiQiuSheng/categoryJson") Call<BaseBean<List<CategoryBean>>> categoryData(@Query("pageCount") int count); /** * App 升级 */ @GET("android/versions/dtsyxgl.json") Call<BaseBean<UpdateBean>> update(); /** * 攻略banner */ @GET("JueDiQiuSheng/recommendedItemJson") Call<BaseBean<List<BannerBean>>> getStrategy(@Query("pageCount") int count, @Query("jid") String jid); /** * 图片分类 */ @GET("JueDiQiuSheng/picCategoryJson") Call<BaseBean<List<PicCategoryBean>>> getPicCategory(); /** * 图片分类结果 * @param id * @param count * @return */ @GET("JueDiQiuSheng/picUrlJson") Call<BaseBean<List<PicBean>>> getCategoryList(@Query("jid")String id,@Query("pageCount") int count); /** * 精品推荐 */ @GET("JueDiQiuSheng/recommendedItemJson") Call<BaseBean<List<RecommendedBean>>> getRecommended(@Query("jid") String jId, @Query("pageCount") String pageCount); /** * 分类详情 */ @GET("JueDiQiuSheng/itemJson") Call<BaseBean<List<SortDetailBean>>> itemJson(@Query("jid") String jId, @Query("pageCount") int count, @Query("page") int page); /** * 瀑布流 * @param id * @param count * @param page * @return */ @GET("JueDiQiuSheng/picUrlJson") Call<BaseBean<List<ItemBean>>> getCategoryListByJId(@Query("jid")String id, @Query("pageCount") int count, @Query("page") int page); }
923706ffb7c58591804efa993cedb4fdb50d7380
3,454
java
Java
spring-boot/oidc-client-login-stateless/src/main/java/no/acntech/sandbox/cache/HttpCookieRequestCache.java
acntech/acntech-sandbox
121487377f9077818df7590eb5d3fe1a5fadcf2a
[ "Apache-2.0" ]
1
2019-06-22T16:09:18.000Z
2019-06-22T16:09:18.000Z
spring-boot/oidc-client-login-stateless/src/main/java/no/acntech/sandbox/cache/HttpCookieRequestCache.java
acntech/acntech-sandbox
121487377f9077818df7590eb5d3fe1a5fadcf2a
[ "Apache-2.0" ]
2
2020-12-11T10:58:13.000Z
2022-03-31T18:35:48.000Z
spring-boot/oidc-client-login-stateless/src/main/java/no/acntech/sandbox/cache/HttpCookieRequestCache.java
acntech/acntech-sandbox
121487377f9077818df7590eb5d3fe1a5fadcf2a
[ "Apache-2.0" ]
null
null
null
47.315068
119
0.739143
997,918
package no.acntech.sandbox.cache; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.web.PortResolver; import org.springframework.security.web.PortResolverImpl; import org.springframework.security.web.savedrequest.DefaultSavedRequest; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.security.web.savedrequest.SimpleSavedRequest; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import no.acntech.sandbox.repository.HttpCookieOAuth2AuthorizationRequestRepository; import no.acntech.sandbox.resolver.CookieResolver; public class HttpCookieRequestCache implements RequestCache { private static final Logger LOGGER = LoggerFactory.getLogger(HttpCookieOAuth2AuthorizationRequestRepository.class); private static final RequestMatcher LOGIN_REQUEST_MATCHER = new AntPathRequestMatcher("/**/login/*"); private static final PortResolver PORT_RESOLVER = new PortResolverImpl(); private static final String REDIRECT_URI_PARAM_NAME = "redirect_uri"; private static final CookieResolver SAVED_REQUEST_COOKIE_RESOLVER = CookieResolver.savedRequestCookieResolver(); private static final CookieResolver REDIRECT_URI_COOKIE_RESOLVER = CookieResolver.redirectUriCookieResolver(); @Override public void saveRequest(final HttpServletRequest request, final HttpServletResponse response) { if (LOGIN_REQUEST_MATCHER.matches(request)) { String existingCookieValue = SAVED_REQUEST_COOKIE_RESOLVER.readCookie(request); if (StringUtils.isBlank(existingCookieValue)) { SavedRequest savedRequest = new DefaultSavedRequest(request, PORT_RESOLVER); String cookieValue = CookieResolver.serialize(savedRequest.getRedirectUrl()); SAVED_REQUEST_COOKIE_RESOLVER.addCookie(response, cookieValue); } String redirectUri = request.getParameter(REDIRECT_URI_PARAM_NAME); if (StringUtils.isNotBlank(redirectUri)) { String cookieValue = CookieResolver.serialize(redirectUri); //REDIRECT_URI_COOKIE_RESOLVER.addCookie(response, cookieValue); } } } @Override public SavedRequest getRequest(final HttpServletRequest request, final HttpServletResponse response) { String cookieValue = SAVED_REQUEST_COOKIE_RESOLVER.readCookie(request); if (StringUtils.isNotBlank(cookieValue)) { String redirectUrl = CookieResolver.deserialize(cookieValue, String.class); return new SimpleSavedRequest(redirectUrl); } else { return null; } } @Override public void removeRequest(final HttpServletRequest request, final HttpServletResponse response) { //SAVED_REQUEST_COOKIE_RESOLVER.removeCookie(response); } @Override public HttpServletRequest getMatchingRequest(final HttpServletRequest request, final HttpServletResponse response) { return null; } }
923708c472725bb247da77e8caeee2366a68fb03
1,041
java
Java
centromere-core/src/main/java/org/oncoblocks/centromere/core/model/Model.java
gitter-badger/centromere
839e2dbd62631e884f0d533653679474c6a9268d
[ "Apache-2.0" ]
3
2016-02-10T02:27:59.000Z
2016-02-11T15:20:56.000Z
centromere-core/src/main/java/org/oncoblocks/centromere/core/model/Model.java
gitter-badger/centromere
839e2dbd62631e884f0d533653679474c6a9268d
[ "Apache-2.0" ]
12
2015-09-12T13:13:40.000Z
2016-03-15T17:22:24.000Z
centromere-core/src/main/java/org/oncoblocks/centromere/core/model/Model.java
gitter-badger/centromere
839e2dbd62631e884f0d533653679474c6a9268d
[ "Apache-2.0" ]
null
null
null
32.53125
100
0.742555
997,919
/* * Copyright 2016 William Oemler, Blueprint Medicines * * 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.oncoblocks.centromere.core.model; import java.io.Serializable; /** * Basic entity interface to ensure that model objects have identifiable attributes. {@code ID} is * intended to reflect database primary key identifiers, whether they be primitive types, or a * unique combination of fields. * * @author woemler */ @Filterable public interface Model<ID extends Serializable> { ID getId(); }
92370a62b3b48a39b9425101cc717381cab4527a
6,760
java
Java
basex-core/src/main/java/org/basex/query/func/crypto/Encryption.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
1
2017-03-23T17:41:51.000Z
2017-03-23T17:41:51.000Z
basex-core/src/main/java/org/basex/query/func/crypto/Encryption.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
null
null
null
basex-core/src/main/java/org/basex/query/func/crypto/Encryption.java
LeoWoerteler/basex
1ca5afa69c4d0088e94f40e73f0fbd684ebc38c3
[ "BSD-3-Clause" ]
null
null
null
33.465347
99
0.672633
997,920
package org.basex.query.func.crypto; import static org.basex.query.QueryError.*; import static org.basex.util.Token.*; import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import org.basex.query.*; import org.basex.query.value.item.*; import org.basex.util.*; import org.basex.util.hash.*; /** * This class encrypts and decrypts textual inputs. * * @author BaseX Team 2005-17, BSD License * @author Lukas Kircher */ final class Encryption { /** Input info. */ private final InputInfo info; /** Token. */ private static final byte[] SYM = token("symmetric"); /** Token. */ private static final byte[] BASE64 = token("base64"); /** Token. */ private static final byte[] HEX = token("hex"); /** Supported encryption algorithms, mapped to correct IV lengths. */ private static final TokenMap ALGE = new TokenMap(); /** Exact encryption algorithm JAVA names. */ private static final TokenMap ALGN = new TokenMap(); /** Supported HMAC algorithms. */ private static final TokenMap ALGHMAC = new TokenMap(); /** Default hash algorithm. */ private static final byte[] DEFA = token("md5"); /** DES encryption token. */ private static final byte[] DES = token("des"); static { ALGE.put("des", "8"); ALGE.put("aes", "16"); ALGN.put("des", "DES/CBC/PKCS5Padding"); ALGN.put("aes", "AES/CBC/PKCS5Padding"); ALGHMAC.put("md5", "hmacmd5"); ALGHMAC.put("sha1", "hmacsha1"); ALGHMAC.put("sha256", "hmacsha256"); ALGHMAC.put("sha384", "hmacsha1"); ALGHMAC.put("sha512", "hmacsha512"); } /** * Constructor. * * @param info input info */ Encryption(final InputInfo info) { this.info = info; } /** * Encrypts or decrypts the given input. * @param in input * @param s encryption type * @param k secret key * @param a encryption algorithm * @param ec encrypt or decrypt * @return encrypted or decrypted input * @throws QueryException query exception */ Str encryption(final byte[] in, final byte[] s, final byte[] k, final byte[] a, final boolean ec) throws QueryException { final boolean symmetric = eq(lc(s), SYM) || s.length == 0; final byte[] aa = a.length == 0 ? DES : a; final byte[] tivl = ALGE.get(lc(aa)); if(!symmetric) throw CX_ENCTYP.get(info, ec); if(tivl == null) throw CX_INVALGO.get(info, s); // initialization vector length final int ivl = toInt(tivl); try { return Str.get(ec ? encrypt(in, k, aa, ivl) : decrypt(in, k, aa, ivl)); } catch(final NoSuchPaddingException e) { throw CX_NOPAD.get(info, e); } catch(final BadPaddingException e) { throw CX_BADPAD.get(info, e); } catch(final InvalidKeyException e) { throw CX_KEYINV.get(info, e); } catch(final IllegalBlockSizeException e) { throw CX_ILLBLO.get(info, e); } catch(final GeneralSecurityException e) { throw CX_INVALGO.get(info, e); } } /** * Encrypts the given input data. * * @param in input data to encrypt * @param k key * @param a encryption algorithm * @param ivl initialization vector length * @return encrypted input data * @throws InvalidKeyException ex * @throws InvalidAlgorithmParameterException ex * @throws NoSuchAlgorithmException ex * @throws NoSuchPaddingException ex * @throws IllegalBlockSizeException ex * @throws BadPaddingException ex */ private static byte[] encrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a)))); final SecretKeySpec kspec = new SecretKeySpec(k, string(a)); // generate random iv. random iv is necessary to make the encryption of a // string look different every time it is encrypted. final byte[] iv = new byte[ivl]; // create new random iv if encrypting final SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); rand.nextBytes(iv); final IvParameterSpec ivspec = new IvParameterSpec(iv); // encrypt/decrypt cipher.init(Cipher.ENCRYPT_MODE, kspec, ivspec); final byte[] t = cipher.doFinal(in); // initialization vector is appended to the message for later decryption return concat(iv, t); } /** * Decrypts the given input data. * * @param in data to decrypt * @param k secret key * @param a encryption algorithm * @param ivl initialization vector length * @return decrypted data * @throws NoSuchAlgorithmException ex * @throws NoSuchPaddingException ex * @throws InvalidKeyException ex * @throws InvalidAlgorithmParameterException ex * @throws IllegalBlockSizeException ex * @throws BadPaddingException ex */ private static byte[] decrypt(final byte[] in, final byte[] k, final byte[] a, final int ivl) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { final SecretKeySpec keySpec = new SecretKeySpec(k, string(a)); final Cipher cipher = Cipher.getInstance(string(ALGN.get(lc(a)))); // extract iv from message beginning final byte[] iv = substring(in, 0, ivl); final IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivspec); return cipher.doFinal(substring(in, ivl, in.length)); } /** * Creates a message authentication code (MAC) for the given input. * @param msg input * @param k secret key * @param a encryption algorithm * @param enc encoding * @return MAC * @throws QueryException query exception */ Item hmac(final byte[] msg, final byte[] k, final byte[] a, final byte[] enc) throws QueryException { // create hash value from input message final Key key = new SecretKeySpec(k, string(a)); final byte[] aa = a.length == 0 ? DEFA : a; if(!ALGHMAC.contains(lc(aa))) throw CX_INVHASH.get(info, aa); final boolean b64 = eq(lc(enc), BASE64) || enc.length == 0; if(!b64 && !eq(lc(enc), HEX)) throw CX_ENC.get(info, enc); try { final Mac mac = Mac.getInstance(string(ALGHMAC.get(lc(aa)))); mac.init(key); final byte[] hash = mac.doFinal(msg); // convert to specified encoding, base64 as a standard, else use hex return Str.get(b64 ? org.basex.util.Base64.encode(hash) : hex(hash, true)); } catch(final NoSuchAlgorithmException e) { throw CX_INVHASH.get(info, e); } catch(final InvalidKeyException e) { throw CX_KEYINV.get(info, e); } } }
92370c9482d0badc4f9c042acb6f20d66aa06c71
584
java
Java
src/main/java/com/person/apirestperson/ApirestPersonApplication.java
tassiotfc/apirestperson-desafioattornatus
a631b43fded74b3a294a9b15832de60c32881689
[ "MIT" ]
null
null
null
src/main/java/com/person/apirestperson/ApirestPersonApplication.java
tassiotfc/apirestperson-desafioattornatus
a631b43fded74b3a294a9b15832de60c32881689
[ "MIT" ]
null
null
null
src/main/java/com/person/apirestperson/ApirestPersonApplication.java
tassiotfc/apirestperson-desafioattornatus
a631b43fded74b3a294a9b15832de60c32881689
[ "MIT" ]
null
null
null
35.5
76
0.835681
997,921
package com.person.apirestperson; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; //@SpringBootApplication(scanBasePackages = "com.person.apirestperson") hzdkv@example.com") dycjh@example.com") @SpringBootApplication public class ApirestPersonApplication { public static void main(String[] args) { SpringApplication.run(ApirestPersonApplication.class, args); } }
92370e0d11047088183f788ea9f5afb552ea4510
2,629
java
Java
app/src/main/java/com/github/tvmazesample/ui/fragment/recycler/holder/SeasonViewHolder.java
hadilq/TvMazeSample
345539c4f6d37487755a4eb85110534daf22ca85
[ "MIT" ]
null
null
null
app/src/main/java/com/github/tvmazesample/ui/fragment/recycler/holder/SeasonViewHolder.java
hadilq/TvMazeSample
345539c4f6d37487755a4eb85110534daf22ca85
[ "MIT" ]
null
null
null
app/src/main/java/com/github/tvmazesample/ui/fragment/recycler/holder/SeasonViewHolder.java
hadilq/TvMazeSample
345539c4f6d37487755a4eb85110534daf22ca85
[ "MIT" ]
null
null
null
36.013699
106
0.621909
997,922
package com.github.tvmazesample.ui.fragment.recycler.holder; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.github.tvmazesample.R; import com.github.tvmazesample.ui.fragment.recycler.data.SeasonData; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; public class SeasonViewHolder extends BaseViewHolder<SeasonData> { @BindView(R.id.title) TextView mTitleView; @BindView(R.id.details) TextView mDetailsView; @BindView(R.id.summary) TextView mSummaryView; SeasonViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } @Override public void onBindView(SeasonData data) { super.onBindView(data); if (TextUtils.isEmpty(data.getName()) && TextUtils.isEmpty(data.getSummary()) && (data.getPremiereDate() == null || data.getEndDate() == null)) { itemView.setVisibility(View.GONE); } else { itemView.setVisibility(View.VISIBLE); } if (!TextUtils.isEmpty(data.getName())) { mTitleView.setText(data.getName()); } else { mTitleView.setText(itemView.getContext().getString(R.string.season_format, data.getNumber())); } if (data.getPremiereDate() != null && data.getEndDate() != null) { mDetailsView.setText(String.format("%tF . %tF", data.getPremiereDate(), data.getEndDate())); mDetailsView.setVisibility(View.VISIBLE); } else { mDetailsView.setVisibility(View.GONE); } if (!TextUtils.isEmpty(data.getSummary())) { mSummaryView.setText(Html.fromHtml(data.getSummary())); mSummaryView.setVisibility(View.VISIBLE); } else { mSummaryView.setVisibility(View.GONE); } } public Observable<SeasonViewHolder> clickStream() { return Observable.create(new ObservableOnSubscribe<SeasonViewHolder>() { @Override public void subscribe(final ObservableEmitter<SeasonViewHolder> e) throws Exception { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!e.isDisposed() && getData() != null) { e.onNext(SeasonViewHolder.this); } } }); } }); } }
9237120f38bd79fb8a594cfcb1852d352c685e15
4,294
java
Java
IntoTheHeavensBase/src/net/darkkilauea/intotheheavens/ITHScript/ScriptObject.java
DarkKilauea/intotheheavens
b60e0c00571f77f2572da1793e82bbc0730e2043
[ "MIT" ]
null
null
null
IntoTheHeavensBase/src/net/darkkilauea/intotheheavens/ITHScript/ScriptObject.java
DarkKilauea/intotheheavens
b60e0c00571f77f2572da1793e82bbc0730e2043
[ "MIT" ]
null
null
null
IntoTheHeavensBase/src/net/darkkilauea/intotheheavens/ITHScript/ScriptObject.java
DarkKilauea/intotheheavens
b60e0c00571f77f2572da1793e82bbc0730e2043
[ "MIT" ]
null
null
null
23.988827
69
0.498603
997,923
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.darkkilauea.intotheheavens.ITHScript; import java.io.*; /** * * @author joshua */ public class ScriptObject { public static final int SOT_NULL = 0; public static final int SOT_INTEGER = 1; public static final int SOT_FLOAT = 2; public static final int SOT_STRING = 4; protected int _type; protected int _intValue; protected double _floatValue; protected String _stringValue; protected ScriptObject(ScriptObject other) { this._type = other._type; this._intValue = other._intValue; this._floatValue = other._floatValue; this._stringValue = other._stringValue; } protected ScriptObject() { _type = SOT_NULL; } protected ScriptObject(int value) { _type = SOT_INTEGER; _intValue = value; } protected ScriptObject(double value) { _type = SOT_FLOAT; _floatValue = value; } protected ScriptObject(String value) { _type = SOT_STRING; _stringValue = value; } public String typeString() { switch (_type) { case SOT_NULL: return "NULL"; case SOT_INTEGER: return "Integer"; case SOT_FLOAT: return "Float"; case SOT_STRING: return "String"; default: return "UNKNOWN"; } } public int toInt() { switch (_type) { case SOT_INTEGER: return _intValue; case SOT_FLOAT: return (int)_floatValue; case SOT_STRING: return Integer.parseInt(_stringValue); default: return 0; } } public double toFloat() { switch (_type) { case SOT_INTEGER: return (double)_intValue; case SOT_FLOAT: return _floatValue; case SOT_STRING: return Double.parseDouble(_stringValue); default: return 0.0; } } public void saveToStream(OutputStream stream) throws IOException { DataOutputStream output = new DataOutputStream(stream); output.write(_type); switch(_type) { case SOT_INTEGER: output.writeInt(_intValue); break; case SOT_FLOAT: output.writeDouble(_floatValue); break; case SOT_STRING: output.writeUTF(_stringValue); break; } } public void loadFromStream(InputStream stream) throws IOException { DataInputStream input = new DataInputStream(stream); _type = input.read(); switch(_type) { case SOT_INTEGER: _intValue = input.readInt(); break; case SOT_FLOAT: _floatValue = input.readDouble(); break; case SOT_STRING: _stringValue = input.readUTF(); break; } } @Override public String toString() { switch (_type) { case SOT_INTEGER: return ((Integer)_intValue).toString(); case SOT_FLOAT: return ((Double)_floatValue).toString(); case SOT_STRING: return _stringValue; default: return "(null)"; } } public boolean equals(ScriptObject other) { if (_type == other._type) { switch (_type) { case SOT_FLOAT: return _floatValue == other._floatValue; case SOT_INTEGER: return _intValue == other._intValue; case SOT_STRING: return _stringValue.equals(other._stringValue); case SOT_NULL: return true; } } return false; } }
9237127c88da0cb8fe7a33966efe6cfec1eb1d91
7,051
java
Java
scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/WireProtocolTest.java
awltux/scm-manager
3c6ae8e3201682facac3b68a01271621d0c04da4
[ "BSD-3-Clause" ]
null
null
null
scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/WireProtocolTest.java
awltux/scm-manager
3c6ae8e3201682facac3b68a01271621d0c04da4
[ "BSD-3-Clause" ]
null
null
null
scm-plugins/scm-hg-plugin/src/test/java/sonia/scm/web/WireProtocolTest.java
awltux/scm-manager
3c6ae8e3201682facac3b68a01271621d0c04da4
[ "BSD-3-Clause" ]
null
null
null
36.533679
111
0.742732
997,924
/** * Copyright (c) 2018, Sebastian Sdorra * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.web; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.*; import static org.mockito.Mockito.when; /** * Unit tests for {@link WireProtocol}. */ @RunWith(MockitoJUnitRunner.class) public class WireProtocolTest { @Mock private HttpServletRequest request; @Test public void testIsWriteRequestOnPost() { assertIsWriteRequest("capabilities", "unbundle"); } @Test public void testIsWriteRequest() { assertIsWriteRequest("unbundle"); assertIsWriteRequest("capabilities", "unbundle"); assertIsWriteRequest("capabilities", "postkeys"); assertIsReadRequest(); assertIsReadRequest("capabilities"); assertIsReadRequest("capabilities", "branches", "branchmap"); } private void assertIsWriteRequest(String... commands) { List<String> cmdList = Lists.newArrayList(commands); assertTrue(WireProtocol.isWriteRequest(cmdList)); } private void assertIsReadRequest(String... commands) { List<String> cmdList = Lists.newArrayList(commands); assertFalse(WireProtocol.isWriteRequest(cmdList)); } @Test public void testGetCommandsOf() { expectQueryCommand("capabilities", "cmd=capabilities"); expectQueryCommand("unbundle", "cmd=unbundle"); expectQueryCommand("unbundle", "prefix=stuff&cmd=unbundle"); expectQueryCommand("unbundle", "cmd=unbundle&suffix=stuff"); expectQueryCommand("unbundle", "prefix=stuff&cmd=unbundle&suffix=stuff"); expectQueryCommand("unbundle", "bool=&cmd=unbundle"); expectQueryCommand("unbundle", "bool&cmd=unbundle"); expectQueryCommand("unbundle", "prefix=stu==ff&cmd=unbundle"); } @Test public void testGetCommandsOfWithHgArgsPost() throws IOException { when(request.getMethod()).thenReturn("POST"); when(request.getQueryString()).thenReturn("cmd=batch"); when(request.getIntHeader("X-HgArgs-Post")).thenReturn(29); when(request.getHeaderNames()).thenReturn(Collections.enumeration(Lists.newArrayList("X-HgArgs-Post"))); when(request.getInputStream()).thenReturn(new BufferedServletInputStream("cmds=lheads+%3Bknown+nodes%3D")); List<String> commands = WireProtocol.commandsOf(new HgServletRequest(request)); assertThat(commands, contains("batch", "lheads", "known")); } @Test public void testGetCommandsOfWithBatch() { prepareBatch("cmds=heads ;known nodes,ef5993bb4abb32a0565c347844c6d939fc4f4b98"); List<String> commands = WireProtocol.commandsOf(request); assertThat(commands, contains("batch", "heads", "known")); } @Test public void testGetCommandsOfWithBatchEncoded() { prepareBatch("cmds=heads+%3Bknown+nodes%3Def5993bb4abb32a0565c347844c6d939fc4f4b98"); List<String> commands = WireProtocol.commandsOf(request); assertThat(commands, contains("batch", "heads", "known")); } @Test public void testGetCommandsOfWithBatchAndMutlipleLines() { prepareBatch( "cmds=heads+%3Bknown+nodes%3Def5993bb4abb32a0565c347844c6d939fc4f4b98", "cmds=unbundle; postkeys", "cmds= branchmap p1=r2,p2=r4; listkeys" ); List<String> commands = WireProtocol.commandsOf(request); assertThat(commands, contains("batch", "heads", "known", "unbundle", "postkeys", "branchmap", "listkeys")); } private void prepareBatch(String... args) { when(request.getQueryString()).thenReturn("cmd=batch"); List<String> headers = Lists.newArrayList(); for (int i=0; i<args.length; i++) { String header = "X-HgArg-" + (i+1); headers.add(header); when(request.getHeader(header)).thenReturn(args[i]); } when(request.getHeaderNames()).thenReturn(Collections.enumeration(headers)); } @Test(expected = IllegalArgumentException.class) public void testGetCommandsOfWithMultipleCommandsInQueryString() { when(request.getQueryString()).thenReturn("cmd=abc&cmd=def"); WireProtocol.commandsOf(request); } @Test public void testGetCommandsOfWithoutCmdInQueryString() { when(request.getQueryString()).thenReturn("abc=def&123=456"); assertTrue(WireProtocol.commandsOf(request).isEmpty()); } @Test public void testGetCommandsOfWithEmptyQueryString() { when(request.getQueryString()).thenReturn(""); assertTrue(WireProtocol.commandsOf(request).isEmpty()); } @Test public void testGetCommandsOfWithNullQueryString() { assertTrue(WireProtocol.commandsOf(request).isEmpty()); } private void expectQueryCommand(String expected, String queryString) { when(request.getQueryString()).thenReturn(queryString); List<String> commands = WireProtocol.commandsOf(request); assertEquals(1, commands.size()); assertTrue(commands.contains(expected)); } private static class BufferedServletInputStream extends ServletInputStream { private ByteArrayInputStream input; BufferedServletInputStream(String content) { this.input = new ByteArrayInputStream(content.getBytes(Charsets.US_ASCII)); } @Override public int read() { return input.read(); } } }
923713b47c36515557b61672fa3c4fd4fc208e51
457
java
Java
src/main/java/leetcode/JudgeRouteCircle.java
nikoo28/java-solutions
2d7f6b80ab6f8f79f11b0c6af9a89d8efce1e418
[ "Apache-2.0" ]
10
2021-02-01T09:40:28.000Z
2022-03-29T09:56:39.000Z
src/main/java/leetcode/JudgeRouteCircle.java
nikoo28/java-solutions
2d7f6b80ab6f8f79f11b0c6af9a89d8efce1e418
[ "Apache-2.0" ]
null
null
null
src/main/java/leetcode/JudgeRouteCircle.java
nikoo28/java-solutions
2d7f6b80ab6f8f79f11b0c6af9a89d8efce1e418
[ "Apache-2.0" ]
9
2021-06-12T05:56:13.000Z
2022-03-24T04:07:35.000Z
13.057143
46
0.380744
997,925
package leetcode; class JudgeRouteCircle { public boolean judgeCircle(String moves) { int x = 0; int y = 0; for (int i = 0; i < moves.length(); i++) { switch (moves.charAt(i)) { case 'U': y++; break; case 'D': y--; break; case 'L': x--; break; case 'R': x++; break; } } return x == 0 && y == 0; } }
923715686cad726e2070d72dbbebf7a00abee445
1,016
java
Java
eider-processor/src/main/java/io/eider/processor/agrona/AgronaWriterState.java
eleventy7/eider
85953904b88fcfc10eea285e23f8045b17602bff
[ "Apache-2.0" ]
13
2020-05-18T00:03:53.000Z
2022-03-19T15:39:31.000Z
eider-processor/src/main/java/io/eider/processor/agrona/AgronaWriterState.java
eleventy7/eider
85953904b88fcfc10eea285e23f8045b17602bff
[ "Apache-2.0" ]
75
2020-08-14T20:54:28.000Z
2022-03-28T22:01:55.000Z
eider-processor/src/main/java/io/eider/processor/agrona/AgronaWriterState.java
eleventy7/eider
85953904b88fcfc10eea285e23f8045b17602bff
[ "Apache-2.0" ]
4
2021-02-11T08:18:35.000Z
2022-01-12T09:54:02.000Z
26.736842
75
0.715551
997,926
/* * Copyright 2019-2021 Shaun Laurens. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.eider.processor.agrona; public class AgronaWriterState { private int currentOffset; public int getCurrentOffset() { return currentOffset; } public void setCurrentOffset(final int currentOffset) { this.currentOffset = currentOffset; } public void extendCurrentOffset(final int byBytes) { this.currentOffset = currentOffset + byBytes; } }
923715c5d4c1f348551a55e2d7f58f4be70ea7fb
14,301
java
Java
org.alloytools.alloy.core/src/test/java/maxsat/CourseSchedule.java
SteveZhangBit/org.alloytools.alloy
648b7c08f38866737b87b5928c2e20e454f4dbcd
[ "Apache-2.0" ]
null
null
null
org.alloytools.alloy.core/src/test/java/maxsat/CourseSchedule.java
SteveZhangBit/org.alloytools.alloy
648b7c08f38866737b87b5928c2e20e454f4dbcd
[ "Apache-2.0" ]
null
null
null
org.alloytools.alloy.core/src/test/java/maxsat/CourseSchedule.java
SteveZhangBit/org.alloytools.alloy
648b7c08f38866737b87b5928c2e20e454f4dbcd
[ "Apache-2.0" ]
null
null
null
42.061765
207
0.620656
997,927
package maxsat; import java.util.Arrays; import java.util.List; import kodkod.ast.*; import kodkod.ast.operator.*; import kodkod.instance.*; import kodkod.engine.*; import kodkod.engine.satlab.SATFactory; import kodkod.engine.config.Options; /* Alloy formula: abstract sig Student { cores: set Course, courses: set Course } abstract sig Course { time: one Time } abstract sig Time {} one sig Alice, Bob extends Student {} one sig Models, Architecture, Management extends Course {} one sig Morning, Afternoon extends Time {} // Set the time for the courses. fact { time = (Models -> Morning) + (Architecture -> Morning) + (Management -> Afternoon) } // Set the cores for the students fact { cores = (Alice -> Models) + (Alice -> Architecture) + (Bob -> Models) + (Bob -> Management) } // Bob only wants to take courses in the afternoon fact LazyBob { Bob.courses.time in Afternoon } pred MustTakeCores[s: Student] { s.cores in s.courses } run { all s: Student | MustTakeCores[s] } */ /* ================================================== kodkod formula: ================================================== no (this/Alice & this/Bob) && no (this/Models & this/Architecture) && no ((this/Models + this/Architecture) & this/Management) && no (this/Morning & this/Afternoon) && (all this: this/Alice + this/Bob | (this . this/Student.cores) in (this/Models + this/Architecture + this/Management)) && (this/Student.cores . univ) in (this/Alice + this/Bob) && (all this: this/Alice + this/Bob | (this . this/Student.courses) in (this/Models + this/Architecture + this/Management)) && (this/Student.courses . univ) in (this/Alice + this/Bob) && (all this: this/Models + this/Architecture + this/Management | one (this . this/Course.time) && (this . this/Course.time) in (this/Morning + this/Afternoon)) && (this/Course.time . univ) in (this/Models + this/Architecture + this/Management) && this/Course.time = ((this/Models -> this/Morning) + (this/Architecture -> this/Morning) + (this/Management -> this/Afternoon)) && this/Student.cores = ((this/Alice -> this/Models) + (this/Alice -> this/Architecture) + (this/Bob -> this/Models) + (this/Bob -> this/Management)) && ((this/Bob . this/Student.courses) . this/Course.time) in this/Afternoon && (all s: this/Alice + this/Bob | (s . this/Student.cores) in (s . this/Student.courses)) && Int/min = Int/min && Int/zero = Int/zero && Int/max = Int/max && Int/next = Int/next && seq/Int = seq/Int && String = String && this/Alice = this/Alice && this/Bob = this/Bob && this/Models = this/Models && this/Architecture = this/Architecture && this/Management = this/Management && this/Morning = this/Morning && this/Afternoon = this/Afternoon && this/Student.cores = this/Student.cores && this/Student.courses = this/Student.courses && this/Course.time = this/Course.time ================================================== */ public final class CourseSchedule { public static void main(String[] args) throws Exception { Relation x0 = Relation.unary("Int/min"); Relation x1 = Relation.unary("Int/zero"); Relation x2 = Relation.unary("Int/max"); Relation x3 = Relation.nary("Int/next", 2); Relation x4 = Relation.unary("seq/Int"); Relation x5 = Relation.unary("String"); Relation x6 = Relation.unary("this/Alice"); Relation x7 = Relation.unary("this/Bob"); Relation x8 = Relation.unary("this/Models"); Relation x9 = Relation.unary("this/Architecture"); Relation x10 = Relation.unary("this/Management"); Relation x11 = Relation.unary("this/Morning"); Relation x12 = Relation.unary("this/Afternoon"); Relation x13 = Relation.nary("this/Student.cores", 2); Relation x14 = Relation.nary("this/Student.courses", 2); Relation x15 = Relation.nary("this/Course.time", 2); List<String> atomlist = Arrays.asList( "-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8", "0", "1", "2", "3", "4", "5", "6", "7", "Afternoon$0", "Alice$0", "Architecture$0", "Bob$0", "Management$0", "Models$0", "Morning$0" ); Universe universe = new Universe(atomlist); TupleFactory factory = universe.factory(); Bounds bounds = new Bounds(universe); TupleSet x0_upper = factory.noneOf(1); x0_upper.add(factory.tuple("-8")); bounds.boundExactly(x0, x0_upper); TupleSet x1_upper = factory.noneOf(1); x1_upper.add(factory.tuple("0")); bounds.boundExactly(x1, x1_upper); TupleSet x2_upper = factory.noneOf(1); x2_upper.add(factory.tuple("7")); bounds.boundExactly(x2, x2_upper); TupleSet x3_upper = factory.noneOf(2); x3_upper.add(factory.tuple("-8").product(factory.tuple("-7"))); x3_upper.add(factory.tuple("-7").product(factory.tuple("-6"))); x3_upper.add(factory.tuple("-6").product(factory.tuple("-5"))); x3_upper.add(factory.tuple("-5").product(factory.tuple("-4"))); x3_upper.add(factory.tuple("-4").product(factory.tuple("-3"))); x3_upper.add(factory.tuple("-3").product(factory.tuple("-2"))); x3_upper.add(factory.tuple("-2").product(factory.tuple("-1"))); x3_upper.add(factory.tuple("-1").product(factory.tuple("0"))); x3_upper.add(factory.tuple("0").product(factory.tuple("1"))); x3_upper.add(factory.tuple("1").product(factory.tuple("2"))); x3_upper.add(factory.tuple("2").product(factory.tuple("3"))); x3_upper.add(factory.tuple("3").product(factory.tuple("4"))); x3_upper.add(factory.tuple("4").product(factory.tuple("5"))); x3_upper.add(factory.tuple("5").product(factory.tuple("6"))); x3_upper.add(factory.tuple("6").product(factory.tuple("7"))); bounds.boundExactly(x3, x3_upper); TupleSet x4_upper = factory.noneOf(1); x4_upper.add(factory.tuple("0")); x4_upper.add(factory.tuple("1")); x4_upper.add(factory.tuple("2")); x4_upper.add(factory.tuple("3")); bounds.boundExactly(x4, x4_upper); TupleSet x5_upper = factory.noneOf(1); bounds.boundExactly(x5, x5_upper); TupleSet x6_upper = factory.noneOf(1); x6_upper.add(factory.tuple("Alice$0")); bounds.boundExactly(x6, x6_upper); TupleSet x7_upper = factory.noneOf(1); x7_upper.add(factory.tuple("Bob$0")); bounds.boundExactly(x7, x7_upper); TupleSet x8_upper = factory.noneOf(1); x8_upper.add(factory.tuple("Models$0")); bounds.boundExactly(x8, x8_upper); TupleSet x9_upper = factory.noneOf(1); x9_upper.add(factory.tuple("Architecture$0")); bounds.boundExactly(x9, x9_upper); TupleSet x10_upper = factory.noneOf(1); x10_upper.add(factory.tuple("Management$0")); bounds.boundExactly(x10, x10_upper); TupleSet x11_upper = factory.noneOf(1); x11_upper.add(factory.tuple("Morning$0")); bounds.boundExactly(x11, x11_upper); TupleSet x12_upper = factory.noneOf(1); x12_upper.add(factory.tuple("Afternoon$0")); bounds.boundExactly(x12, x12_upper); TupleSet x13_upper = factory.noneOf(2); x13_upper.add(factory.tuple("Alice$0").product(factory.tuple("Models$0"))); x13_upper.add(factory.tuple("Alice$0").product(factory.tuple("Architecture$0"))); x13_upper.add(factory.tuple("Alice$0").product(factory.tuple("Management$0"))); x13_upper.add(factory.tuple("Bob$0").product(factory.tuple("Models$0"))); x13_upper.add(factory.tuple("Bob$0").product(factory.tuple("Architecture$0"))); x13_upper.add(factory.tuple("Bob$0").product(factory.tuple("Management$0"))); bounds.bound(x13, x13_upper); TupleSet x14_upper = factory.noneOf(2); x14_upper.add(factory.tuple("Alice$0").product(factory.tuple("Models$0"))); x14_upper.add(factory.tuple("Alice$0").product(factory.tuple("Architecture$0"))); x14_upper.add(factory.tuple("Alice$0").product(factory.tuple("Management$0"))); x14_upper.add(factory.tuple("Bob$0").product(factory.tuple("Models$0"))); x14_upper.add(factory.tuple("Bob$0").product(factory.tuple("Architecture$0"))); x14_upper.add(factory.tuple("Bob$0").product(factory.tuple("Management$0"))); bounds.bound(x14, x14_upper); TupleSet x15_upper = factory.noneOf(2); x15_upper.add(factory.tuple("Models$0").product(factory.tuple("Morning$0"))); x15_upper.add(factory.tuple("Models$0").product(factory.tuple("Afternoon$0"))); x15_upper.add(factory.tuple("Architecture$0").product(factory.tuple("Morning$0"))); x15_upper.add(factory.tuple("Architecture$0").product(factory.tuple("Afternoon$0"))); x15_upper.add(factory.tuple("Management$0").product(factory.tuple("Morning$0"))); x15_upper.add(factory.tuple("Management$0").product(factory.tuple("Afternoon$0"))); bounds.bound(x15, x15_upper); bounds.boundExactly(-8,factory.range(factory.tuple("-8"),factory.tuple("-8"))); bounds.boundExactly(-7,factory.range(factory.tuple("-7"),factory.tuple("-7"))); bounds.boundExactly(-6,factory.range(factory.tuple("-6"),factory.tuple("-6"))); bounds.boundExactly(-5,factory.range(factory.tuple("-5"),factory.tuple("-5"))); bounds.boundExactly(-4,factory.range(factory.tuple("-4"),factory.tuple("-4"))); bounds.boundExactly(-3,factory.range(factory.tuple("-3"),factory.tuple("-3"))); bounds.boundExactly(-2,factory.range(factory.tuple("-2"),factory.tuple("-2"))); bounds.boundExactly(-1,factory.range(factory.tuple("-1"),factory.tuple("-1"))); bounds.boundExactly(0,factory.range(factory.tuple("0"),factory.tuple("0"))); bounds.boundExactly(1,factory.range(factory.tuple("1"),factory.tuple("1"))); bounds.boundExactly(2,factory.range(factory.tuple("2"),factory.tuple("2"))); bounds.boundExactly(3,factory.range(factory.tuple("3"),factory.tuple("3"))); bounds.boundExactly(4,factory.range(factory.tuple("4"),factory.tuple("4"))); bounds.boundExactly(5,factory.range(factory.tuple("5"),factory.tuple("5"))); bounds.boundExactly(6,factory.range(factory.tuple("6"),factory.tuple("6"))); bounds.boundExactly(7,factory.range(factory.tuple("7"),factory.tuple("7"))); Expression x18=x6.intersection(x7); Formula x17=x18.no(); Expression x20=x8.intersection(x9); Formula x19=x20.no(); Expression x23=x8.union(x9); Expression x22=x23.intersection(x10); Formula x21=x22.no(); Expression x25=x11.intersection(x12); Formula x24=x25.no(); Variable x28=Variable.unary("this"); Expression x29=x6.union(x7); Decls x27=x28.oneOf(x29); Expression x31=x28.join(x13); Expression x32=x23.union(x10); Formula x30=x31.in(x32); Formula x26=x30.forAll(x27); Expression x34=x13.join(Expression.UNIV); Formula x33=x34.in(x29); Variable x38=Variable.unary("this"); Decls x37=x38.oneOf(x29); Expression x40=x38.join(x14); Formula x39=x40.in(x32); Formula x36=x39.forAll(x37); Expression x42=x14.join(Expression.UNIV); Formula x41=x42.in(x29); Variable x45=Variable.unary("this"); Decls x44=x45.oneOf(x32); Expression x48=x45.join(x15); Formula x47=x48.one(); Expression x50=x11.union(x12); Formula x49=x48.in(x50); Formula x46=x47.and(x49); Formula x43=x46.forAll(x44); Expression x52=x15.join(Expression.UNIV); Formula x51=x52.in(x32); Expression x56=x8.product(x11); Expression x57=x9.product(x11); Expression x55=x56.union(x57); Expression x58=x10.product(x12); Expression x54=x55.union(x58); Formula x53=x15.eq(x54); Expression x63=x6.product(x8); Expression x64=x6.product(x9); Expression x62=x63.union(x64); Expression x65=x7.product(x8); Expression x61=x62.union(x65); Expression x66=x7.product(x10); Expression x60=x61.union(x66); Formula x59=x13.eq(x60); Expression x69=x7.join(x14); Expression x68=x69.join(x15); Formula x67=x68.in(x12); x67.setSoft(true, 0); // Set ((this/Bob . this/Student.courses) . this/Course.time) in this/Afternoon to soft constraint Variable x72=Variable.unary("s"); Decls x71=x72.oneOf(x29); Expression x74=x72.join(x13); Expression x75=x72.join(x14); Formula x73=x74.in(x75); Formula x70=x73.forAll(x71); Formula x76=x0.eq(x0); Formula x77=x1.eq(x1); Formula x78=x2.eq(x2); Formula x79=x3.eq(x3); Formula x80=x4.eq(x4); Formula x81=x5.eq(x5); Formula x82=x6.eq(x6); Formula x83=x7.eq(x7); Formula x84=x8.eq(x8); Formula x85=x9.eq(x9); Formula x86=x10.eq(x10); Formula x87=x11.eq(x11); Formula x88=x12.eq(x12); Formula x89=x13.eq(x13); Formula x90=x14.eq(x14); Formula x91=x15.eq(x15); Formula x16=Formula.compose(FormulaOperator.AND, x17, x19, x21, x24, x26, x33, x36, x41, x43, x51, x53, x59, x67, x70, x76, x77, x78, x79, x80, x81, x82, x83, x84, x85, x86, x87, x88, x89, x90, x91); Solver solver = new Solver(); solver.options().setSolver(SATFactory.DefaultSAT4JMax); solver.options().setLogTranslation(2); solver.options().setCoreGranularity(0); solver.options().setBitwidth(4); // solver.options().setFlatten(false); solver.options().setIntEncoding(Options.IntEncoding.TWOSCOMPLEMENT); solver.options().setSymmetryBreaking(20); solver.options().setSkolemDepth(0); System.out.println("Solving..."); System.out.flush(); Solution sol = solver.solve(x16,bounds); System.out.println(sol.toString()); } }
923715d619e6a21cc3ffe98936effbbfb5b1133d
7,474
java
Java
ELDependenci-plugin/src/main/java/com/ericlam/mc/eld/services/scheduler/ELDSchedulerService.java
eric2788/ELDependenci
e102fdb92b1b11af5d1e97f9ffe9c0876c63a67f
[ "MIT" ]
2
2021-08-16T16:18:14.000Z
2021-08-28T07:18:56.000Z
ELDependenci-plugin/src/main/java/com/ericlam/mc/eld/services/scheduler/ELDSchedulerService.java
ELDEpendenci/ELDependenci
e102fdb92b1b11af5d1e97f9ffe9c0876c63a67f
[ "MIT" ]
null
null
null
ELDependenci-plugin/src/main/java/com/ericlam/mc/eld/services/scheduler/ELDSchedulerService.java
ELDEpendenci/ELDependenci
e102fdb92b1b11af5d1e97f9ffe9c0876c63a67f
[ "MIT" ]
1
2021-03-16T16:02:05.000Z
2021-03-16T16:02:05.000Z
31.535865
159
0.580011
997,928
package com.ericlam.mc.eld.services.scheduler; import com.ericlam.mc.eld.misc.ChainCallable; import com.ericlam.mc.eld.services.ScheduleService; import com.google.inject.Inject; import com.google.inject.Injector; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer; public final class ELDSchedulerService implements ScheduleService { @Inject private Injector injector; @Override public ScheduleFactory injectTask(BukkitRunnable runnable) { return new ELDSchedulerFactory(runnable); } @Override public <E> BukkitPromise<E> callAsync(Plugin plugin, Callable<E> callable) { return new ELDBukkitPromise<>(callable, plugin); } @Override public BukkitPromise<Void> runAsync(Plugin plugin, Runnable runnable) { return new ELDBukkitPromise<>(() -> { runnable.run(); return Void.TYPE.cast(null); }, plugin); } private class ELDSchedulerFactory implements ScheduleFactory { private final BukkitRunnable bukkitRunnable; private boolean async = false; private long interval = -1; private long timeout = -1; private ELDSchedulerFactory(BukkitRunnable bukkitRunnable) { injector.injectMembers(bukkitRunnable); this.bukkitRunnable = bukkitRunnable; } @Override public ScheduleFactory asynchronous(boolean async) { this.async = async; return this; } @Override public ScheduleFactory interval(long ticks) { this.interval = ticks; return this; } @Override public ScheduleFactory timeout(long ticks) { this.timeout = ticks; return this; } @Override public BukkitTask run(Plugin plugin) { if (timeout == -1 && interval == -1) { if (async) { return bukkitRunnable.runTaskAsynchronously(plugin); } else { return bukkitRunnable.runTask(plugin); } } else if (timeout != -1 && interval == -1) { if (async) { return bukkitRunnable.runTaskLaterAsynchronously(plugin, timeout); } else { return bukkitRunnable.runTaskLater(plugin, timeout); } } else { if (async) { return bukkitRunnable.runTaskTimerAsynchronously(plugin, timeout, interval); } else { return bukkitRunnable.runTaskTimer(plugin, timeout, interval); } } } } private class ELDBukkitPromise<E> implements BukkitPromise<E> { private final Plugin plugin; private final BukkitCallable<E> bukkitCallable; private ELDBukkitPromise(Callable<E> callable, Plugin plugin) { injector.injectMembers(callable); bukkitCallable = new BukkitCallable<>(callable); this.plugin = plugin; } @Override public <R> BukkitPromise<R> thenApplySync(ChainCallable<E, R> function) { var s = new ELDBukkitPromise2<>(new LinkedList<>(List.of(bukkitCallable)), function, plugin, false); bukkitCallable.setHandler(e -> { s.setElement(e); s.start(); }); return s; } @Override public BukkitPromise<Void> thenRunSync(Consumer<E> function) { return thenApplySync(e -> { function.accept(e); return Void.TYPE.cast(null); }); } @Override public <R> BukkitPromise<R> thenApplyAsync(ChainCallable<E, R> function) { var s = new ELDBukkitPromise2<>(new LinkedList<>(List.of(bukkitCallable)), function, plugin, true); bukkitCallable.setHandler(e -> { s.setElement(e); s.start(); }); return s; } @Override public BukkitPromise<Void> thenRunAsync(Consumer<E> function) { return thenApplyAsync(e -> { function.accept(e); return Void.TYPE.cast(null); }); } @Override public void join() { bukkitCallable.runTaskAsynchronously(plugin); } @Override public void joinWithCatch(Consumer<Throwable> handler) { bukkitCallable.catcher = handler; this.join(); } } private class ELDBukkitPromise2<E, R> implements BukkitPromise<R> { public final Plugin plugin; private final boolean async; private final LinkedList<CatchableRunnable> catchableRunnableLinkedList; private final BukkitChainCallable<E, R> bukkitChainCallable; public ELDBukkitPromise2(final LinkedList<CatchableRunnable> catchableRunnableLinkedList, ChainCallable<E, R> function, Plugin plugin, boolean async) { injector.injectMembers(function); bukkitChainCallable = new BukkitChainCallable<>(function); this.catchableRunnableLinkedList = catchableRunnableLinkedList; this.catchableRunnableLinkedList.addLast(bukkitChainCallable); this.plugin = plugin; this.async = async; } public void setElement(E element) { bukkitChainCallable.setAccept(element); } @Override public <J> BukkitPromise<J> thenApplySync(ChainCallable<R, J> function) { var s = new ELDBukkitPromise2<>(catchableRunnableLinkedList, function, plugin, false); bukkitChainCallable.setHandler(e -> { s.setElement(e); s.start(); }); return s; } @Override public BukkitPromise<Void> thenRunSync(Consumer<R> function) { return thenApplySync(e -> { function.accept(e); return Void.TYPE.cast(null); }); } @Override public <J> BukkitPromise<J> thenApplyAsync(ChainCallable<R, J> function) { var s = new ELDBukkitPromise2<>(catchableRunnableLinkedList, function, plugin, true); bukkitChainCallable.setHandler(e -> { s.setElement(e); s.start(); }); return s; } @Override public BukkitPromise<Void> thenRunAsync(Consumer<R> function) { return thenApplyAsync(e ->{ function.accept(e); return Void.TYPE.cast(null); }); } private void start() { if (async) { bukkitChainCallable.runTaskAsynchronously(plugin); } else { bukkitChainCallable.runTask(plugin); } } @Override public void join() { var runnable = catchableRunnableLinkedList.pollFirst(); if (runnable != null) runnable.runTaskAsynchronously(plugin); } @Override public void joinWithCatch(Consumer<Throwable> handler) { catchableRunnableLinkedList.forEach(r -> r.catcher = handler); this.join(); } } }
923716111fc57e5e5260c166114704b9dcad7eb5
1,016
java
Java
sql/hive/target/java/org/apache/spark/sql/hive/HiveSimpleUdf.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
sql/hive/target/java/org/apache/spark/sql/hive/HiveSimpleUdf.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
sql/hive/target/java/org/apache/spark/sql/hive/HiveSimpleUdf.java
kzx1025/spark_improve
c16b7be94bf2190609b8a22a8b7be48bf2ec6997
[ "Apache-2.0" ]
null
null
null
84.666667
180
0.773622
997,929
package org.apache.spark.sql.hive; private class HiveSimpleUdf extends org.apache.spark.sql.hive.HiveUdf implements org.apache.spark.sql.hive.HiveInspectors, scala.Product, scala.Serializable { public java.lang.String functionClassName () { throw new RuntimeException(); } public scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> children () { throw new RuntimeException(); } // not preceding public HiveSimpleUdf (java.lang.String functionClassName, scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> children) { throw new RuntimeException(); } protected java.lang.reflect.Method method () { throw new RuntimeException(); } public org.apache.spark.sql.catalyst.types.DataType dataType () { throw new RuntimeException(); } protected scala.Function1<java.lang.Object, java.lang.Object>[] wrappers () { throw new RuntimeException(); } public Object eval (org.apache.spark.sql.catalyst.expressions.Row input) { throw new RuntimeException(); } }
923716183ddcf70ffb89bf618737b3b8dd6ecb3e
166
java
Java
src/main/java/pattern/structural/Adapter/Target.java
lnjasdf/JavaPractice
dc925e5ffe5027161c6aea07cfc854663a1676dc
[ "MIT" ]
null
null
null
src/main/java/pattern/structural/Adapter/Target.java
lnjasdf/JavaPractice
dc925e5ffe5027161c6aea07cfc854663a1676dc
[ "MIT" ]
null
null
null
src/main/java/pattern/structural/Adapter/Target.java
lnjasdf/JavaPractice
dc925e5ffe5027161c6aea07cfc854663a1676dc
[ "MIT" ]
null
null
null
16.6
35
0.698795
997,930
package pattern.structural.Adapter; /** * Created by lnjasdf on 2017/5/6. */ public interface Target { void sampleOperation1(); void sampleOperation2(); }
923716a0f95ee2a52eae636c46e2f8eb1488ce16
1,001
java
Java
src/jichu/erfenchazhao.java
3198ys/algorithm
6323a263abde34520a3836df0b4397b77bcd8703
[ "MIT" ]
null
null
null
src/jichu/erfenchazhao.java
3198ys/algorithm
6323a263abde34520a3836df0b4397b77bcd8703
[ "MIT" ]
null
null
null
src/jichu/erfenchazhao.java
3198ys/algorithm
6323a263abde34520a3836df0b4397b77bcd8703
[ "MIT" ]
null
null
null
25.025
78
0.495504
997,931
package jichu; public class erfenchazhao { public static void main(String[] args) { int a[]=new int[]{2,4,6,8,9,210,234}; int i = binSearchDigui(8, a,0,a.length-1); System.out.println(i); } public static int binSerarch(int key,int [] array){ int low=0; int heigh=array.length-1; int mid=0; while (low<=heigh){ mid=(low+heigh)>>1; if(array[mid]==key){ return array[mid]; }else if(array[mid]<key){ low=mid+1; }else{ heigh=mid-1; } } return -1; } public static int binSearchDigui(int key,int [] array,int low,int height){ int mid=(low+height)>>1; if(array[mid]>key){ return binSearchDigui(key,array,low,mid-1); }else if(array[mid]<key){ return binSearchDigui(key, array, mid+1,height ); }else{ return array[mid]; } } }
9237171731669c9f32e268b0dd8285de9bc02c77
6,585
java
Java
src/main/java/com/niara/logger/apps/Logger.java
HewlettPackard/logger
c56c1a71ca6364c3c15595f1583795e96f1272a1
[ "Apache-2.0" ]
13
2018-03-02T17:21:16.000Z
2021-01-22T18:31:38.000Z
src/main/java/com/niara/logger/apps/Logger.java
ramakrishnanrakesh/logger
277f0be00b7e6332c8d7d5498d2478211dbdb0dc
[ "Apache-2.0" ]
1
2018-03-05T03:53:57.000Z
2018-03-05T03:53:57.000Z
src/main/java/com/niara/logger/apps/Logger.java
ramakrishnanrakesh/logger
277f0be00b7e6332c8d7d5498d2478211dbdb0dc
[ "Apache-2.0" ]
5
2018-03-03T02:45:47.000Z
2022-01-23T15:24:45.000Z
46.373239
182
0.742141
997,932
/* * (C) Copyright [2018] Hewlett Packard Enterprise Development LP. * * 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.niara.logger.apps; import com.niara.logger.listeners.LogListener; import com.niara.logger.parsers.LogParserCounter; import com.niara.logger.handlers.*; import com.niara.logger.monitors.LogParserMonitor; import com.niara.logger.monitors.LogReaderMonitor; import com.niara.logger.monitors.LogWriterMonitor; import com.niara.logger.parsers.Parser; import com.niara.logger.utils.GrokHandler; import com.niara.logger.monitors.LogParserSemaphoreMonitor; import com.niara.logger.utils.LoggerConfig; import com.niara.logger.utils.Tuple; import com.niara.logger.writers.LogWriterCounter; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; public class Logger { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Logger.class); private static final CountDownLatch logListenerLatch = new CountDownLatch(1); private static final CountDownLatch logReaderLatch = new CountDownLatch(1); private static final CountDownLatch logParserLatch = new CountDownLatch(1); private static final CountDownLatch logWriterLatch = new CountDownLatch(1); private static AtomicLong atomicCounter = new AtomicLong(0); static { LoggerConfig.init("PRODUCTION"); GrokHandler.init(); Parser.init(LoggerConfig.getTimestampKeys(), LoggerConfig.getTimestampDefault()); } public static AtomicLong getAtomicCounter() { return atomicCounter; } // LogReader private static final ExecutorService logReaderService = LoggerConfig.getLogReadersExecutorService(); private static final ExecutorCompletionService<Tuple<Long, String>> logReaderECS = new ExecutorCompletionService<>(logReaderService); // LogParser private static final Semaphore logParserSemaphore = new Semaphore(LoggerConfig.getLogParsersQueueLength()); private static final ExecutorService logParserService = LoggerConfig.getLogParsersExecutorService(); private static final ExecutorCompletionService<LogParserCounter> logParserECS = new ExecutorCompletionService<>(logParserService); // LogWriter private static final ExecutorService logWriterService = LoggerConfig.getLogWritersExecutorService(); private static final ExecutorCompletionService<LogWriterCounter> logWriterECS = new ExecutorCompletionService<>(logWriterService); public static ExecutorCompletionService<Tuple<Long, String>> getLogReaderECS() { return logReaderECS; } public static Semaphore getLogParserSemaphore() { return logParserSemaphore; } public static ExecutorCompletionService<LogParserCounter> getLogParserECS() { return logParserECS; } public static ExecutorCompletionService<LogWriterCounter> getLogWriterECS() { return logWriterECS; } private static void addShutdownHook(final CountDownLatch logListenerLatch, final FutureTask<Void> logListenerFuture, final CountDownLatch logReaderLatch, final ExecutorService logReaderService, final CountDownLatch logParserLatch, final ExecutorService logParserService, final CountDownLatch logWriterLatch, final ExecutorService logWriterService) { Runtime.getRuntime().addShutdownHook( new Thread(new ShutdownHandler(logListenerLatch, logListenerFuture, logReaderLatch, logReaderService, logParserLatch, logParserService, logWriterLatch, logWriterService)) ); } public static void main(String[] args) throws Exception { final FileToLogReaderHandler fileToLogReaderHandler = new FileToLogReaderHandler(getLogReaderECS()); final Class<? extends LogListener> logListenerClass = (Class<? extends LogListener>) Logger.class.getClassLoader().loadClass(LoggerConfig.getLogListenerClass()); Constructor<? extends LogListener> logListenerCtor = logListenerClass.getConstructor(CountDownLatch.class, FileToLogReaderHandler.class); LogListener logListener = logListenerCtor.newInstance(logListenerLatch, fileToLogReaderHandler); final FutureTask<Void> logListenerFuture = new FutureTask<>(logListener, null); // Add the shutdown hook now (after initializing all variables). addShutdownHook(logListenerLatch, logListenerFuture, logReaderLatch, logReaderService, logParserLatch, logParserService, logWriterLatch, logWriterService); // Start the thread to monitor file reader objects, and print stats. new Thread(new LogReaderMonitor(logReaderLatch, logReaderService, logReaderECS)).start(); new Thread(new LogParserSemaphoreMonitor(logParserSemaphore, logParserLatch)).start(); // Start the thread to monitor parser objects, and submit output to log writers. new Thread(new LogParserMonitor(logParserSemaphore, logParserLatch, logParserService, logParserECS)).start(); // Start the thread to monitor writer objects, and print stats. new Thread(new LogWriterMonitor(logWriterLatch, logWriterService, logWriterECS)).start(); // Start the listener and block for it to finish. logListenerFuture.run(); // If the runtime logReaderToLogParser exits earlier, program won't reach here. if (logListenerLatch.getCount() != 0) { logger.warn("Listener died! Too many threads being created? Please check the system limit on number of processes/threads, and tune the thread parameters."); } logger.info("Directory watcher finished."); } }
92371750558b0320d93dac14cf9bae4d717084aa
2,972
java
Java
admin/src/main/java/com/xinqihd/sns/gameserver/admin/data/WeaponManualDataImportService.java
zyb2013/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
21
2015-04-13T18:29:56.000Z
2020-02-03T20:35:32.000Z
admin/src/main/java/com/xinqihd/sns/gameserver/admin/data/WeaponManualDataImportService.java
zyb2013/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
2
2016-01-07T01:57:39.000Z
2016-05-07T15:40:18.000Z
admin/src/main/java/com/xinqihd/sns/gameserver/admin/data/WeaponManualDataImportService.java
wangqi/gameserver
a06cbd577684767dc50f61ff2a7a65be6001aec1
[ "Apache-2.0" ]
18
2015-07-26T04:12:41.000Z
2021-08-16T10:03:02.000Z
23.967742
79
0.70895
997,933
package com.xinqihd.sns.gameserver.admin.data; import java.awt.Point; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.JDialog; import javax.swing.JProgressBar; import javax.swing.SwingWorker; import net.miginfocom.swing.MigLayout; import org.jdesktop.swingx.JXLabel; import org.jdesktop.swingx.JXPanel; import org.jdesktop.swingx.util.WindowUtils; /** * 武器的数据文件可以导出为EXCEL格式,策划可以手工编辑这个文件,修改新的数值并导入系统。 * 注意: * 1: 以'#'开始的行为注释 * 2: 该文件应只还有'黑铁'类型的武器数值,其他类型由系统根据强化10级自动计算 * @author wangqi * */ public class WeaponManualDataImportService extends SwingWorker<Void, Integer> { private JDialog dialog = null; private JProgressBar progressBar = new JProgressBar();; private JXPanel panel = null; private JXLabel label = new JXLabel("正在读取文件中的武器数值"); private Stage stage = Stage.INIT; private int totalCount = 100; private WeaponTableModel weaponModel = null; private File importExcelFile = null; private ArrayList<Double> levelDprList = null; public WeaponManualDataImportService( File file, WeaponTableModel model, ArrayList<Double> dprList) { this.importExcelFile = file; this.weaponModel = model; this.levelDprList = dprList; panel = new JXPanel(); panel.setLayout(new MigLayout("wrap 1")); panel.add(label, "growx, wrap 20"); panel.add(progressBar, "grow, push"); dialog = new JDialog(); dialog.add(panel); dialog.setSize(300, 120); Point p = WindowUtils.getPointForCentering(dialog); dialog.setLocation(p); dialog.setModal(true); dialog.setResizable(false); dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); } public JDialog getDialog() { return dialog; } /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Void doInBackground() throws Exception { stage = Stage.INIT; publish(); stage = Stage.READ_DATA; publish(); ((WeaponTableModel)weaponModel).importExcel( this.importExcelFile, this.levelDprList); stage = Stage.SAVE_DATA; publish(); return null; } /* (non-Javadoc) * @see javax.swing.SwingWorker#process(java.util.List) */ @Override protected void process(List<Integer> chunks) { if ( stage == Stage.INIT ) { // dialog.setVisible(true); progressBar.setMinimum(0); progressBar.setMaximum(totalCount*2); progressBar.setStringPainted(true); } else { int value = 0; if ( chunks != null && chunks.size()>0 ) { value = chunks.get(chunks.size()-1); } if ( stage == Stage.READ_DATA ) { label.setText("正在读取文件中的武器数值..."); progressBar.setValue(value); } else if ( stage == Stage.SAVE_DATA ) { label.setText("正在保存装备数据..."); progressBar.setValue(totalCount+value); } } } /* (non-Javadoc) * @see javax.swing.SwingWorker#done() */ @Override protected void done() { this.dialog.dispose(); // JOptionPane.showMessageDialog(null, "数据同步成功!"); } static enum Stage { INIT, READ_DATA, SAVE_DATA, } }
923717549582cd9ab6535a2ec6a4b53204e3a30b
1,301
java
Java
JuneLeetCode/JuneLeetCode/src/main/java/org/phoenix/leetcode/challenges/Problem20_PermutationSequence.java
vibhorsingh11/LeetCode
91ba17179ea36b9949f4f887b41cca0504939755
[ "MIT" ]
null
null
null
JuneLeetCode/JuneLeetCode/src/main/java/org/phoenix/leetcode/challenges/Problem20_PermutationSequence.java
vibhorsingh11/LeetCode
91ba17179ea36b9949f4f887b41cca0504939755
[ "MIT" ]
3
2020-06-28T16:54:14.000Z
2021-02-01T16:17:33.000Z
JuneLeetCode/JuneLeetCode/src/main/java/org/phoenix/leetcode/challenges/Problem20_PermutationSequence.java
vibhorsingh11/LeetCode
91ba17179ea36b9949f4f887b41cca0504939755
[ "MIT" ]
null
null
null
22.431034
100
0.541122
997,934
package org.phoenix.leetcode.challenges; /* * The set [1,2,3,...,n] contains a total of n! unique permutations. * By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" * Given n and k, return the kth permutation sequence. * * Note: * Given n will be between 1 and 9 inclusive. * Given k will be between 1 and n! inclusive. * * Example 1: * Input: n = 3, k = 3 * Output: "213" * * Example 2: * Input: n = 4, k = 9 * Output: "2314" */ import java.util.ArrayList; import java.util.List; public class Problem20_PermutationSequence { public String getPermutation(int n, int k) { if (n <= 0 || k <= 0) { return ""; } List<Integer> numbers = new ArrayList<>(n); for (int i = 1; i <= n; i++) { numbers.add(i); } int factorial = 1; for (int i = 2; i <= n; i++) { factorial *= i; } k--; StringBuilder result = new StringBuilder(); for (int i = 0; i < n; i++) { factorial /= (n - i); int index = k / factorial; result.append(numbers.get(index)); numbers.remove(index); k %= factorial; } return result.toString(); } }
9237194dc8fddee08a716f02de7e676408decd08
4,225
java
Java
dhis2/src/test/java/org/motechproject/dhis2/it/Dhis2DummyServer.java
kmadej/modules
d04b6bd8203dae2c89991194ee544afd3211187a
[ "BSD-3-Clause" ]
null
null
null
dhis2/src/test/java/org/motechproject/dhis2/it/Dhis2DummyServer.java
kmadej/modules
d04b6bd8203dae2c89991194ee544afd3211187a
[ "BSD-3-Clause" ]
null
null
null
dhis2/src/test/java/org/motechproject/dhis2/it/Dhis2DummyServer.java
kmadej/modules
d04b6bd8203dae2c89991194ee544afd3211187a
[ "BSD-3-Clause" ]
null
null
null
45.923913
162
0.711953
997,935
package org.motechproject.dhis2.it; import org.apache.commons.io.IOUtils; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.AbstractHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.Charset; public class Dhis2DummyServer { private static final Logger LOGGER = LoggerFactory.getLogger(Dhis2DummyServer.class); private static final String PROGRAM_ENDPOINT = "/programs/programId"; private static final String DATA_ELEMENTS_ENDPOINT = "/dataElements"; private static final String DATA_SETS_ENDPOINT = "/dataSets"; private static final String ORGANISATION_UNITS_ENDPOINT = "/organisationUnits"; private static final String PROGRAMS_ENDPOINT = "/programs"; private static final String TRACKED_ENTITIES_ENDPOINT = "/trackedEntities"; private static final String TRACKED_ENTITY_ATTRIBUTES_ENDPOINT = "/trackedEntityAttributes"; private static final String PROGRAM_RESPONSE = "/json/program-response.json"; private static final String DATA_ELEMENTS_RESPONSE = "/json/data-elements-response.json"; private static final String DATA_SETS_RESPONSE = "/json/data-sets-response.json"; private static final String ORGANISATION_UNITS_RESPONSE = "/json/organisation-units-response.json"; private static final String PROGRAMS_RESPONSE = "/json/programs-response.json"; private static final String TRACKED_ENTITIES_RESPONSE = "/json/tracked-entities-response.json"; private static final String TRACKED_ENTITY_ATTRIBUTES_RESPONSE = "/json/tracked-entity-attributes-response.json"; private Server server; public Dhis2DummyServer() { server = new Server(9780); } public void start() { try { server.setHandler(new Dhis2RequestsHandler()); server.start(); } catch (Exception e) { LOGGER.error("Failed to start the Jetty server.", e); } } public void stop() { try { server.stop(); } catch (Exception e) { LOGGER.error("Failed to stop the Jetty server.", e); } } private static class Dhis2RequestsHandler extends AbstractHandler { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { String requestURI = httpServletRequest.getRequestURI().toString(); if (requestURI.contains(PROGRAM_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAM_RESPONSE); } else if (requestURI.contains(DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_ELEMENTS_RESPONSE); } else if (requestURI.contains(DATA_SETS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_SETS_RESPONSE); } else if (requestURI.contains(ORGANISATION_UNITS_ENDPOINT)) { writeResponse(httpServletResponse, ORGANISATION_UNITS_RESPONSE); } else if (requestURI.contains(PROGRAMS_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAMS_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITIES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITIES_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITY_ATTRIBUTES_RESPONSE); } } private void writeResponse(HttpServletResponse response, String filePath) throws IOException { response.setContentType("application/json; charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); try (InputStream inputStream = getClass().getResourceAsStream(filePath); PrintWriter responseWriter = response.getWriter()) { responseWriter.println(IOUtils.toString(inputStream, Charset.forName("UTF-8"))); } } } }
923719cc6ff89461d5e211dc289d2a0e29ed617e
188,032
java
Java
JavaSource/org/unitime/timetable/gwt/client/sectioning/StudentSectioningWidget.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
3
2016-02-12T07:09:03.000Z
2021-04-02T13:24:34.000Z
JavaSource/org/unitime/timetable/gwt/client/sectioning/StudentSectioningWidget.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
null
null
null
JavaSource/org/unitime/timetable/gwt/client/sectioning/StudentSectioningWidget.java
avilaton/unitime
e2daa8d78fa3175c9ae507d9c16607926245da84
[ "Apache-2.0" ]
null
null
null
48.511868
419
0.702178
997,936
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.gwt.client.sectioning; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.unitime.timetable.gwt.client.ToolBox; import org.unitime.timetable.gwt.client.aria.AriaButton; import org.unitime.timetable.gwt.client.aria.AriaStatus; import org.unitime.timetable.gwt.client.aria.AriaTabBar; import org.unitime.timetable.gwt.client.sectioning.StudentSectioningPage.Mode; import org.unitime.timetable.gwt.client.sectioning.TimeGrid.Meeting; import org.unitime.timetable.gwt.client.widgets.CourseFinder; import org.unitime.timetable.gwt.client.widgets.CourseFinderClasses; import org.unitime.timetable.gwt.client.widgets.CourseFinderCourses; import org.unitime.timetable.gwt.client.widgets.CourseFinderDetails; import org.unitime.timetable.gwt.client.widgets.CourseFinderDialog; import org.unitime.timetable.gwt.client.widgets.DataProvider; import org.unitime.timetable.gwt.client.widgets.ImageLink; import org.unitime.timetable.gwt.client.widgets.LoadingWidget; import org.unitime.timetable.gwt.client.widgets.P; import org.unitime.timetable.gwt.client.widgets.UniTimeConfirmationDialog; import org.unitime.timetable.gwt.client.widgets.UniTimeHeaderPanel; import org.unitime.timetable.gwt.client.widgets.WebTable; import org.unitime.timetable.gwt.resources.GwtAriaMessages; import org.unitime.timetable.gwt.resources.GwtMessages; import org.unitime.timetable.gwt.resources.StudentSectioningConstants; import org.unitime.timetable.gwt.resources.StudentSectioningMessages; import org.unitime.timetable.gwt.resources.StudentSectioningResources; import org.unitime.timetable.gwt.services.SectioningService; import org.unitime.timetable.gwt.services.SectioningServiceAsync; import org.unitime.timetable.gwt.shared.AcademicSessionProvider; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface; import org.unitime.timetable.gwt.shared.CourseRequestInterface; import org.unitime.timetable.gwt.shared.DegreePlanInterface; import org.unitime.timetable.gwt.shared.SectioningException; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.CancelSpecialRegistrationRequest; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.CancelSpecialRegistrationResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.ChangeGradeModesResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.RetrieveAllSpecialRegistrationsRequest; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.RetrieveSpecialRegistrationResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SpecialRegistrationContext; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SpecialRegistrationEligibilityRequest; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SpecialRegistrationEligibilityResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SpecialRegistrationStatus; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SubmitSpecialRegistrationRequest; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.SubmitSpecialRegistrationResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.UpdateSpecialRegistrationRequest; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.UpdateSpecialRegistrationResponse; import org.unitime.timetable.gwt.shared.SpecialRegistrationInterface.VariableTitleCourseResponse; import org.unitime.timetable.gwt.shared.AcademicSessionProvider.AcademicSessionChangeEvent; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface.ClassAssignment; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface.CourseAssignment; import org.unitime.timetable.gwt.shared.ClassAssignmentInterface.ErrorMessage; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CheckCoursesResponse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.CourseMessage; import org.unitime.timetable.gwt.shared.CourseRequestInterface.FreeTime; import org.unitime.timetable.gwt.shared.CourseRequestInterface.Preference; import org.unitime.timetable.gwt.shared.CourseRequestInterface.Request; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestPriority; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourse; import org.unitime.timetable.gwt.shared.CourseRequestInterface.RequestedCourseStatus; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.EligibilityCheck.EligibilityFlag; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.GradeMode; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.StudentSectioningContext; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface.WaitListMode; import org.unitime.timetable.gwt.shared.OnlineSectioningInterface; import org.unitime.timetable.gwt.shared.UserAuthenticationProvider; import com.google.gwt.aria.client.Id; import com.google.gwt.aria.client.Roles; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.RunAsyncCallback; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Style.Overflow; import com.google.gwt.dom.client.Style.TextAlign; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.HasResizeHandlers; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.LocaleInfo; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Cookies; import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; /** * @author Tomas Muller */ public class StudentSectioningWidget extends Composite implements HasResizeHandlers { public static final StudentSectioningResources RESOURCES = GWT.create(StudentSectioningResources.class); public static final StudentSectioningMessages MESSAGES = GWT.create(StudentSectioningMessages.class); public static final StudentSectioningConstants CONSTANTS = GWT.create(StudentSectioningConstants.class); public static final GwtAriaMessages ARIA = GWT.create(GwtAriaMessages.class); public static final GwtMessages GWT_MESSAGES = GWT.create(GwtMessages.class); private static DateTimeFormat sDF = DateTimeFormat.getFormat(CONSTANTS.requestWaitListedDateFormat()); private final SectioningServiceAsync iSectioningService = GWT.create(SectioningService.class); private AcademicSessionProvider iSessionSelector; private UserAuthenticationProvider iUserAuthentication; private VerticalPanel iPanel; private P iFooter, iHeader; private AriaMultiButton iRequests, iReset, iSchedule, iEnroll, iPrint, iExport = null, iSave, iStartOver, iDegreePlan, iChangeGradeModes, iAdvisorReqs; private AriaTabBar iAssignmentTab; private DockPanel iAssignmentDock; private FocusPanel iAssignmentPanel; private ImageLink iCalendar = null; private CourseRequestsTable iCourseRequests; private WebTable iAssignments; private TimeGrid iAssignmentGrid; private SuggestionsBox iSuggestionsBox; private CheckBox iShowUnassignments; private Label iTotalCredit; private P iGridMessage; private Image iTotalCreditRequestsStatus; private P iTotalCreditRequests; private SpecialRegistrationsPanel iSpecialRegistrationsPanel; private WaitListsPanel iWaitListsPanel; private ArrayList<ClassAssignmentInterface.ClassAssignment> iLastResult, iLastEnrollment; private ClassAssignmentInterface iLastAssignment, iSavedAssignment = null, iSpecialRegAssignment = null; private CourseRequestInterface iSavedRequest = null; private ArrayList<HistoryItem> iHistory = new ArrayList<HistoryItem>(); private boolean iInRestore = false; private boolean iTrackHistory = true; private StudentSectioningContext iContext; private SpecialRegistrationContext iSpecRegCx = new SpecialRegistrationContext(); private StudentSectioningPage.Mode iMode = null; private OnlineSectioningInterface.EligibilityCheck iEligibilityCheck = null; private PinDialog iPinDialog = null; private boolean iScheduleChanged = false; private ScheduleStatus iStatus = null; private AriaButton iQuickAdd, iRequestVarTitleCourse; private CourseFinder iQuickAddFinder = null; private SuggestionsBox iQuickAddSuggestions = null; private CheckBox iCustomCheckbox = null; private DegreePlansSelectionDialog iDegreePlansSelectionDialog = null; private DegreePlanDialog iDegreePlanDialog = null; private ChangeGradeModesDialog iChangeGradeModesDialog = null; private RequestVariableTitleCourseDialog iRequestVariableTitleCourseDialog = null; private Float iCurrentCredit = null; public StudentSectioningWidget(boolean online, AcademicSessionProvider sessionSelector, UserAuthenticationProvider userAuthentication, StudentSectioningPage.Mode mode, boolean history) { iMode = mode; iContext = new StudentSectioningContext(); iContext.setOnline(online); iContext.setSectioning(mode.isSectioning()); iContext.setSessionId(sessionSelector.getAcademicSessionId()); iSessionSelector = sessionSelector; iUserAuthentication = userAuthentication; iTrackHistory = history; iPanel = new VerticalPanel(); iPanel.addStyleName("unitime-SchedulingAssistant"); iCourseRequests = new CourseRequestsTable(iContext, iSpecRegCx); iCourseRequests.addValueChangeHandler(new ValueChangeHandler<CourseRequestInterface>() { @Override public void onValueChange(ValueChangeEvent<CourseRequestInterface> event) { if (iTotalCreditRequests != null) { iTotalCreditRequestsStatus.setVisible(false); if (!isChanged() && iSavedRequest != null && iSavedRequest.getMaxCreditOverrideStatus() != null) { String cw = (iSavedRequest.hasCreditWarning() ? iSavedRequest.getCreditWarning() : MESSAGES.creditWarning(iSavedRequest.getMaxCredit())); String note = ""; if (iSavedRequest.hasRequestorNote()) note += "\n" + MESSAGES.requestNote(iSavedRequest.getRequestorNote()); if (iSavedRequest.hasCreditNote()) note += "\n" + MESSAGES.overrideNote(iSavedRequest.getCreditNote()); switch (iSavedRequest.getMaxCreditOverrideStatus()) { case CREDIT_HIGH: iTotalCreditRequestsStatus.setResource(RESOURCES.requestNeeded()); iTotalCreditRequestsStatus.setAltText(cw + "\n" + MESSAGES.creditStatusTooHigh() + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case OVERRIDE_REJECTED: iTotalCreditRequestsStatus.setResource(RESOURCES.requestError()); iTotalCreditRequestsStatus.setAltText(cw + "\n" + MESSAGES.creditStatusDenied() + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case OVERRIDE_CANCELLED: iTotalCreditRequestsStatus.setResource(RESOURCES.requestNeeded()); iTotalCreditRequestsStatus.setAltText(cw + "\n" + MESSAGES.creditStatusCancelled() + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case CREDIT_LOW: case OVERRIDE_NEEDED: iTotalCreditRequestsStatus.setResource(RESOURCES.requestNeeded()); iTotalCreditRequestsStatus.setAltText(cw + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case OVERRIDE_PENDING: iTotalCreditRequestsStatus.setResource(RESOURCES.requestPending()); iTotalCreditRequestsStatus.setAltText(cw + "\n" + MESSAGES.creditStatusPending() + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case OVERRIDE_APPROVED: iTotalCreditRequestsStatus.setResource(RESOURCES.requestSaved()); iTotalCreditRequestsStatus.setAltText(MESSAGES.creditStatusApproved() + note); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; case SAVED: iTotalCreditRequestsStatus.setResource(RESOURCES.requestSaved()); iTotalCreditRequestsStatus.setAltText(note.isEmpty() ? "" : note.substring(1)); iTotalCreditRequestsStatus.setTitle(iTotalCreditRequestsStatus.getAltText()); iTotalCreditRequestsStatus.setVisible(true); break; } } float[] credit = iCourseRequests.getRequest().getCreditRange(iEligibilityCheck == null ? null : iEligibilityCheck.getAdvisorWaitListedCourseIds()); if (credit[1] > 0) { if (credit[0] != credit[1]) iTotalCreditRequests.setText(MESSAGES.totalCreditRange(credit[0], credit[1])); else iTotalCreditRequests.setText(MESSAGES.totalCredit(credit[0])); } else { iTotalCreditRequests.setText(""); } } if (!iMode.isSectioning() && iSavedRequest != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER)) { if (!iSavedRequest.equals(iCourseRequests.getRequest())) { iScheduleChanged = true; iSave.addStyleName("unitime-EnrollButton"); iStatus.warning(iSavedRequest.isEmpty() ? MESSAGES.warnRequestsEmptyOnCourseRequest() : MESSAGES.warnRequestsChangedOnCourseRequest(), false); } else if (iScheduleChanged) { iScheduleChanged = false; iSave.removeStyleName("unitime-EnrollButton"); clearMessage(); } return; } if (iLastAssignment == null || !iLastAssignment.isCanEnroll() || iEligibilityCheck == null || !iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL)) return; if (!iScheduleChanged) { courses: for (ClassAssignmentInterface.CourseAssignment course: iLastAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (CourseRequestInterface.Request r: event.getValue().getCourses()) { if (r.hasRequestedCourse(course)) continue courses; } for (CourseRequestInterface.Request r: event.getValue().getAlternatives()) { if (r.hasRequestedCourse(course)) continue courses; } iScheduleChanged = true; iStatus.warning(MESSAGES.warnScheduleChangedOnCourseRequest(), false); iEnroll.addStyleName("unitime-EnrollButton"); return; } } else if (MESSAGES.warnScheduleChangedOnCourseRequest().equals(iStatus.getMessage())) { updateScheduleChangedNoteIfNeeded(); } } }); iHeader = new P("unitime-SchedulingAssistantButtons", "unitime-SchedulingAssistantButtonsHeader"); iPanel.add(iHeader); iPanel.add(iCourseRequests); iFooter = new P("unitime-SchedulingAssistantButtons", "unitime-SchedulingAssistantButtonsFooter"); P leftFooterPanel = new P("left-panel"); P leftHeaderPanel = new P("left-panel"); iDegreePlan = new AriaMultiButton(MESSAGES.buttonDegreePlan()); iDegreePlan.setTitle(MESSAGES.hintDegreePlan()); iDegreePlan.setVisible(false); iDegreePlan.setEnabled(false); leftFooterPanel.add(iDegreePlan); leftHeaderPanel.add(iDegreePlan.createClone()); iAdvisorReqs = new AriaMultiButton(MESSAGES.buttonAdvisorRequests()); iAdvisorReqs.setTitle(MESSAGES.hintAdvisorRequests()); iAdvisorReqs.setVisible(false); iAdvisorReqs.setEnabled(false); leftFooterPanel.add(iAdvisorReqs); leftHeaderPanel.add(iAdvisorReqs.createClone()); iRequests = (LocaleInfo.getCurrentLocale().isRTL() ? new AriaMultiButton(MESSAGES.buttonRequests(), RESOURCES.arrowForward()) : new AriaMultiButton(RESOURCES.arrowBack(), MESSAGES.buttonRequests())); iRequests.setTitle(MESSAGES.hintRequests()); iRequests.setVisible(false); iRequests.setEnabled(false); leftFooterPanel.add(iRequests); leftHeaderPanel.add(iRequests.createClone()); iReset = new AriaMultiButton(MESSAGES.buttonReset()); iReset.setTitle(MESSAGES.hintReset()); iReset.setVisible(false); iReset.setEnabled(false); leftFooterPanel.add(iReset); leftHeaderPanel.add(iReset.createClone()); iFooter.add(leftFooterPanel); iHeader.add(leftHeaderPanel); if (mode == StudentSectioningPage.Mode.REQUESTS) { iTotalCreditRequestsStatus = new Image(); iTotalCreditRequestsStatus.addStyleName("credit-status"); iTotalCreditRequestsStatus.setVisible(false); iTotalCreditRequestsStatus.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (!iSpecRegCx.isAllowChangeRequestNote() || !iSpecRegCx.getChangeRequestorNoteInterface().changeRequestorCreditNote(iSavedRequest)) { if (iTotalCreditRequestsStatus.getAltText() != null && !iTotalCreditRequestsStatus.getAltText().isEmpty()) UniTimeConfirmationDialog.info(iTotalCreditRequestsStatus.getAltText()); } } }); iCourseRequests.setCreditStatusIcon(iTotalCreditRequestsStatus); iTotalCreditRequests = new P("credit-text"); P credit = new P("center-panel", "total-request-credit"); credit.add(iTotalCreditRequestsStatus); credit.add(iTotalCreditRequests); iFooter.add(credit); } P rightFooterPanel = new P("right-panel"); iFooter.add(rightFooterPanel); P rightHeaderPanel = new P("right-panel"); iHeader.add(rightHeaderPanel); iStartOver = new AriaMultiButton(MESSAGES.buttonStartOver()); iStartOver.setTitle(MESSAGES.hintStartOver()); leftFooterPanel.add(iStartOver); iStartOver.setVisible(false); iStartOver.setEnabled(false); leftHeaderPanel.add(iStartOver.createClone()); iSchedule = (LocaleInfo.getCurrentLocale().isRTL() ? new AriaMultiButton(RESOURCES.arrowBack(), MESSAGES.buttonSchedule()) : new AriaMultiButton(MESSAGES.buttonSchedule(), RESOURCES.arrowForward())); iSchedule.setTitle(MESSAGES.hintSchedule()); if (mode.isSectioning()) { rightFooterPanel.add(iSchedule); rightHeaderPanel.add(iSchedule.createClone()); } iSchedule.setVisible(mode.isSectioning()); iSchedule.setEnabled(mode.isSectioning()); iSave = new AriaMultiButton(MESSAGES.buttonSave()); iSave.setTitle(MESSAGES.hintSave()); if (!mode.isSectioning()) { rightFooterPanel.add(iSave); rightHeaderPanel.add(iSave.createClone()); } iSave.setVisible(!mode.isSectioning()); iSave.setEnabled(false); iEnroll = new AriaMultiButton(MESSAGES.buttonEnroll()); iEnroll.setTitle(MESSAGES.hintEnroll()); iEnroll.setVisible(false); iEnroll.setEnabled(false); rightFooterPanel.add(iEnroll); rightHeaderPanel.add(iEnroll.createClone()); iChangeGradeModes = new AriaMultiButton(MESSAGES.buttonChangeGradeModes()); iChangeGradeModes.setTitle(MESSAGES.hintChangeGradeModes()); iChangeGradeModes.setVisible(false); iChangeGradeModes.setEnabled(false); rightFooterPanel.add(iChangeGradeModes); rightHeaderPanel.add(iChangeGradeModes.createClone()); iRequestVarTitleCourse = new AriaMultiButton(RESOURCES.quickAddCourse(), MESSAGES.buttonRequestVariableTitleCourse()); iRequestVarTitleCourse.setStyleName("unitime-QuickAddButton"); iRequestVarTitleCourse.setTitle(MESSAGES.hintRequestVariableTitleCourse()); iRequestVarTitleCourse.setVisible(false); iRequestVarTitleCourse.setEnabled(false); iPrint = new AriaMultiButton(MESSAGES.buttonPrint()); iPrint.setTitle(MESSAGES.hintPrint()); iPrint.setVisible(false); iPrint.setEnabled(false); rightFooterPanel.add(iPrint); rightHeaderPanel.add(iPrint.createClone()); if (CONSTANTS.allowCalendarExport()) { iExport = new AriaMultiButton(MESSAGES.buttonExport()); iExport.setTitle(MESSAGES.hintExport()); iExport.setVisible(false); iExport.setEnabled(false); rightFooterPanel.add(iExport); rightHeaderPanel.add(iExport.createClone()); } iPanel.add(iFooter); iStatus = new ScheduleStatus(); iPanel.add(iStatus); iLastResult = new ArrayList<ClassAssignmentInterface.ClassAssignment>(); iQuickAdd = new AriaButton(RESOURCES.quickAddCourse(), MESSAGES.buttonQuickAdd()); iQuickAdd.setTitle(MESSAGES.hintQuickAdd()); iQuickAdd.setStyleName("unitime-QuickAddButton"); iQuickAdd.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { getQuickAddFinder().findCourse(); } }); iQuickAdd.setEnabled(false); iQuickAdd.setVisible(false); iDegreePlan.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { LoadingWidget.getInstance().show(MESSAGES.waitListDegreePlans()); iSectioningService.listDegreePlans(iContext, new AsyncCallback<List<DegreePlanInterface>>() { @Override public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); if (caught instanceof SectioningException) { SectioningException s = (SectioningException)caught; if (s.isInfo()) iStatus.info(s.getMessage()); else if (s.isWarning()) iStatus.warning(s.getMessage()); else if (s.isError()) iStatus.error(s.getMessage()); else iStatus.error(MESSAGES.failedListDegreePlans(s.getMessage()), s); } else { iStatus.error(MESSAGES.failedListDegreePlans(caught.getMessage()), caught); } } @Override public void onSuccess(List<DegreePlanInterface> result) { LoadingWidget.getInstance().hide(); if (result == null || result.isEmpty()) { iStatus.info(MESSAGES.failedNoDegreePlans()); } else { CourseFinderDetails details = new CourseFinderDetails(); details.setDataProvider(new DataProvider<CourseAssignment, String>() { @Override public void getData(CourseAssignment source, AsyncCallback<String> callback) { iSectioningService.retrieveCourseDetails(iContext, source.hasUniqueName() ? source.getCourseName() : source.getCourseNameWithTitle(), callback); } }); CourseFinderClasses classes = new CourseFinderClasses(false, iSpecRegCx); classes.setDataProvider(new DataProvider<CourseAssignment, Collection<ClassAssignment>>() { @Override public void getData(CourseAssignment source, AsyncCallback<Collection<ClassAssignment>> callback) { iSectioningService.listClasses(iContext, source.hasUniqueName() ? source.getCourseName() : source.getCourseNameWithTitle(), callback); } }); if (iDegreePlanDialog == null) { iDegreePlanDialog = new DegreePlanDialog(iMode, iCourseRequests, new DegreePlanDialog.AssignmentProvider() { @Override public ClassAssignmentInterface getSavedAssignment() { return iSavedAssignment; } @Override public ClassAssignmentInterface getLastAssignment() { return iLastAssignment; } }, details, classes) { protected void doBack() { super.doBack(); iDegreePlansSelectionDialog.show(); } protected void doApply() { updateHistory(); super.doApply(); addHistory(); } }; } if (iDegreePlansSelectionDialog == null) { iDegreePlansSelectionDialog = new DegreePlansSelectionDialog() { public void doSubmit(DegreePlanInterface plan) { super.doSubmit(plan); iDegreePlanDialog.open(plan, true); } }; } if (result.size() == 1) iDegreePlanDialog.open(result.get(0), false); else iDegreePlansSelectionDialog.open(result); } } }); } }); iAdvisorReqs.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { LoadingWidget.getInstance().show(MESSAGES.waitAdvisorRequests()); iSectioningService.getAdvisorRequests(iContext, new AsyncCallback<CourseRequestInterface>() { @Override public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); if (caught instanceof SectioningException) { SectioningException s = (SectioningException)caught; if (s.isInfo()) iStatus.info(s.getMessage()); else if (s.isWarning()) iStatus.warning(s.getMessage()); else if (s.isError()) iStatus.error(s.getMessage()); else iStatus.error(MESSAGES.failedAdvisorRequests(s.getMessage()), s); } else { iStatus.error(MESSAGES.failedAdvisorRequests(caught.getMessage()), caught); } } @Override public void onSuccess(CourseRequestInterface result) { LoadingWidget.getInstance().hide(); new AdvisorCourseRequestsDialog(iCourseRequests, new DegreePlanDialog.AssignmentProvider() { @Override public ClassAssignmentInterface getSavedAssignment() { return iSavedAssignment; } @Override public ClassAssignmentInterface getLastAssignment() { return iLastAssignment; } }) { @Override protected void doApply() { updateHistory(); super.doApply(); addHistory(); } }.open(result); } }); } }); iSpecRegCx.setChangeRequestorNote(new SpecialRegistrationInterface.ChangeRequestorNoteInterface() { @Override public boolean changeRequestorNote(final RequestedCourse rc) { if (rc == null || rc.getRequestId() == null || rc.getStatus() != RequestedCourseStatus.OVERRIDE_PENDING) return false; String message = null; if (iCourseRequests.getLastCheck() != null) { for (CourseMessage m: iCourseRequests.getLastCheck().getMessages(rc.getCourseName())) { if ("NO_ALT".equals(m.getCode())) continue; if ("OVERLAP".equals(m.getCode())) continue; if ("CREDIT".equals(m.getCode())) continue; if ("WL-OVERLAP".equals(m.getCode())) continue; if ("WL-CREDIT".equals(m.getCode())) continue; if (message == null) message = MESSAGES.courseMessage(m.getMessage()); else message += "\n" + MESSAGES.courseMessage(m.getMessage()); } } if (message == null && iSavedRequest != null && iSavedRequest.hasConfirmations()) { for (CourseMessage m: iSavedRequest.getConfirmations()) { if ("NO_ALT".equals(m.getCode())) continue; if ("OVERLAP".equals(m.getCode())) continue; if ("CREDIT".equals(m.getCode())) continue; if ("WL-OVERLAP".equals(m.getCode())) continue; if ("WL-CREDIT".equals(m.getCode())) continue; if (m.hasCourse() && rc.getCourseId().equals(m.getCourseId())) { if (message == null) message = MESSAGES.courseMessage(m.getMessage()); else message += "\n" + MESSAGES.courseMessage(m.getMessage()); } } } if (message == null) return false; CheckCoursesResponse confirm = new CheckCoursesResponse(); confirm.setConfirmation(0, MESSAGES.dialogChangeRequestNote(rc.getCourseName()), MESSAGES.buttonChangeRequestNote(), MESSAGES.buttonHideRequestNote(), MESSAGES.titleChangeRequestNote(), MESSAGES.titleHideRequestNote()); confirm.addConfirmation(MESSAGES.requestedWarnings(message), 0, 1); confirm.addConfirmation("\n" + MESSAGES.messageRequestOverridesNote(), 0, 2); final CourseRequestInterface.CourseMessage note = confirm.addConfirmation(rc.hasRequestorNote() ? rc.getRequestorNote() : "", 0, 3); note.setCode("REQUEST_NOTE"); if (rc.hasRequestorNoteSuggestions()) for (String suggestion: rc.getRequestorNoteSuggestions()) note.addSuggestion(suggestion); if (rc.hasStatusNote()) confirm.addConfirmation("\n" + MESSAGES.overrideNote(rc.getStatusNote()), 0, 4); CourseRequestsConfirmationDialog.confirm(confirm, 0, RESOURCES.statusInfo(), new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { final String requestorNote = note.getMessage(); UpdateSpecialRegistrationRequest request = new UpdateSpecialRegistrationRequest( iContext, rc.getRequestId(), requestorNote, iMode == Mode.REQUESTS); iSectioningService.updateSpecialRequest(request, new AsyncCallback<UpdateSpecialRegistrationResponse>() { @Override public void onSuccess(UpdateSpecialRegistrationResponse result) { if (result.isFailure() && result.hasMessage()) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(result.getMessage())); } else { CourseRequestInterface req = iCourseRequests.getValue(); if (req.updateRequestorNote(rc.getRequestId(), requestorNote)) { iCourseRequests.setValue(req); } if (iSavedRequest != null) { iSavedRequest.updateRequestorNote(rc.getRequestId(), requestorNote); if (iWaitListsPanel != null) iWaitListsPanel.populate(iSavedRequest); } updateHistory(); } } @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(caught.getMessage()), caught); } }); } } @Override public void onFailure(Throwable caught) {} }); return true; } @Override public boolean changeRequestorCreditNote(final CourseRequestInterface request) { if (request == null || request.getRequestId() == null || request.getMaxCreditOverrideStatus() != RequestedCourseStatus.OVERRIDE_PENDING) return false; String message = (request.hasCreditWarning() ? request.getCreditWarning() : MESSAGES.creditWarning(request.getMaxCredit())); CheckCoursesResponse confirm = new CheckCoursesResponse(); confirm.setConfirmation(0, MESSAGES.dialogChangeCreditRequestNote(), MESSAGES.buttonChangeRequestNote(), MESSAGES.buttonHideRequestNote(), MESSAGES.titleChangeRequestNote(), MESSAGES.titleHideRequestNote()); confirm.addConfirmation(MESSAGES.requestedWarnings(MESSAGES.courseMessage(message)), 0, 1); confirm.addConfirmation("\n" + MESSAGES.messageRequestOverridesNote(), 0, 2); final CourseRequestInterface.CourseMessage note = confirm.addConfirmation(request.hasRequestorNote() ? request.getRequestorNote() : "", 0, 3); note.setCode("REQUEST_NOTE"); if (request.hasRequestorNoteSuggestions()) for (String suggestion: request.getRequestorNoteSuggestions()) note.addSuggestion(suggestion); if (request.hasCreditNote()) confirm.addConfirmation("\n" + MESSAGES.overrideNote(request.getCreditNote()), 0, 4); CourseRequestsConfirmationDialog.confirm(confirm, 0, RESOURCES.statusInfo(), new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { final String requestorNote = note.getMessage(); UpdateSpecialRegistrationRequest req = new UpdateSpecialRegistrationRequest( iContext, request.getRequestId(), requestorNote, iMode == Mode.REQUESTS); iSectioningService.updateSpecialRequest(req, new AsyncCallback<UpdateSpecialRegistrationResponse>() { @Override public void onSuccess(UpdateSpecialRegistrationResponse result) { if (result.isFailure() && result.hasMessage()) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(result.getMessage())); } else { if (request.updateRequestorNote(request.getRequestId(), requestorNote)) { iCourseRequests.setValue(request); if (iWaitListsPanel != null) iWaitListsPanel.populate(request); } updateHistory(); } } @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(caught.getMessage()), caught); } }); } } @Override public void onFailure(Throwable caught) {} }); return true; } @Override public boolean changeRequestorNote(final RetrieveSpecialRegistrationResponse reg) { if (reg == null || reg.getRequestId() == null || reg.getStatus() != SpecialRegistrationStatus.Pending) return false; CheckCoursesResponse confirm = new CheckCoursesResponse(); confirm.setConfirmation(0, MESSAGES.dialogChangeSpecRegRequestNote(), MESSAGES.buttonChangeRequestNote(), MESSAGES.buttonHideRequestNote(), MESSAGES.titleChangeRequestNote(), MESSAGES.titleHideRequestNote()); if (reg.hasErrors()) { confirm.addConfirmation(MESSAGES.requestedApprovals(), 0, 1); for (ErrorMessage e: reg.getErrors()) confirm.addMessage(null, e.getCourse(), e.getCode(), e.getMessage(), 0, 2); } confirm.addConfirmation(MESSAGES.messageRequestOverridesNote(), 0, 3); final CourseRequestInterface.CourseMessage note = confirm.addConfirmation(reg.getNote() == null ? "" : reg.getNote(), 0, 4); note.setCode("REQUEST_NOTE"); if (reg.hasSuggestions()) for (String suggestion: reg.getSuggestions()) note.addSuggestion(suggestion); CourseRequestsConfirmationDialog.confirm(confirm, 0, RESOURCES.statusInfo(), new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { final String requestorNote = note.getMessage(); UpdateSpecialRegistrationRequest request = new UpdateSpecialRegistrationRequest( iContext, reg.getRequestId(), requestorNote, iMode == Mode.REQUESTS); iSectioningService.updateSpecialRequest(request, new AsyncCallback<UpdateSpecialRegistrationResponse>() { @Override public void onSuccess(UpdateSpecialRegistrationResponse result) { if (result.isFailure() && result.hasMessage()) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(result.getMessage())); } else { reg.setNote(requestorNote); iSpecialRegistrationsPanel.populate(iSpecialRegistrationsPanel.getRegistrations(), iSavedAssignment); updateHistory(); } } @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.updateSpecialRegistrationFail(caught.getMessage()), caught); } }); } } @Override public void onFailure(Throwable caught) {} }); return true; } }); initWidget(iPanel); init(); } /* private void initAsync() { GWT.runAsync(new RunAsyncCallback() { public void onSuccess() { init(); } public void onFailure(Throwable reason) { Label error = new Label(MESSAGES.failedToLoadTheApp(reason.getMessage())); error.setStyleName("unitime-ErrorMessage"); RootPanel.get("loading").setVisible(false); RootPanel.get("body").add(error); } }); } */ private void addHistory() { if (iInRestore || !iTrackHistory || iUserAuthentication.getUser() == null) return; iHistory.add(new HistoryItem()); History.newItem(String.valueOf(iHistory.size() - 1), false); } private void updateHistory() { if (iInRestore || !iTrackHistory || iUserAuthentication.getUser() == null) return; if (!iHistory.isEmpty()) iHistory.remove(iHistory.size() - 1); addHistory(); } private void init() { if (CONSTANTS.allowCalendarExport()) { iCalendar = new ImageLink(); iCalendar.setImage(new Image(RESOURCES.calendar())); iCalendar.setTarget(null); iCalendar.setTitle(MESSAGES.exportICalendar()); iCalendar.setAriaLabel(MESSAGES.exportICalendar()); } iAssignments = new WebTable(); WebTable.Cell grMd = new WebTable.Cell(MESSAGES.colGradeMode()); grMd.setTitle(MESSAGES.colTitleGradeMode()); grMd.setAriaLabel(MESSAGES.colTitleGradeMode()); iAssignments.setHeader(new WebTable.Row( new WebTable.Cell(MESSAGES.colLock()), new WebTable.Cell(MESSAGES.colSubject()), new WebTable.Cell(MESSAGES.colCourse()), new WebTable.Cell(MESSAGES.colSubpart()), new WebTable.Cell(MESSAGES.colClass()), new WebTable.Cell(MESSAGES.colLimit()).aria(ARIA.colLimit()), new WebTable.Cell(MESSAGES.colDays()), new WebTable.Cell(MESSAGES.colStart()), new WebTable.Cell(MESSAGES.colEnd()), new WebTable.Cell(MESSAGES.colDate()), new WebTable.Cell(MESSAGES.colRoom()), new WebTable.Cell(MESSAGES.colInstructor()), new WebTable.Cell(MESSAGES.colParent()), new WebTable.Cell(MESSAGES.colNote()), new WebTable.Cell(MESSAGES.colCredit()), grMd, (iCalendar != null ? new WebTable.WidgetCell(iCalendar, MESSAGES.colIcons()) : new WebTable.Cell(MESSAGES.colIcons())) )); iAssignments.setWidth("100%"); iAssignments.setEmptyMessage(MESSAGES.emptySchedule()); ScrollPanel assignmentsPanel = new ScrollPanel(iAssignments); assignmentsPanel.setStyleName("body"); assignmentsPanel.getElement().getStyle().setOverflowY(Overflow.HIDDEN); final P panel = new P("unitime-Panel"); panel.add(assignmentsPanel); iRequestVarTitleCourse.addStyleName("left"); iTotalCredit = new Label("", false); iShowUnassignments = new CheckBox(MESSAGES.showUnassignments()); iQuickAdd.addStyleName("left"); iRequestVarTitleCourse.addStyleName("left"); P bottom = new P("footer"); iTotalCredit.addStyleName("center"); iTotalCredit.getElement().getStyle().setMarginTop(3, Unit.PX); iShowUnassignments.addStyleName("right"); iShowUnassignments.getElement().getStyle().setMarginTop(3, Unit.PX); bottom.add(iQuickAdd); bottom.add(iRequestVarTitleCourse); bottom.add(iShowUnassignments); bottom.add(iTotalCredit); panel.add(bottom); iSpecialRegistrationsPanel = new SpecialRegistrationsPanel(iSpecRegCx) { public void doSubmit(final RetrieveSpecialRegistrationResponse specReg) { super.doSubmit(specReg); if (specReg == null) { iSpecRegCx.update(iEligibilityCheck); iSpecRegCx.setRequestId(null); iSpecRegCx.setStatus(null); iSpecRegCx.setNote(null); iSpecialRegAssignment = iSavedAssignment; fillIn(iSavedAssignment); addHistory(); } else { iSpecRegCx.setRequestId(specReg.getRequestId()); iSpecRegCx.setStatus(specReg.getStatus()); iSpecRegCx.setNote(specReg.getNote()); iSpecialRegAssignment = null; if ((specReg.hasChanges() && !specReg.isGradeModeChange() && !specReg.isCreditChange()) || (specReg.hasChanges() && specReg.isVariableTitleCourseChange())) { final CourseRequestInterface courseRequests = iCourseRequests.getRequest(); courseRequests.setTimeConflictsAllowed(specReg.hasTimeConflict()); courseRequests.setSpaceConflictsAllowed(specReg.hasSpaceConflict()); courseRequests.setLinkedConflictsAllowed(specReg.hasLinkedConflict()); courseRequests.setDeadlineConflictsAllowed(specReg.isExtended()); Set<Long> specRegDrops = new HashSet<Long>(); Set<Long> specRegAdds = new HashSet<Long>(); for (ClassAssignmentInterface.ClassAssignment ch: specReg.getChanges()) if (!ch.isCourseAssigned()) specRegDrops.add(ch.getCourseId()); else specRegAdds.add(ch.getCourseId()); for (ClassAssignmentInterface.ClassAssignment ch: specReg.getChanges()) if (ch.isCourseAssigned() && (!specRegDrops.contains(ch.getCourseId()) || ch.getSpecRegStatus() != null)) { RequestedCourse rc = new RequestedCourse(ch.getCourseId(), CONSTANTS.showCourseTitle() ? ch.getCourseNameWithTitle() : ch.getCourseName()); rc.setCanWaitList(ch.isCanWaitList()); courseRequests.addCourse(rc); } else if (!ch.isCourseAssigned() && !specRegAdds.contains(ch.getCourseId())) { RequestedCourse rc = new RequestedCourse(ch.getCourseId(), CONSTANTS.showCourseTitle() ? ch.getCourseNameWithTitle() : ch.getCourseName()); rc.setCanWaitList(ch.isCanWaitList()); courseRequests.dropCourse(rc); } LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); iSectioningService.section(courseRequests, iLastResult, specReg.getChanges(), new AsyncCallback<ClassAssignmentInterface>() { public void onSuccess(ClassAssignmentInterface result) { if (specReg.hasSpaceConflict() || specReg.hasTimeConflict() || specReg.hasLinkedConflict()) iSpecRegCx.setDisclaimerAccepted(true); iCourseRequests.setRequest(courseRequests); fillIn(result); addHistory(); // Wait-list check for (final ClassAssignmentInterface.CourseAssignment course: result.getCourseAssignments()) { if (!course.isFreeTime() && specReg.isAdd(course.getCourseId()) && !course.isAssigned() && course.isCanWaitList() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST) && course.isNotAvailable() && !iCourseRequests.isWaitListed(course.getCourseId())) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), (course.isFull() ? MESSAGES.suggestionsNoChoicesCourseIsFull(course.getCourseName()) : MESSAGES.suggestionsNoChoices(course.getCourseName()))+ "\n" + MESSAGES.confirmQuickWaitList(course.getCourseName()), new Command() { @Override public void execute() { final CourseRequestInterface undo = iCourseRequests.getRequest(); iCourseRequests.setWaitList(course.getCourseId(), true); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); iCourseRequests.setRequest(undo); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } }); break; } } } public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); } }); } else { fillIn(iSavedAssignment); addHistory(); } } } public void doCancel(String requestId, final AsyncCallback<Boolean> callback) { CancelSpecialRegistrationRequest req = new CancelSpecialRegistrationRequest(iContext); req.setRequestId(requestId); iSectioningService.cancelSpecialRequest(req, new AsyncCallback<CancelSpecialRegistrationResponse>() { @Override public void onSuccess(CancelSpecialRegistrationResponse result) { if (result.isFailure() && result.hasMessage()) iStatus.error(MESSAGES.cancelSpecialRegistrationFail(result.getMessage())); callback.onSuccess(result.isSuccess()); } @Override public void onFailure(Throwable caught) { callback.onFailure(caught); iStatus.error(MESSAGES.cancelSpecialRegistrationFail(caught.getMessage()), caught); } }); } }; panel.add(iSpecialRegistrationsPanel); iWaitListsPanel = new WaitListsPanel(iSpecRegCx); panel.add(iWaitListsPanel); iShowUnassignments.setVisible(false); String showUnassignments = Cookies.getCookie("UniTime:Unassignments"); iShowUnassignments.setValue(showUnassignments == null || "1".equals(showUnassignments)); iAssignmentGrid = new TimeGrid(); iGridMessage = new P("unitime-TimeGridMessage"); iGridMessage.setVisible(false); final P gridPanel = new P("unitime-TimeGridPanel"); gridPanel.add(iGridMessage); gridPanel.add(iAssignmentGrid); iAssignmentTab = new AriaTabBar(); iAssignmentTab.addTab(MESSAGES.tabClasses(), true); iAssignmentTab.addTab(MESSAGES.tabTimetable(), true); iAssignmentTab.selectTab(0); iAssignmentTab.addSelectionHandler(new SelectionHandler<Integer>() { @Override public void onSelection(SelectionEvent<Integer> event) { if (event.getSelectedItem() == 0) { iAssignmentPanel.setWidget(panel); AriaStatus.getInstance().setHTML(ARIA.listOfClasses()); } else { iAssignmentGrid.shrink(); iAssignmentPanel.setWidget(gridPanel); iAssignmentGrid.scrollDown(); AriaStatus.getInstance().setHTML(ARIA.timetable()); } addHistory(); ResizeEvent.fire(StudentSectioningWidget.this, StudentSectioningWidget.this.getOffsetWidth(), StudentSectioningWidget.this.getOffsetHeight()); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { iAssignmentPanel.setFocus(true); } }); } }); iAssignmentPanel = new FocusPanel(panel); iAssignmentPanel.setStyleName("unitime-ClassScheduleTabPanel"); iAssignmentPanel.addStyleName("unitime-FocusPanel"); final Character classesAccessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.tabClasses()); final Character timetableAccessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.tabTimetable()); iAssignmentPanel.addKeyUpHandler(new KeyUpHandler() { @Override public void onKeyUp(KeyUpEvent event) { if (iAssignmentTab.getSelectedTab() == 0) { if (event.getNativeKeyCode()==KeyCodes.KEY_DOWN) { do { iAssignments.setSelectedRow(iAssignments.getSelectedRow()+1); } while (iAssignments.getRows()[iAssignments.getSelectedRow()] != null && !iAssignments.getRows()[iAssignments.getSelectedRow()].isSelectable()); if (iAssignments.getSelectedRow() >= 0 && iAssignments.getSelectedRow() < iAssignments.getRows().length && iAssignments.getRows()[iAssignments.getSelectedRow()] != null) AriaStatus.getInstance().setHTML(ARIA.classSelected(1 + iAssignments.getSelectedRow(), iAssignments.getRowsCount(), iAssignments.getRows()[iAssignments.getSelectedRow()].getAriaLabel())); } if (event.getNativeKeyCode()==KeyCodes.KEY_UP) { do { iAssignments.setSelectedRow(iAssignments.getSelectedRow()==0?iAssignments.getRowsCount()-1:iAssignments.getSelectedRow()-1); } while (iAssignments.getRows()[iAssignments.getSelectedRow()] != null && !iAssignments.getRows()[iAssignments.getSelectedRow()].isSelectable()); if (iAssignments.getSelectedRow() >= 0 && iAssignments.getSelectedRow() < iAssignments.getRows().length && iAssignments.getRows()[iAssignments.getSelectedRow()] != null) AriaStatus.getInstance().setHTML(ARIA.classSelected(1 + iAssignments.getSelectedRow(), iAssignments.getRowsCount(), iAssignments.getRows()[iAssignments.getSelectedRow()].getAriaLabel())); } if (event.getNativeKeyCode()==KeyCodes.KEY_ENTER) { updateHistory(); showSuggestionsAsync(iAssignments.getSelectedRow()); } } int tab = -1; if (classesAccessKey != null && event.getNativeEvent().getCtrlKey() && ( event.getNativeKeyCode() == classesAccessKey || event.getNativeKeyCode() == Character.toUpperCase(classesAccessKey))) { tab = 0; } if (timetableAccessKey != null && event.getNativeEvent().getCtrlKey() && ( event.getNativeKeyCode() == timetableAccessKey || event.getNativeKeyCode() == Character.toUpperCase(timetableAccessKey))) { tab = 1; } if (tab >= 0) { iAssignmentTab.selectTab(tab); event.preventDefault(); } } }); iAssignmentDock = new DockPanel(); iAssignmentDock.setStyleName("unitime-ClassSchedulePanel"); iAssignmentDock.setSpacing(0); iAssignmentDock.add(iAssignmentPanel, DockPanel.SOUTH); iAssignmentDock.add(iAssignmentTab, DockPanel.WEST); iAssignmentDock.setCellWidth(iAssignmentTab, "33%"); iAssignmentDock.setCellVerticalAlignment(iAssignmentTab, HasVerticalAlignment.ALIGN_BOTTOM); iAssignmentDock.setCellHorizontalAlignment(iAssignmentTab, HasHorizontalAlignment.ALIGN_LEFT); Roles.getTabpanelRole().set(iAssignmentDock.getElement()); Roles.getTabpanelRole().setAriaOwnsProperty(iAssignmentDock.getElement(), Id.of(iAssignmentTab.getElement())); P header = new P("unitime-MainHeader"); header.setHTML(MESSAGES.headerClassSchedule()); header.getElement().getStyle().setTextAlign(TextAlign.CENTER); iAssignmentDock.add(header, DockPanel.CENTER); iAssignmentDock.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER); iAssignmentDock.setCellWidth(header, "34%"); P padding = new P("unitime-HeaderPadding"); padding.setHTML("&nbsp;"); iAssignmentDock.add(padding, DockPanel.EAST); iAssignmentDock.setCellWidth(padding, "33%"); iRequests.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { prev(); addHistory(); } }); iReset.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearMessage(); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); iSectioningService.section(iCourseRequests.getRequest(), null, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } }); iSchedule.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { iCourseRequests.changeTip(); clearMessage(); iCourseRequests.validate(new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { updateHistory(); if (result) { LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); iSectioningService.section(iCourseRequests.getRequest(), iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } else { String error = iCourseRequests.getFirstError(); iStatus.error(error == null ? MESSAGES.validationFailed() : MESSAGES.validationFailedWithMessage(error)); LoadingWidget.getInstance().hide(); updateHistory(); } } public void onFailure(Throwable caught) { if (caught != null) iStatus.error(MESSAGES.validationFailedWithMessage(caught.getMessage()), caught); else iStatus.error(MESSAGES.validationFailed()); LoadingWidget.getInstance().hide(); updateHistory(); } }); } }); iStartOver.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (isChanged()) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), iMode.isSectioning() ? MESSAGES.queryLeaveChangesOnClassSchedule() : MESSAGES.queryLeaveChangesOnCourseRequests(), new Command() { @Override public void execute() { clearMessage(); clear(false); iStartOver.setVisible(false); iStartOver.setEnabled(false); iSpecRegCx.reset(iEligibilityCheck); addHistory(); lastRequest(false); } }); } else { clearMessage(); clear(false); iStartOver.setVisible(false); iStartOver.setEnabled(false); iSpecRegCx.reset(iEligibilityCheck); addHistory(); lastRequest(false); } } }); iAssignments.addRowClickHandler(new WebTable.RowClickHandler() { public void onRowClick(WebTable.RowClickEvent event) { if (iLastResult.get(event.getRowIdx()) == null) return; updateHistory(); showSuggestionsAsync(event.getRowIdx()); } }); iAssignmentGrid.addMeetingClickHandler(new TimeGrid.MeetingClickHandler() { public void onMeetingClick(TimeGrid.MeetingClickEvent event) { updateHistory(); showSuggestionsAsync(event.getRowIndex()); } }); iAssignmentGrid.addPinClickHandler(new TimeGrid.PinClickHandler() { public void onPinClick(TimeGrid.PinClickEvent event) { ((HasValue<Boolean>)iAssignments.getRows()[event.getRowIndex()].getCell(0).getWidget()).setValue(event.isPinChecked(), false); iLastResult.get(event.getRowIndex()).setPinned(event.isPinChecked()); updateHistory(); } }); iEnroll.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Command enroll = new Command() { @Override public void execute() { clearMessage(); LoadingWidget.getInstance().show(MESSAGES.waitEnroll()); final ArrayList<ClassAssignmentInterface.ClassAssignment> lastEnrollment = new ArrayList<ClassAssignmentInterface.ClassAssignment>(iLastResult); iSectioningService.enroll(iCourseRequests.getRequest(), iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onSuccess(ClassAssignmentInterface result) { LoadingWidget.getInstance().hide(); iSavedAssignment = result; iStartOver.setVisible(iSavedAssignment != null && !iSavedAssignment.getCourseAssignments().isEmpty()); iStartOver.setEnabled(iSavedAssignment != null && !iSavedAssignment.getCourseAssignments().isEmpty()); if (result.hasCurrentCredit() && iEligibilityCheck != null) iEligibilityCheck.setCurrentCredit(result.getCurrentCredit()); if (result.getRequest() != null && result.getRequest().hasWaitListChecks()) iCourseRequests.setLastCheck(result.getRequest().getWaitListChecks()); if (result.hasRequest()) { for (Request r: result.getRequest().getCourses()) { for (RequestedCourse rc: r.getRequestedCourse()) { if (rc.hasCourseId() && !iCourseRequests.isActive(rc) && !r.isWaitList()) rc.setInactive(true); } } for (Request r: result.getRequest().getAlternatives()) { for (RequestedCourse rc: r.getRequestedCourse()) { if (rc.hasCourseId() && !iCourseRequests.isActive(rc) && !r.isWaitList()) rc.setInactive(true); } } iCourseRequests.setRequest(result.getRequest()); iSavedRequest = result.getRequest(); if (iWaitListsPanel != null) iWaitListsPanel.populate(result.getRequest()); } fillIn(result, iEligibilityCheck == null || !iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)); if (!result.hasMessages()) iStatus.done(MESSAGES.enrollOK()); updateHistory(); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.RECHECK_AFTER_ENROLLMENT)) { iSectioningService.checkEligibility(iContext, new AsyncCallback<OnlineSectioningInterface.EligibilityCheck>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(OnlineSectioningInterface.EligibilityCheck result) { setElibibilityCheckDuringEnrollment(result); } }); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)) { if (result.isError() || result.hasErrors()) { checkSpecialRegistrationAfterFailedSubmitSchedule(lastEnrollment, null, result, new Command() { @Override public void execute() { checkWaitListAfterSubmitSchedule(); } }); } else { checkWaitListAfterSubmitSchedule(); } iSpecialRegistrationsPanel.populate(iSpecialRegistrationsPanel.getRegistrations(), iSavedAssignment); } else { checkWaitListAfterSubmitSchedule(); } } public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)) iStatus.error(MESSAGES.enrollFailed(caught.getMessage()), (caught instanceof SectioningException && ((SectioningException)caught).isCanRequestOverride() ? false : true), caught); else iStatus.error(MESSAGES.enrollFailed(caught.getMessage()), caught); updateHistory(); if (caught instanceof SectioningException) { SectioningException se = (SectioningException) caught; EligibilityCheck check = se.getEligibilityCheck(); if (check != null) { setElibibilityCheckDuringEnrollment(check); if (check.hasFlag(EligibilityFlag.PIN_REQUIRED)) { if (iPinDialog == null) iPinDialog = new PinDialog(); PinDialog.PinCallback callback = new PinDialog.PinCallback() { @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionFailedEligibilityCheck(caught.getMessage()), caught); } @Override public void onSuccess(OnlineSectioningInterface.EligibilityCheck result) { setElibibilityCheckDuringEnrollment(result); if (result.hasFlag(EligibilityFlag.CAN_ENROLL) && !result.hasFlag(EligibilityFlag.RECHECK_BEFORE_ENROLLMENT)) iEnroll.click(); } @Override public void onMessage(OnlineSectioningInterface.EligibilityCheck result) { if (result.hasMessage()) { iStatus.error(result.getMessage()); } else if (result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.PIN_REQUIRED)) { iStatus.warning(MESSAGES.exceptionAuthenticationPinRequired()); } else { clearMessage(false); } } }; iPinDialog.checkEligibility(iContext, callback, iSessionSelector.getAcademicSessionInfo()); } } if (se.hasErrors()) iLastAssignment.setErrors(se.getErrors()); if (se.hasSectionMessages()) { for (CourseAssignment ca: iLastAssignment.getCourseAssignments()) { for (ClassAssignment c: ca.getClassAssignments()) { c.setError(se.getSectionMessage(c.getClassId())); } } fillIn(iLastAssignment); iStatus.error(caught.getMessage() , false); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG) && se.isCanRequestOverride()) { checkSpecialRegistrationAfterFailedSubmitSchedule(lastEnrollment, caught, null, null); } } } }); } }; enroll = confirmEnrollment(enroll); enroll.execute(); } }); iChangeGradeModes.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { changeGradeModes(new ArrayList<ClassAssignmentInterface.ClassAssignment>(iLastResult), iSpecialRegistrationsPanel.getRegistrations()); } }); iRequestVarTitleCourse.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { requestVariableTitleCourse(); } }); iPrint.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { boolean allSaved = true; for (ClassAssignmentInterface.ClassAssignment clazz: iLastResult) { if (clazz != null && !clazz.isFreeTime() && !clazz.isTeachingAssignment() && !clazz.isSaved()) allSaved = false; } Widget w = iAssignments.getPrintWidget(0, 5, 16); w.setWidth("100%"); ToolBox.print((allSaved && !isChanged() ? MESSAGES.studentSchedule() : MESSAGES.studentScheduleNotEnrolled()), (CONSTANTS.printReportShowUserName() ? iUserAuthentication.getUser() : ""), iSessionSelector.getAcademicSessionName(), iAssignmentGrid.getPrintWidget(900), w, iStatus); } }); if (iExport != null) iExport.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { ToolBox.open(iCalendar.getUrl()); } }); if (iTrackHistory) { History.addValueChangeHandler(new ValueChangeHandler<String>() { public void onValueChange(ValueChangeEvent<String> event) { if (!event.getValue().isEmpty()) { int item = iHistory.size() - 1; try { item = Integer.parseInt(event.getValue()); } catch (NumberFormatException e) {} if (item < 0) item = 0; if (item >= iHistory.size()) item = iHistory.size() - 1; if (item >= 0) iHistory.get(item).restore(); } else if (isChanged()) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), iMode.isSectioning() ? MESSAGES.queryLeaveChangesOnClassSchedule() : MESSAGES.queryLeaveChangesOnCourseRequests(), new Command() { @Override public void execute() { iCourseRequests.clear(); if (!iSchedule.isVisible()) prev(); } }); } } }); } iSessionSelector.addAcademicSessionChangeHandler(new AcademicSessionSelector.AcademicSessionChangeHandler() { public void onAcademicSessionChange(AcademicSessionChangeEvent event) { addHistory(); } }); iSave.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { addHistory(); iCourseRequests.changeTip(); clearMessage(); iCourseRequests.validate(new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { if (result) { LoadingWidget.getInstance().show(MESSAGES.courseRequestsSaving()); final CourseRequestInterface request = iCourseRequests.getRequest(); iSectioningService.saveRequest(request, new AsyncCallback<CourseRequestInterface>() { public void onSuccess(final CourseRequestInterface result) { if (result != null) { if (iScheduleChanged) { iScheduleChanged = false; clearMessage(); } iSavedRequest = result; if (iWaitListsPanel != null) iWaitListsPanel.populate(result); iCourseRequests.setValue(result, false); iCourseRequests.notifySaveSucceeded(); iStatus.done(MESSAGES.saveRequestsOK()); UniTimeConfirmationDialog.confirm(MESSAGES.saveRequestsConfirmation(), RESOURCES.statusDone(), new Command() { @Override public void execute() { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { printConfirmation(result); } }); } }); } LoadingWidget.getInstance().hide(); updateHistory(); } public void onFailure(Throwable caught) { iStatus.error(MESSAGES.saveRequestsFail(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } }); } else { if (iSavedRequest != null && !iSavedRequest.equals(iCourseRequests.getRequest())) { iScheduleChanged = true; iSave.addStyleName("unitime-EnrollButton"); iStatus.warning(iSavedRequest.isEmpty() ? MESSAGES.warnRequestsEmptyOnCourseRequest() : MESSAGES.warnRequestsChangedOnCourseRequest(), false); } updateHistory(); } } public void onFailure(Throwable caught) { if (caught != null) { iStatus.error(MESSAGES.validationFailedWithMessage(caught.getMessage()), caught); } else { String error = iCourseRequests.getFirstError(); iStatus.error(error == null ? MESSAGES.validationFailed() : MESSAGES.validationFailedWithMessage(error)); } if (iSavedRequest != null && !iSavedRequest.equals(iCourseRequests.getRequest())) { iScheduleChanged = true; } updateHistory(); } }); } }); iShowUnassignments.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { Cookies.setCookie("UniTime:Unassignments", event.getValue() ? "1" : "0"); fillIn(iLastAssignment); } }); } public void openSuggestionsBox(int rowIndex) { if (iSuggestionsBox == null) { iSuggestionsBox = new SuggestionsBox(iAssignmentGrid.getColorProvider(), iSpecRegCx); iSuggestionsBox.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { iAssignmentPanel.setFocus(true); } }); } }); iSuggestionsBox.addSuggestionSelectedHandler(new SuggestionsBox.SuggestionSelectedHandler() { public void onSuggestionSelected(SuggestionsBox.SuggestionSelectedEvent event) { ClassAssignmentInterface result = event.getSuggestion(); clearMessage(); fillIn(result); addHistory(); } }); iSuggestionsBox.addQuickDropHandler(new SuggestionsBox.QuickDropHandler() { @Override public void onQuickDrop(SuggestionsBox.QuickDropEvent event) { final CourseRequestInterface undo = iCourseRequests.getRequest(); iCourseRequests.dropCourse(event.getAssignment()); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); iCourseRequests.setRequest(undo); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } }); } iAssignments.setSelectedRow(rowIndex); clearMessage(); iSuggestionsBox.open(iCourseRequests.getRequest(), iLastResult, rowIndex, iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.ALTERNATIVES_DROP), useDefaultConfirmDialog()); } private void fillIn(ClassAssignmentInterface result) { fillIn(result, true); } private void fillIn(ClassAssignmentInterface result, boolean popup) { iLastEnrollment = null; iLastResult.clear(); iLastAssignment = result; String calendarUrl = GWT.getHostPageBaseURL() + "calendar?sid=" + iSessionSelector.getAcademicSessionId() + "&cid="; String ftParam = "&ft="; boolean hasError = false, hasWarning = false; iCurrentCredit = 0f; boolean hasGradeMode = false; if (!result.getCourseAssignments().isEmpty() || CONSTANTS.allowEmptySchedule()) { ArrayList<WebTable.Row> rows = new ArrayList<WebTable.Row>(); iAssignmentGrid.clear(true); for (final ClassAssignmentInterface.CourseAssignment course: result.getCourseAssignments()) { boolean firstClazz = true; if (course.isAssigned()) { if (course.getCourseId() != null) iCourseRequests.activate(course); for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.getClassId() != null) calendarUrl += clazz.getCourseId() + "-" + clazz.getClassId() + ","; else if (clazz.isFreeTime()) ftParam += clazz.getDaysString(CONSTANTS.shortDays()) + "-" + clazz.getStart() + "-" + clazz.getLength() + ","; String style = (firstClazz && !rows.isEmpty() ? "top-border-dashed": ""); WebTable.Row row = null; WebTable.IconsCell icons = new WebTable.IconsCell(); if (clazz.isTeachingAssignment()) { if (clazz.isInstructing()) icons.add(RESOURCES.isInstructing(), MESSAGES.instructing(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); style += (clazz.isInstructing() ? " text-steelblue" : " text-steelblue-italic"); } else if (clazz.isSaved()) icons.add(RESOURCES.saved(), MESSAGES.saved(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); else if (clazz.isDummy()) icons.add(RESOURCES.unassignment(), MESSAGES.unassignment(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); else if (!clazz.isFreeTime() && result.isCanEnroll()) icons.add(RESOURCES.assignment(), MESSAGES.assignment(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); WebTable.CheckboxCell waitList = null; if (firstClazz && !clazz.isTeachingAssignment() && !clazz.isSaved() && !clazz.isFreeTime() && (clazz.isDummy() || result.isCanEnroll()) && clazz.hasError()) { boolean courseEnrolled = false; for (ClassAssignmentInterface.ClassAssignment x: course.getClassAssignments()) if (x.isSaved()) { courseEnrolled = true; break; } if (!courseEnrolled) { Boolean w = iCourseRequests.getWaitList(course.getCourseId()); if (w != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST) && course.isCanWaitList()) { waitList = new WebTable.CheckboxCell(w, MESSAGES.toggleWaitList(), ARIA.titleRequestedWaitListForCourse(MESSAGES.course(course.getSubject(), course.getCourseNbr()))); waitList.getWidget().setStyleName("toggle"); ((CheckBox)waitList.getWidget()).addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { clearMessage(); iCourseRequests.setWaitList(course.getCourseId(), event.getValue()); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } }); } } } GradeMode gradeMode = clazz.getGradeMode(); SpecialRegistrationStatus specRegStatus = iSpecialRegistrationsPanel.getStatus(clazz); Float creditHour = null; if (specRegStatus != null) { String error = iSpecialRegistrationsPanel.getError(clazz); GradeMode gm = iSpecialRegistrationsPanel.getGradeMode(clazz); if (gm != null && gradeMode != null) gradeMode = gm; Float ch = iSpecialRegistrationsPanel.getCreditHours(clazz); if (ch != null) { creditHour = ch; iCurrentCredit += creditHour; } switch (specRegStatus) { case Draft: icons.add(RESOURCES.specRegDraft(), (error != null ? error + "\n" : "") + MESSAGES.hintSpecRegDraft(), true); break; case Approved: icons.add(RESOURCES.specRegApproved(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegApproved(), true); break; case Cancelled: icons.add(RESOURCES.specRegCancelled(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegCancelled(), true); break; case Pending: icons.add(RESOURCES.specRegPending(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegPending(), true); break; case Rejected: icons.add(RESOURCES.specRegRejected(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegRejected(), true); break; } style += (specRegStatus != SpecialRegistrationStatus.Rejected ? " text-blue" : " text-red"); if (clazz.hasError()) hasError = true; else if (clazz.hasWarn()) hasWarning = true; } else if (clazz.hasError()) { icons.add(RESOURCES.error(), clazz.getError(), true); style += " text-red"; hasError = true; } else if (clazz.hasWarn()) { icons.add(RESOURCES.warning(), clazz.getWarn(), true); hasWarning = true; } else if (clazz.hasInfo()) { icons.add(RESOURCES.info(), clazz.getInfo(), true); } if (course.isLocked()) icons.add(RESOURCES.courseLocked(), MESSAGES.courseLocked(course.getSubject() + " " + course.getCourseNbr())); if (clazz.isOfHighDemand()) icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(clazz.getExpected(), clazz.getAvailableLimit())); if (clazz != null && clazz.hasOverlapNote()) icons.add(RESOURCES.overlap(), clazz.getOverlapNote()); if (clazz.isCancelled()) icons.add(RESOURCES.cancelled(), MESSAGES.classCancelled(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); if (!clazz.isTeachingAssignment() && creditHour == null) iCurrentCredit += clazz.guessCreditCount(); if (gradeMode != null) hasGradeMode = true; if (clazz.isAssigned()) { row = new WebTable.Row( clazz.isDummy() || clazz.isTeachingAssignment() ? new WebTable.Cell(null) : new WebTable.LockCell(clazz.isPinned(), course.isFreeTime() ? ARIA.freeTimePin(clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours())) : ARIA.classPin(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection())), MESSAGES.hintLocked(), MESSAGES.hintUnlocked()), new WebTable.Cell(firstClazz ? course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject() : "").aria(firstClazz ? "" : course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()), new WebTable.Cell(firstClazz ? course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle()) : "").aria(firstClazz ? "" : course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(clazz.getDaysString(CONSTANTS.shortDays())).aria(clazz.getDaysString(CONSTANTS.longDays(), " ")), new WebTable.Cell(clazz.getStartString(CONSTANTS.useAmPm())).aria(clazz.getStartStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getEndString(CONSTANTS.useAmPm())).aria(clazz.getEndStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getDatePattern()), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (waitList != null ? waitList : creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } else { row = new WebTable.Row( clazz.isDummy() || clazz.isTeachingAssignment() ? new WebTable.Cell(null) : new WebTable.LockCell(clazz.isPinned() , course.isFreeTime() ? ARIA.freeTimePin(clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours())) : ARIA.classPin(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection())), MESSAGES.hintLocked(), MESSAGES.hintUnlocked()), new WebTable.Cell(firstClazz ? course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject() : ""), new WebTable.Cell(firstClazz ? course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle()) : ""), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(MESSAGES.arrangeHours(), 3, null), new WebTable.Cell(clazz.hasDatePattern() ? clazz.getDatePattern() : ""), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (waitList != null ? waitList : creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } if (course.isFreeTime()) { row.setAriaLabel(ARIA.freeTimeAssignment(clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()))); } else if (clazz.isTeachingAssignment()) { row.setStyleName("teaching-assignment"); if (clazz.isInstructing()) row.setAriaLabel(ARIA.instructingAssignment(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection()), clazz.isAssigned() ? clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(",") : ARIA.arrangeHours())); else row.setAriaLabel(ARIA.teachingAssignment(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection()), clazz.isAssigned() ? clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(",") : ARIA.arrangeHours())); } else { row.setAriaLabel(ARIA.classAssignment(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection()), clazz.isAssigned() ? clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(",") : ARIA.arrangeHours())); } final ArrayList<TimeGrid.Meeting> meetings = (clazz.isFreeTime() ? null : iAssignmentGrid.addClass(clazz, rows.size())); // row.setId(course.isFreeTime() ? "Free " + clazz.getDaysString() + " " +clazz.getStartString() + " - " + clazz.getEndString() : course.getCourseId() + ":" + clazz.getClassId()); final int index = rows.size(); if (!clazz.isDummy() && !clazz.isTeachingAssignment()) ((HasValueChangeHandlers<Boolean>)row.getCell(0).getWidget()).addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { if (meetings == null) { iLastResult.get(index).setPinned(event.getValue()); } else { for (Meeting m: meetings) { m.setPinned(event.getValue()); iLastResult.get(m.getIndex()).setPinned(event.getValue()); } } } }); rows.add(row); iLastResult.add(clazz.isDummy() || clazz.isTeachingAssignment() ? null : clazz); for (WebTable.Cell cell: row.getCells()) cell.setStyleName(style); firstClazz = false; } } else if (!iSpecialRegistrationsPanel.isDrop(course.getCourseId()) && iCourseRequests.isActive(course)) { String style = "text-red" + (!rows.isEmpty() ? " top-border-dashed": ""); WebTable.Row row = null; String unassignedMessage = MESSAGES.courseNotAssigned(); if (course.hasEnrollmentMessage()) unassignedMessage = course.getEnrollmentMessage(); else if (course.getNote() != null) unassignedMessage = course.getNote(); else if (course.getOverlaps()!=null && !course.getOverlaps().isEmpty()) { unassignedMessage = ""; for (Iterator<String> i = course.getOverlaps().iterator(); i.hasNext();) { String x = i.next(); if (unassignedMessage.isEmpty()) unassignedMessage += MESSAGES.conflictWithFirst(x); else if (!i.hasNext()) unassignedMessage += MESSAGES.conflictWithLast(x); else unassignedMessage += MESSAGES.conflictWithMiddle(x); } if (course.getInstead() != null) unassignedMessage += MESSAGES.conflictAssignedAlternative(course.getInstead()); unassignedMessage += "."; } else if (course.isNotAvailable()) { if (course.isFull()) unassignedMessage = MESSAGES.courseIsFull(); else unassignedMessage = MESSAGES.classNotAvailable(); } else if (course.isLocked()) { unassignedMessage = MESSAGES.courseLocked(course.getSubject() + " " + course.getCourseNbr()); } if (course.isOverMaxCredit()) unassignedMessage = MESSAGES.conflictOverMaxCredit(course.getOverMaxCredit()) + (MESSAGES.courseNotAssigned().equals(unassignedMessage) ? "" : "\n" + unassignedMessage); WebTable.IconsCell icons = new WebTable.IconsCell(); if (course.isLocked()) icons.add(RESOURCES.courseLocked(), course.getNote() != null ? course.getNote() : MESSAGES.courseLocked(course.getSubject() + " " + course.getCourseNbr())); WebTable.CheckboxCell waitList = null; Boolean w = iCourseRequests.getWaitList(course.getCourseId()); if (w != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST) && course.isCanWaitList()) { if (w.booleanValue() && iSavedRequest != null) { if (course.getWaitListedDate() != null && iSavedRequest.getStatus(course.getCourseName()) != RequestedCourseStatus.OVERRIDE_NEEDED) { style = (!rows.isEmpty() ? "top-border-dashed": ""); unassignedMessage = MESSAGES.conflictWaitListed(sDF.format(course.getWaitListedDate())); if (course.getOverlaps()!=null && !course.getOverlaps().isEmpty()) { unassignedMessage += "\n<span class='unitime-ErrorText'>"; boolean firstOverlap = true; for (Iterator<String> i = course.getOverlaps().iterator(); i.hasNext();) { String x = i.next(); if (firstOverlap) unassignedMessage += MESSAGES.conflictWithFirst(x); else if (!i.hasNext()) unassignedMessage += MESSAGES.conflictWithLast(x); else unassignedMessage += MESSAGES.conflictWithMiddle(x); firstOverlap = false; } if (course.getInstead() != null) unassignedMessage += MESSAGES.conflictAssignedAlternative(course.getInstead()); unassignedMessage += ".</span>"; } } if (course.hasEnrollmentMessage()) unassignedMessage += "\n" + course.getEnrollmentMessage(); if (w.booleanValue() && !iSpecialRegistrationsPanel.canWaitList(course.getCourseId())) { unassignedMessage += "\n<span class='unitime-ErrorText'>" + MESSAGES.messageWaitListApprovalAlreadyRequested(course.getCourseName()) + "</span>"; } RequestedCourseStatus status = iSavedRequest.getStatus(course.getCourseName()); if (status != null) { switch (status) { case OVERRIDE_NEEDED: case OVERRIDE_REJECTED: unassignedMessage += "<span class='unitime-ErrorText'>"; break; case OVERRIDE_PENDING: unassignedMessage += "<span class='unitime-WarningText'>"; break; case OVERRIDE_CANCELLED: unassignedMessage += "<span class='unitime-GrayText'>"; break; case OVERRIDE_APPROVED: unassignedMessage += "<span class='unitime-GreenText'>"; break; } } for (CourseMessage cm: iSavedRequest.getConfirmations(course.getCourseName())) if (!"WL-OVERLAP".equals(cm.getCode())) unassignedMessage += "\n" + cm.getMessage(); if (status != null) { switch (status) { case OVERRIDE_NEEDED: case OVERRIDE_REJECTED: case OVERRIDE_PENDING: case OVERRIDE_CANCELLED: case OVERRIDE_APPROVED: unassignedMessage += "</span>"; break; } } String msg = iSavedRequest.getConfirmation(course.getCourseName(), "\n"); if (status != null) { switch (status) { case OVERRIDE_NEEDED: icons.add(RESOURCES.requestNeeded(), MESSAGES.overrideNeeded(msg)); break; case OVERRIDE_REJECTED: icons.add(RESOURCES.requestRejected(), (msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideRejectedWaitList(course.getCourseName())); break; case OVERRIDE_PENDING: icons.add(RESOURCES.requestPending(), (msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overridePending(course.getCourseName())); break; case OVERRIDE_CANCELLED: icons.add(RESOURCES.requestCancelled(), (msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideCancelledWaitList(course.getCourseName())); break; case OVERRIDE_APPROVED: icons.add(RESOURCES.requestSaved(), (msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideApproved(course.getCourseName())); break; case SAVED: icons.add(RESOURCES.requestSaved(), MESSAGES.courseWaitListed()); break; default: if (iSavedRequest.isError(course.getCourseName())) icons.add(RESOURCES.requestError(), msg); } } /* RequestedCourse rc = iCourseRequests.getRequestedCourse(course.getCourseId()); if (rc != null && rc.hasRequestorNote()) unassignedMessage += "\n<span class='unitime-GrayText'>" + rc.getRequestorNote() + "</span>"; if (rc != null && rc.hasStatusNote()) unassignedMessage += "\n<span class='unitime-GrayText'>" + rc.getStatusNote() + "</span>"; */ } waitList = new WebTable.CheckboxCell(w, MESSAGES.toggleWaitList(), ARIA.titleRequestedWaitListForCourse(MESSAGES.course(course.getSubject(), course.getCourseNbr()))); waitList.getWidget().setStyleName("toggle"); ((CheckBox)waitList.getWidget()).addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { clearMessage(); iCourseRequests.setWaitList(course.getCourseId(), event.getValue()); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); } }); } }); } for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.isAssigned()) { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(clazz.getDaysString(CONSTANTS.shortDays())).aria(clazz.getDaysString(CONSTANTS.longDays(), " ")), new WebTable.Cell(clazz.getStartString(CONSTANTS.useAmPm())).aria(clazz.getStartStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getEndString(CONSTANTS.useAmPm())).aria(clazz.getEndStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getDatePattern()), new WebTable.PreCell(unassignedMessage, 3), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (waitList != null ? waitList : new WebTable.AbbvTextCell(clazz.getCredit())), (clazz.getGradeMode() == null ? new WebTable.Cell("") : new WebTable.Cell(clazz.getGradeMode().getCode()).title(clazz.getGradeMode().getLabel()).aria(clazz.getGradeMode().getLabel())), icons); if (course.isFreeTime()) row.setAriaLabel(ARIA.freeTimeUnassignment(clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()), unassignedMessage)); else row.setAriaLabel(ARIA.courseUnassginment(MESSAGES.course(course.getSubject(), course.getCourseNbr()), unassignedMessage)); } else if (clazz.getClassId() != null) { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(MESSAGES.arrangeHours(), 3, null), new WebTable.Cell(clazz.hasDatePattern() ? clazz.getDatePattern() : ""), new WebTable.PreCell(unassignedMessage, 3), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (waitList != null ? waitList : new WebTable.AbbvTextCell(clazz.getCredit())), (clazz.getGradeMode() == null ? new WebTable.Cell("") : new WebTable.Cell(clazz.getGradeMode().getCode()).title(clazz.getGradeMode().getLabel()).aria(clazz.getGradeMode().getLabel())), icons); if (course.isFreeTime()) row.setAriaLabel(ARIA.freeTimeUnassignment("", unassignedMessage)); else row.setAriaLabel(ARIA.courseUnassginment(MESSAGES.course(course.getSubject(), course.getCourseNbr()), unassignedMessage)); } else { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeSubject() : course.getSubject()), new WebTable.Cell(course.isFreeTime() ? MESSAGES.freeTimeCourse() : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.PreCell(unassignedMessage, 7), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (waitList != null ? waitList : new WebTable.AbbvTextCell(clazz.getCredit())), (clazz.getGradeMode() == null ? new WebTable.Cell("") : new WebTable.Cell(clazz.getGradeMode().getCode()).title(clazz.getGradeMode().getLabel()).aria(clazz.getGradeMode().getLabel())), icons); if (course.isFreeTime()) row.setAriaLabel(ARIA.freeTimeUnassignment("", unassignedMessage)); else row.setAriaLabel(ARIA.courseUnassginment(MESSAGES.course(course.getSubject(), course.getCourseNbr()), unassignedMessage)); } row.setId(course.isFreeTime() ? CONSTANTS.freePrefix() + clazz.getDaysString(CONSTANTS.shortDays()) + " " +clazz.getStartString(CONSTANTS.useAmPm()) + " - " + clazz.getEndString(CONSTANTS.useAmPm()) : course.getCourseId() + ":" + clazz.getClassId()); iLastResult.add(clazz.isDummy() || clazz.isTeachingAssignment() ? null : clazz); break; } if (row == null) { if (waitList != null) { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(course.getSubject()), new WebTable.Cell(course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.PreCell(unassignedMessage, 11), waitList, new WebTable.Cell(null), icons); } else { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(course.getSubject()), new WebTable.Cell(course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.PreCell(unassignedMessage, 12), new WebTable.Cell(null), icons); } row.setId(course.getCourseId().toString()); row.setAriaLabel(ARIA.courseUnassginment(MESSAGES.course(course.getSubject(), course.getCourseNbr()), unassignedMessage)); iLastResult.add(course.addClassAssignment()); } for (WebTable.Cell cell: row.getCells()) cell.setStyleName(style); row.getCell(row.getNrCells() - 1).setStyleName("text-red-centered" + (!rows.isEmpty() ? " top-border-dashed": "")); rows.add(row); firstClazz = false; } if (iSavedAssignment != null && !course.isFreeTime() && !course.isTeachingAssignment() && iShowUnassignments.getValue()) { for (ClassAssignmentInterface.CourseAssignment saved: iSavedAssignment.getCourseAssignments()) { if (!saved.isAssigned() || saved.isFreeTime() || saved.isTeachingAssignment() || !course.getCourseId().equals(saved.getCourseId())) continue; classes: for (ClassAssignmentInterface.ClassAssignment clazz: saved.getClassAssignments()) { for (ClassAssignmentInterface.ClassAssignment x: course.getClassAssignments()) if (clazz.getClassId().equals(x.getClassId())) continue classes; String style = "text-gray"; WebTable.Row row = null; if (firstClazz && !rows.isEmpty()) style += " top-border-dashed"; WebTable.IconsCell icons = new WebTable.IconsCell(); GradeMode gradeMode = clazz.getGradeMode(); Float creditHour = null; SpecialRegistrationStatus specRegStatus = iSpecialRegistrationsPanel.getStatus(clazz); if (specRegStatus != null) { String error = iSpecialRegistrationsPanel.getError(clazz); GradeMode gm = iSpecialRegistrationsPanel.getGradeMode(clazz); if (gm != null && gradeMode != null) gradeMode = gm; Float ch = iSpecialRegistrationsPanel.getCreditHours(clazz); if (ch != null) creditHour = ch; switch (specRegStatus) { case Draft: icons.add(RESOURCES.specRegDraft(), (error != null ? error + "\n" : "") + MESSAGES.hintSpecRegDraft(), true); break; case Approved: icons.add(RESOURCES.specRegApproved(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegApproved(), true); break; case Cancelled: icons.add(RESOURCES.specRegCancelled(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegCancelled(), true); break; case Pending: icons.add(RESOURCES.specRegPending(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegPending(), true); break; case Rejected: icons.add(RESOURCES.specRegRejected(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegRejected(), true); break; } } else if (clazz.hasError()) { icons.add(RESOURCES.error(), clazz.getError(), true); } else if (clazz.hasWarn()) { icons.add(RESOURCES.warning(), clazz.getWarn(), true); } else if (clazz.hasInfo()) { icons.add(RESOURCES.info(), clazz.getInfo(), true); } if (clazz.isSaved()) icons.add(RESOURCES.unassignment(), MESSAGES.unassignment(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); if (clazz.isOfHighDemand()) icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(clazz.getExpected(), clazz.getAvailableLimit())); if (clazz.isCancelled()) icons.add(RESOURCES.cancelled(), MESSAGES.classCancelled(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); if (clazz.isAssigned()) { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(firstClazz ? course.getSubject() : "").aria(course.getSubject()), new WebTable.Cell(firstClazz ? course.getCourseNbr(CONSTANTS.showCourseTitle()) : "").aria(course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(clazz.getDaysString(CONSTANTS.shortDays())).aria(clazz.getDaysString(CONSTANTS.longDays(), " ")), new WebTable.Cell(clazz.getStartString(CONSTANTS.useAmPm())).aria(clazz.getStartStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getEndString(CONSTANTS.useAmPm())).aria(clazz.getEndStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getDatePattern()), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } else { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(firstClazz ? course.getSubject() : "").aria(course.getSubject()), new WebTable.Cell(firstClazz ? course.getCourseNbr(CONSTANTS.showCourseTitle()) : "").aria(course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(MESSAGES.arrangeHours(), 3, null), new WebTable.Cell(clazz.hasDatePattern() ? clazz.getDatePattern() : ""), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } row.setAriaLabel(ARIA.previousAssignment(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection()), clazz.isAssigned() ? clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(",") : ARIA.arrangeHours())); rows.add(row); row.setSelectable(false); iLastResult.add(null); for (WebTable.Cell cell: row.getCells()) cell.setStyleName(style); firstClazz = false; } } } } if (iSavedAssignment != null && iShowUnassignments.getValue()) { courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.CourseAssignment x: result.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId())) continue courses; boolean firstClazz = true; for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { String style = "text-gray" + (firstClazz && !rows.isEmpty() ? " top-border-dashed": ""); WebTable.Row row = null; WebTable.IconsCell icons = new WebTable.IconsCell(); GradeMode gradeMode = clazz.getGradeMode(); Float creditHour = null; SpecialRegistrationStatus specRegStatus = iSpecialRegistrationsPanel.getStatus(clazz); if (specRegStatus != null) { String error = iSpecialRegistrationsPanel.getError(clazz); GradeMode gm = iSpecialRegistrationsPanel.getGradeMode(clazz); if (gm != null && gradeMode != null) gradeMode = gm; Float ch = iSpecialRegistrationsPanel.getCreditHours(clazz); if (ch != null) creditHour = ch; switch (specRegStatus) { case Draft: icons.add(RESOURCES.specRegDraft(), (error != null ? error + "\n" : "") + MESSAGES.hintSpecRegDraft(), true); break; case Approved: icons.add(RESOURCES.specRegApproved(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegApproved(), true); break; case Cancelled: icons.add(RESOURCES.specRegCancelled(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegCancelled(), true); break; case Pending: icons.add(RESOURCES.specRegPending(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegPending(), true); break; case Rejected: icons.add(RESOURCES.specRegRejected(), (error != null ? error + "\n" : "") + "\n" + MESSAGES.hintSpecRegRejected(), true); break; } } else if (clazz.hasError()) { icons.add(RESOURCES.error(), clazz.getError(), true); } else if (clazz.hasWarn()) { icons.add(RESOURCES.warning(), clazz.getWarn(), true); } else if (clazz.hasInfo()) { icons.add(RESOURCES.info(), clazz.getInfo(), true); } if (clazz.isSaved()) icons.add(RESOURCES.unassignment(), MESSAGES.unassignment(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); if (clazz.isOfHighDemand()) icons.add(RESOURCES.highDemand(), MESSAGES.highDemand(clazz.getExpected(), clazz.getAvailableLimit())); if (clazz.isCancelled()) icons.add(RESOURCES.cancelled(), MESSAGES.classCancelled(course.getSubject() + " " + course.getCourseNbr() + " " + clazz.getSubpart() + " " + clazz.getSection())); if (clazz.isAssigned()) { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(firstClazz ? course.getSubject() : "").aria(firstClazz ? "" : course.getSubject()), new WebTable.Cell(firstClazz ? course.getCourseNbr(CONSTANTS.showCourseTitle()) : "").aria(firstClazz ? "" : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(clazz.getDaysString(CONSTANTS.shortDays())).aria(clazz.getDaysString(CONSTANTS.longDays(), " ")), new WebTable.Cell(clazz.getStartString(CONSTANTS.useAmPm())).aria(clazz.getStartStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getEndString(CONSTANTS.useAmPm())).aria(clazz.getEndStringAria(CONSTANTS.useAmPm())), new WebTable.Cell(clazz.getDatePattern()), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } else { row = new WebTable.Row( new WebTable.Cell(null), new WebTable.Cell(firstClazz ? course.getSubject() : "").aria(firstClazz ? "" : course.getSubject()), new WebTable.Cell(firstClazz ? course.getCourseNbr(CONSTANTS.showCourseTitle()) : "").aria(firstClazz ? "" : course.getCourseNbr(CONSTANTS.showCourseTitle())), new WebTable.Cell(clazz.getSubpart()), new WebTable.Cell(clazz.getSection()), new WebTable.Cell(clazz.getLimitString()), new WebTable.Cell(MESSAGES.arrangeHours(), 3, null), new WebTable.Cell(clazz.hasDatePattern() ? clazz.getDatePattern() : ""), (clazz.hasDistanceConflict() ? new WebTable.RoomCell(RESOURCES.distantConflict(), MESSAGES.backToBackDistance(clazz.getBackToBackRooms(), clazz.getBackToBackDistance()), clazz.getRooms(), ", ") : new WebTable.RoomCell(clazz.getRooms(), ", ")), new WebTable.InstructorCell(clazz.getInstructors(), clazz.getInstructorEmails(), ", "), new WebTable.Cell(clazz.getParentSection(), clazz.getParentSection() == null || clazz.getParentSection().length() > 10), new WebTable.NoteCell(clazz.getOverlapAndNote("text-red"), clazz.getOverlapAndNote(null)), (creditHour != null ? new WebTable.Cell(MESSAGES.credit(creditHour)) : new WebTable.AbbvTextCell(clazz.getCredit())), (gradeMode == null ? new WebTable.Cell("") : new WebTable.Cell(gradeMode.getCode()).title(gradeMode.getLabel()).aria(gradeMode.getLabel())), icons); } row.setAriaLabel(ARIA.previousAssignment(MESSAGES.clazz(course.getSubject(), course.getCourseNbr(), clazz.getSubpart(), clazz.getSection()), clazz.isAssigned() ? clazz.getTimeStringAria(CONSTANTS.longDays(), CONSTANTS.useAmPm(), ARIA.arrangeHours()) + " " + clazz.getRooms(",") : ARIA.arrangeHours())); rows.add(row); row.setSelectable(false); iLastResult.add(null); for (WebTable.Cell cell: row.getCells()) cell.setStyleName(style); firstClazz = false; } } } for (ClassAssignmentInterface.CourseAssignment course: result.getCourseAssignments()) { for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.isFreeTime()) { CourseRequestInterface.FreeTime ft = new CourseRequestInterface.FreeTime(); ft.setLength(clazz.getLength()); ft.setStart(clazz.getStart()); for (int d: clazz.getDays()) ft.addDay(d); iAssignmentGrid.addFreeTime(ft); } } } WebTable.Row[] rowArray = new WebTable.Row[rows.size()]; int idx = 0; for (WebTable.Row row: rows) rowArray[idx++] = row; iAssignmentGrid.shrink(); // iAssignmentPanel.setWidth(iAssignmentGrid.getWidth() + "px"); if (hasNotAssignedClass(result)) { iGridMessage.setText(MESSAGES.timeGridNotAssignedTimes()); iGridMessage.setVisible(true); } else { iGridMessage.setVisible(false); } iAssignments.setData(rowArray); iAssignments.setColumnVisible(15, hasGradeMode); if (LoadingWidget.getInstance().isShowing()) LoadingWidget.getInstance().hide(); iPanel.remove(iCourseRequests); iPanel.insert(iAssignmentDock, 1); iRequests.setVisible(true); iRequests.setEnabled(true); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_RESET)) { iReset.setVisible(true); iReset.setEnabled(true); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.QUICK_ADD_DROP)) { iQuickAdd.setVisible(true); iQuickAdd.setEnabled(true); } iEnroll.setVisible(result.isCanEnroll() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL)); if (hasGradeMode && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_CHANGE_GRADE_MODE, EligibilityFlag.CAN_CHANGE_VAR_CREDIT)) { iChangeGradeModes.setEnabled(true); iChangeGradeModes.setVisible(true); if (!iEligibilityCheck.hasFlag(EligibilityFlag.CAN_CHANGE_GRADE_MODE)) { iChangeGradeModes.setHTML(MESSAGES.buttonChangeVariableCredits()); iChangeGradeModes.setTitle(MESSAGES.hintChangeVariableCredits()); } else if (!iEligibilityCheck.hasFlag(EligibilityFlag.CAN_CHANGE_VAR_CREDIT)) { iChangeGradeModes.setHTML(MESSAGES.buttonChangeGradeModes()); iChangeGradeModes.setTitle(MESSAGES.hintChangeGradeModes()); } else { iChangeGradeModes.setHTML(MESSAGES.buttonChangeGradeModesAndVariableCredits()); iChangeGradeModes.setTitle(MESSAGES.hintChangeGradeModesAndVariableCredits()); } } else { iChangeGradeModes.setEnabled(false); iChangeGradeModes.setVisible(false); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REQUEST_VAR_TITLE_COURSE)) { iRequestVarTitleCourse.setEnabled(true); iRequestVarTitleCourse.setVisible(true); } else { iRequestVarTitleCourse.setEnabled(false); iRequestVarTitleCourse.setVisible(false); } if (iEligibilityCheck != null && iEligibilityCheck.hasCheckboxMessage()) { if (iCustomCheckbox == null) { iCustomCheckbox = new CheckBox(iEligibilityCheck.getCheckboxMessage(), true); ((HorizontalPanel)iFooter.getWidget(1)).insert(iCustomCheckbox, 0); ((HorizontalPanel)iFooter.getWidget(1)).setCellVerticalAlignment(iCustomCheckbox, HasVerticalAlignment.ALIGN_MIDDLE); iCustomCheckbox.getElement().getStyle().setPaddingRight(10, Unit.PX); iCustomCheckbox.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { iEnroll.setEnabled(event.getValue()); } }); } iEnroll.setEnabled(iCustomCheckbox.getValue()); iCustomCheckbox.setEnabled(true); iCustomCheckbox.setVisible(true); } else { iEnroll.setEnabled(result.isCanEnroll() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL)); } iPrint.setVisible(true); iPrint.setEnabled(true); iStartOver.setVisible(iSavedAssignment != null); iStartOver.setEnabled(iSavedAssignment != null); if (iExport != null) { iExport.setVisible(true); iExport.setEnabled(true); } iSchedule.setVisible(false); iSchedule.setEnabled(false); iDegreePlan.setVisible(false); iDegreePlan.setEnabled(false); iAdvisorReqs.setVisible(false); iAdvisorReqs.setEnabled(false); iAssignmentGrid.scrollDown(); if (iCalendar != null) { if (calendarUrl.endsWith(",")) calendarUrl = calendarUrl.substring(0, calendarUrl.length() - 1); calendarUrl += ftParam; if (calendarUrl.endsWith(",")) calendarUrl = calendarUrl.substring(0, calendarUrl.length() - 1); iAssignmentGrid.setCalendarUrl(calendarUrl); iCalendar.setUrl(calendarUrl); } ResizeEvent.fire(this, getOffsetWidth(), getOffsetHeight()); if (iAssignmentTab.getSelectedTab() == 0) { AriaStatus.getInstance().setHTML(ARIA.listOfClasses()); } else { AriaStatus.getInstance().setHTML(ARIA.timetable()); } if (result.hasMessages()) { if (hasError) { iStatus.error(result.getMessages("<br>"), popup); } else if (hasWarning) { iStatus.warning(result.getMessages("<br>"), popup); } else { iStatus.info(result.getMessages("<br>"), popup); } } else { updateScheduleChangedNoteIfNeeded(); } iTotalCredit.setVisible(iCurrentCredit > 0f); iTotalCredit.setText(MESSAGES.totalCredit(iCurrentCredit)); } else { iTotalCredit.setVisible(false); iStatus.error(MESSAGES.noSchedule()); if (LoadingWidget.getInstance().isShowing()) LoadingWidget.getInstance().hide(); } } public void prev() { iPanel.remove(iAssignmentDock); iPanel.insert(iCourseRequests, 1); iRequests.setVisible(false); iRequests.setEnabled(false); iReset.setVisible(false); iReset.setEnabled(false); iQuickAdd.setVisible(false); iQuickAdd.setEnabled(false); iEnroll.setVisible(false); iEnroll.setEnabled(false); iChangeGradeModes.setVisible(false); iChangeGradeModes.setEnabled(false); iRequestVarTitleCourse.setVisible(false); iRequestVarTitleCourse.setEnabled(false); if (iCustomCheckbox != null) { iCustomCheckbox.setVisible(false); iCustomCheckbox.setEnabled(false); } iPrint.setVisible(false); iPrint.setEnabled(false); if (iExport != null) { iExport.setVisible(false); iExport.setEnabled(false); } iSchedule.setVisible(iMode.isSectioning()); iSchedule.setEnabled(iMode.isSectioning()); iSave.setVisible(!iMode.isSectioning()); iSave.setEnabled(!iMode.isSectioning() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER)); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.DEGREE_PLANS)) { iDegreePlan.setVisible(true); iDegreePlan.setEnabled(true); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.HAS_ADVISOR_REQUESTS)) { iAdvisorReqs.setVisible(true); iAdvisorReqs.setEnabled(true); } clearMessage(); ResizeEvent.fire(this, getOffsetWidth(), getOffsetHeight()); AriaStatus.getInstance().setHTML(ARIA.courseRequests()); updateScheduleChangedNoteIfNeeded(); } public void clear(boolean switchToRequests) { if (iShowUnassignments != null) iShowUnassignments.setVisible(false); iSavedAssignment = null; iLastAssignment = null; iSpecialRegAssignment = null; iCourseRequests.clear(); iLastResult.clear(); iAssignments.clearData(true); iAssignmentGrid.clear(true); iShowUnassignments.setVisible(true); if (iRequests.isVisible() && switchToRequests) { prev(); } } public void clear() { clear(true); } public void checkEligibility(final AsyncCallback<OnlineSectioningInterface.EligibilityCheck> ret) { checkEligibility(ret, null); } public void checkEligibility(final AsyncCallback<OnlineSectioningInterface.EligibilityCheck> ret, String pin) { LoadingWidget.getInstance().show(MESSAGES.courseRequestsLoading()); iStartOver.setVisible(false); iStartOver.setEnabled(false); iSpecRegCx.reset(); iContext.setPin(pin); iSectioningService.checkEligibility(iContext, new AsyncCallback<OnlineSectioningInterface.EligibilityCheck>() { @Override public void onSuccess(OnlineSectioningInterface.EligibilityCheck result) { clearMessage(false); iEligibilityCheck = result; iContext.setStudentId(result == null ? null : result.getStudentId()); iSpecRegCx.update(result); iCourseRequests.setWaitListMode( result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST) ? WaitListMode.WaitList : result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) ? WaitListMode.NoSubs : WaitListMode.None); iCourseRequests.setArrowsVisible(!result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.NO_REQUEST_ARROWS), result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) && !result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST)); if (result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_USE_ASSISTANT)) { if (result.hasMessage() && (iMode.isSectioning() && !result.hasFlag(EligibilityFlag.CAN_ENROLL))) { iStatus.error(iEligibilityCheck.getMessage()); } else if (result.hasMessage() && (!iMode.isSectioning() && !result.hasFlag(EligibilityFlag.CAN_REGISTER))) { iStatus.error(iEligibilityCheck.getMessage()); } else if (result.hasMessage()) { iStatus.warning(result.getMessage()); } else { clearMessage(); } if (result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.PIN_REQUIRED)) { if (iPinDialog == null) iPinDialog = new PinDialog(); LoadingWidget.getInstance().hide(); PinDialog.PinCallback callback = new PinDialog.PinCallback() { @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionFailedEligibilityCheck(caught.getMessage()), caught); iSchedule.setVisible(iMode.isSectioning()); iSchedule.setEnabled(iMode.isSectioning()); iSave.setVisible(!iMode.isSectioning()); iSave.setEnabled(!iMode.isSectioning() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER)); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.DEGREE_PLANS)) { iDegreePlan.setVisible(true); iDegreePlan.setEnabled(true); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.HAS_ADVISOR_REQUESTS)) { iAdvisorReqs.setVisible(true); iAdvisorReqs.setEnabled(true); } lastRequest(true); if (ret != null) ret.onSuccess(iEligibilityCheck); } @Override public void onSuccess(OnlineSectioningInterface.EligibilityCheck result) { iCourseRequests.setWaitListMode( result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST) ? WaitListMode.WaitList : result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) ? WaitListMode.NoSubs : WaitListMode.None); iCourseRequests.setArrowsVisible(!result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.NO_REQUEST_ARROWS), result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) && !result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST)); iEligibilityCheck = result; iContext.setStudentId(result == null ? null : result.getStudentId()); iSpecRegCx.update(result); iSchedule.setVisible(iMode.isSectioning()); iSchedule.setEnabled(iMode.isSectioning()); iSave.setVisible(!iMode.isSectioning()); iSave.setEnabled(!iMode.isSectioning() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER)); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.DEGREE_PLANS)) { iDegreePlan.setVisible(true); iDegreePlan.setEnabled(true); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.HAS_ADVISOR_REQUESTS)) { iAdvisorReqs.setVisible(true); iAdvisorReqs.setEnabled(true); } lastRequest(true); if (ret != null) ret.onSuccess(iEligibilityCheck); } @Override public void onMessage(OnlineSectioningInterface.EligibilityCheck result) { if (result.hasMessage()) { iStatus.error(result.getMessage()); } else if (result.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.PIN_REQUIRED)) { iStatus.warning(MESSAGES.exceptionAuthenticationPinRequired()); } else { clearMessage(false); } } }; iPinDialog.checkEligibility(iContext, callback, iSessionSelector.getAcademicSessionInfo()); } else { iSchedule.setVisible(iMode.isSectioning()); iSchedule.setEnabled(iMode.isSectioning()); iSave.setVisible(!iMode.isSectioning()); iSave.setEnabled(!iMode.isSectioning() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER)); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.DEGREE_PLANS)) { iDegreePlan.setVisible(true); iDegreePlan.setEnabled(true); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.HAS_ADVISOR_REQUESTS)) { iAdvisorReqs.setVisible(true); iAdvisorReqs.setEnabled(true); } lastRequest(true); if (ret != null) ret.onSuccess(iEligibilityCheck); } } else { iCourseRequests.setWaitListMode(WaitListMode.None); LoadingWidget.getInstance().hide(); if (result.hasMessage()) { iStatus.error(result.getMessage()); } iSchedule.setVisible(false); iSchedule.setEnabled(false); iSave.setVisible(false); iSave.setEnabled(false); iDegreePlan.setVisible(false); iDegreePlan.setEnabled(false); iAdvisorReqs.setVisible(false); iAdvisorReqs.setEnabled(false); if (result.hasMessage()) { iStatus.warning(result.getMessage()); } else { clearMessage(); } if (ret != null) ret.onFailure(new SectioningException(result.getMessage())); } } @Override public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iEligibilityCheck = null; if (ret != null) ret.onFailure(caught); iStatus.error(MESSAGES.exceptionFailedEligibilityCheck(caught.getMessage()), caught); } }); } private void lastResult(final CourseRequestInterface request, final boolean changeViewIfNeeded) { AsyncCallback<ClassAssignmentInterface> callback = new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { iStatus.error(caught.getMessage(), caught); LoadingWidget.getInstance().hide(); } public void onSuccess(final ClassAssignmentInterface saved) { iSavedAssignment = saved; iSpecialRegAssignment = null; iShowUnassignments.setVisible(true); if (request.isSaved() || !CONSTANTS.checkLastResult()) { if ((saved.isEnrolled() && (changeViewIfNeeded || CONSTANTS.startOverCanChangeView())) || iRequests.isVisible()) { fillIn(saved); updateHistory(); } else { iLastAssignment = saved; iLastResult = new ArrayList<ClassAssignmentInterface.ClassAssignment>(); for (final ClassAssignmentInterface.CourseAssignment course: saved.getCourseAssignments()) { if (course.isAssigned()) for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { iLastResult.add(clazz.isDummy() ? null : clazz); } } iStartOver.setVisible(true); iStartOver.setEnabled(true); updateScheduleChangedNoteIfNeeded(); LoadingWidget.getInstance().hide(); } } else { iCourseRequests.validate(new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); } @Override public void onSuccess(Boolean result) { if (result) { ArrayList<ClassAssignmentInterface.ClassAssignment> classes = new ArrayList<ClassAssignmentInterface.ClassAssignment>(); for (ClassAssignmentInterface.CourseAssignment course: saved.getCourseAssignments()) classes.addAll(course.getClassAssignments()); iSectioningService.section(request, classes, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); updateHistory(); } }); } else { LoadingWidget.getInstance().hide(); } } }); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.HAS_SPECREG)) { // && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG) iSpecialRegistrationsPanel.showWaiting(); iSectioningService.retrieveAllSpecialRequests( new RetrieveAllSpecialRegistrationsRequest(iContext), new AsyncCallback<List<RetrieveSpecialRegistrationResponse>>() { @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.retrieveAllSpecialRegistrationsFail(caught.getMessage()), caught); iSpecialRegistrationsPanel.hideWaiting(); } @Override public void onSuccess(List<RetrieveSpecialRegistrationResponse> response) { iSpecialRegistrationsPanel.hideWaiting(); iSpecialRegistrationsPanel.populate(response, iSavedAssignment); if (!iSpecialRegistrationsPanel.isVisible()) iStatus.info(MESSAGES.failedNoSpecialRegistrations()); else if (iSpecialRegistrationsPanel.hasOneOrMoreFullyApproved() && (iStatus.getLevel() == null || iStatus.getLevel() == ScheduleStatus.Level.INFO)) iStatus.info(MESSAGES.statusOneOrMoreFullyApprovedRequestsNotYetApplied()); updateHistory(); } }); } } }; iSpecialRegistrationsPanel.clearRegistrations(); iSectioningService.savedResult(iContext, callback); } public void lastRequest(final boolean changeViewIfNeeded) { if (!LoadingWidget.getInstance().isShowing()) LoadingWidget.getInstance().show(MESSAGES.courseRequestsLoading()); AsyncCallback<CourseRequestInterface> callback = new AsyncCallback<CourseRequestInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); clear(changeViewIfNeeded); if (!MESSAGES.exceptionNoStudent().equals(caught.getMessage()) || iEligibilityCheck == null || !iEligibilityCheck.hasFlag(EligibilityFlag.IS_ADMIN, EligibilityFlag.IS_ADVISOR)) iStatus.error(caught.getMessage(), caught); } public void onSuccess(final CourseRequestInterface request) { if (request.isSaved()) { iSavedRequest = request; if (iWaitListsPanel != null) iWaitListsPanel.populate(request); } else if (!iMode.isSectioning() && iSavedRequest == null) { iSectioningService.savedRequest(iContext, new AsyncCallback<CourseRequestInterface>() { @Override public void onFailure(Throwable caught) { iStatus.error(caught.getMessage(), caught); } @Override public void onSuccess(CourseRequestInterface savedRequest) { iSavedRequest = savedRequest; } }); } clear(changeViewIfNeeded); if (iWaitListsPanel != null) iWaitListsPanel.populate(iSavedRequest); /* if (request.isSaved() && request.getCourses().isEmpty()) { LoadingWidget.getInstance().hide(); return; }*/ iCourseRequests.setRequest(request); updateHistory(); if (iSchedule.isVisible() || iRequests.isVisible()) { lastResult(request, changeViewIfNeeded); } else { LoadingWidget.getInstance().hide(); iStartOver.setVisible(true); iStartOver.setEnabled(true); if (request.hasErrorMessage() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL, EligibilityFlag.CAN_REGISTER)) if (iEligibilityCheck.hasMessage()) iStatus.warning(iEligibilityCheck.getMessage() + "\n" + request.getErrorMessaeg()); else iStatus.warning(request.getErrorMessaeg()); if (request.hasPopupMessage()) UniTimeConfirmationDialog.info(request.getPopupMessage(), true); } } }; iSectioningService.savedRequest(iContext, callback); } public void showSuggestionsAsync(final int rowIndex) { if (rowIndex < 0) return; GWT.runAsync(new RunAsyncCallback() { public void onSuccess() { openSuggestionsBox(rowIndex); } public void onFailure(Throwable caught) { iStatus.error(MESSAGES.exceptionSuggestionsFailed(caught.getMessage()), caught); } }); } public class HistoryItem { private CourseRequestInterface iRequest; private ClassAssignmentInterface iAssignment; private boolean iFirstPage; private String iUser; private String iMessage = null; private ScheduleStatus.Level iMessageLevel = null; private int iTab = 0; private SpecialRegistrationContext iSRCx; private ClassAssignmentInterface iSRassignment = null; private HistoryItem() { iRequest = iCourseRequests.getRequest(); iAssignment = iLastAssignment; iFirstPage = iSchedule.isVisible(); iUser = iUserAuthentication.getUser(); iMessage = iStatus.getMessage(); iMessageLevel = iStatus.getLevel(); iTab = iAssignmentTab.getSelectedTab(); iSRCx = new SpecialRegistrationContext(iSpecRegCx); iSRassignment = iSpecialRegAssignment; } public void restore() { if (isChanged() && ((iUser != null && !iUser.equals(iUserAuthentication.getUser())) || (iRequest.getSessionId() != null && !iRequest.getSessionId().equals(iSessionSelector.getAcademicSessionId())))) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), iMode.isSectioning() ? MESSAGES.queryLeaveChangesOnClassSchedule() : MESSAGES.queryLeaveChangesOnCourseRequests(), new Command() { @Override public void execute() { doRestore(); } }); } else { doRestore(); } } protected void doRestore() { iInRestore = true; iUserAuthentication.setUser(iUser, new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { if (result) { iSessionSelector.selectSession(iRequest.getSessionId(), new AsyncCallback<Boolean>() { public void onSuccess(Boolean result) { if (result) { iSpecRegCx.copy(iSRCx); iContext.setSessionId(iRequest.getSessionId()); iContext.setStudentId(iRequest.getStudentId()); iSpecialRegAssignment = iSRassignment; if (iSpecialRegistrationsPanel.isVisible()) { iSpecialRegistrationsPanel.populate(iSpecialRegistrationsPanel.getRegistrations(), iSavedAssignment); } iCourseRequests.setRequest(iRequest); if (iTab != iAssignmentTab.getSelectedTab()) iAssignmentTab.selectTab(iTab); if (iFirstPage) { if (!iSchedule.isVisible()) prev(); iCourseRequests.changeTip(); } else { if (iAssignment != null) fillIn(iAssignment); } iStatus.setMessage(iMessageLevel, iMessage); if (!iMode.isSectioning() && iSavedRequest != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER) && !iSavedRequest.equals(iCourseRequests.getRequest())) { iScheduleChanged = true; iSave.addStyleName("unitime-EnrollButton"); iStatus.warning(iSavedRequest.isEmpty() ? MESSAGES.warnRequestsEmptyOnCourseRequest() : MESSAGES.warnRequestsChangedOnCourseRequest(), false); } } iInRestore = false; ResizeEvent.fire(StudentSectioningWidget.this, getOffsetWidth(), getOffsetHeight()); } public void onFailure(Throwable reason) { iInRestore = false; } }); } else { iInRestore = false; } } public void onFailure(Throwable reason) { iInRestore = false; } }); } } public void setData(CourseRequestInterface request, ClassAssignmentInterface response) { clear(); iCourseRequests.setRequest(request); if (request.isSaved()) { iSavedRequest = request; if (iWaitListsPanel != null) iWaitListsPanel.populate(request); } if (response != null) { if (request.isSaved()) { iSavedAssignment = response; iShowUnassignments.setVisible(true); } fillIn(response); } } @Override public HandlerRegistration addResizeHandler(ResizeHandler handler) { return addHandler(handler, ResizeEvent.getType()); } public void updateScheduleChangedNoteIfNeeded() { if (iScheduleChanged) { iScheduleChanged = false; clearMessage(); } if (iLastAssignment == null || !iLastAssignment.isCanEnroll() || iEligibilityCheck == null || !iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL)) { return; } if (iLastAssignment != null && iSpecialRegAssignment != null) { boolean changed = false; for (ClassAssignmentInterface.CourseAssignment course: iLastAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; classes: for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { for (ClassAssignmentInterface.CourseAssignment saved: iSpecialRegAssignment.getCourseAssignments()) { if (!saved.isAssigned() || saved.isFreeTime() || saved.isTeachingAssignment() || !course.getCourseId().equals(saved.getCourseId())) continue; for (ClassAssignmentInterface.ClassAssignment x: saved.getClassAssignments()) { if (clazz.getClassId().equals(x.getClassId())) continue classes; } } changed = true; break; } for (ClassAssignmentInterface.CourseAssignment saved: iSpecialRegAssignment.getCourseAssignments()) { if (!saved.isAssigned() || saved.isFreeTime() || saved.isTeachingAssignment() || !course.getCourseId().equals(saved.getCourseId())) continue; classes: for (ClassAssignmentInterface.ClassAssignment clazz: saved.getClassAssignments()) { for (ClassAssignmentInterface.ClassAssignment x: course.getClassAssignments()) { if (clazz.getClassId().equals(x.getClassId())) continue classes; } if (clazz.isSaved() && !clazz.hasError()) { changed = true; break; } } } } courses: for (ClassAssignmentInterface.CourseAssignment course: iSpecialRegAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId())) continue courses; for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.isSaved() && !clazz.hasError()) { changed = true; break; } } } if (!changed) return; } boolean cr = iSchedule.isVisible(); boolean empty = true; if (iSavedAssignment != null) courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.isSaved()) { empty = false; break courses; } } } for (ClassAssignmentInterface.CourseAssignment course: iLastAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (!clazz.isSaved() && !clazz.hasError()) { iScheduleChanged = true; iEnroll.addStyleName("unitime-EnrollButton"); if (cr) iStatus.warning(empty ? MESSAGES.warnScheduleEmptyOnCourseRequest() : MESSAGES.warnScheduleChangedOnCourseRequest(), false); else iStatus.warning(empty ? MESSAGES.warnScheduleEmptyOnClassSchedule() : MESSAGES.warnScheduleChangedOnClassSchedule(), false); return; } } if (iSavedAssignment != null) for (ClassAssignmentInterface.CourseAssignment saved: iSavedAssignment.getCourseAssignments()) { if (!saved.isAssigned() || saved.isFreeTime() || saved.isTeachingAssignment() || !course.getCourseId().equals(saved.getCourseId())) continue; classes: for (ClassAssignmentInterface.ClassAssignment clazz: saved.getClassAssignments()) { for (ClassAssignmentInterface.ClassAssignment x: course.getClassAssignments()) { if (clazz.getClassId().equals(x.getClassId())) continue classes; } if (clazz.isSaved() && !clazz.hasError()) { iScheduleChanged = true; iEnroll.addStyleName("unitime-EnrollButton"); iStatus.warning(cr ? MESSAGES.warnScheduleChangedOnCourseRequest() : MESSAGES.warnScheduleChangedOnClassSchedule(), false); } } } } if (iSavedAssignment != null) courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId())) continue courses; for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (clazz.isSaved() && !clazz.hasError()) { iScheduleChanged = true; iEnroll.addStyleName("unitime-EnrollButton"); iStatus.warning(cr ? MESSAGES.warnScheduleChangedOnCourseRequest() : MESSAGES.warnScheduleChangedOnClassSchedule(), false); } } } CourseRequestInterface request = iCourseRequests.getRequest(); courses: for (ClassAssignmentInterface.CourseAssignment course: iLastAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (CourseRequestInterface.Request r: request.getCourses()) { if (r.hasRequestedCourse(course)) continue courses; } for (CourseRequestInterface.Request r: request.getAlternatives()) { if (r.hasRequestedCourse(course)) continue courses; } iScheduleChanged = true; iEnroll.addStyleName("unitime-EnrollButton"); iStatus.warning(cr ? MESSAGES.warnScheduleChangedOnCourseRequest() : MESSAGES.warnScheduleChangedOnClassSchedule(), false); } if (iSavedRequest != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST)) { if (!iSavedRequest.sameWaitListedCourses(request)) { iScheduleChanged = true; iEnroll.addStyleName("unitime-EnrollButton"); iStatus.warning(cr ? MESSAGES.warnScheduleChangedOnCourseRequest() : MESSAGES.warnScheduleChangedOnClassSchedule(), false); } } } public boolean isChanged() { return iScheduleChanged; } public void clearMessage() { clearMessage(true); } public void clearMessage(boolean showEligibility) { if (iEligibilityCheck != null && iContext.isOnline() && showEligibility) { if (iEligibilityCheck.hasFlag(EligibilityFlag.PIN_REQUIRED)) iStatus.error(MESSAGES.exceptionAuthenticationPinNotProvided(), false); else if (iEligibilityCheck.hasMessage() && (iMode.isSectioning() && !iEligibilityCheck.hasFlag(EligibilityFlag.CAN_ENROLL))) iStatus.error(iEligibilityCheck.getMessage(), false); else if (iEligibilityCheck.hasMessage() && (!iMode.isSectioning() && !iEligibilityCheck.hasFlag(EligibilityFlag.CAN_REGISTER))) iStatus.error(iEligibilityCheck.getMessage(), false); else if (iEligibilityCheck.hasMessage() && iEligibilityCheck.hasFlag(EligibilityFlag.RECHECK_BEFORE_ENROLLMENT)) iStatus.warning(iEligibilityCheck.getMessage(), false); else if (iEligibilityCheck.hasMessage()) iStatus.info(iEligibilityCheck.getMessage(), false); else { iStatus.clear(); iEnroll.removeStyleName("unitime-EnrollButton"); iSave.removeStyleName("unitime-EnrollButton"); } } else { iStatus.clear(); iEnroll.removeStyleName("unitime-EnrollButton"); iSave.removeStyleName("unitime-EnrollButton"); } if (isChanged()) updateScheduleChangedNoteIfNeeded(); } protected void setElibibilityCheckDuringEnrollment(EligibilityCheck check) { iEligibilityCheck = check; iSpecRegCx.update(check); iCourseRequests.setWaitListMode( check.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST) ? WaitListMode.WaitList : check.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) ? WaitListMode.NoSubs : WaitListMode.None); iCourseRequests.setArrowsVisible(!check.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.NO_REQUEST_ARROWS), check.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_NO_SUBS) && !check.hasFlag(OnlineSectioningInterface.EligibilityCheck.EligibilityFlag.CAN_WAITLIST)); if (check.hasFlag(EligibilityFlag.CAN_ENROLL)) { iEnroll.setVisible(true); if (check.hasCheckboxMessage()) { if (iCustomCheckbox == null) { iCustomCheckbox = new CheckBox(iEligibilityCheck.getCheckboxMessage(), true); ((HorizontalPanel)iFooter.getWidget(1)).insert(iCustomCheckbox, 0); ((HorizontalPanel)iFooter.getWidget(1)).setCellVerticalAlignment(iCustomCheckbox, HasVerticalAlignment.ALIGN_MIDDLE); iCustomCheckbox.getElement().getStyle().setPaddingRight(10, Unit.PX); iCustomCheckbox.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { iEnroll.setEnabled(event.getValue()); } }); } else { iCustomCheckbox.setHTML(check.getCheckboxMessage()); } iEnroll.setEnabled(iCustomCheckbox.getValue()); iCustomCheckbox.setEnabled(true); iCustomCheckbox.setVisible(true); } else { iEnroll.setEnabled(true); } } else { iEnroll.setEnabled(false); iEnroll.setVisible(false); if (iCustomCheckbox != null) { iCustomCheckbox.setVisible(false); iCustomCheckbox.setEnabled(false); } } } public boolean hasNotAssignedClass(ClassAssignmentInterface result) { for (final ClassAssignmentInterface.CourseAssignment course: result.getCourseAssignments()) { if (course.isAssigned() && !course.isFreeTime()) { for (ClassAssignmentInterface.ClassAssignment clazz: course.getClassAssignments()) { if (!clazz.isAssigned()) return true; } } } return false; } public List<String> getCriticalCoursesToDrop() { if (iLastAssignment != null && iSavedAssignment != null && iSavedRequest != null) { List<String> ret = new ArrayList<String>(); for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; RequestPriority rp = iSavedRequest.getRequestPriority(course); if (rp == null || rp.isAlternative() || (!rp.getRequest().isCritical() && !rp.getRequest().isImportant())) continue; boolean hasCourse = false; for (RequestedCourse alt: rp.getRequest().getRequestedCourse()) { if (alt.getCourseId() == null) continue; for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (alt.getCourseId().equals(x.getCourseId()) && x.isAssigned()) { hasCourse = true; break; } } if (!hasCourse) ret.add(MESSAGES.course(course.getSubject(), course.getCourseNbr())); } return ret; } return null; } public List<String> getCoursesToDrop() { if (iLastAssignment != null && iSavedAssignment != null) { List<String> ret = new ArrayList<String>(); courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId()) && x.isAssigned()) continue courses; ret.add(MESSAGES.course(course.getSubject(), course.getCourseNbr())); } return ret; } return null; } public List<String> getCourseChangesWithHonorsGradeMode() { if (iLastAssignment != null && iSavedAssignment != null) { List<String> ret = new ArrayList<String>(); courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; classes: for (ClassAssignmentInterface.ClassAssignment ca: course.getClassAssignments()) { if (ca.getGradeMode() != null && ca.getGradeMode().isHonor()) { for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId()) && x.isAssigned()) for (ClassAssignmentInterface.ClassAssignment y: x.getClassAssignments()) if (ca.getClassId().equals(y.getClassId())) continue classes; ret.add(MESSAGES.course(course.getSubject(), course.getCourseNbr())); continue courses; } } } return ret; } return null; } public List<String> getCourseChangesWithVarbiableCredit() { if (iLastAssignment != null && iSavedAssignment != null) { List<String> ret = new ArrayList<String>(); courses: for (ClassAssignmentInterface.CourseAssignment course: iSavedAssignment.getCourseAssignments()) { if (!course.isAssigned() || course.isFreeTime() || course.isTeachingAssignment()) continue; classes: for (ClassAssignmentInterface.ClassAssignment ca: course.getClassAssignments()) { if (ca.getCreditHour() != null && ca.hasVariableCredit() && ca.getCreditMin() < ca.getCreditHour()) { for (ClassAssignmentInterface.CourseAssignment x: iLastAssignment.getCourseAssignments()) if (course.getCourseId().equals(x.getCourseId()) && x.isAssigned()) for (ClassAssignmentInterface.ClassAssignment y: x.getClassAssignments()) if (ca.getClassId().equals(y.getClassId())) continue classes; ret.add(MESSAGES.course(course.getSubject(), course.getCourseNbr())); continue courses; } } } return ret; } return null; } public boolean useDefaultConfirmDialog() { return iEligibilityCheck == null || !iEligibilityCheck.hasFlag(EligibilityFlag.GWT_CONFIRMATIONS); } protected Command confirmEnrollment(final Command callback) { return confirmEnrollmentDrop(confirmWaitListDrop(confirmEnrollmentHonors(confirmEnrollmentVariableCredits(callback)))); } protected Command confirmEnrollmentDrop(final Command callback) { if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CONFIRM_DROP)) { final List<String> critical = getCriticalCoursesToDrop(); if (critical != null && !critical.isEmpty()) { return new Command() { @Override public void execute() { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmEnrollmentCriticalCourseDrop(ToolBox.toString(critical)), callback); } }; } final List<String> drops = getCoursesToDrop(); if (drops != null && !drops.isEmpty()) { return new Command() { @Override public void execute() { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmEnrollmentCourseDrop(ToolBox.toString(drops)), callback); } }; } } return callback; } public List<String> getCoursesToDropWaitList() { if (iSavedRequest != null && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST)) { List<String> ret = new ArrayList<String>(); r: for (Request r: iSavedRequest.getCourses()) { if (r.isWaitList() && r.hasRequestedCourse()) { for (RequestedCourse rc: r.getRequestedCourse()) if (rc.getStatus() == RequestedCourseStatus.ENROLLED) continue r; for (RequestedCourse rc: r.getRequestedCourse()) { if (rc.isCanWaitList() && rc.hasCourseId() && !Boolean.TRUE.equals(iCourseRequests.getWaitList(rc.getCourseId()))) { if (rc.getStatus() == RequestedCourseStatus.SAVED || rc.getStatus() == RequestedCourseStatus.OVERRIDE_APPROVED) { ret.add(rc.getCourseName()); } } } } } return ret; } return null; } public Command confirmWaitListDrop(final Command callback) { if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CONFIRM_DROP)) { final List<String> wl = getCoursesToDropWaitList(); if (wl != null && !wl.isEmpty()) { return new Command() { @Override public void execute() { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmCourseDropFromWaitList(ToolBox.toString(wl)), callback); } }; } } return callback; } protected Command confirmEnrollmentHonors(final Command callback) { if (iEligibilityCheck != null && iEligibilityCheck.hasGradeModes()) { final List<String> changes = getCourseChangesWithHonorsGradeMode(); if (changes != null && !changes.isEmpty()) { return new Command() { @Override public void execute() { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmEnrollmentHonorsGradeModeChange(ToolBox.toString(changes)), callback); } }; } } return callback; } protected Command confirmEnrollmentVariableCredits(final Command callback) { if (iEligibilityCheck != null && iEligibilityCheck.hasGradeModes()) { final List<String> changes = getCourseChangesWithVarbiableCredit(); if (changes != null && !changes.isEmpty()) { return new Command() { @Override public void execute() { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmEnrollmentVariableCreditChange(ToolBox.toString(changes)), callback); } }; } } return callback; } protected CourseFinder getQuickAddFinder() { if (iQuickAddFinder == null) { iQuickAddFinder = new CourseFinderDialog(); ((CourseFinderDialog)iQuickAddFinder).setText(MESSAGES.dialogQuickAdd()); ((CourseFinderDialog)iQuickAddFinder).addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { iAssignmentPanel.setFocus(true); } }); } }); CourseFinderCourses courses = new CourseFinderCourses(CONSTANTS.showCourseTitle(), CONSTANTS.courseFinderSuggestWhenEmpty(), CONSTANTS.courseFinderShowRequired(), iSpecRegCx); courses.setDataProvider(new DataProvider<String, Collection<CourseAssignment>>() { @Override public void getData(String source, AsyncCallback<Collection<CourseAssignment>> callback) { iSectioningService.listCourseOfferings(iContext, source, null, callback); } }); CourseFinderDetails details = new CourseFinderDetails(); details.setDataProvider(new DataProvider<CourseAssignment, String>() { @Override public void getData(CourseAssignment source, AsyncCallback<String> callback) { iSectioningService.retrieveCourseDetails(iContext, source.hasUniqueName() ? source.getCourseName() : source.getCourseNameWithTitle(), callback); } }); CourseFinderClasses classes = new CourseFinderClasses(true, iSpecRegCx, courses.getRequiredCheckbox()); classes.setDataProvider(new DataProvider<CourseAssignment, Collection<ClassAssignment>>() { @Override public void getData(CourseAssignment source, AsyncCallback<Collection<ClassAssignment>> callback) { iSectioningService.listClasses(iContext, source.hasUniqueName() ? source.getCourseName() : source.getCourseNameWithTitle(), callback); } }); courses.setCourseDetails(details, classes); iQuickAddFinder.setTabs(courses); iQuickAddFinder.addSelectionHandler(new SelectionHandler<RequestedCourse>() { @Override public void onSelection(final SelectionEvent<RequestedCourse> event) { if (event.getSelectedItem() == null || event.getSelectedItem().isEmpty()) { iStatus.warning(MESSAGES.courseSelectionNoCourseSelected()); return; } if (iCourseRequests.hasCourseActive(event.getSelectedItem())) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), MESSAGES.confirmQuickDrop(event.getSelectedItem().getCourseName()), new Command() { @Override public void execute() { final CourseRequestInterface undo = iCourseRequests.getRequest(); iCourseRequests.dropCourse(event.getSelectedItem()); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); iCourseRequests.setRequest(undo); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); iQuickAddFinder.setValue(null, true); } }); } }); } else { if (iQuickAddSuggestions == null) { iQuickAddSuggestions = new SuggestionsBox(iAssignmentGrid.getColorProvider(), iSpecRegCx); iQuickAddSuggestions.addCloseHandler(new CloseHandler<PopupPanel>() { public void onClose(CloseEvent<PopupPanel> event) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { iAssignmentPanel.setFocus(true); } }); } }); } iQuickAddSuggestions.open(iCourseRequests.getRequest(), iLastResult, event.getSelectedItem(), useDefaultConfirmDialog(), new AsyncCallback<ClassAssignmentInterface>() { @Override public void onSuccess(ClassAssignmentInterface result) { clearMessage(); if (!iCourseRequests.hasCourseActive(event.getSelectedItem())) iCourseRequests.addCourse(event.getSelectedItem()); fillIn(result); addHistory(); iQuickAddFinder.setValue(null, true); } @Override public void onFailure(Throwable caught) { if (caught != null) iStatus.error(caught.getMessage()); iAssignmentPanel.setFocus(true); if (event.getSelectedItem().isCanWaitList() && iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_WAITLIST)) { UniTimeConfirmationDialog.confirm(useDefaultConfirmDialog(), caught.getMessage() + "\n" + MESSAGES.confirmQuickWaitList(event.getSelectedItem().getCourseName()), new Command() { @Override public void execute() { final CourseRequestInterface undo = iCourseRequests.getRequest(); Request request = new Request(); request.setWaitList(true); request.addRequestedCourse(event.getSelectedItem()); iCourseRequests.addRequest(request); LoadingWidget.getInstance().show(MESSAGES.courseRequestsScheduling()); CourseRequestInterface r = iCourseRequests.getRequest(); r.setNoChange(true); iSectioningService.section(r, iLastResult, new AsyncCallback<ClassAssignmentInterface>() { public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iStatus.error(MESSAGES.exceptionSectioningFailed(caught.getMessage()), caught); iCourseRequests.setRequest(undo); } public void onSuccess(ClassAssignmentInterface result) { fillIn(result); addHistory(); iQuickAddFinder.setValue(null, true); } }); } }); } } }); } } }); } return iQuickAddFinder; } protected void requestEnrollmentOverrides(final SpecialRegistrationEligibilityResponse eligibilityResponse, final Command callWhenDone) { if (eligibilityResponse == null) { if (callWhenDone != null) callWhenDone.execute(); return; } final Collection<ErrorMessage> errors = eligibilityResponse.getErrors(); CheckCoursesResponse confirm = new CheckCoursesResponse(); confirm.setConfirmation(0, MESSAGES.dialogRequestOverrides(), MESSAGES.buttonRequestOverrides(), MESSAGES.buttonCancelRequest(), MESSAGES.titleRequestOverrides(), MESSAGES.titleCancelRequest()); confirm.addConfirmation(MESSAGES.messageRegistrationErrorsDetected(), 0, -1); confirm.addConfirmation(MESSAGES.messageRequestOverridesNote(), 0, 2); final CourseRequestInterface.CourseMessage note = confirm.addConfirmation(iSpecRegCx.getNote() == null ? "" : iSpecRegCx.getNote(), 0, 3); note.setCode("REQUEST_NOTE"); if (eligibilityResponse.hasSuggestions()) for (String suggestion: eligibilityResponse.getSuggestions()) note.addSuggestion(suggestion); confirm.addConfirmation(MESSAGES.messageRequestOverridesOptions(), 0, 4); confirm.addConfirmation(MESSAGES.messageRequestOverridesDisclaimer(), 0, 7); if (iSpecRegCx.hasDisclaimer()) confirm.addCheckBox(iSpecRegCx.getDisclaimer(), 0, 8); else confirm.addCheckBox(MESSAGES.messageRequestOverridesDisclaimerMessage(), 0, 8); for (ErrorMessage e: errors) { if ("IGNORE".equals(e.getCode())) { continue; } else if (iEligibilityCheck.hasOverride(e.getCode())) { confirm.addMessage(null, e.getCourse(), e.getCode(), e.getMessage(), 0); } else { confirm.addMessage(null, e.getCourse(), e.getCode(), e.getMessage(), 0); } } if (eligibilityResponse.hasCancelErrors()) { confirm.addConfirmation(MESSAGES.messageRequestOverridesCancel(), 0, 5); for (ErrorMessage e: eligibilityResponse.getCancelErrors()) confirm.addMessage(null, e.getCourse(), e.getCode(), e.getMessage(), 0, 6); } CourseRequestsConfirmationDialog.confirm(confirm, 0, new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { clearMessage(); LoadingWidget.getInstance().show(MESSAGES.waitSpecialRegistration()); iSectioningService.submitSpecialRequest( new SubmitSpecialRegistrationRequest(iContext, iSpecRegCx.getRequestId(), iCourseRequests.getRequest(), iLastEnrollment != null ? iLastEnrollment : iLastResult, errors, note.getMessage(), eligibilityResponse.getCredit()), new AsyncCallback<SubmitSpecialRegistrationResponse>() { @Override public void onFailure(Throwable caught) { LoadingWidget.getInstance().hide(); iStatus.error(MESSAGES.submitSpecialRegistrationFail(caught.getMessage()), caught); updateHistory(); if (callWhenDone != null) callWhenDone.execute(); } @Override public void onSuccess(SubmitSpecialRegistrationResponse response) { LoadingWidget.getInstance().hide(); if (response.isSuccess()) { iSpecialRegAssignment = iLastAssignment; } iSpecRegCx.setStatus(response.getStatus()); iSpecRegCx.setRequestId(response.getRequestId()); iSpecRegCx.setNote(note.getMessage()); if (response.hasRequests()) { List<RetrieveSpecialRegistrationResponse> requests = new ArrayList<RetrieveSpecialRegistrationResponse>(response.getRequests()); for (RetrieveSpecialRegistrationResponse r: iSpecialRegistrationsPanel.getRegistrations()) { if (eligibilityResponse.isToBeCancelled(r.getRequestId())) continue; if (response.isCancelledRequest(r.getRequestId())) continue; if (response.hasRequest(r.getRequestId())) continue; requests.add(r); } Collections.sort(requests); iSpecialRegistrationsPanel.populate(requests, iSavedAssignment); } if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)) { iEligibilityCheck.setFlag(EligibilityFlag.HAS_SPECREG, true); } for (CourseAssignment ca: iLastAssignment.getCourseAssignments()) for (ClassAssignment a: ca.getClassAssignments()) { a.setError(null); a.setWarn(null); a.setInfo(null); a.setSpecRegStatus(null); for (ErrorMessage f: errors) { if (a.getExternalId() != null && a.getExternalId().equals(f.getSection())) { a.addError(f.getMessage()); a.setSpecRegStatus(response.getStatus()); } } } fillIn(iLastAssignment); if (response.isSuccess()) { iStatus.done(response.hasMessage() ? response.getMessage() : MESSAGES.submitSecialRegistrationOK()); } else { iStatus.error(response.getMessage()); } updateHistory(); if (callWhenDone != null) callWhenDone.execute(); } }); } else { if (callWhenDone != null) callWhenDone.execute(); } } @Override public void onFailure(Throwable caught) { iStatus.error(MESSAGES.requestSpecialRegistrationFail(caught.getMessage()), caught); if (callWhenDone != null) callWhenDone.execute(); } }); } protected void checkSpecialRegistrationAfterFailedSubmitSchedule(ArrayList<ClassAssignmentInterface.ClassAssignment> lastEnrollment, Throwable exception, ClassAssignmentInterface result, final Command callWhenDone) { iLastEnrollment = lastEnrollment; final EnrollmentConfirmationDialog dialog = new EnrollmentConfirmationDialog(exception, result, new AsyncCallback<SpecialRegistrationEligibilityResponse>() { @Override public void onSuccess(SpecialRegistrationEligibilityResponse result) { requestEnrollmentOverrides(result, callWhenDone); } @Override public void onFailure(Throwable caught) { if (callWhenDone != null) callWhenDone.execute(); } }); dialog.center(); iSectioningService.checkSpecialRequestEligibility( new SpecialRegistrationEligibilityRequest(iContext, iSpecRegCx.getRequestId(), iLastEnrollment, iLastAssignment == null ? null : iLastAssignment.getErrors()), new AsyncCallback<SpecialRegistrationEligibilityResponse>() { @Override public void onFailure(Throwable caught) { dialog.showError(caught.getMessage()); } @Override public void onSuccess(final SpecialRegistrationEligibilityResponse eligibilityResponse) { dialog.setResponse(eligibilityResponse); } }); } protected void checkWaitListAfterSubmitSchedule() { if (iSavedAssignment.getRequest() != null && iSavedAssignment.getRequest().hasWaitListChecks()) { final CheckCoursesResponse lastCheck = iSavedAssignment.getRequest().getWaitListChecks(); iCourseRequests.setLastCheck(lastCheck); if (lastCheck.isError()) { iStatus.error(lastCheck.getErrorMessage()); return; } if (lastCheck.hasMessages()) { String error = null; for (CourseMessage m: lastCheck.getMessages()) { if (m.isConfirm() && !iSpecialRegistrationsPanel.canWaitList(m.getCourseId())) { if (error == null) error = MESSAGES.errorWaitListApprovalAlreadyRequested(m.getCourse()); else if (!error.contains(MESSAGES.errorWaitListApprovalAlreadyRequested(m.getCourse()))) error += "\n" + MESSAGES.errorWaitListApprovalAlreadyRequested(m.getCourse()); } } if (error != null) { iStatus.error(error + "\n" + MESSAGES.errorWaitListApprovalCancelFirst()); return; } } if (lastCheck.isConfirm()) { final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { LoadingWidget.getInstance().show(MESSAGES.waitRequestWaitListOverrides()); iSectioningService.waitListSubmitOverrides(iSavedAssignment.getRequest(), lastCheck.getMaxCreditNeeded(), new AsyncCallback<CourseRequestInterface>() { @Override public void onSuccess(CourseRequestInterface result) { iSavedRequest = result; if (iWaitListsPanel != null) iWaitListsPanel.populate(result); iCourseRequests.setValue(result, false); iCourseRequests.notifySaveSucceeded(); fillIn(iLastAssignment, false); iStatus.done(MESSAGES.waitListOverridesRequested()); LoadingWidget.getInstance().hide(); updateHistory(); } public void onFailure(Throwable caught) { iStatus.error(MESSAGES.failedRequestWaitListOverrides(caught.getMessage()), caught); LoadingWidget.getInstance().hide(); updateHistory(); } }); } else { iStatus.warning(MESSAGES.waitListOverridesNotRequested()); } } @Override public void onFailure(Throwable caught) {} }; final Iterator<Integer> it = lastCheck.getConfirms().iterator(); new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) {} @Override public void onSuccess(Boolean accept) { if (accept && it.hasNext()) { CourseRequestsConfirmationDialog.confirm(lastCheck, it.next(), this); } else { callback.onSuccess(accept); } } }.onSuccess(true); } } } protected void printConfirmation(CourseRequestInterface savedRequests) { WebTable requests = new WebTable(); requests.setEmptyMessage(StudentSectioningWidget.MESSAGES.emptyRequests()); requests.setHeader(new WebTable.Row( new WebTable.Cell(StudentSectioningWidget.MESSAGES.colPriority(), 1, "25px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colCourse(), 1, "75px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colTitle(), 1, "200px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colCredit(), 1, "20px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colPreferences(), 1, "100px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colWarnings(), 1, "200px"), new WebTable.Cell(StudentSectioningWidget.MESSAGES.colStatus(), 1, "20px"), new WebTable.Cell(iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_NO_SUBS) ? StudentSectioningWidget.MESSAGES.colNoSubs() : StudentSectioningWidget.MESSAGES.colWaitList(), 1, "20px") )); ArrayList<WebTable.Row> rows = new ArrayList<WebTable.Row>(); boolean hasPref = false, hasWarn = false, hasWait = false; NumberFormat df = NumberFormat.getFormat("0.#"); CheckCoursesResponse check = new CheckCoursesResponse(savedRequests.getConfirmations()); hasWarn = savedRequests.hasConfirmations(); int priority = 1; for (Request request: savedRequests.getCourses()) { if (!request.hasRequestedCourse()) continue; boolean first = true; if (request.isWaitList()) hasWait = true; for (RequestedCourse rc: request.getRequestedCourse()) { if (rc.isCourse()) { ImageResource icon = null; String iconText = null; String msg = check.getMessage(rc.getCourseName(), "\n", "CREDIT"); if (check.isError(rc.getCourseName()) && (rc.getStatus() == null || rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED)) { icon = RESOURCES.requestError(); iconText = (msg); } else if (rc.getStatus() != null) { switch (rc.getStatus()) { case ENROLLED: icon = RESOURCES.requestEnrolled(); iconText = (MESSAGES.enrolled(rc.getCourseName())); break; case OVERRIDE_NEEDED: icon = RESOURCES.requestNeeded(); iconText = (MESSAGES.overrideNeeded(msg)); break; case SAVED: icon = RESOURCES.requestSaved(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.requested(rc.getCourseName())); break; case OVERRIDE_REJECTED: icon = RESOURCES.requestRejected(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideRejected(rc.getCourseName())); break; case OVERRIDE_PENDING: icon = RESOURCES.requestPending(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overridePending(rc.getCourseName())); break; case OVERRIDE_CANCELLED: icon = RESOURCES.requestCancelled(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideCancelled(rc.getCourseName())); break; case OVERRIDE_APPROVED: icon = RESOURCES.requestSaved(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideApproved(rc.getCourseName())); break; default: if (check.isError(rc.getCourseName())) icon = RESOURCES.requestError(); iconText = (msg); } } if (rc.hasRequestorNote()) iconText += "\n" + MESSAGES.requestNote(rc.getRequestorNote()); if (rc.hasStatusNote()) iconText += "\n" + MESSAGES.overrideNote(rc.getStatusNote()); Collection<Preference> prefs = null; if (rc.hasSelectedIntructionalMethods()) { if (rc.hasSelectedClasses()) { prefs = new ArrayList<Preference>(rc.getSelectedIntructionalMethods().size() + rc.getSelectedClasses().size()); prefs.addAll(new TreeSet<Preference>(rc.getSelectedIntructionalMethods())); prefs.addAll(new TreeSet<Preference>(rc.getSelectedClasses())); } else { prefs = new TreeSet<Preference>(rc.getSelectedIntructionalMethods()); } } else if (rc.hasSelectedClasses()) { prefs = new TreeSet<Preference>(rc.getSelectedClasses()); } String status = ""; if (rc.getStatus() != null) { switch (rc.getStatus()) { case ENROLLED: status = MESSAGES.reqStatusEnrolled(); break; case OVERRIDE_APPROVED: status = MESSAGES.reqStatusApproved(); break; case OVERRIDE_CANCELLED: status = MESSAGES.reqStatusCancelled(); break; case OVERRIDE_PENDING: status = MESSAGES.reqStatusPending(); break; case OVERRIDE_REJECTED: status = MESSAGES.reqStatusRejected(); break; } } if (status.isEmpty()) status = MESSAGES.reqStatusRegistered(); if (prefs != null) hasPref = true; WebTable.Cell credit = new WebTable.Cell(rc.hasCredit() ? (rc.getCreditMin().equals(rc.getCreditMax()) ? df.format(rc.getCreditMin()) : df.format(rc.getCreditMin()) + " - " + df.format(rc.getCreditMax())) : ""); credit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); String note = null; if (check != null) note = check.getMessage(rc.getCourseName(), "\n", "CREDIT"); if (rc.hasRequestorNote()) note = (note == null ? "" : note + "\n") + rc.getRequestorNote(); if (rc.hasStatusNote()) note = (note == null ? "" : note + "\n") + rc.getStatusNote(); P messages = new P("text-pre-wrap"); messages.setText(note); WebTable.Row row = new WebTable.Row( new WebTable.Cell(first ? MESSAGES.courseRequestsPriority(priority) : ""), new WebTable.Cell(rc.getCourseName()), new WebTable.Cell(rc.hasCourseTitle() ? rc.getCourseTitle() : ""), credit, new WebTable.Cell(ToolBox.toString(prefs)), new WebTable.WidgetCell(messages, note), (icon == null ? new WebTable.Cell(status) : new WebTable.IconCell(icon, iconText, status)), (first && request.isWaitList() ? new WebTable.IconCell(RESOURCES.requestsWaitList(), MESSAGES.descriptionRequestWaitListed(), "") : new WebTable.Cell("")) ); if (priority > 1 && first) for (WebTable.Cell cell: row.getCells()) cell.setStyleName("top-border-dashed"); rows.add(row); } else if (rc.isFreeTime()) { String free = ""; for (FreeTime ft: rc.getFreeTime()) { if (!free.isEmpty()) free += ", "; free += ft.toString(CONSTANTS.shortDays(), CONSTANTS.useAmPm()); } String note = null; if (check != null) note = check.getMessage(CONSTANTS.freePrefix() + free, "<br>"); P messages = new P("text-pre-wrap"); messages.setText(note); WebTable.Row row = new WebTable.Row( new WebTable.Cell(first ? MESSAGES.courseRequestsPriority(priority) : ""), new WebTable.Cell(CONSTANTS.freePrefix() + free, 3, null), new WebTable.Cell(""), new WebTable.WidgetCell(messages, note), new WebTable.IconCell(RESOURCES.requestSaved(), MESSAGES.requested(free), MESSAGES.reqStatusRegistered()), new WebTable.Cell("")); if (priority > 1 && first) for (WebTable.Cell cell: row.getCells()) cell.setStyleName("top-border-dashed"); rows.add(row); } first = false; } priority ++; } priority = 1; for (Request request: savedRequests.getAlternatives()) { if (!request.hasRequestedCourse()) continue; boolean first = true; if (request.isWaitList()) hasWait = true; for (RequestedCourse rc: request.getRequestedCourse()) { if (rc.isCourse()) { ImageResource icon = null; String iconText = null; String msg = check.getMessage(rc.getCourseName(), "\n", "CREDIT"); if (check.isError(rc.getCourseName()) && (rc.getStatus() == null || rc.getStatus() != RequestedCourseStatus.OVERRIDE_REJECTED)) { icon = RESOURCES.requestError(); iconText = (msg); } else if (rc.getStatus() != null) { switch (rc.getStatus()) { case ENROLLED: icon = RESOURCES.requestEnrolled(); iconText = (MESSAGES.enrolled(rc.getCourseName())); break; case OVERRIDE_NEEDED: icon = RESOURCES.requestNeeded(); iconText = (MESSAGES.overrideNeeded(msg)); break; case SAVED: icon = RESOURCES.requestSaved(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.requested(rc.getCourseName())); break; case OVERRIDE_REJECTED: icon = RESOURCES.requestRejected(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideRejected(rc.getCourseName())); break; case OVERRIDE_PENDING: icon = RESOURCES.requestPending(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overridePending(rc.getCourseName())); break; case OVERRIDE_CANCELLED: icon = RESOURCES.requestCancelled(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideCancelled(rc.getCourseName())); break; case OVERRIDE_APPROVED: icon = RESOURCES.requestSaved(); iconText = ((msg == null ? "" : MESSAGES.requestWarnings(msg) + "\n\n") + MESSAGES.overrideApproved(rc.getCourseName())); break; default: if (check.isError(rc.getCourseName())) icon = RESOURCES.requestError(); iconText = (msg); } } if (rc.hasRequestorNote()) iconText += "\n" + MESSAGES.requestNote(rc.getRequestorNote()); if (rc.hasStatusNote()) iconText += "\n" + MESSAGES.overrideNote(rc.getStatusNote()); Collection<Preference> prefs = null; if (rc.hasSelectedIntructionalMethods()) { if (rc.hasSelectedClasses()) { prefs = new ArrayList<Preference>(rc.getSelectedIntructionalMethods().size() + rc.getSelectedClasses().size()); prefs.addAll(new TreeSet<Preference>(rc.getSelectedIntructionalMethods())); prefs.addAll(new TreeSet<Preference>(rc.getSelectedClasses())); } else { prefs = new TreeSet<Preference>(rc.getSelectedIntructionalMethods()); } } else if (rc.hasSelectedClasses()) { prefs = new TreeSet<Preference>(rc.getSelectedClasses()); } if (prefs != null) hasPref = true; String status = ""; if (rc.getStatus() != null) { switch (rc.getStatus()) { case ENROLLED: status = MESSAGES.reqStatusEnrolled(); break; case OVERRIDE_APPROVED: status = MESSAGES.reqStatusApproved(); break; case OVERRIDE_CANCELLED: status = MESSAGES.reqStatusCancelled(); break; case OVERRIDE_PENDING: status = MESSAGES.reqStatusPending(); break; case OVERRIDE_REJECTED: status = MESSAGES.reqStatusRejected(); break; } } if (status.isEmpty()) status = MESSAGES.reqStatusRegistered(); WebTable.Cell credit = new WebTable.Cell(rc.hasCredit() ? (rc.getCreditMin().equals(rc.getCreditMax()) ? df.format(rc.getCreditMin()) : df.format(rc.getCreditMin()) + " - " + df.format(rc.getCreditMax())) : ""); credit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); String note = null; if (check != null) note = check.getMessage(rc.getCourseName(), "\n", "CREDIT"); if (rc.hasRequestorNote()) note = (note == null ? "" : note + "\n") + rc.getRequestorNote(); if (rc.hasStatusNote()) note = (note == null ? "" : note + "\n") + rc.getStatusNote(); P messages = new P("text-pre-wrap"); messages.setText(note); WebTable.Row row = new WebTable.Row( new WebTable.Cell(first ? MESSAGES.courseRequestsAlternate(priority) : ""), new WebTable.Cell(rc.getCourseName()), new WebTable.Cell(rc.hasCourseTitle() ? rc.getCourseTitle() : ""), credit, new WebTable.Cell(ToolBox.toString(prefs)), new WebTable.WidgetCell(messages, note), (icon == null ? new WebTable.Cell(status) : new WebTable.IconCell(icon, iconText, status)), (first && request.isWaitList() ? new WebTable.IconCell(RESOURCES.requestsWaitList(), MESSAGES.descriptionRequestWaitListed(), "") : new WebTable.Cell("")) ); if (first) for (WebTable.Cell cell: row.getCells()) cell.setStyleName(priority == 1 ? "top-border-solid" : "top-border-dashed"); rows.add(row); } else if (rc.isFreeTime()) { String free = ""; for (FreeTime ft: rc.getFreeTime()) { if (!free.isEmpty()) free += ", "; free += ft.toString(CONSTANTS.shortDays(), CONSTANTS.useAmPm()); } WebTable.Row row = new WebTable.Row( new WebTable.Cell(first ? MESSAGES.courseRequestsPriority(priority) : ""), new WebTable.Cell(CONSTANTS.freePrefix() + free, 3, null), new WebTable.Cell(""), new WebTable.Cell(""), new WebTable.IconCell(RESOURCES.requestSaved(), MESSAGES.requested(free), MESSAGES.reqStatusRegistered()), new WebTable.Cell("")); if (first) for (WebTable.Cell cell: row.getCells()) cell.setStyleName(priority == 1 ? "top-border-solid" : "top-border-dashed"); rows.add(row); } first = false; } priority ++; } if (savedRequests.getMaxCreditOverrideStatus() != null) { ImageResource icon = null; String status = ""; String note = null; String iconText = null; if (savedRequests.hasCreditWarning()) { note = savedRequests.getCreditWarning(); iconText = savedRequests.getCreditWarning(); hasWarn = true; } switch (savedRequests.getMaxCreditOverrideStatus()) { case CREDIT_HIGH: icon = RESOURCES.requestNeeded(); status = MESSAGES.reqStatusWarning(); iconText += "\n" + MESSAGES.creditStatusTooHigh(); break; case OVERRIDE_REJECTED: icon = RESOURCES.requestError(); status = MESSAGES.reqStatusRejected(); iconText += "\n" + MESSAGES.creditStatusDenied(); break; case CREDIT_LOW: case OVERRIDE_NEEDED: icon = RESOURCES.requestNeeded(); status = MESSAGES.reqStatusWarning(); break; case OVERRIDE_CANCELLED: icon = RESOURCES.requestNeeded(); status = MESSAGES.reqStatusCancelled(); iconText += "\n" + MESSAGES.creditStatusCancelled(); break; case OVERRIDE_PENDING: icon = RESOURCES.requestPending(); status = MESSAGES.reqStatusPending(); iconText += "\n" + MESSAGES.creditStatusPending(); break; case OVERRIDE_APPROVED: icon = RESOURCES.requestSaved(); status = MESSAGES.reqStatusApproved(); iconText += (iconText == null ? "" : iconText + "\n") + MESSAGES.creditStatusApproved(); break; case SAVED: icon = RESOURCES.requestSaved(); status = MESSAGES.reqStatusRegistered(); break; } if (savedRequests.hasRequestorNote()) { note = (note == null ? "" : note + "\n") + savedRequests.getRequestorNote(); hasWarn = true; } if (savedRequests.hasCreditNote()) { note = (note == null ? "" : note + "\n") + savedRequests.getCreditNote(); hasWarn = true; } float[] range = savedRequests.getCreditRange(iEligibilityCheck == null ? null : iEligibilityCheck.getAdvisorWaitListedCourseIds()); WebTable.Cell credit = new WebTable.Cell(range != null ? range[0] < range[1] ? df.format(range[0]) + " - " + df.format(range[1]) : df.format(range[0]) : ""); credit.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); P messages = new P("text-pre-wrap"); messages.setText(note); WebTable.Row row = new WebTable.Row( new WebTable.Cell(MESSAGES.rowRequestedCredit(), 2, null), new WebTable.Cell(""), credit, new WebTable.Cell(""), new WebTable.WidgetCell(messages, note), (icon == null ? new WebTable.Cell(status) : new WebTable.IconCell(icon, iconText, status)), new WebTable.Cell("") ); for (WebTable.Cell cell: row.getCells()) cell.setStyleName("top-border-solid"); row.getCell(0).setStyleName("top-border-solid text-bold"); rows.add(row); } WebTable.Row[] rowArray = new WebTable.Row[rows.size()]; int idx = 0; for (WebTable.Row row: rows) rowArray[idx++] = row; requests.setData(rowArray); requests.setColumnVisible(4, hasPref); requests.setColumnVisible(5, hasWarn); requests.setColumnVisible(7, hasWait); P credit = new P("unitime-StatusLine"); float[] range = savedRequests.getCreditRange(iEligibilityCheck == null ? null : iEligibilityCheck.getAdvisorWaitListedCourseIds()); if (range != null && range[1] > 0f) { if (range[0] == range[1]) credit.setText(MESSAGES.requestedCredit(range[0])); else credit.setText(MESSAGES.requestedCreditRange(range[0], range[1])); } ToolBox.print(GWT_MESSAGES.pageStudentCourseRequests(), iUserAuthentication.getUser(), iSessionSelector.getAcademicSessionName(), requests//, credit ); } protected void changeGradeModes(ArrayList<ClassAssignmentInterface.ClassAssignment> lastEnrollment, List<RetrieveSpecialRegistrationResponse> approvals) { if (iChangeGradeModesDialog == null) { iChangeGradeModesDialog = new ChangeGradeModesDialog(iContext, iStatus) { protected void onChange(ChangeGradeModesResponse response) { if (response.hasGradeModes()) { for (CourseAssignment course: iSavedAssignment.getCourseAssignments()) for (ClassAssignment ca: course.getClassAssignments()) { GradeMode mode = response.getGradeMode(ca); if (mode != null) ca.setGradeMode(mode); } } if (response.hasCreditHours()) { for (CourseAssignment course: iSavedAssignment.getCourseAssignments()) for (ClassAssignment ca: course.getClassAssignments()) { Float creditHour = response.getCreditHour(ca); if (creditHour != null) { ca.setCreditHour(creditHour); ca.setCredit(creditHour == 0f ? "" : MESSAGES.credit(creditHour)); } } } if (response.hasRequests()) { List<RetrieveSpecialRegistrationResponse> requests = new ArrayList<RetrieveSpecialRegistrationResponse>(response.getRequests()); for (RetrieveSpecialRegistrationResponse r: iSpecialRegistrationsPanel.getRegistrations()) { if (response.isToBeCancelled(r.getRequestId())) continue; if (response.hasRequest(r.getRequestId())) continue; requests.add(r); } Collections.sort(requests); iSpecialRegistrationsPanel.populate(requests, iSavedAssignment); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)) { iEligibilityCheck.setFlag(EligibilityFlag.HAS_SPECREG, true); } } fillIn(iSavedAssignment); addHistory(); } }; } if (iEligibilityCheck != null) { if (!iEligibilityCheck.hasFlag(EligibilityFlag.CAN_CHANGE_GRADE_MODE)) { iChangeGradeModesDialog.setText(MESSAGES.dialogChangeVariableCredit()); } else if (!iEligibilityCheck.hasFlag(EligibilityFlag.CAN_CHANGE_VAR_CREDIT)) { iChangeGradeModesDialog.setText(MESSAGES.dialogChangeGradeMode()); } else { iChangeGradeModesDialog.setText(MESSAGES.dialogChangeGradeModeAndVariableCredit()); } } iChangeGradeModesDialog.changeGradeModes(lastEnrollment, approvals); } protected void requestVariableTitleCourse() { if (iRequestVariableTitleCourseDialog == null) { iRequestVariableTitleCourseDialog = new RequestVariableTitleCourseDialog(iContext, iStatus) { protected void onChange(final VariableTitleCourseResponse response) { if (response.hasRequests()) { List<RetrieveSpecialRegistrationResponse> requests = new ArrayList<RetrieveSpecialRegistrationResponse>(response.getRequests()); for (RetrieveSpecialRegistrationResponse r: iSpecialRegistrationsPanel.getRegistrations()) { if (response.isToBeCancelled(r.getRequestId())) continue; if (response.hasRequest(r.getRequestId())) continue; requests.add(r); } Collections.sort(requests); iSpecialRegistrationsPanel.populate(requests, iSavedAssignment); if (iEligibilityCheck != null && iEligibilityCheck.hasFlag(EligibilityFlag.CAN_SPECREG)) { iEligibilityCheck.setFlag(EligibilityFlag.HAS_SPECREG, true); } } if (response.getCourse() != null) { getQuickAddFinder().setValue(response.getCourse(), true); getQuickAddFinder().findCourse(); } } }; } iRequestVariableTitleCourseDialog.requestVariableTitleCourse( iEligibilityCheck == null || !iEligibilityCheck.hasCurrentCredit() ? iCurrentCredit : iEligibilityCheck.getCurrentCredit(), iEligibilityCheck == null ? null : iEligibilityCheck.getMaxCredit()); } public void setSessionId(Long sessionId) { iContext.setSessionId(sessionId); } public void setStudentId(Long studentId) { iContext.setStudentId(studentId); } }
92371a0c9ce96269bae3032347bde8bb1cc80079
922
java
Java
java-algorithm/src/main/java/com/leetcode/Problem113.java
isudox/nerd-algorithm
c1fbe153953cf3fc24395f75d102016fdf9ea0fa
[ "MIT" ]
5
2017-06-11T09:19:34.000Z
2019-01-16T16:58:31.000Z
java-algorithm/src/main/java/com/leetcode/Problem113.java
isudox/leetcode-solution
60085e64deaf396a171367affc94b18114565c43
[ "MIT" ]
5
2020-03-22T13:53:54.000Z
2020-03-23T08:49:35.000Z
java-algorithm/src/main/java/com/leetcode/Problem113.java
isudox/nerd-algorithm
c1fbe153953cf3fc24395f75d102016fdf9ea0fa
[ "MIT" ]
1
2019-03-02T15:50:43.000Z
2019-03-02T15:50:43.000Z
24.918919
70
0.562907
997,937
package com.leetcode; import com.common.TreeNode; import java.util.ArrayList; import java.util.List; /** * 113. Path Sum II * https://leetcode.com/problems/path-sum-ii/ */ public class Problem113 { private List<List<Integer>> ans = new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int targetSum) { if (root == null) return ans; dfs(root, new ArrayList<>(), targetSum); return ans; } private void dfs(TreeNode node, List<Integer> path, int remain) { path.add(node.val); remain -= node.val; if (node.left == null && node.right == null) { if (remain == 0) ans.add(new ArrayList<>(path)); } if (node.left != null) dfs(node.left, path, remain); if (node.right != null) dfs(node.right, path, remain); path.remove(path.size() - 1); } }
92371a47c3df06055b1df93b815c675fc2cc2e85
4,479
java
Java
ARToolKitEm/src/to/augmented/reality/android/em/artoolkitem/sample/shader/SimpleVertexShader.java
donaldmunro/AARemu
f45c0909b2be645672ca16957d1d72741f93c9f1
[ "Apache-2.0" ]
33
2015-03-16T06:29:48.000Z
2021-05-03T15:13:18.000Z
ARToolKitEm/src/to/augmented/reality/android/em/artoolkitem/sample/shader/SimpleVertexShader.java
donaldmunro/AARemu
f45c0909b2be645672ca16957d1d72741f93c9f1
[ "Apache-2.0" ]
1
2018-11-30T09:06:49.000Z
2020-06-24T14:12:09.000Z
ARToolKitEm/src/to/augmented/reality/android/em/artoolkitem/sample/shader/SimpleVertexShader.java
donaldmunro/AARemu
f45c0909b2be645672ca16957d1d72741f93c9f1
[ "Apache-2.0" ]
14
2015-02-26T16:39:03.000Z
2022-02-19T12:45:59.000Z
51.482759
182
0.65461
997,938
/* * ARActivity.java * ARToolKit5 * * This file is part of ARToolKit. * * ARToolKit is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARToolKit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ARToolKit. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and to * copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module * which is neither derived from nor based on this library. If you modify this * library, you may extend this exception to your version of the library, but you * are not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Copyright 2015 Daqri, LLC. * Copyright 2011-2015 ARToolworks, Inc. * * Author(s): Julian Looser, Philip Lamb * */ package to.augmented.reality.android.em.artoolkitem.sample.shader; import org.artoolkit.ar.base.rendering.gles20.BaseVertexShader; import org.artoolkit.ar.base.rendering.gles20.OpenGLShader; /** * Created by Thorsten Bux on 21.01.2016. * SimpleVertexShader class that extends the {@link BaseVertexShader} class. * Here you define your vertex shader and what it does with the geometry position. * This vertex shader class calculates the MVP matrix and applies it to the passed * in geometry position vectors. */ public class SimpleVertexShader extends BaseVertexShader { public static String colorVectorString = "a_Color"; final String vertexShader = "uniform mat4 u_MVPMatrix; \n" // A constant representing the combined model/view/projection matrix. + "uniform mat4 " + OpenGLShader.projectionMatrixString + "; \n" // projection matrix + "uniform mat4 " + OpenGLShader.modelViewMatrixString + "; \n" // modelView matrix + "attribute vec4 " + OpenGLShader.positionVectorString + "; \n" // Per-vertex position information we will pass in. + "attribute vec4 " + colorVectorString + "; \n" // Per-vertex color information we will pass in. + "varying vec4 v_Color; \n" // This will be passed into the fragment shader. + "void main() \n" // The entry point for our vertex shader. + "{ \n" + " v_Color = " + colorVectorString + "; \n" // Pass the color through to the fragment shader. // It will be interpolated across the triangle. + " vec4 p = " + OpenGLShader.modelViewMatrixString + " * " + OpenGLShader.positionVectorString + "; \n " // transform vertex position with modelview matrix + " gl_Position = " + OpenGLShader.projectionMatrixString + " \n" // gl_Position is a special variable used to store the final position. + " * p; \n" // Multiply the vertex by the matrix to get the final point in + "} \n"; // normalized screen coordinates. @Override /** * This method gets called by the {@link org.artoolkit.ar.base.rendering.gles20.BaseShaderProgram} * during initializing the shaders. * You can use it to pass in your own shader program as shown here. If you do not pass your own * shader program the one from {@link BaseVertexShader} is used. * * @return The handle of the fragment shader */ public int configureShader() { this.setShaderSource(vertexShader); return super.configureShader(); } }
92371b87ff8595460dd3b170081523f23d28ab79
780
java
Java
java/src/main/java/cn/plusman/learn/java/override/CollectionClassifier.java
plusmancn/learn-arithmetic
f16d4a8fa6f5dfc23e3ee02b5bb4bb4bc91b7ad8
[ "Apache-2.0" ]
null
null
null
java/src/main/java/cn/plusman/learn/java/override/CollectionClassifier.java
plusmancn/learn-arithmetic
f16d4a8fa6f5dfc23e3ee02b5bb4bb4bc91b7ad8
[ "Apache-2.0" ]
1
2021-03-14T15:33:46.000Z
2021-03-14T15:33:46.000Z
java/src/main/java/cn/plusman/learn/java/override/CollectionClassifier.java
plusmancn/learn-arithmetic
f16d4a8fa6f5dfc23e3ee02b5bb4bb4bc91b7ad8
[ "Apache-2.0" ]
1
2020-11-08T09:11:19.000Z
2020-11-08T09:11:19.000Z
22.285714
52
0.557692
997,939
package cn.plusman.learn.java.override; import java.math.BigInteger; import java.util.*; /** * @author plusman * @since 2021/7/7 12:02 PM */ public class CollectionClassifier { public static String classify(Set<?> s) { return "Set"; } public static String classify(List<?> lst) { return "List"; } public static String classify(Collection<?> c) { return "Unknown Collection"; } public static void main(String[] args) { Collection<?>[] collections = { new HashSet<>(), new ArrayList<BigInteger>(), new HashMap<String, String>().values() }; for (Collection<?> c : collections) { System.out.println(classify(c)); } } }
92371c58c54551f48a4226ed470a609f1094cf2e
213
java
Java
src/main/java/com/zxsample/demo/domain/model/InventoryDetail.java
leizhnxp/sbt-ddd-inventory-demo
80987c8fdab72efa121c95c7b4a04d89eb84f6e9
[ "Apache-2.0" ]
1
2021-11-06T12:40:20.000Z
2021-11-06T12:40:20.000Z
src/main/java/com/zxsample/demo/domain/model/InventoryDetail.java
leizhnxp/sbt-ddd-inventory-demo
80987c8fdab72efa121c95c7b4a04d89eb84f6e9
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zxsample/demo/domain/model/InventoryDetail.java
leizhnxp/sbt-ddd-inventory-demo
80987c8fdab72efa121c95c7b4a04d89eb84f6e9
[ "Apache-2.0" ]
3
2021-11-26T12:39:54.000Z
2022-02-23T11:51:59.000Z
13.3125
39
0.760563
997,940
package com.zxsample.demo.domain.model; import lombok.*; /** * 库存详情 */ @Data @Builder @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode public class InventoryDetail { private String description; }
92371c6792c53e6ee44eb2f4e925bd9e02537678
97
java
Java
src/main/java/it/davidenastri/healthcheck/model/Protocol.java
ltpitt/java-spring-restful-webservice
adf339d43ec2e22f5c69add180d0b8cdc284e32b
[ "MIT" ]
null
null
null
src/main/java/it/davidenastri/healthcheck/model/Protocol.java
ltpitt/java-spring-restful-webservice
adf339d43ec2e22f5c69add180d0b8cdc284e32b
[ "MIT" ]
null
null
null
src/main/java/it/davidenastri/healthcheck/model/Protocol.java
ltpitt/java-spring-restful-webservice
adf339d43ec2e22f5c69add180d0b8cdc284e32b
[ "MIT" ]
null
null
null
13.857143
42
0.690722
997,941
package it.davidenastri.healthcheck.model; public enum Protocol { HTTP, HTTPS, TCP }
92371d24d77fa3154105f6a0fbd35a582364367b
857
java
Java
Velocity/src/main/java/me/fixeddev/commandflow/velocity/factory/VelocityModule.java
GatitoUwU/CommandFlow
2ed55f1e8ef19b5d7dc452e00bd3e4fdd4b7446c
[ "MIT" ]
96
2020-09-08T00:26:47.000Z
2021-12-08T01:40:28.000Z
Velocity/src/main/java/me/fixeddev/commandflow/velocity/factory/VelocityModule.java
GatitoUwU/CommandFlow
2ed55f1e8ef19b5d7dc452e00bd3e4fdd4b7446c
[ "MIT" ]
10
2020-10-08T02:56:10.000Z
2021-09-11T07:44:27.000Z
Velocity/src/main/java/me/fixeddev/commandflow/velocity/factory/VelocityModule.java
GatitoUwU/CommandFlow
2ed55f1e8ef19b5d7dc452e00bd3e4fdd4b7446c
[ "MIT" ]
12
2020-10-08T02:33:59.000Z
2021-11-22T01:37:03.000Z
34.28
88
0.779463
997,942
package me.fixeddev.commandflow.velocity.factory; import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; import me.fixeddev.commandflow.annotated.part.AbstractModule; import me.fixeddev.commandflow.annotated.part.Key; import me.fixeddev.commandflow.velocity.annotation.Sender; public class VelocityModule extends AbstractModule { private final ProxyServer proxyServer; public VelocityModule(ProxyServer proxyServer) { this.proxyServer = proxyServer; } @Override public void configure() { bindFactory(CommandSource.class, new CommandSourcePartFactory()); bindFactory(Player.class, new PlayerPartFactory(proxyServer)); bindFactory(new Key(Player.class, Sender.class), new PlayerSenderPartFactory()); } }
92371f84f9d2de14e836098b07d07ed50bd2ca2d
1,310
java
Java
jetstreamcore/src/main/java/com/ebay/jetstream/common/NameableThreadFactory.java
pulsarIO/jetstream
bc2e2be93ca280f74f83d9c0307a9357240a33f9
[ "MIT" ]
122
2015-02-22T02:15:31.000Z
2020-12-07T03:25:57.000Z
jetstreamcore/src/main/java/com/ebay/jetstream/common/NameableThreadFactory.java
pulsarIO/jetstream
bc2e2be93ca280f74f83d9c0307a9357240a33f9
[ "MIT" ]
8
2015-03-05T02:57:45.000Z
2015-08-21T07:53:51.000Z
jetstreamcore/src/main/java/com/ebay/jetstream/common/NameableThreadFactory.java
pulsarIO/jetstream
bc2e2be93ca280f74f83d9c0307a9357240a33f9
[ "MIT" ]
41
2015-02-23T20:05:04.000Z
2020-12-07T03:25:58.000Z
33.589744
101
0.629771
997,943
/******************************************************************************* * Copyright © 2012-2015 eBay Software Foundation * This program is dual licensed under the MIT and Apache 2.0 licenses. * Please see LICENSE for more information. *******************************************************************************/ package com.ebay.jetstream.common; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Thread factory that duplicates java.util.concurrent.Executors.DefaultThreadFactory and allows the * thread name to be set. */ public class NameableThreadFactory implements ThreadFactory { final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; public NameableThreadFactory(final String name) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = name + "-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) { t.setDaemon(false); } if (t.getPriority() != Thread.NORM_PRIORITY) { t.setPriority(Thread.NORM_PRIORITY); } return t; } }
923720586c7be5ff7fa3cdd380b4a73e063deb00
4,016
java
Java
core/src/main/java/org/apache/carbondata/core/datastore/page/SafeVarLengthColumnPage.java
Kejian-Li/carbondata
7c114261303787142bec7a704f7481ac223fe5c3
[ "Apache-2.0" ]
1,083
2017-05-08T14:53:46.000Z
2022-03-28T08:23:08.000Z
core/src/main/java/org/apache/carbondata/core/datastore/page/SafeVarLengthColumnPage.java
Kejian-Li/carbondata
7c114261303787142bec7a704f7481ac223fe5c3
[ "Apache-2.0" ]
3,397
2017-05-08T13:38:57.000Z
2022-03-31T16:32:47.000Z
core/src/main/java/org/apache/carbondata/core/datastore/page/SafeVarLengthColumnPage.java
Kejian-Li/carbondata
7c114261303787142bec7a704f7481ac223fe5c3
[ "Apache-2.0" ]
565
2017-05-09T01:41:38.000Z
2022-03-15T01:25:34.000Z
31.622047
93
0.737052
997,944
/* * 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.carbondata.core.datastore.page; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.carbondata.core.datastore.page.encoding.ColumnPageEncoderMeta; import org.apache.carbondata.core.metadata.datatype.DataType; import org.apache.carbondata.core.util.DataTypeUtil; public class SafeVarLengthColumnPage extends VarLengthColumnPageBase { // for string and decimal data private List<byte[]> byteArrayData; SafeVarLengthColumnPage(ColumnPageEncoderMeta columnPageEncoderMeta, int pageSize) { super(columnPageEncoderMeta, pageSize); byteArrayData = new ArrayList<>(); } @Override public void freeMemory() { byteArrayData = null; super.freeMemory(); } @Override public void putBytesAtRow(int rowId, byte[] bytes) { byteArrayData.add(bytes); } @Override public void putBytes(int rowId, byte[] bytes, int offset, int length) { byteArrayData.add(bytes); } @Override public void putDecimal(int rowId, BigDecimal decimal) { throw new UnsupportedOperationException( "invalid data type: " + columnPageEncoderMeta.getStoreDataType()); } @Override public BigDecimal getDecimal(int rowId) { throw new UnsupportedOperationException( "invalid data type: " + columnPageEncoderMeta.getStoreDataType()); } @Override public byte[] getBytes(int rowId) { return byteArrayData.get(rowId); } @Override public void setByteArrayPage(byte[][] byteArray) { byteArrayData.addAll(Arrays.asList(byteArray)); } @Override public byte[] getLVFlattenedBytePage() throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(stream); for (byte[] byteArrayDatum : byteArrayData) { out.writeInt(byteArrayDatum.length); out.write(byteArrayDatum); } return stream.toByteArray(); } @Override public byte[] getComplexChildrenLVFlattenedBytePage(DataType dataType) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(stream); for (byte[] byteArrayDatum : byteArrayData) { if (DataTypeUtil.isByteArrayComplexChildColumn(dataType)) { out.writeInt(byteArrayDatum.length); } else { out.writeShort((short) byteArrayDatum.length); } out.write(byteArrayDatum); } return stream.toByteArray(); } @Override public byte[] getComplexParentFlattenedBytePage() throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(stream); for (byte[] byteArrayDatum : byteArrayData) { out.write(byteArrayDatum); } return stream.toByteArray(); } @Override public byte[][] getByteArrayPage() { return byteArrayData.toArray(new byte[byteArrayData.size()][]); } @Override void copyBytes(int rowId, byte[] dest, int destOffset, int length) { System.arraycopy(byteArrayData.get(rowId), 0, dest, destOffset, length); } }
92372119ed817964fde023cc8d72b0725ef64e5b
1,258
java
Java
references/bcb_chosen_clones/selected#2646900#194#231.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
23
2018-10-03T15:02:53.000Z
2021-09-16T11:07:36.000Z
references/bcb_chosen_clones/selected#2646900#194#231.java
cragkhit/elasticsearch
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
18
2019-02-10T04:52:54.000Z
2022-01-25T02:14:40.000Z
references/bcb_chosen_clones/selected#2646900#194#231.java
cragkhit/Siamese
05567b30c5bde08badcac1bf421454e5d995eb91
[ "Apache-2.0" ]
19
2018-11-16T13:39:05.000Z
2021-09-05T23:59:30.000Z
32.25641
98
0.426868
997,945
public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
9237212e09e245b3b75a24edf26aee442ceb0f76
82
java
Java
android/cm/src/com/flarebyte/cm/trash/admin/ForumBox.java
flarebyte/wonderful-bazar
810514cd7d73505b11d738f8b84d91842d18d074
[ "MIT" ]
null
null
null
android/cm/src/com/flarebyte/cm/trash/admin/ForumBox.java
flarebyte/wonderful-bazar
810514cd7d73505b11d738f8b84d91842d18d074
[ "MIT" ]
null
null
null
android/cm/src/com/flarebyte/cm/trash/admin/ForumBox.java
flarebyte/wonderful-bazar
810514cd7d73505b11d738f8b84d91842d18d074
[ "MIT" ]
null
null
null
13.666667
39
0.780488
997,946
package com.flarebyte.cm.trash.admin; public interface ForumBox extends Box { }
923721cfaaa106399dde679acaacf45926ba9824
6,776
java
Java
sql/src/main/java/com/vmware/ddlog/translator/WindowVisitor.java
lalithsuresh/differential-datalog
2fce9e84d1049bcd9c61523af5554d0489394418
[ "MIT" ]
910
2019-06-22T05:01:02.000Z
2022-03-31T18:33:27.000Z
sql/src/main/java/com/vmware/ddlog/translator/WindowVisitor.java
lalithsuresh/differential-datalog
2fce9e84d1049bcd9c61523af5554d0489394418
[ "MIT" ]
570
2019-06-21T17:29:15.000Z
2022-03-22T17:56:00.000Z
sql/src/main/java/com/vmware/ddlog/translator/WindowVisitor.java
lalithsuresh/differential-datalog
2fce9e84d1049bcd9c61523af5554d0489394418
[ "MIT" ]
95
2019-06-27T20:53:24.000Z
2022-03-22T11:33:35.000Z
39.395349
100
0.644481
997,947
/* * Copyright (c) 2021 VMware, Inc. * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.vmware.ddlog.translator; import com.facebook.presto.sql.tree.*; import com.vmware.ddlog.util.Linq; import com.vmware.ddlog.util.Ternary; import com.vmware.ddlog.util.Utilities; import java.util.*; /** * This visitor computes the AggregateDecomposition of an expression that * may contain aggregation functions over windows. * See for example https://www.postgresql.org/docs/9.1/tutorial-window.html * for a documentation of SQL Window functions. * It returns 'true' if the expression does contain window function aggregations. */ public class WindowVisitor extends AggregationVisitorBase { /* Consider this query: SELECT c1, 3 + count(c3 + 1) OVER (PARTITION BY c2) FROM T This can be executed as multiple queries: - Prepare the input for the windowed computation. (This query could even involve WHERE/GROUP BY/AGGREGATE/HAVING if the original query contained them). CREATE VIEW OverInput AS SELECT c3 + 1 as tmp, c2 AS gb FROM T - Compute the aggregation (one for each window): CREATE VIEW Over AS SELECT count(tmp) as tmp2, gb FROM OverInput GROUP BY gb - join the original table with the aggregations and apply the computations to combine the results: SELECT T.c1, 3 + Over.tmp2 FROM T JOIN Over ON T.c2 = Over.c2 */ /** * Information required to compute a Window query */ static class WindowAggregation { /** * Expressions defining the window, e.g., tmp in the * previous example. */ public final List<SingleColumn> groupOn; /** * Values computed by each window. * E.g., count(tmp) in the previous example. * These will depend on temporary variables that * show up in the inputSelectItems below. */ public final List<SingleColumn> windowResult; public GroupBy getGroupBy() { //noinspection OptionalGetWithoutIsPresent return new GroupBy(false, Collections.singletonList( new SimpleGroupBy(Linq.map(this.groupOn, s -> s.getAlias().get())))); } WindowAggregation() { this.groupOn = new ArrayList<SingleColumn>(); this.windowResult = new ArrayList<SingleColumn>(); } @Override public String toString() { return "GroupOn: " + this.groupOn.toString() + "\n" + "Aggregated: " + this.windowResult.toString() + "\n"; } } /** * Expressions computed by the first select. Each has an alias * writing to a temporary variable, e.g., "tmp" in the previous example. */ final List<SingleColumn> firstSelect; /** * Aggregation windows found in the current expression visited. * An expression can involve multiple windows: e.g. * * SELECT COUNT(col2) OVER (PARTITION BY col1) + COUNT(col1) OVER (PARTITION BY col2). * This would produce two WindowAggregation structures. */ final List<WindowAggregation> windows; /** * In the final select these expressions should be substituted. */ final SubstitutionRewriter.SubstitutionMap substitutions; public WindowVisitor() { this.windows = new ArrayList<WindowAggregation>(); this.firstSelect = new ArrayList<SingleColumn>(); this.substitutions = new SubstitutionRewriter.SubstitutionMap(); } @Override protected Ternary visitFunctionCall(FunctionCall fc, TranslationContext context) { if (!fc.getWindow().isPresent()) return Ternary.No; WindowAggregation wag = new WindowAggregation(); this.windows.add(wag); Window win = fc.getWindow().get(); if (win.getOrderBy().isPresent()) throw new TranslationException("group-by not supported", fc); if (win.getFrame().isPresent()) throw new TranslationException("frames not yet supported", fc); List<Expression> partitions = win.getPartitionBy(); for (Expression e: partitions) { String gb = context.freshLocalName("gb"); wag.groupOn.add(new SingleColumn(e, new Identifier(gb))); } String name = Utilities.convertQualifiedName(fc.getName()); Ternary result = Ternary.Maybe; boolean isAggregate = SqlSemantics.semantics.isAggregateFunction(name); if (isAggregate) { List<Expression> newArguments = new ArrayList<Expression>(); for (Expression e: fc.getArguments()) { // temporary name for input arguments to aggregation function; // e.g., tmp in our example String var = context.freshLocalName("tmp"); Identifier arg = new Identifier(var); SingleColumn si = new SingleColumn(e, arg); this.firstSelect.add(si); newArguments.add(arg); } // temporary name for the result of the window function; // e.g., tmp2 in our example. String var = context.freshLocalName(fc.getName().toString()); Identifier agg = new Identifier(var); FunctionCall noWindow = new FunctionCall(fc.getName(), Optional.empty(), fc.getFilter(), fc.getOrderBy(), fc.isDistinct(), newArguments); wag.windowResult.add(new SingleColumn(noWindow, agg)); this.substitutions.add(fc, agg); return Ternary.Yes; } return result; } }
92372252345aaf213218a5efbf8866488cf5901b
2,346
java
Java
trace-sdk/src/test/java/io/bitrise/trace/data/management/CrashSaverTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
1
2021-09-01T09:55:04.000Z
2021-09-01T09:55:04.000Z
trace-sdk/src/test/java/io/bitrise/trace/data/management/CrashSaverTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
35
2021-04-06T11:30:46.000Z
2021-08-25T13:47:32.000Z
trace-sdk/src/test/java/io/bitrise/trace/data/management/CrashSaverTest.java
bitrise-io/trace-android-sdk
cbcd711adf4d918188581d89ac692364b20e0042
[ "MIT" ]
null
null
null
27.6
80
0.738704
997,948
package io.bitrise.trace.data.management; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.internal.verification.VerificationModeFactory.times; import io.bitrise.trace.data.CrashTestDataProvider; import io.bitrise.trace.data.storage.TraceDataStorage; import io.bitrise.trace.session.ApplicationSessionManager; import io.bitrise.trace.session.Session; import io.bitrise.trace.test.DataTestUtils; import io.bitrise.trace.test.TraceTestProvider; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; /** * Unit tests for {@link CrashSaver}. */ public class CrashSaverTest { final TraceDataStorage mockDataStorage = Mockito.mock(TraceDataStorage.class); @BeforeClass public static void setUpBeforeClass() { ApplicationSessionManager.getInstance().startSession(); } @AfterClass public static void tearDownClass() { ApplicationSessionManager.getInstance().stopSession(); } @Test public void saveCrash_validData() { CrashSaver.saveCrash( DataTestUtils.getSampleResource("session-id"), new Session("session-id"), TraceTestProvider.getEmptyTrace(), CrashTestDataProvider.createCrashReport(), mockDataStorage); verify(mockDataStorage, times(1)).saveCrashRequest(any()); } @Test public void saveCrash_nullSession() { CrashSaver.saveCrash( DataTestUtils.getSampleResource("session-id"), null, TraceTestProvider.getEmptyTrace(), CrashTestDataProvider.createCrashReport(), mockDataStorage); verifyNoInteractions(mockDataStorage); } @Test public void saveCrash_nullResource() { CrashSaver.saveCrash( null, new Session("session-id"), TraceTestProvider.getEmptyTrace(), CrashTestDataProvider.createCrashReport(), mockDataStorage); verifyNoInteractions(mockDataStorage); } @Test public void saveCrash_nullActiveResource() { CrashSaver.saveCrash( DataTestUtils.getSampleResource("session-id"), new Session("session-id"), null, CrashTestDataProvider.createCrashReport(), mockDataStorage); verifyNoInteractions(mockDataStorage); } }
9237232b6c937f8a3aeb9cd77ded8343a0945913
206
java
Java
src/main/java/com/mgcp/exceptions/MGCPParseException.java
byypipo/Mgcp-Client
eccfc6a5101322d35990ac65b94b64d67cba6df7
[ "MIT" ]
null
null
null
src/main/java/com/mgcp/exceptions/MGCPParseException.java
byypipo/Mgcp-Client
eccfc6a5101322d35990ac65b94b64d67cba6df7
[ "MIT" ]
null
null
null
src/main/java/com/mgcp/exceptions/MGCPParseException.java
byypipo/Mgcp-Client
eccfc6a5101322d35990ac65b94b64d67cba6df7
[ "MIT" ]
null
null
null
18.727273
51
0.786408
997,949
package com.mgcp.exceptions; public class MGCPParseException extends Exception { private static final long serialVersionUID = 1L; public MGCPParseException(String exception) { super(exception); } }
923723e45b147665dd9775a84aba05993d10fc7d
2,710
java
Java
src/main/java/org/softpres/donkeysql/params/IndexedParamQuery.java
vyadh/donkeysql
e93b4ea3d2f44883bd51ce71c928827c13d2e7ea
[ "Apache-2.0" ]
1
2015-07-10T14:51:38.000Z
2015-07-10T14:51:38.000Z
src/main/java/org/softpres/donkeysql/params/IndexedParamQuery.java
vyadh/donkeysql
e93b4ea3d2f44883bd51ce71c928827c13d2e7ea
[ "Apache-2.0" ]
null
null
null
src/main/java/org/softpres/donkeysql/params/IndexedParamQuery.java
vyadh/donkeysql
e93b4ea3d2f44883bd51ce71c928827c13d2e7ea
[ "Apache-2.0" ]
null
null
null
27.373737
92
0.696679
997,950
/* * Copyright (c) 2017, Kieron Wilkinson */ package org.softpres.donkeysql.params; import org.softpres.donkeysql.tokeniser.StatementTokeniser; import org.softpres.donkeysql.tokeniser.Tokens; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import static java.util.stream.Collectors.joining; /** * Associates an indexed parameterised SQL statement with the values to populate it. */ class IndexedParamQuery implements ParamQuery { private final String sql; private final Object[] params; IndexedParamQuery(String sql, Object[] params) { this.sql = sql; this.params = params; } @Override public PreparedStatement createStatement(Connection connection) throws SQLException { PreparedStatement statement = connection.prepareStatement(sql); applyParameters(statement); return statement; } private void applyParameters(PreparedStatement statement) throws SQLException { check(); for (int i = 0; i < params.length; i++) { statement.setObject(i + 1, params[i]); } } private void check() { if (count(sql) != params.length) { throw new MismatchedParametersException(sql, params); } } /** * Count the number of indexed parameters in a normalised statement, not including any * '?' characters existing within quoted values. */ static long count(String statement) { return StatementTokeniser.tokenise(statement).stream() .filter(token -> token instanceof Tokens.IndexedParam) .count(); } @Override public String toString() { return humanise(sql, params); } /** * Replace all the parameters in an SQL statement with the supplied parameter values. * The result should be an SQL statement as a human would want to read it. * * @param statement an SQL statement, which should have been normalised (no named params). */ static String humanise(String statement, Object... params) { if (count(statement) != params.length) { throw new MismatchedParametersException(statement, params); } ParamIterator paramIterator = new ParamIterator(params); return StatementTokeniser.tokenise(statement).stream() .map(token -> token instanceof Tokens.IndexedParam ? Humanise.paramValue(paramIterator.next()) : token.text) .collect(joining()); } /** Allows iteration of parameters. Assumes count has already been validated. */ private static class ParamIterator { private int index; private final Object[] params; ParamIterator(Object[] params) { index = 0; this.params = params; } Object next() { return params[index++]; } } }
923724ed64f5dec0c8052e0b8d4bc56aa2d794a3
2,475
java
Java
app/src/main/java/apps/jizzu/simpletodo/alarm/AlarmHelper.java
johan--/SimpleToDo
f6ca50156199a8de62ea20308efab03424107f4e
[ "MIT" ]
1
2021-06-17T05:16:52.000Z
2021-06-17T05:16:52.000Z
app/src/main/java/apps/jizzu/simpletodo/alarm/AlarmHelper.java
johan--/SimpleToDo
f6ca50156199a8de62ea20308efab03424107f4e
[ "MIT" ]
null
null
null
app/src/main/java/apps/jizzu/simpletodo/alarm/AlarmHelper.java
johan--/SimpleToDo
f6ca50156199a8de62ea20308efab03424107f4e
[ "MIT" ]
null
null
null
30.555556
169
0.693333
997,951
package apps.jizzu.simpletodo.alarm; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import apps.jizzu.simpletodo.model.ModelTask; import static android.content.Context.NOTIFICATION_SERVICE; /** * Class for initializing alarm service (uses the Singleton pattern). */ public class AlarmHelper { private static AlarmHelper mInstance; private Context mContext; private AlarmManager mAlarmManager; /** * Constructor is private to prevent direct instantiation. */ private AlarmHelper() { } /** * This static method ensures that only one AlarmHelper will ever exist at any given time. */ public static AlarmHelper getInstance() { if (mInstance == null) { mInstance = new AlarmHelper(); } return mInstance; } /** * Alarm service initialization. */ public void init(Context context) { this.mContext = context; mAlarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE); } /** * Passes the required data to the AlarmReceiver to create a notification. */ public void setAlarm(ModelTask task) { Intent intent = new Intent(mContext, AlarmReceiver.class); intent.putExtra("title", task.getTitle()); intent.putExtra("time_stamp", task.getTimeStamp()); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext.getApplicationContext(), (int) task.getTimeStamp(), intent, PendingIntent.FLAG_UPDATE_CURRENT); mAlarmManager.set(AlarmManager.RTC_WAKEUP, task.getDate(), pendingIntent); } /** * Removes a notification by id (timeStamp). */ public void removeNotification(long taskTimeStamp, Context context) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE); notificationManager.cancel((int) taskTimeStamp); } /** * Removes a alarm by id (timeStamp). */ public void removeAlarm(long taskTimeStamp) { Intent intent = new Intent(mContext, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, (int) taskTimeStamp, intent, PendingIntent.FLAG_UPDATE_CURRENT); mAlarmManager.cancel(pendingIntent); } }
9237254d3a110fbd28d34dda6af999191e336c14
595
java
Java
dubbo-vip/demo/async-demo/src/main/java/com/luban/async_demo/provider/impl/HelloServiceImpl.java
Xuyiwlx/incubator-dubbo-vip1
97c28fa5fc508123953d0ec7bfe1847e88241d7b
[ "Apache-2.0" ]
15
2019-11-24T12:15:49.000Z
2022-03-18T02:56:18.000Z
dubbo-vip/demo/async-demo/src/main/java/com/luban/async_demo/provider/impl/HelloServiceImpl.java
Xuyiwlx/incubator-dubbo-vip1
97c28fa5fc508123953d0ec7bfe1847e88241d7b
[ "Apache-2.0" ]
4
2020-01-31T18:24:42.000Z
2021-12-14T21:37:57.000Z
dubbo-vip/demo/async-demo/src/main/java/com/luban/async_demo/provider/impl/HelloServiceImpl.java
AnyYANG/dubbo-x
949f897f9261cf467bb18b6ebf57cf458f00981c
[ "Apache-2.0" ]
52
2019-11-01T07:03:01.000Z
2021-12-06T02:14:07.000Z
21.25
55
0.591597
997,952
package com.luban.async_demo.provider.impl; import com.luban.async_demo.api.HelloService; import java.util.concurrent.TimeUnit; /** * *************书山有路勤为径*************** * 鲁班学院 * 往期资料加木兰老师 QQ: 2746251334 * VIP课程加安其拉老师 QQ: 3164703201 * 讲师:周瑜老师 * *************学海无涯苦作舟*************** */ public class HelloServiceImpl implements HelloService { @Override public String sayHello(String username) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return "hello" + username; } }
923725b8242232667f83550dd508319354325133
2,594
java
Java
nettest-shared-server-storage-couchdb/src/main/java/at/alladin/nettest/shared/server/storage/couchdb/domain/model/MeasurementServerInfo.java
tuw-sqm-ss2020-02/nntool
f53042509346d67da437d940fb193ea039809c4a
[ "Apache-2.0" ]
null
null
null
nettest-shared-server-storage-couchdb/src/main/java/at/alladin/nettest/shared/server/storage/couchdb/domain/model/MeasurementServerInfo.java
tuw-sqm-ss2020-02/nntool
f53042509346d67da437d940fb193ea039809c4a
[ "Apache-2.0" ]
8
2020-04-13T12:17:35.000Z
2020-06-20T19:21:30.000Z
nettest-shared-server-storage-couchdb/src/main/java/at/alladin/nettest/shared/server/storage/couchdb/domain/model/MeasurementServerInfo.java
tuw-sqm-ss2020-02/nntool
f53042509346d67da437d940fb193ea039809c4a
[ "Apache-2.0" ]
1
2020-05-02T14:27:06.000Z
2020-05-02T14:27:06.000Z
30.833333
91
0.669884
997,953
/******************************************************************************* * Copyright 2019 alladin-IT GmbH * * 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 at.alladin.nettest.shared.server.storage.couchdb.domain.model; import com.fasterxml.jackson.annotation.JsonClassDescription; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Contains additional detail information about a measurement server. * * @author alladin-IT GmbH (dycjh@example.com) */ @JsonClassDescription("Contains additional detail information about a measurement server.") public class MeasurementServerInfo { /** * The city the measurement server is located in. */ @JsonPropertyDescription("The city the measurement server is located in.") @Expose @SerializedName("city") @JsonProperty("city") private String city; /** * The country the measurement server is located in. */ @JsonPropertyDescription("The country the measurement server is located in.") @Expose @SerializedName("country") @JsonProperty("country") private String country; /** * The geographic location of the measurement server. */ @JsonPropertyDescription("The geographic location of the measurement server.") @Expose @SerializedName("geo_location") @JsonProperty("geo_location") private GeoLocation geoLocation; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public GeoLocation getGeoLocation() { return geoLocation; } public void setGeoLocation(GeoLocation geoLocation) { this.geoLocation = geoLocation; } }
92372641f6c0a04e6f576a41641dae316e763d5b
5,536
java
Java
B4AObjects/src/anywheresoftware/b4a/keywords/constants/KeyCodes.java
gitoscc/B4A
5c7a41a55f3acf303985c5906e506dfc0fd1a568
[ "Apache-2.0" ]
63
2020-03-09T16:20:26.000Z
2022-03-19T02:15:53.000Z
B4AObjects/src/anywheresoftware/b4a/keywords/constants/KeyCodes.java
cyberwizard-dev/B4A
00f8a23a6fe9eb0743bab30a8770acadcc286c43
[ "Apache-2.0" ]
null
null
null
B4AObjects/src/anywheresoftware/b4a/keywords/constants/KeyCodes.java
cyberwizard-dev/B4A
00f8a23a6fe9eb0743bab30a8770acadcc286c43
[ "Apache-2.0" ]
25
2020-03-10T07:12:06.000Z
2022-01-14T21:34:58.000Z
55.36
121
0.609104
997,954
package anywheresoftware.b4a.keywords.constants; /** * A predefined object with the key codes constants. These constants are passed to Activity KeyPressed event for example. */ public class KeyCodes { public static final int KEYCODE_UNKNOWN = 0; public static final int KEYCODE_SOFT_LEFT = 1; public static final int KEYCODE_SOFT_RIGHT = 2; public static final int KEYCODE_HOME = 3; public static final int KEYCODE_BACK = 4; public static final int KEYCODE_CALL = 5; public static final int KEYCODE_ENDCALL = 6; public static final int KEYCODE_0 = 7; public static final int KEYCODE_1 = 8; public static final int KEYCODE_2 = 9; public static final int KEYCODE_3 = 10; public static final int KEYCODE_4 = 11; public static final int KEYCODE_5 = 12; public static final int KEYCODE_6 = 13; public static final int KEYCODE_7 = 14; public static final int KEYCODE_8 = 15; public static final int KEYCODE_9 = 16; public static final int KEYCODE_STAR = 17; public static final int KEYCODE_POUND = 18; public static final int KEYCODE_DPAD_UP = 19; public static final int KEYCODE_DPAD_DOWN = 20; public static final int KEYCODE_DPAD_LEFT = 21; public static final int KEYCODE_DPAD_RIGHT = 22; public static final int KEYCODE_DPAD_CENTER = 23; public static final int KEYCODE_VOLUME_UP = 24; public static final int KEYCODE_VOLUME_DOWN = 25; public static final int KEYCODE_POWER = 26; public static final int KEYCODE_CAMERA = 27; public static final int KEYCODE_CLEAR = 28; public static final int KEYCODE_A = 29; public static final int KEYCODE_B = 30; public static final int KEYCODE_C = 31; public static final int KEYCODE_D = 32; public static final int KEYCODE_E = 33; public static final int KEYCODE_F = 34; public static final int KEYCODE_G = 35; public static final int KEYCODE_H = 36; public static final int KEYCODE_I = 37; public static final int KEYCODE_J = 38; public static final int KEYCODE_K = 39; public static final int KEYCODE_L = 40; public static final int KEYCODE_M = 41; public static final int KEYCODE_N = 42; public static final int KEYCODE_O = 43; public static final int KEYCODE_P = 44; public static final int KEYCODE_Q = 45; public static final int KEYCODE_R = 46; public static final int KEYCODE_S = 47; public static final int KEYCODE_T = 48; public static final int KEYCODE_U = 49; public static final int KEYCODE_V = 50; public static final int KEYCODE_W = 51; public static final int KEYCODE_X = 52; public static final int KEYCODE_Y = 53; public static final int KEYCODE_Z = 54; public static final int KEYCODE_COMMA = 55; public static final int KEYCODE_PERIOD = 56; public static final int KEYCODE_ALT_LEFT = 57; public static final int KEYCODE_ALT_RIGHT = 58; public static final int KEYCODE_SHIFT_LEFT = 59; public static final int KEYCODE_SHIFT_RIGHT = 60; public static final int KEYCODE_TAB = 61; public static final int KEYCODE_SPACE = 62; public static final int KEYCODE_SYM = 63; public static final int KEYCODE_EXPLORER = 64; public static final int KEYCODE_ENVELOPE = 65; public static final int KEYCODE_ENTER = 66; public static final int KEYCODE_DEL = 67; public static final int KEYCODE_GRAVE = 68; public static final int KEYCODE_MINUS = 69; public static final int KEYCODE_EQUALS = 70; public static final int KEYCODE_LEFT_BRACKET = 71; public static final int KEYCODE_RIGHT_BRACKET = 72; public static final int KEYCODE_BACKSLASH = 73; public static final int KEYCODE_SEMICOLON = 74; public static final int KEYCODE_APOSTROPHE = 75; public static final int KEYCODE_SLASH = 76; public static final int KEYCODE_AT = 77; public static final int KEYCODE_NUM = 78; public static final int KEYCODE_HEADSETHOOK = 79; public static final int KEYCODE_FOCUS = 80; public static final int KEYCODE_PLUS = 81; public static final int KEYCODE_MENU = 82; public static final int KEYCODE_NOTIFICATION = 83; public static final int KEYCODE_SEARCH = 84; public static final int KEYCODE_MEDIA_PLAY_PAUSE= 85; public static final int KEYCODE_MEDIA_STOP = 86; public static final int KEYCODE_MEDIA_NEXT = 87; public static final int KEYCODE_MEDIA_PREVIOUS = 88; public static final int KEYCODE_MEDIA_REWIND = 89; public static final int KEYCODE_MEDIA_FAST_FORWARD = 90; public static final int KEYCODE_MUTE = 91; }
9237269243caf9d1d76667becc1327ea3f44e338
1,994
java
Java
src/com/example/tenancy/ConnectionProviderImpl.java
mukilarasan101/MultiTenancyTest
92a152f560d0d225659763676491ac4d327c43a6
[ "Apache-2.0" ]
null
null
null
src/com/example/tenancy/ConnectionProviderImpl.java
mukilarasan101/MultiTenancyTest
92a152f560d0d225659763676491ac4d327c43a6
[ "Apache-2.0" ]
null
null
null
src/com/example/tenancy/ConnectionProviderImpl.java
mukilarasan101/MultiTenancyTest
92a152f560d0d225659763676491ac4d327c43a6
[ "Apache-2.0" ]
null
null
null
29.761194
121
0.743731
997,955
//$Id$ package com.example.tenancy; import java.sql.Connection; import java.sql.SQLException; import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.hibernate.HibernateException; import org.hibernate.c3p0.internal.C3P0ConnectionProvider; public class ConnectionProviderImpl extends C3P0ConnectionProvider { private static final long serialVersionUID = -1768592744904010791L; private final BasicDataSource basicDataSource = new BasicDataSource(); private String schema; private String host; private String database; public ConnectionProviderImpl(String host,String database,String schema){ basicDataSource.setDriverClassName("org.postgresql.Driver"); basicDataSource.setUrl("jdbc:postgresql://"+host+":5432/"+database+"?currentSchema="+schema+"&searchpath="+schema); basicDataSource.setUsername("postgres"); basicDataSource.setPassword("postgres"); basicDataSource.setInitialSize(2); basicDataSource.setMaxActive(100); this.host = host; this.database = database; this.schema = schema; } public ConnectionProviderImpl() { } @Override public void closeConnection(Connection con) throws SQLException { con.close(); } @Override public Connection getConnection() throws SQLException { final Connection connection = basicDataSource.getConnection(); try { connection.setCatalog(schema); //connection.setSchema(schema); connection.createStatement().execute("SET SCHEMA '" + this.schema + "'"); } catch (SQLException e) { throw new HibernateException("Could not alter JDBC connection to specified schema [" + this.schema + "]", e); } return connection; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ConnectionProviderImpl [schema="); builder.append(schema); builder.append(", host="); builder.append(host); builder.append(", database="); builder.append(database); builder.append("]"); return builder.toString(); } }
923726b76963f8607b2ce3860e7d617071ca9364
3,970
java
Java
config-model/src/main/java/com/yahoo/searchdefinition/processing/ValidateFieldTypes.java
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
config-model/src/main/java/com/yahoo/searchdefinition/processing/ValidateFieldTypes.java
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
config-model/src/main/java/com/yahoo/searchdefinition/processing/ValidateFieldTypes.java
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
47.261905
143
0.674811
997,956
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.searchdefinition.processing; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.document.DataType; import com.yahoo.document.TensorDataType; import com.yahoo.searchdefinition.RankProfileRegistry; import com.yahoo.searchdefinition.Search; import com.yahoo.searchdefinition.document.Attribute; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.model.container.search.QueryProfiles; import java.util.HashMap; import java.util.Map; /** * This Processor makes sure all fields with the same name have the same {@link DataType}. This check * explicitly disregards whether a field is an index field, an attribute or a summary field. This is a requirement if we * hope to move to a model where index fields, attributes and summary fields share a common field class. * * @author Simon Thoresen Hult */ public class ValidateFieldTypes extends Processor { public ValidateFieldTypes(Search search, DeployLogger deployLogger, RankProfileRegistry rankProfileRegistry, QueryProfiles queryProfiles) { super(search, deployLogger, rankProfileRegistry, queryProfiles); } @Override public void process(boolean validate, boolean documentsOnly) { if (!validate) return; String searchName = search.getName(); Map<String, DataType> seenFields = new HashMap<>(); verifySearchAndDocFields(searchName, seenFields); verifySummaryFields(searchName, seenFields); } final protected void verifySearchAndDocFields(String searchName, Map<String, DataType> seenFields) { search.allFields().forEach(field -> { checkFieldType(searchName, "index field", field.getName(), field.getDataType(), seenFields); for (Map.Entry<String, Attribute> entry : field.getAttributes().entrySet()) { checkFieldType(searchName, "attribute", entry.getKey(), entry.getValue().getDataType(), seenFields); } }); } final protected void verifySummaryFields(String searchName, Map<String, DataType> seenFields) { for (DocumentSummary summary : search.getSummaries().values()) { for (SummaryField field : summary.getSummaryFields()) { checkFieldType(searchName, "summary field", field.getName(), field.getDataType(), seenFields); } } } private void checkFieldType(String searchName, String fieldDesc, String fieldName, DataType fieldType, Map<String, DataType> seenFields) { DataType seenType = seenFields.get(fieldName); if (seenType == null) { seenFields.put(fieldName, fieldType); } else if ( ! compatibleTypes(seenType, fieldType)) { throw newProcessException(searchName, fieldName, "Incompatible types. Expected " + seenType.getName() + " for " + fieldDesc + " '" + fieldName + "', got " + fieldType.getName() + "."); } } private static boolean compatibleTypes(DataType seenType, DataType fieldType) { // legacy tag field type compatibility; probably not needed any more (Oct 2016) if ("tag".equals(seenType.getName())) { return "tag".equals(fieldType.getName()) || "WeightedSet<string>".equals(fieldType.getName()); } if ("tag".equals(fieldType.getName())) { return "tag".equals(seenType.getName()) || "WeightedSet<string>".equals(seenType.getName()); } if (seenType instanceof TensorDataType && fieldType instanceof TensorDataType) { return fieldType.isAssignableFrom(seenType); // TODO: Just do this for all types } return seenType.equals(fieldType); } }