blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
a16bb092e3b8a329c46a4339b71076ce658536d2
bf191013d04cf9597bc93241e56db63ef20018af
/lwmybatis/src/main/java/com/linkwe/sqlsession/Excutor.java
ecf1f60bbf1795b1d177873ae2c030b3fea49671
[]
no_license
linkwe-z/myproject
a2d725f41a58a7c059c5f37bbe573a566e8ca17b
271dba4e528da58e6e1e67fcc468ab0bd97dea89
refs/heads/master
2020-04-22T14:04:38.727986
2019-02-14T07:21:49
2019-02-14T07:21:49
170,431,022
0
0
null
null
null
null
UTF-8
Java
false
false
162
java
package com.linkwe.sqlsession; /** * @Author: zenglw * @Date: 2019-01-31 */ public interface Excutor { <T> T query(String statement, Object parameter); }
cdacf7eed583110633554bb583eb4d170913c715
7bbadc3a4cfa16193ec33f457f18eb3d547222dc
/redis-distributed-lock-starter/src/main/java/com/ciwei/lock/redisson/config/EnableRedissonLock.java
2b4c47ec571b8175e2cf22da252e5d7ca2502368
[]
no_license
FuhangOliver/springboot-starter-collection
1688de96345db0f85144880b0f68d2344ce9956f
3236d0c91b0d741764a76157536ea68f494d55d8
refs/heads/master
2022-12-16T23:43:05.113419
2020-09-14T08:26:04
2020-09-14T08:26:04
295,346,009
1
1
null
null
null
null
UTF-8
Java
false
false
376
java
package com.ciwei.lock.redisson.config; import org.springframework.context.annotation.Import; import java.lang.annotation.*; /** * @author FuHang * @date 2019/7/10 * @desc 开启Redisson注解支持 */ @Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(RedissonAutoConfiguration.class) public @interface EnableRedissonLock { }
28e077d803bfcd0141fae48940faa9c12cf5e42a
91b766a4e710d74ca9e54cd74f1b25c2217c5a13
/Rotate_Array.java
3bd774b32aa103248051dd703910d56bd7bd58ca
[]
no_license
Ronny-22-Code/Java-Programming-Codes
02a6e7a020e1f371dab1ab96608fea288c40647d
6407cc898c1b73fec4f9d9c716909b558afa3556
refs/heads/master
2020-07-09T22:35:53.891637
2020-02-10T18:10:26
2020-02-10T18:10:26
204,098,945
1
0
null
null
null
null
UTF-8
Java
false
false
893
java
package Classes_7sep_8sep_2019; import java.util.*; public class Rotate_Array { static Scanner sc = new Scanner(System.in); public static void Rotate(int[] a, int n, int k) { int i, j, temp; for (j = 0; j < k; j++) { temp = a[n - 1]; for (i = n - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = temp; } System.out.println("The rotated array is:"); for (i = 0; i < n; i++) { System.out.println(a[i]); } } public static void main(String[] args) { int n, i, k; System.out.println("Enter the size of the array:"); n = sc.nextInt(); int[] a = new int[n]; System.out.println("Enter the array elements:"); for (i = 0; i < n; i++) { a[i] = sc.nextInt(); } System.out.println("Enter the rotation of the array:"); k = sc.nextInt(); Rotate(a, n, k); } }
8bb6d5037a2682c305d5609116077c45d88cdb20
0907c886f81331111e4e116ff0c274f47be71805
/sources/com/google/android/gms/internal/location/zzbb.java
e2e692b938c1e6bf687acc168c456dda4697349b
[ "MIT" ]
permissive
Minionguyjpro/Ghostly-Skills
18756dcdf351032c9af31ec08fdbd02db8f3f991
d1a1fb2498aec461da09deb3ef8d98083542baaf
refs/heads/Android-OS
2022-07-27T19:58:16.442419
2022-04-15T07:49:53
2022-04-15T07:49:53
415,272,874
2
0
MIT
2021-12-21T10:23:50
2021-10-09T10:12:36
Java
UTF-8
Java
false
false
1,104
java
package com.google.android.gms.internal.location; import android.app.PendingIntent; import android.util.Log; import com.google.android.gms.common.api.Status; import com.google.android.gms.common.api.internal.BaseImplementation; import com.google.android.gms.location.LocationStatusCodes; final class zzbb extends zzan { private BaseImplementation.ResultHolder<Status> zzdf; public zzbb(BaseImplementation.ResultHolder<Status> resultHolder) { this.zzdf = resultHolder; } private final void zze(int i) { if (this.zzdf == null) { Log.wtf("LocationClientImpl", "onRemoveGeofencesResult called multiple times"); return; } this.zzdf.setResult(LocationStatusCodes.zzd(LocationStatusCodes.zzc(i))); this.zzdf = null; } public final void zza(int i, PendingIntent pendingIntent) { zze(i); } public final void zza(int i, String[] strArr) { Log.wtf("LocationClientImpl", "Unexpected call to onAddGeofencesResult"); } public final void zzb(int i, String[] strArr) { zze(i); } }
a13b30ed2eca49d8c4b439e3ce322cce7011a21d
8586e98fb86c40dd53d5dc6715e8abb2b8258150
/src/visitor/exercise1/Element.java
d56446166b7ab971016cf333663888a4c647eb7e
[]
no_license
Kanject-Lang/DesignPatterns
95b3aa04e79cb8797cb438c7aba781148ce17d85
30295422406f5073c4c162e03018802dabbe43f5
refs/heads/master
2023-07-01T13:08:21.422208
2021-08-07T02:49:14
2021-08-07T02:49:14
332,122,820
0
0
null
null
null
null
UTF-8
Java
false
false
107
java
package visitor.exercise1; public interface Element { public abstract void accept(Visitor visitor); }
[ "Um123456" ]
Um123456
5ce983178b9d1891d4575c5d9d60558f8ff5fbb0
7e7c18edbdc789155b248ff5e7be6ba3c2b7a50c
/app/src/main/java/com/example/user/weadda/ProfileActivity.java
2818330db2372fb885133b7ab2ba4b20bb8e40d0
[]
no_license
nazmul-7/ChatApp-WeAdda
0eeff8e881dadacb49ec58c98829cd10752e1815
9dbca3cbb93998df41c4a54fcf2fa5a8a21175c9
refs/heads/master
2020-04-19T00:09:33.626207
2019-01-27T17:55:25
2019-01-27T17:55:25
167,839,677
0
0
null
null
null
null
UTF-8
Java
false
false
16,802
java
package com.example.user.weadda; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.HashMap; import de.hdodenhof.circleimageview.CircleImageView; public class ProfileActivity extends AppCompatActivity { private String receiveUserID,senderUserID,Current_State; private CircleImageView userProfileImage; private TextView userProfileName,userProfileStatus; private Button SendMessagrRequestButton,DeclineMessageRequestButton; private FirebaseAuth mAuth; private DatabaseReference UserRef,ChatRequestRef,ContactsRef,NotificationRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); mAuth = FirebaseAuth.getInstance(); UserRef = FirebaseDatabase.getInstance().getReference().child("Users"); ChatRequestRef = FirebaseDatabase.getInstance().getReference().child("Chat Requests"); ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts"); NotificationRef = FirebaseDatabase.getInstance().getReference().child("Notifications"); receiveUserID = getIntent().getExtras().get("visit_user_id").toString(); senderUserID = mAuth.getCurrentUser().getUid(); userProfileImage = (CircleImageView) findViewById(R.id.visit_profile_image); userProfileName = (TextView) findViewById(R.id.visit_user_name); userProfileStatus= (TextView) findViewById(R.id.visit_profile_status); SendMessagrRequestButton = (Button) findViewById(R.id.send_message_request_button); DeclineMessageRequestButton = (Button) findViewById(R.id.decline_message_request_button); Current_State = "new" ; RetrieveUserInfo(); } private void RetrieveUserInfo() { UserRef.child(receiveUserID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if ((dataSnapshot.exists()) && dataSnapshot.hasChild("image")) { String userImage = dataSnapshot.child("image").getValue().toString(); String userName = dataSnapshot.child("name").getValue().toString(); String userStatus = dataSnapshot.child("status").getValue().toString(); Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(userProfileImage); userProfileName.setText(userName); userProfileStatus.setText(userStatus); ManageChatRequests(); } else { String userName = dataSnapshot.child("name").getValue().toString(); String userStatus = dataSnapshot.child("status").getValue().toString(); userProfileName.setText(userName); userProfileStatus.setText(userStatus); ManageChatRequests(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } private void ManageChatRequests() { ChatRequestRef.child(senderUserID) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(receiveUserID)) { String request_type = dataSnapshot.child(receiveUserID).child("request_type").getValue().toString(); if (request_type.equals("sent")){ Current_State = "request_sent"; SendMessagrRequestButton.setText("Cancel chat request"); } else if(request_type.equals("received")) { Current_State = "request_received"; SendMessagrRequestButton.setText("Accept chat request"); DeclineMessageRequestButton.setVisibility(View.VISIBLE); DeclineMessageRequestButton.setEnabled(true); DeclineMessageRequestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CancelChatRequest(); } }); } } else{ ContactsRef.child(senderUserID) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(receiveUserID)){ Current_State = "friends"; SendMessagrRequestButton.setText("Remove this contact"); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); if (!senderUserID.equals(receiveUserID)) { SendMessagrRequestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SendMessagrRequestButton.setEnabled(false); if(Current_State.equals("new")) { SendChatRequest(); } if (Current_State.equals("request_sent")) { CancelChatRequest(); } if (Current_State.equals("request_received")) { AcceptChatRequest(); } if (Current_State.equals("friends")) { RemoveSpecificContact(); } } }); } else { SendMessagrRequestButton.setVisibility(View.INVISIBLE); } } private void RemoveSpecificContact() { ContactsRef.child(senderUserID).child(receiveUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { ContactsRef.child(receiveUserID).child(senderUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ SendMessagrRequestButton.setEnabled(true); Current_State = "new"; SendMessagrRequestButton.setText("Send Message"); DeclineMessageRequestButton.setVisibility(View.INVISIBLE); DeclineMessageRequestButton.setEnabled(false); } } }); } } }); } private void AcceptChatRequest() { ContactsRef.child(senderUserID).child(receiveUserID) .child("Contacts").setValue("Saved") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { ContactsRef.child(receiveUserID).child(senderUserID) .child("Contacts").setValue("Saved") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { ChatRequestRef.child(senderUserID).child(receiveUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ ChatRequestRef.child(receiveUserID).child(senderUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { SendMessagrRequestButton.setEnabled(true); Current_State = "friends"; SendMessagrRequestButton.setText("Remove this contact"); DeclineMessageRequestButton.setText(View.INVISIBLE); DeclineMessageRequestButton.setEnabled(false); } }); } } }); } } }); } } }); } private void CancelChatRequest() { ChatRequestRef.child(senderUserID).child(receiveUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { ChatRequestRef.child(receiveUserID).child(senderUserID) .removeValue() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ SendMessagrRequestButton.setEnabled(true); Current_State = "new"; SendMessagrRequestButton.setText("Send Message"); DeclineMessageRequestButton.setVisibility(View.INVISIBLE); DeclineMessageRequestButton.setEnabled(false); } } }); } } }); } private void SendChatRequest() { ChatRequestRef.child(senderUserID).child(receiveUserID) .child("request_type").setValue("sent") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { ChatRequestRef.child(receiveUserID).child(senderUserID) .child("request_type").setValue("received") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { HashMap<String, String> chatnotification = new HashMap<>(); chatnotification.put("from",senderUserID); chatnotification.put("type","request"); NotificationRef.child(receiveUserID).push() .setValue(chatnotification) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { SendMessagrRequestButton.setEnabled(true); Current_State = "request_sent"; SendMessagrRequestButton.setText("Cancel chat request"); } } }); } } }); } } }); } }
a7dabfae2289b63ac82ec5a0897f799990bb5ce5
81719679e3d5945def9b7f3a6f638ee274f5d770
/aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/UpdateManagedInstanceRoleResult.java
869646e1ebf424dfaf758aabfb507d3fa36b6549
[ "Apache-2.0" ]
permissive
ZeevHayat1/aws-sdk-java
1e3351f2d3f44608fbd3ff987630b320b98dc55c
bd1a89e53384095bea869a4ea064ef0cf6ed7588
refs/heads/master
2022-04-10T14:18:43.276970
2020-03-07T12:15:44
2020-03-07T12:15:44
172,681,373
1
0
Apache-2.0
2019-02-26T09:36:47
2019-02-26T09:36:47
null
UTF-8
Java
false
false
2,418
java
/* * Copyright 2014-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://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simplesystemsmanagement.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateManagedInstanceRole" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateManagedInstanceRoleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateManagedInstanceRoleResult == false) return false; UpdateManagedInstanceRoleResult other = (UpdateManagedInstanceRoleResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public UpdateManagedInstanceRoleResult clone() { try { return (UpdateManagedInstanceRoleResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
6f69b10c755f9fc9b91601918132fad4ffcd1026
7f522789c31154a33dde9d62e9a6df02f7d7d744
/src/main/java/com/pet/bankservice/entity/Transaction.java
552c785cb41e357ed12340bdf5aa0785b4d4ae40
[]
no_license
semyonich/bank-service
ea0b197f70ce9b3d86c7c4689777cebcd894ff29
b76917fbc0bde8cf3d4e351985b453cd745bf767
refs/heads/master
2023-03-20T01:51:38.401406
2021-03-16T16:40:33
2021-03-16T16:40:33
342,699,413
1
0
null
2021-03-16T16:40:33
2021-02-26T20:58:47
Java
UTF-8
Java
false
false
1,746
java
package com.pet.bankservice.entity; import java.math.BigDecimal; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "transactions") public class Transaction { public enum TransactionType { INCOMING, OUTCOMING; } public enum StatusType { OK, ERROR; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "from_account_id") private Account fromAccount; @ManyToOne @JoinColumn(name = "to_account_id") private Account toAccount; @Column(name = "date_time") private LocalDateTime dateTime; private BigDecimal amount; @Enumerated(EnumType.STRING) private TransactionType type; @Enumerated(EnumType.STRING) private StatusType status; @Override public String toString() { return "Transaction{" + "id=" + id + ", fromAccount=" + fromAccount.getAccountNumber() + ", toAccount=" + toAccount.getAccountNumber() + ", dateTime=" + dateTime + ", amount=" + amount + ", type=" + type + ", status='" + status + '\'' + '}'; } }
fdfccac5fbf443c0531cc18ae69553c51a95cc0c
6d6f10478cbdf4a34b418f8fb677208be09ff417
/src/mvc/WarUiEventListener.java
77d01c176ddd6455138e351a09bfcc1dc8f23cf6
[]
no_license
mennyaboush/warSimulator
0610e740f3c60b7610c4d2c6a052d91c01728d8f
237c7febcad07208698bc629ddb27a15999fcbe5
refs/heads/master
2020-03-08T14:38:50.614631
2018-06-12T13:25:01
2018-06-12T13:25:01
128,191,689
0
0
null
null
null
null
UTF-8
Java
false
false
409
java
package mvc; import java.util.List; import Enum.City; import bl.Missile; public interface WarUiEventListener { void addLauncherFromUi(); void addLauncherDestructorFromUi(); void addMissileDestructorFromUi(); void fireFromLauncherFromUi(City city); void fireFromlauncherDestructorsFromUi(); void fireFromMissileDestructorsFromUi(); void printSummaryFromUi(); void ExitFromUi(); }
8f016e661b20ef09a695de9f2c608223e0cf9cdf
c5a67e2aeabbde81c93a329ae2e9c7ccc3631246
/src/main/java/com/vnw/data/jooq/tables/pojos/TbltrackEmployerSignin.java
5e06c70ac070f27904a20b1829496016ab0ea1b3
[]
no_license
phuonghuynh/dtools
319d773d01c32093fd17d128948ef89c81f3f4bf
883d15ef19da259396a7bc16ac9df590e8add015
refs/heads/master
2016-09-14T03:46:53.463230
2016-05-25T04:04:32
2016-05-25T04:04:32
59,534,869
1
0
null
null
null
null
UTF-8
Java
false
false
2,229
java
/** * This class is generated by jOOQ */ package com.vnw.data.jooq.tables.pojos; import java.io.Serializable; import java.sql.Timestamp; import javax.annotation.Generated; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.0" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class TbltrackEmployerSignin implements Serializable { private static final long serialVersionUID = 1218469016; private Integer trackid; private String ipaddress; private Integer userid; private Timestamp createdate; public TbltrackEmployerSignin() {} public TbltrackEmployerSignin(TbltrackEmployerSignin value) { this.trackid = value.trackid; this.ipaddress = value.ipaddress; this.userid = value.userid; this.createdate = value.createdate; } public TbltrackEmployerSignin( Integer trackid, String ipaddress, Integer userid, Timestamp createdate ) { this.trackid = trackid; this.ipaddress = ipaddress; this.userid = userid; this.createdate = createdate; } public Integer getTrackid() { return this.trackid; } public void setTrackid(Integer trackid) { this.trackid = trackid; } public String getIpaddress() { return this.ipaddress; } public void setIpaddress(String ipaddress) { this.ipaddress = ipaddress; } public Integer getUserid() { return this.userid; } public void setUserid(Integer userid) { this.userid = userid; } public Timestamp getCreatedate() { return this.createdate; } public void setCreatedate(Timestamp createdate) { this.createdate = createdate; } @Override public String toString() { StringBuilder sb = new StringBuilder("TbltrackEmployerSignin ("); sb.append(trackid); sb.append(", ").append(ipaddress); sb.append(", ").append(userid); sb.append(", ").append(createdate); sb.append(")"); return sb.toString(); } }
451bd44cc39a3936d3cf3e58d7cd14be3596806d
a7ecbb1e5f83a1e8dd9bfca1e7c64f872a8b40ac
/app/src/main/java/com/example/altunmursalov/news/MainActivity.java
525250e31f4cab297ef48e7f5e9ca0fbef065f3f
[]
no_license
AltunMursalov/News
363c85cdc63e87713d38e8dd3f33422be29766e5
b3243d2ba9bd225d8c2e4250f40c74c4155549f5
refs/heads/master
2020-04-12T03:19:50.264885
2018-12-18T09:32:35
2018-12-18T09:32:35
162,263,770
0
0
null
null
null
null
UTF-8
Java
false
false
3,874
java
package com.example.altunmursalov.news; import android.annotation.SuppressLint; import android.support.v4.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("Explore"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs); ViewPager pager = (ViewPager)findViewById(R.id.explore_pager); MyTabPagerAdapter tabPagerAdapter = new MyTabPagerAdapter(getSupportFragmentManager()); pager.setAdapter(tabPagerAdapter); tabLayout.setupWithViewPager(pager); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.search) { return true; } return super.onOptionsItemSelected(item); } @SuppressLint("ResourceType") private void displaySelectedScreen(int id) { Fragment fragment = null; switch (id) { case R.id.technology: fragment = new Technology(); break; } if(fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.layout.content_main, fragment); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); return true; } }
d7e5858ad5d705e647ac5604909b8870fa9d40f4
e537bbcecd379a3e97a0c81a7e23edac788a1371
/src/main/java/com/jenkov/db/impl/mapping/method/CharacterStream.java
b2658334efd090f60b4f83f1ac18df0ab7044f44
[ "Apache-2.0" ]
permissive
jjenkov/butterfly-persistence
92670d41d48fe0f129c2ce2ea246b8aa7ff4cf18
c644d102b32e433119f6ac7871ac18bdc9d69948
refs/heads/master
2022-02-21T06:11:43.732748
2022-02-04T16:35:17
2022-02-04T16:35:17
54,051,360
23
16
Apache-2.0
2022-02-04T16:35:18
2016-03-16T17:08:46
Java
UTF-8
Java
false
false
1,044
java
package com.jenkov.db.impl.mapping.method; import java.io.Reader; /** * @author Jakob Jenkov, Jenkov Development */ public class CharacterStream { protected Reader reader = null; protected int length = 0; public CharacterStream(Reader reader) { this.reader = reader; } public CharacterStream(Reader reader, int length) { this.reader = reader; this.length = length; } public Reader getReader() { return reader; } public void setReader(Reader reader) { this.reader = reader; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof CharacterStream)) return false; CharacterStream otherStream = (CharacterStream) obj; if(getLength() != otherStream.getLength()) return false; return getReader().equals(otherStream.getReader()); } }
85a6caa498589e37952964dac4624b034c59696f
4a7ca7d0bf92dfc382b789a50db091bbb2d5f266
/eureka-client/src/main/java/com/mashibing/eureka/controller/MainController.java
cbc960a8c94bb1c3b2dc785573571ef80f75fde3
[]
no_license
kevinNewBird/springcloud-all
5e9658cadc0bd2e8c86363c9c01a4625047cfede
2f6ae137dbe669e5422d0a67b9ba0a1666048e33
refs/heads/master
2023-04-18T18:45:56.847890
2021-04-28T06:07:52
2021-04-28T06:07:52
355,623,766
0
0
null
null
null
null
UTF-8
Java
false
false
2,121
java
package com.mashibing.eureka.controller; import com.mashibing.eureka.pojo.Person; import com.mashibing.eureka.service.HealthStatusService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.Map; /*********************** * @Description: TODO 类描述<BR> * @author: zhao.song * @since: 2021/4/9 0:25 * @version: 1.0 ***********************/ @RestController public class MainController { @Value("${server.port}") private String port; @Autowired private HealthStatusService healthService; @GetMapping("/hello") public String sayHello(){ return "hello eureka client0,我的port: " + port; } @GetMapping("/getMap") public Map<String,String> getMap(){ return Collections.singletonMap("id", "100"); } @GetMapping("/getObj") public Person getObj(){ return new Person(1, "xiaoliuliu111"); } @GetMapping("/getObj2") public Person getObj2(String name){ return new Person(1, name); } @PostMapping("/postObj") public Person postObj(@RequestParam String name){ return new Person(1, name); } @PostMapping("/postObj2") public Person postObj(@RequestParam String name,@RequestBody Map<String,String> map){ System.out.println(map); return new Person(1, name); } @PostMapping("/postLocation") public URI postLocation(@RequestBody Person oPerson, HttpServletResponse response) throws URISyntaxException { System.out.println(oPerson); URI uri = new URI("http://www.baidu.com?wd=" + oPerson.getName()); response.addHeader("Location", uri.toString()); return uri; } @GetMapping("/health") public String health(boolean status) { healthService.setStatus(status); return status ? "服务上线" : "服务下线"; } }
e0f6ff2e6115589278326ce02ff63fc5417b4484
13f8de23ea9ad4ee9e91d215c62eaf5ffeb09239
/src/main/java/com/demo/alg/c27多线程算法/矩阵/TestDemo.java
5f8fcb7880c936276e2eb8338a97a56e76d33064
[]
no_license
yhb2010/alg_demo
b0b50d17c0321fd935dbdef90c6964661ebc97ec
0c0aa27939a4f4f57c5f139b7d0e4a2794688206
refs/heads/master
2020-04-09T22:08:19.853052
2018-12-08T07:08:31
2018-12-08T07:08:31
160,620,930
0
0
null
null
null
null
UTF-8
Java
false
false
1,266
java
package com.demo.alg.c27多线程算法.矩阵; import java.util.concurrent.CountDownLatch; public class TestDemo { static int[][] a = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; static int[][] b = new int[][]{{1, 3, 5, 7}, {2, 4, 6, 8}, {11, 13, 15, 17}, {12, 14, 16, 18}}; static int[][] result = new int[a.length][b[0].length]; // 存放矩阵相乘结果 public static void main(String args[]) { CountDownLatch cdl = new CountDownLatch(a.length); OperateMatrix om = new OperateMatrix(a, b, result); // 实例化OperateMatrix对象 // 根据第一个矩阵的行数,启动对应数量的线程 for (int i = 0; i < a.length; i++) { new ThreadOperate(om, i, "计算第一个矩阵的第" + (i) + "行*第二个矩阵的所有列", cdl).start(); } try { cdl.await(); } catch (InterruptedException e) { e.printStackTrace(); } display(om.getResult()); // 打印结果 } public static void display(int[][] c) { for (int i = 0; i < c.length; i++) { for (int j = 0; j < c[i].length; j++) { System.out.print(c[i][j] + " "); } System.out.println(); } } }
f4d65a43e44bf3f0949f5498fea7c48164d5bae0
c1bbb030862c00bd8f4cce851bca9919a3486da8
/androidWidget/src/com/kerkr/edu/recycleView/VerticalDividerItemDecoration.java
d3cadcc8a96c4c277d1e2f2c7e16d6f730fc0526
[]
no_license
caocf/androidBaseLib
19c8a2032d527b92e66fd7a3da55d0694854d282
4ec7398f113cf2bd3d2ace9032d825b6c3165cd9
refs/heads/master
2020-02-26T17:12:54.865258
2015-07-17T09:35:05
2015-07-17T09:35:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,929
java
package com.kerkr.edu.recycleView; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.DimenRes; import android.support.v4.view.ViewCompat; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by yqritc on 2015/01/15. */ public class VerticalDividerItemDecoration extends FlexibleDividerDecoration { private MarginProvider mMarginProvider; protected VerticalDividerItemDecoration(Builder builder) { super(builder); mMarginProvider = builder.mMarginProvider; } @Override protected Rect getDividerBound(int position, RecyclerView parent, View child) { Rect bounds = new Rect(0, 0, 0, 0); int transitionX = (int) ViewCompat.getTranslationX(child); int transitionY = (int) ViewCompat.getTranslationY(child); RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); bounds.top = parent.getPaddingTop() + mMarginProvider.dividerTopMargin(position, parent) + transitionY; bounds.bottom = parent.getHeight() - parent.getPaddingBottom() - mMarginProvider.dividerBottomMargin(position, parent) + transitionY; int dividerSize = getDividerSize(position, parent); if (mDividerType == DividerType.DRAWABLE) { bounds.left = child.getRight() + params.leftMargin + transitionX; bounds.right = bounds.left + dividerSize; } else { bounds.left = child.getRight() + params.leftMargin + dividerSize / 2 + transitionX; bounds.right = bounds.left; } return bounds; } @Override protected void setItemOffsets(Rect outRect, int position, RecyclerView parent) { outRect.set(0, 0, getDividerSize(position, parent), 0); } private int getDividerSize(int position, RecyclerView parent) { if (mPaintProvider != null) { return (int) mPaintProvider.dividerPaint(position, parent).getStrokeWidth(); } else if (mSizeProvider != null) { return mSizeProvider.dividerSize(position, parent); } else if (mDrawableProvider != null) { Drawable drawable = mDrawableProvider.drawableProvider(position, parent); return drawable.getIntrinsicWidth(); } throw new RuntimeException("failed to get size"); } /** * Interface for controlling divider margin */ public interface MarginProvider { /** * Returns top margin of divider. * * @param position Divider position * @param parent RecyclerView * @return top margin */ int dividerTopMargin(int position, RecyclerView parent); /** * Returns bottom margin of divider. * * @param position Divider position * @param parent RecyclerView * @return bottom margin */ int dividerBottomMargin(int position, RecyclerView parent); } public static class Builder extends FlexibleDividerDecoration.Builder<Builder> { private MarginProvider mMarginProvider = new MarginProvider() { @Override public int dividerTopMargin(int position, RecyclerView parent) { return 0; } @Override public int dividerBottomMargin(int position, RecyclerView parent) { return 0; } }; public Builder(Context context) { super(context); } public Builder margin(final int topMargin, final int bottomMargin) { return marginProvider(new MarginProvider() { @Override public int dividerTopMargin(int position, RecyclerView parent) { return topMargin; } @Override public int dividerBottomMargin(int position, RecyclerView parent) { return bottomMargin; } }); } public Builder margin(int verticalMargin) { return margin(verticalMargin, verticalMargin); } public Builder marginResId(@DimenRes int topMarginId, @DimenRes int bottomMarginId) { return margin(mResources.getDimensionPixelSize(topMarginId), mResources.getDimensionPixelSize(bottomMarginId)); } public Builder marginResId(@DimenRes int verticalMarginId) { return marginResId(verticalMarginId, verticalMarginId); } public Builder marginProvider(MarginProvider provider) { mMarginProvider = provider; return this; } public VerticalDividerItemDecoration build() { checkBuilderParams(); return new VerticalDividerItemDecoration(this); } } }
e9a6293adf3c3fb0c575bd10d3b6c95e8db6058b
0be82b9a18db00f0e0b0ac28b9fe3caaa2e276a6
/open-metadata-implementation/repository-services/repository-services-implementation/src/main/java/org/odpi/openmetadata/repositoryservices/enterprise/repositoryconnector/EnterpriseOMRSMetadataCollection.java
d4afe4cce6a963e53e8baf46808a0b2eeeb58453
[ "Apache-2.0" ]
permissive
constantinnastase/egeria
6d2882e08745d07b432477be93d43b4ce2a524b7
80f0a3cc172e063b61401a23268f5d1e2ccd8095
refs/heads/master
2020-03-22T09:47:26.442127
2018-07-18T12:58:11
2018-07-18T12:58:11
139,860,496
0
0
Apache-2.0
2018-07-05T14:33:29
2018-07-05T14:23:22
Java
UTF-8
Java
false
false
350,084
java
/* SPDX-License-Identifier: Apache-2.0 */ package org.odpi.openmetadata.repositoryservices.enterprise.repositoryconnector; import org.odpi.openmetadata.repositoryservices.ffdc.OMRSErrorCode; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.OMRSMetadataCollection; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.MatchCriteria; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.SequencingOrder; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.*; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.*; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryValidator; import org.odpi.openmetadata.repositoryservices.ffdc.exception.*; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Date; /** * EnterpriseOMRSMetadataCollection executes the calls to the open metadata repositories registered * with the OMRSEnterpriseConnectorManager. The effect is a federated view over these open metadata * repositories. * <p> * EnterpriseOMRSMetadataCollection is part of an EnterpriseOMRSRepositoryConnector. The EnterpriseOMRSRepositoryConnector * holds the list of OMRS Connectors, one for each of the metadata repositories. This list may change * over time as metadata repositories register and deregister with the connected cohorts. * The EnterpriseOMRSRepositoryConnector is responsible for keeping the list of connectors up-to-date through * contact with the OMRSEnterpriseConnectorManager. * </p> * <p> * When a request is made to the EnterpriseOMRSMetadataCollection, it calls the EnterpriseOMRSRepositoryConnector * to request the appropriate list of metadata collection for the request. Then the EnterpriseOMRSConnector * calls the appropriate remote connectors. * </p> * <p> * The first OMRS Connector in the list is the OMRS Repository Connector for the "local" repository. * The local repository is favoured when new metadata is to be created, unless the type of metadata * is not supported by the local repository. In which case, the EnterpriseOMRSMetadataCollection searches its * list looking for the first metadata repository that supports the metadata type and stores it there. * </p> * <p> * Updates and deletes are routed to the owning (home) repository. Searches are made to each repository in turn * and the duplicates are removed. Queries are directed to the local repository and then the remote repositories * until all of the requested metadata is assembled. * </p> */ public class EnterpriseOMRSMetadataCollection extends OMRSMetadataCollection { /* * Private variables for a metadata collection instance */ private EnterpriseOMRSRepositoryConnector enterpriseParentConnector; /** * Constructor ensures the metadata collection is linked to its connector and knows its metadata collection Id. * * @param enterpriseParentConnector connector that this metadata collection supports. The connector has the information * to call the metadata repository. * @param repositoryName name of the repository used for logging. * @param repositoryHelper class used to build type definitions and instances. * @param repositoryValidator class used to validate type definitions and instances. * @param metadataCollectionId unique Identifier of the metadata collection Id. */ public EnterpriseOMRSMetadataCollection(EnterpriseOMRSRepositoryConnector enterpriseParentConnector, String repositoryName, OMRSRepositoryHelper repositoryHelper, OMRSRepositoryValidator repositoryValidator, String metadataCollectionId) { /* * The metadata collection Id is the unique identifier for the metadata collection. It is managed by the super class. */ super(enterpriseParentConnector, repositoryName, metadataCollectionId, repositoryHelper, repositoryValidator); /* * Save enterpriseParentConnector since this has the connection information and * access to the metadata about the open metadata repository cohort. */ this.enterpriseParentConnector = enterpriseParentConnector; } /* ====================================================================== * Group 1: Confirm the identity of the metadata repository being called. */ /** * Returns the identifier of the metadata repository. This is the identifier used to register the * metadata repository with the metadata repository cohort. It is also the identifier used to * identify the home repository of a metadata instance. * * @return String metadata collection id. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. */ public String getMetadataCollectionId() throws RepositoryErrorException { final String methodName = "getMetadataCollectionId"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); /* * Perform operation */ return super.metadataCollectionId; } /* ============================== * Group 2: Working with typedefs */ /** * Returns the list of different types of metadata organized into two groups. The first are the * attribute type definitions (AttributeTypeDefs). These provide types for properties in full * type definitions. Full type definitions (TypeDefs) describe types for entities, relationships * and classifications. * * @param userId unique identifier for requesting user. * @return TypeDefs List of different categories of TypeDefs. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public TypeDefGallery getAllTypes(String userId) throws RepositoryErrorException, UserNotAuthorizedException { final String methodName = "getAllTypes"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, TypeDef> combinedTypeDefResults = new HashMap<>(); Map<String, AttributeTypeDef> combinedAttributeTypeDefResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ TypeDefGallery results = metadataCollection.getAllTypes(userId); /* * Step through the list of returned TypeDefs and consolidate. */ if (results != null) { combinedAttributeTypeDefResults = this.addUniqueAttributeTypeDefs(combinedAttributeTypeDefResults, results.getAttributeTypeDefs(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); combinedTypeDefResults = this.addUniqueTypeDefs(combinedTypeDefResults, results.getTypeDefs(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefGalleryResults(repositoryName, combinedTypeDefResults, combinedAttributeTypeDefResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Returns a list of type definitions that have the specified name. Type names should be unique. This * method allows wildcard character to be included in the name. These are * (asterisk) for an * arbitrary string of characters and ampersand for an arbitrary character. * * @param userId unique identifier for requesting user. * @param name name of the TypeDefs to return (including wildcard characters). * @return TypeDefs list. * @throws InvalidParameterException the name of the TypeDef is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public TypeDefGallery findTypesByName(String userId, String name) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "findTypesByName"; final String nameParameterName = "name"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, TypeDef> combinedTypeDefResults = new HashMap<>(); Map<String, AttributeTypeDef> combinedAttributeTypeDefResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ TypeDefGallery results = metadataCollection.findTypesByName(userId, name); /* * Step through the list of returned TypeDefs and consolidate. */ if (results != null) { combinedAttributeTypeDefResults = this.addUniqueAttributeTypeDefs(combinedAttributeTypeDefResults, results.getAttributeTypeDefs(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); combinedTypeDefResults = this.addUniqueTypeDefs(combinedTypeDefResults, results.getTypeDefs(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefGalleryResults(repositoryName, combinedTypeDefResults, combinedAttributeTypeDefResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Returns all of the TypeDefs for a specific category. * * @param userId unique identifier for requesting user. * @param category enum value for the category of TypeDef to return. * @return TypeDefs list. * @throws InvalidParameterException the TypeDefCategory is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<TypeDef> findTypeDefsByCategory(String userId, TypeDefCategory category) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "findTypeDefsByCategory"; final String categoryParameterName = "category"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeDefCategory(repositoryName, categoryParameterName, category, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, TypeDef> combinedResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<TypeDef> results = metadataCollection.findTypeDefsByCategory(userId, category); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueTypeDefs(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefListResults(repositoryName, combinedResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Returns all of the AttributeTypeDefs for a specific category. * * @param userId unique identifier for requesting user. * @param category enum value for the category of an AttributeTypeDef to return. * @return TypeDefs list. * @throws InvalidParameterException the TypeDefCategory is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<AttributeTypeDef> findAttributeTypeDefsByCategory(String userId, AttributeTypeDefCategory category) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "findAttributeTypeDefsByCategory"; final String categoryParameterName = "category"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateAttributeTypeDefCategory(repositoryName, categoryParameterName, category, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, AttributeTypeDef> combinedResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<AttributeTypeDef> results = metadataCollection.findAttributeTypeDefsByCategory(userId, category); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueAttributeTypeDefs(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedAttributeTypeDefListResults(repositoryName, combinedResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Return the TypeDefs that have the properties matching the supplied match criteria. * * @param userId unique identifier for requesting user. * @param matchCriteria TypeDefProperties a list of property names. * @return TypeDefs list. * @throws InvalidParameterException the matchCriteria is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<TypeDef> findTypeDefsByProperty(String userId, TypeDefProperties matchCriteria) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "findTypeDefsByProperty"; final String matchCriteriaParameterName = "matchCriteria"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateMatchCriteria(repositoryName, matchCriteriaParameterName, matchCriteria, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, TypeDef> combinedResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<TypeDef> results = metadataCollection.findTypeDefsByProperty(userId, matchCriteria); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueTypeDefs(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefListResults(repositoryName, combinedResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Return the types that are linked to the elements from the specified standard. * * @param userId unique identifier for requesting user. * @param standard name of the standard null means any. * @param organization name of the organization null means any. * @param identifier identifier of the element in the standard null means any. * @return TypeDefs list each entry in the list contains a typedef. This is is a structure * describing the TypeDef's category and properties. * @throws InvalidParameterException all attributes of the external Id are null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<TypeDef> findTypesByExternalID(String userId, String standard, String organization, String identifier) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "findTypesByExternalID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateExternalId(repositoryName, standard, organization, identifier, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, TypeDef> combinedResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<TypeDef> results = metadataCollection.findTypesByExternalID(userId, standard, organization, identifier); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueTypeDefs(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefListResults(repositoryName, combinedResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Return the TypeDefs that match the search criteria. * * @param userId unique identifier for requesting user. * @param searchCriteria String search criteria. * @return TypeDefs list each entry in the list contains a typedef. This is is a structure * describing the TypeDef's category and properties. * @throws InvalidParameterException the searchCriteria is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<TypeDef> searchForTypeDefs(String userId, String searchCriteria) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "searchForTypeDefs"; final String searchCriteriaParameterName = "searchCriteria"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateSearchCriteria(repositoryName, searchCriteriaParameterName, searchCriteria, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no results from any repository. */ Map<String, TypeDef> combinedResults = new HashMap<>(); UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<TypeDef> results = metadataCollection.searchForTypeDefs(userId, searchCriteria); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueTypeDefs(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedTypeDefListResults(repositoryName, combinedResults, userNotAuthorizedException, repositoryErrorException, anotherException, methodName); } /** * Return the TypeDef identified by the GUID. * * @param userId unique identifier for requesting user. * @param guid String unique Id of the TypeDef * @return TypeDef structure describing its category and properties. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotKnownException The requested TypeDef is not known in the metadata collection. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public TypeDef getTypeDefByGUID(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, TypeDefNotKnownException, UserNotAuthorizedException { final String methodName = "getTypeDefByGUID"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotKnownException typeDefNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.getTypeDefByGUID(userId, guid); } catch (TypeDefNotKnownException error) { typeDefNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeDefNotKnownException(typeDefNotKnownException); return null; } /** * Return the AttributeTypeDef identified by the GUID. * * @param userId unique identifier for requesting user. * @param guid String unique id of the TypeDef * @return TypeDef structure describing its category and properties. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotKnownException The requested TypeDef is not known in the metadata collection. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public AttributeTypeDef getAttributeTypeDefByGUID(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, TypeDefNotKnownException, UserNotAuthorizedException { final String methodName = "getAttributeTypeDefByGUID"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotKnownException typeDefNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.getAttributeTypeDefByGUID(userId, guid); } catch (TypeDefNotKnownException error) { typeDefNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); if (typeDefNotKnownException != null) { throw typeDefNotKnownException; } return null; } /** * Return the TypeDef identified by the unique name. * * @param userId unique identifier for requesting user. * @param name String name of the TypeDef. * @return TypeDef structure describing its category and properties. * @throws InvalidParameterException the name is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotKnownException the requested TypeDef is not found in the metadata collection. */ public TypeDef getTypeDefByName(String userId, String name) throws InvalidParameterException, RepositoryErrorException, TypeDefNotKnownException, UserNotAuthorizedException { final String methodName = "getTypeDefByName"; final String nameParameterName = "name"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotKnownException typeDefNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.getTypeDefByName(userId, name); } catch (TypeDefNotKnownException error) { typeDefNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeDefNotKnownException(typeDefNotKnownException); return null; } /** * Return the AttributeTypeDef identified by the unique name. * * @param userId unique identifier for requesting user. * @param name String name of the TypeDef. * @return TypeDef structure describing its category and properties. * @throws InvalidParameterException the name is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotKnownException the requested TypeDef is not found in the metadata collection. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public AttributeTypeDef getAttributeTypeDefByName(String userId, String name) throws InvalidParameterException, RepositoryErrorException, TypeDefNotKnownException, UserNotAuthorizedException { final String methodName = "getAttributeTypeDefByName"; final String nameParameterName = "name"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotKnownException typeDefNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.getAttributeTypeDefByName(userId, name); } catch (TypeDefNotKnownException error) { typeDefNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeDefNotKnownException(typeDefNotKnownException); return null; } /** * Create a collection of related types. * * @param userId unique identifier for requesting user. * @param newTypes TypeDefGalleryResponse structure describing the new AttributeTypeDefs and TypeDefs. * @throws FunctionNotSupportedException the repository does not support this call. */ public void addTypeDefGallery(String userId, TypeDefGallery newTypes) throws FunctionNotSupportedException { final String methodName = "addTypeDefGallery()"; throwNotEnterpriseFunction(methodName); } /** * Create a definition of a new TypeDef. This new TypeDef is pushed to each repository that will accept it. * An exception is passed to the caller if the TypeDef is invalid, or if none of the repositories accept it. * * @param userId unique identifier for requesting user. * @param newTypeDef TypeDef structure describing the new TypeDef. * @throws FunctionNotSupportedException the repository does not support this call. */ public void addTypeDef(String userId, TypeDef newTypeDef) throws FunctionNotSupportedException { final String methodName = "addTypeDef()"; throwNotEnterpriseFunction(methodName); } /** * Create a definition of a new AttributeTypeDef. * * @param userId unique identifier for requesting user. * @param newAttributeTypeDef TypeDef structure describing the new TypeDef. * @throws FunctionNotSupportedException the repository does not support this call. */ public void addAttributeTypeDef(String userId, AttributeTypeDef newAttributeTypeDef) throws FunctionNotSupportedException { final String methodName = "addAttributeTypeDef()"; throwNotEnterpriseFunction(methodName); } /** * Verify that a definition of a TypeDef is either new or matches the definition already stored. * * @param userId unique identifier for requesting user. * @param typeDef TypeDef structure describing the TypeDef to test. * @return boolean true means the TypeDef matches the local definition false means the TypeDef is not known. * @throws InvalidParameterException the TypeDef is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotSupportedException the repository is not able to support this TypeDef. * @throws TypeDefConflictException the new TypeDef conflicts with an existing TypeDef. * @throws InvalidTypeDefException the new TypeDef has invalid contents. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public boolean verifyTypeDef(String userId, TypeDef typeDef) throws InvalidParameterException, RepositoryErrorException, TypeDefNotSupportedException, TypeDefConflictException, InvalidTypeDefException, UserNotAuthorizedException { final String methodName = "verifyTypeDef"; final String typeDefParameterName = "typeDef"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeDef(repositoryName, typeDefParameterName, typeDef, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotSupportedException typeDefNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds (TypeDefConflictException is also returned * immediately.) */ return metadataCollection.verifyTypeDef(userId, typeDef); } catch (TypeDefNotSupportedException error) { typeDefNotSupportedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeDefNotSupportedException(typeDefNotSupportedException); return false; } /** * Verify that a definition of an AttributeTypeDef is either new or matches the definition already stored. * * @param userId unique identifier for requesting user. * @param attributeTypeDef TypeDef structure describing the TypeDef to test. * @return boolean true means the TypeDef matches the local definition false means the TypeDef is not known. * @throws InvalidParameterException the TypeDef is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeDefNotSupportedException the repository is not able to support this TypeDef. * @throws TypeDefConflictException the new TypeDef conflicts with an existing TypeDef. * @throws InvalidTypeDefException the new TypeDef has invalid contents. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public boolean verifyAttributeTypeDef(String userId, AttributeTypeDef attributeTypeDef) throws InvalidParameterException, RepositoryErrorException, TypeDefNotSupportedException, TypeDefConflictException, InvalidTypeDefException, UserNotAuthorizedException { final String methodName = "verifyAttributeTypeDef"; final String typeDefParameterName = "attributeTypeDef"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateAttributeTypeDef(repositoryName, typeDefParameterName, attributeTypeDef, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ TypeDefNotSupportedException typeDefNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds (TypeDefConflictException is also returned * immediately.) */ return metadataCollection.verifyAttributeTypeDef(userId, attributeTypeDef); } catch (TypeDefNotSupportedException error) { typeDefNotSupportedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeDefNotSupportedException(typeDefNotSupportedException); return false; } /** * Update one or more properties of the TypeDef. The TypeDefPatch controls what types of updates * are safe to make to the TypeDef. * * @param userId unique identifier for requesting user. * @param typeDefPatch TypeDef patch describing change to TypeDef. * @return updated TypeDef * @throws FunctionNotSupportedException the repository does not support this call. */ public TypeDef updateTypeDef(String userId, TypeDefPatch typeDefPatch) throws FunctionNotSupportedException { final String methodName = "updateTypeDef()"; throwNotEnterpriseFunction(methodName); return null; } /** * Delete the TypeDef. This is only possible if the TypeDef has never been used to create instances or any * instances of this TypeDef have been purged from the metadata collection. * * @param userId unique identifier for requesting user. * @param obsoleteTypeDefGUID String unique identifier for the TypeDef. * @param obsoleteTypeDefName String unique name for the TypeDef. * @throws FunctionNotSupportedException the repository does not support this call. */ public void deleteTypeDef(String userId, String obsoleteTypeDefGUID, String obsoleteTypeDefName) throws FunctionNotSupportedException { final String methodName = "deleteTypeDef()"; throwNotEnterpriseFunction(methodName); } /** * Delete an AttributeTypeDef. This is only possible if the AttributeTypeDef has never been used to create * instances or any instances of this AttributeTypeDef have been purged from the metadata collection. * * @param userId unique identifier for requesting user. * @param obsoleteTypeDefGUID String unique identifier for the AttributeTypeDef. * @param obsoleteTypeDefName String unique name for the AttributeTypeDef. * @throws FunctionNotSupportedException the repository does not support this call. */ public void deleteAttributeTypeDef(String userId, String obsoleteTypeDefGUID, String obsoleteTypeDefName) throws FunctionNotSupportedException { final String methodName = "deleteAttributeTypeDef()"; throwNotEnterpriseFunction(methodName); } /** * Change the guid or name of an existing TypeDef to a new value. This is used if two different * TypeDefs are discovered to have the same guid. This is extremely unlikely but not impossible so * the open metadata protocol has provision for this. * * @param userId unique identifier for requesting user. * @param originalTypeDefGUID the original guid of the TypeDef. * @param originalTypeDefName the original name of the TypeDef. * @param newTypeDefGUID the new identifier for the TypeDef. * @param newTypeDefName new name for this TypeDef. * @return typeDef new values for this TypeDef, including the new guid/name. * @throws FunctionNotSupportedException the repository does not support this call. */ public TypeDef reIdentifyTypeDef(String userId, String originalTypeDefGUID, String originalTypeDefName, String newTypeDefGUID, String newTypeDefName) throws FunctionNotSupportedException { final String methodName = "reIdentifyTypeDef()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the guid or name of an existing TypeDef to a new value. This is used if two different * TypeDefs are discovered to have the same guid. This is extremely unlikely but not impossible so * the open metadata protocol has provision for this. * * @param userId unique identifier for requesting user. * @param originalAttributeTypeDefGUID the original guid of the AttributeTypeDef. * @param originalAttributeTypeDefName the original name of the AttributeTypeDef. * @param newAttributeTypeDefGUID the new identifier for the AttributeTypeDef. * @param newAttributeTypeDefName new name for this AttributeTypeDef. * @return attributeTypeDef new values for this AttributeTypeDef, including the new guid/name. * @throws FunctionNotSupportedException the repository does not support this call. */ public AttributeTypeDef reIdentifyAttributeTypeDef(String userId, String originalAttributeTypeDefGUID, String originalAttributeTypeDefName, String newAttributeTypeDefGUID, String newAttributeTypeDefName) throws FunctionNotSupportedException { final String methodName = "reIdentifyAttributeTypeDef()"; throwNotEnterpriseFunction(methodName); return null; } /* =================================================== * Group 3: Locating entity and relationship instances */ /** * Returns the entity if the entity is stored in the metadata collection, otherwise null. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the entity * @return the entity details if the entity is found in the metadata collection; otherwise return null * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail isEntityKnown(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "isEntityKnown"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.isEntityKnown(userId, guid); } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); return null; } /** * Return the header and classifications for a specific entity. The returned entity summary may be from * a full entity object or an entity proxy. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the entity * @return EntitySummary structure * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the requested entity instance is not known in the metadata collection. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntitySummary getEntitySummary(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, UserNotAuthorizedException { final String methodName = "getEntitySummary"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ EntityNotKnownException entityNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ EntitySummary entity = metadataCollection.getEntitySummary(userId, guid); repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName); return entity; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedEntityNotKnownException(entityNotKnownException); return null; } /** * Return the header, classifications and properties of a specific entity. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the entity. * @return EntityDetail structure. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the requested entity instance is not known in the metadata collection. * @throws EntityProxyOnlyException the requested entity instance is only a proxy in the metadata collection. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail getEntityDetail(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, EntityProxyOnlyException, UserNotAuthorizedException { final String methodName = "getEntityDetail"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ EntityNotKnownException entityNotKnownException = null; EntityProxyOnlyException entityProxyOnlyException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ EntityDetail entity = metadataCollection.getEntityDetail(userId, guid); repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName); return entity; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (EntityProxyOnlyException error) { entityProxyOnlyException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedEntityNotKnownException(entityNotKnownException); throwCapturedEntityProxyOnlyException(entityProxyOnlyException); return null; } /** * Return a historical version of an entity. This includes the header, classifications and properties of the entity. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the entity. * @param asOfTime the time used to determine which version of the entity that is desired. * @return EntityDetail structure. * @throws InvalidParameterException the guid or date is null or the date is for a future time. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the requested entity instance is not known in the metadata collection * at the time requested. * @throws EntityProxyOnlyException the requested entity instance is only a proxy in the metadata collection. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail getEntityDetail(String userId, String guid, Date asOfTime) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, EntityProxyOnlyException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getEntityDetail"; final String guidParameterName = "guid"; final String asOfTimeParameter = "asOfTime"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ EntityNotKnownException entityNotKnownException = null; EntityProxyOnlyException entityProxyOnlyException = null; FunctionNotSupportedException functionNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ EntityDetail entity = metadataCollection.getEntityDetail(userId, guid, asOfTime); repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName); return entity; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (EntityProxyOnlyException error) { entityProxyOnlyException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedEntityNotKnownException(entityNotKnownException); throwCapturedEntityProxyOnlyException(entityProxyOnlyException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } /** * Return the relationships for a specific entity. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier for the entity. * @param relationshipTypeGUID String GUID of the the type of relationship required (null for all). * @param fromRelationshipElement the starting element number of the relationships to return. * This is used when retrieving elements * beyond the first page of results. Zero means start from the first element. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize -- the maximum number of result classifications that can be returned on this request. Zero means * unrestricted return results size. * @return Relationships list. Null means no relationships associated with the entity. * @throws InvalidParameterException a parameter is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the requested entity instance is not known in the metadata collection. * @throws PropertyErrorException the sequencing property is not valid for the attached classifications. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<Relationship> getRelationshipsForEntity(String userId, String entityGUID, String relationshipTypeGUID, int fromRelationshipElement, List<InstanceStatus> limitResultsByStatus, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, EntityNotKnownException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getRelationshipsForEntity"; final String guidParameterName = "entityGUID"; final String asOfTimeParameter = "asOfTime"; final String typeGUIDParameter = "relationshipTypeGUID"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, entityGUID, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, typeGUIDParameter, relationshipTypeGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, Relationship> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; EntityNotKnownException entityNotKnownException = null; FunctionNotSupportedException functionNotSupportedException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<Relationship> results = metadataCollection.getRelationshipsForEntity(userId, entityGUID, relationshipTypeGUID, fromRelationshipElement, limitResultsByStatus, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueRelationships(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); throwCapturedEntityNotKnownException(entityNotKnownException); return null; } return validatedRelationshipResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Return a list of entities that match the supplied properties according to the match criteria. The results * can be returned over many pages. * * @param userId unique identifier for requesting user. * @param entityTypeGUID String unique identifier for the entity type of interest (null means any entity type). * @param matchProperties List of entity properties to match to (null means match on entityTypeGUID only). * @param matchCriteria Enum defining how the properties should be matched to the entities in the repository. * @param fromEntityElement the starting element number of the entities to return. * This is used when retrieving elements * beyond the first page of results. Zero means start from the first element. * @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param limitResultsByClassification List of classifications that must be present on all returned entities. * @param asOfTime Requests a historical query of the entity. Null means return the present values. * @param sequencingProperty String name of the entity property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @return a list of entities matching the supplied criteria null means no matching entities in the metadata * collection. * @throws InvalidParameterException a parameter is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws PropertyErrorException the properties specified are not valid for any of the requested types of * entity. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<EntityDetail> findEntitiesByProperty(String userId, String entityTypeGUID, InstanceProperties matchProperties, MatchCriteria matchCriteria, int fromEntityElement, List<InstanceStatus> limitResultsByStatus, List<String> limitResultsByClassification, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "findEntitiesByProperty"; final String matchCriteriaParameterName = "matchCriteria"; final String matchPropertiesParameterName = "matchProperties"; final String asOfTimeParameter = "asOfTime"; final String guidParameter = "entityTypeGUID"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, entityTypeGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); repositoryValidator.validateMatchCriteria(repositoryName, matchCriteriaParameterName, matchPropertiesParameterName, matchCriteria, matchProperties, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; FunctionNotSupportedException functionNotSupportedException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<EntityDetail> results = metadataCollection.findEntitiesByProperty(userId, entityTypeGUID, matchProperties, matchCriteria, fromEntityElement, limitResultsByStatus, limitResultsByClassification, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueEntities(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } return validatedEntityListResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Return a list of entities that have the requested type of classifications attached. * * @param userId unique identifier for requesting user. * @param entityTypeGUID unique identifier for the type of entity requested. Null mans any type of entity. * @param classificationName name of the classification a null is not valid. * @param matchClassificationProperties list of classification properties used to narrow the search. * @param matchCriteria Enum defining how the properties should be matched to the classifications in the repository. * @param fromEntityElement the starting element number of the entities to return. * This is used when retrieving elements * beyond the first page of results. Zero means start from the first element. * @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param asOfTime Requests a historical query of the entity. Null means return the present values. * @param sequencingProperty String name of the entity property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @return a list of entities matching the supplied criteria null means no matching entities in the metadata * collection. * @throws InvalidParameterException a parameter is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws ClassificationErrorException the classification request is not known to the metadata collection. * @throws PropertyErrorException the properties specified are not valid for the requested type of * classification. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<EntityDetail> findEntitiesByClassification(String userId, String entityTypeGUID, String classificationName, InstanceProperties matchClassificationProperties, MatchCriteria matchCriteria, int fromEntityElement, List<InstanceStatus> limitResultsByStatus, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, ClassificationErrorException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "findEntitiesByClassification"; final String classificationParameterName = "classificationName"; final String entityTypeGUIDParameterName = "entityTypeGUID"; final String matchCriteriaParameterName = "matchCriteria"; final String matchPropertiesParameterName = "matchClassificationProperties"; final String asOfTimeParameter = "asOfTime"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, entityTypeGUIDParameterName, entityTypeGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); /* * Validate TypeDef */ if (entityTypeGUID != null) { TypeDef entityTypeDef = repositoryHelper.getTypeDef(repositoryName, entityTypeGUIDParameterName, entityTypeGUID, methodName); repositoryValidator.validateTypeDefForInstance(repositoryName, entityTypeGUIDParameterName, entityTypeDef, methodName); repositoryValidator.validateClassification(repositoryName, classificationParameterName, classificationName, entityTypeDef.getName(), methodName); } repositoryValidator.validateMatchCriteria(repositoryName, matchCriteriaParameterName, matchPropertiesParameterName, matchCriteria, matchClassificationProperties, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; FunctionNotSupportedException functionNotSupportedException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<EntityDetail> results = metadataCollection.findEntitiesByClassification(userId, entityTypeGUID, classificationName, matchClassificationProperties, matchCriteria, fromEntityElement, limitResultsByStatus, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueEntities(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } return validatedEntityListResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Return a list of entities whose string based property values match the search criteria. The * search criteria may include regex style wild cards. * * @param userId unique identifier for requesting user. * @param entityTypeGUID GUID of the type of entity to search for. Null means all types will * be searched (could be slow so not recommended). * @param searchCriteria String expression contained in any of the property values within the entities * of the supplied type. * @param fromEntityElement the starting element number of the entities to return. * This is used when retrieving elements * beyond the first page of results. Zero means start from the first element. * @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param limitResultsByClassification List of classifications that must be present on all returned entities. * @param asOfTime Requests a historical query of the entity. Null means return the present values. * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @return a list of entities matching the supplied criteria null means no matching entities in the metadata * collection. * @throws InvalidParameterException a parameter is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws PropertyErrorException the sequencing property specified is not valid for any of the requested types of * entity. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<EntityDetail> findEntitiesByPropertyValue(String userId, String entityTypeGUID, String searchCriteria, int fromEntityElement, List<InstanceStatus> limitResultsByStatus, List<String> limitResultsByClassification, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "findEntitiesByPropertyValue"; final String searchCriteriaParameterName = "searchCriteria"; final String asOfTimeParameter = "asOfTime"; final String guidParameter = "entityTypeGUID"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateSearchCriteria(repositoryName, searchCriteriaParameterName, searchCriteria, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, entityTypeGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; FunctionNotSupportedException functionNotSupportedException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<EntityDetail> results = metadataCollection.findEntitiesByPropertyValue(userId, entityTypeGUID, searchCriteria, fromEntityElement, limitResultsByStatus, limitResultsByClassification, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueEntities(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } return validatedEntityListResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Returns a boolean indicating if the relationship is stored in the metadata collection. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the relationship * @return relationship details if the relationship is found in the metadata collection; otherwise return null * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship isRelationshipKnown(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, UserNotAuthorizedException { final String methodName = "isRelationshipKnown"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ Relationship relationship = this.isRelationshipKnown(userId, guid); repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName); return relationship; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); return null; } /** * Return a requested relationship. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the relationship. * @return a relationship structure. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the metadata collection does not have a relationship with * the requested GUID stored. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship getRelationship(String userId, String guid) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, UserNotAuthorizedException { final String methodName = "getRelationship"; final String guidParameterName = "guid"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ RelationshipNotKnownException relationshipNotKnownException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ Relationship relationship = this.getRelationship(userId, guid); repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName); return relationship; } catch (RelationshipNotKnownException error) { relationshipNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedRelationshipNotKnownException(relationshipNotKnownException); return null; } /** * Return a historical version of a relationship. * * @param userId unique identifier for requesting user. * @param guid String unique identifier for the relationship. * @param asOfTime the time used to determine which version of the entity that is desired. * @return Relationship structure. * @throws InvalidParameterException the guid or date is null or the date is for a future time. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested entity instance is not known in the metadata collection * at the time requested. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship getRelationship(String userId, String guid, Date asOfTime) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getRelationship"; final String guidParameterName = "guid"; final String asOfTimeParameter = "asOfTime"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ RelationshipNotKnownException relationshipNotKnownException = null; FunctionNotSupportedException functionNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ Relationship relationship = this.getRelationship(userId, guid, asOfTime); repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName); return relationship; } catch (RelationshipNotKnownException error) { relationshipNotKnownException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedRelationshipNotKnownException(relationshipNotKnownException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } /** * Return a list of relationships that match the requested properties by the matching criteria. The results * can be broken into pages. * * @param userId unique identifier for requesting user. * @param relationshipTypeGUID unique identifier (guid) for the new relationship's type. * @param matchProperties list of properties used to narrow the search. * @param matchCriteria Enum defining how the properties should be matched to the relationships in the repository. * @param fromRelationshipElement the starting element number of the entities to return. * This is used when retrieving elements * beyond the first page of results. Zero means start from the first element. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result relationships that can be returned on this request. Zero means * unrestricted return results size. * @return a list of relationships. Null means no matching relationships. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws PropertyErrorException the properties specified are not valid for any of the requested types of * relationships. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<Relationship> findRelationshipsByProperty(String userId, String relationshipTypeGUID, InstanceProperties matchProperties, MatchCriteria matchCriteria, int fromRelationshipElement, List<InstanceStatus> limitResultsByStatus, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "findRelationshipsByProperty"; final String matchCriteriaParameterName = "matchCriteria"; final String matchPropertiesParameterName = "matchProperties"; final String asOfTimeParameter = "asOfTime"; final String guidParameter = "relationshipTypeGUID"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, relationshipTypeGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); repositoryValidator.validateMatchCriteria(repositoryName, matchCriteriaParameterName, matchPropertiesParameterName, matchCriteria, matchProperties, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, Relationship> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; FunctionNotSupportedException functionNotSupportedException = null; PropertyErrorException propertyErrorException = null; TypeErrorException typeErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<Relationship> results = metadataCollection.findRelationshipsByProperty(userId, relationshipTypeGUID, matchProperties, matchCriteria, fromRelationshipElement, limitResultsByStatus, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueRelationships(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); throwCapturedTypeErrorException(typeErrorException); return null; } return validatedRelationshipResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Return a list of relationships whose string based property values match the search criteria. The * search criteria may include regex style wild cards. * * @param userId unique identifier for requesting user. * @param relationshipTypeGUID GUID of the type of entity to search for. Null means all types will * be searched (could be slow so not recommended). * @param searchCriteria String expression contained in any of the property values within the entities * of the supplied type. * @param fromRelationshipElement Element number of the results to skip to when building the results list * to return. Zero means begin at the start of the results. This is used * to retrieve the results over a number of pages. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result relationships that can be returned on this request. Zero means * unrestricted return results size. * @return a list of relationships. Null means no matching relationships. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws TypeErrorException the type guid passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws PropertyErrorException there is a problem with one of the other parameters. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<Relationship> findRelationshipsByPropertyValue(String userId, String relationshipTypeGUID, String searchCriteria, int fromRelationshipElement, List<InstanceStatus> limitResultsByStatus, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "findRelationshipsByPropertyValue"; final String asOfTimeParameter = "asOfTime"; final String guidParameter = "relationshipTypeGUID"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, relationshipTypeGUID, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, Relationship> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; FunctionNotSupportedException functionNotSupportedException = null; PropertyErrorException propertyErrorException = null; TypeErrorException typeErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<Relationship> results = metadataCollection.findRelationshipsByPropertyValue(userId, relationshipTypeGUID, searchCriteria, fromRelationshipElement, limitResultsByStatus, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueRelationships(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } return validatedRelationshipResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /** * Return all of the relationships and intermediate entities that connect the startEntity with the endEntity. * * @param userId unique identifier for requesting user. * @param startEntityGUID The entity that is used to anchor the query. * @param endEntityGUID the other entity that defines the scope of the query. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @return InstanceGraph the sub-graph that represents the returned linked entities and their relationships. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by either the startEntityGUID or the endEntityGUID * is not found in the metadata collection. * @throws PropertyErrorException there is a problem with one of the other parameters. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public InstanceGraph getLinkingEntities(String userId, String startEntityGUID, String endEntityGUID, List<InstanceStatus> limitResultsByStatus, Date asOfTime) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, PropertyErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getLinkingEntities"; final String startEntityGUIDParameterName = "startEntityGUID"; final String endEntityGUIDParameterName = "entityGUID"; final String asOfTimeParameter = "asOfTime"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, startEntityGUIDParameterName, startEntityGUID, methodName); repositoryValidator.validateGUID(repositoryName, endEntityGUIDParameterName, endEntityGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedEntityResults = new HashMap<>(); Map<String, Relationship> combinedRelationshipResults = new HashMap<>(); EntityNotKnownException entityNotKnownException = null; FunctionNotSupportedException functionNotSupportedException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ InstanceGraph results = metadataCollection.getLinkingEntities(userId, startEntityGUID, endEntityGUID, limitResultsByStatus, asOfTime); /* * Step through the list of returned TypeDefs and consolidate. */ if (results != null) { combinedRelationshipResults = this.addUniqueRelationships(combinedRelationshipResults, results.getRelationships(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); combinedEntityResults = this.addUniqueEntities(combinedEntityResults, results.getEntities(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedInstanceGraphResults(repositoryName, combinedEntityResults, combinedRelationshipResults, userNotAuthorizedException, propertyErrorException, functionNotSupportedException, entityNotKnownException, repositoryErrorException, anotherException, methodName); } /** * Return the entities and relationships that radiate out from the supplied entity GUID. * The results are scoped both the instance type guids and the level. * * @param userId unique identifier for requesting user. * @param entityGUID the starting point of the query. * @param entityTypeGUIDs list of entity types to include in the query results. Null means include * all entities found, irrespective of their type. * @param relationshipTypeGUIDs list of relationship types to include in the query results. Null means include * all relationships found, irrespective of their type. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param limitResultsByClassification List of classifications that must be present on all returned entities. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @param level the number of the relationships out from the starting entity that the query will traverse to * gather results. * @return InstanceGraph the sub-graph that represents the returned linked entities and their relationships. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws TypeErrorException one or more of the type guids passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the entityGUID is not found in the metadata collection. * @throws PropertyErrorException there is a problem with one of the other parameters. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public InstanceGraph getEntityNeighborhood(String userId, String entityGUID, List<String> entityTypeGUIDs, List<String> relationshipTypeGUIDs, List<InstanceStatus> limitResultsByStatus, List<String> limitResultsByClassification, Date asOfTime, int level) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, EntityNotKnownException, PropertyErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getEntityNeighborhood"; final String entityGUIDParameterName = "entityGUID"; final String entityTypeGUIDParameterName = "entityTypeGUIDs"; final String relationshipTypeGUIDParameterName = "relationshipTypeGUIDs"; final String limitedResultsByClassificationParameterName = "limitResultsByClassification"; final String asOfTimeParameter = "asOfTime"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); if (entityTypeGUIDs != null) { for (String guid : entityTypeGUIDs) { repositoryValidator.validateTypeGUID(repositoryName, entityTypeGUIDParameterName, guid, methodName); } } if (relationshipTypeGUIDs != null) { for (String guid : relationshipTypeGUIDs) { repositoryValidator.validateTypeGUID(repositoryName, relationshipTypeGUIDParameterName, guid, methodName); } } if (limitResultsByClassification != null) { for (String classificationName : limitResultsByClassification) { repositoryValidator.validateClassificationName(repositoryName, limitedResultsByClassificationParameterName, classificationName, methodName); } } /* * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedEntityResults = new HashMap<>(); Map<String, Relationship> combinedRelationshipResults = new HashMap<>(); EntityNotKnownException entityNotKnownException = null; FunctionNotSupportedException functionNotSupportedException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ InstanceGraph results = metadataCollection.getEntityNeighborhood(userId, entityGUID, entityTypeGUIDs, relationshipTypeGUIDs, limitResultsByStatus, limitResultsByClassification, asOfTime, level); /* * Step through the list of returned TypeDefs and consolidate. */ if (results != null) { combinedRelationshipResults = this.addUniqueRelationships(combinedRelationshipResults, results.getRelationships(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); combinedEntityResults = this.addUniqueEntities(combinedEntityResults, results.getEntities(), cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } return validatedInstanceGraphResults(repositoryName, combinedEntityResults, combinedRelationshipResults, userNotAuthorizedException, propertyErrorException, functionNotSupportedException, entityNotKnownException, repositoryErrorException, anotherException, methodName); } /** * Return the list of entities that are of the types listed in instanceTypes and are connected, either directly or * indirectly to the entity identified by startEntityGUID. * * @param userId unique identifier for requesting user. * @param startEntityGUID unique identifier of the starting entity * @param instanceTypes list of types to search for. Null means any type. * @param fromEntityElement starting element for results list. Used in paging. Zero means first element. * @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible * to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all * status values. * @param limitResultsByClassification List of classifications that must be present on all returned entities. * @param asOfTime Requests a historical query of the relationships for the entity. Null means return the * present values. * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @return list of entities either directly or indirectly connected to the start entity * @throws InvalidParameterException one of the parameters is invalid or null. * @throws TypeErrorException one or more of the type guids passed on the request is not known by the * metadata collection. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the startEntityGUID * is not found in the metadata collection. * @throws PropertyErrorException the sequencing property specified is not valid for any of the requested types of * entity. * @throws PagingErrorException the paging/sequencing parameters are set up incorrectly. * @throws FunctionNotSupportedException the repository does not support the asOfTime parameter. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public List<EntityDetail> getRelatedEntities(String userId, String startEntityGUID, List<String> instanceTypes, int fromEntityElement, List<InstanceStatus> limitResultsByStatus, List<String> limitResultsByClassification, Date asOfTime, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize) throws InvalidParameterException, TypeErrorException, RepositoryErrorException, EntityNotKnownException, PropertyErrorException, PagingErrorException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "getRelatedEntities"; final String entityGUIDParameterName = "startEntityGUID"; final String typeGUIDParameterName = "instanceTypes"; final String asOfTimeParameter = "asOfTime"; final String pageSizeParameter = "pageSize"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, startEntityGUID, methodName); repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName); repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName); if (instanceTypes != null) { for (String guid : instanceTypes) { repositoryValidator.validateTypeGUID(repositoryName, typeGUIDParameterName, guid, methodName); } } /* * Perform operation * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Search results need to come from all members of the cohort. * They need to be combined and then duplicates removed to create the final list of results. * Some repositories may produce exceptions. These exceptions are saved and one selected to * be returned if there are no results from any repository. */ Map<String, EntityDetail> combinedResults = new HashMap<>(); InvalidParameterException invalidParameterException = null; EntityNotKnownException entityNotKnownException = null; FunctionNotSupportedException functionNotSupportedException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request */ List<EntityDetail> results = metadataCollection.getRelatedEntities(userId, startEntityGUID, instanceTypes, fromEntityElement, limitResultsByStatus, limitResultsByClassification, asOfTime, sequencingProperty, sequencingOrder, pageSize); /* * Step through the list of returned TypeDefs and remove duplicates. */ combinedResults = this.addUniqueEntities(combinedResults, results, cohortConnector.getServerName(), cohortConnector.getMetadataCollectionId(), methodName); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } if (combinedResults.isEmpty()) { throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); throwCapturedEntityNotKnownException(entityNotKnownException); return null; } return validatedEntityListResults(repositoryName, combinedResults, sequencingProperty, sequencingOrder, pageSize, methodName); } /* ====================================================== * Group 4: Maintaining entity and relationship instances */ /** * Create a new entity and put it in the requested state. The new entity is returned. * * @param userId unique identifier for requesting user. * @param entityTypeGUID unique identifier (guid) for the new entity's type. * @param initialProperties initial list of properties for the new entity null means no properties. * @param initialClassifications initial list of classifications for the new entity null means no classifications. * @param initialStatus initial status typically DRAFT, PREPARED or ACTIVE. * @return EntityDetail showing the new header plus the requested properties and classifications. The entity will * not have any relationships at this stage. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeErrorException the requested type is not known, or not supported in the metadata repository * hosting the metadata collection. * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this entity's type. * @throws ClassificationErrorException one or more of the requested classifications are either not known or * not defined for this entity type. * @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support * the requested status. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail addEntity(String userId, String entityTypeGUID, InstanceProperties initialProperties, List<Classification> initialClassifications, InstanceStatus initialStatus) throws InvalidParameterException, RepositoryErrorException, TypeErrorException, PropertyErrorException, ClassificationErrorException, StatusNotSupportedException, UserNotAuthorizedException { final String methodName = "addEntity"; final String entityGUIDParameterName = "entityTypeGUID"; final String propertiesParameterName = "initialProperties"; final String classificationsParameterName = "initialClassifications"; final String initialStatusParameterName = "initialStatus"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeGUID(repositoryName, entityGUIDParameterName, entityTypeGUID, methodName); TypeDef typeDef = repositoryHelper.getTypeDef(repositoryName, entityGUIDParameterName, entityTypeGUID, methodName); repositoryValidator.validateTypeDefForInstance(repositoryName, entityGUIDParameterName, typeDef, methodName); repositoryValidator.validateClassificationList(repositoryName, classificationsParameterName, initialClassifications, typeDef.getName(), methodName); repositoryValidator.validatePropertiesForType(repositoryName, propertiesParameterName, typeDef, initialProperties, methodName); repositoryValidator.validateInstanceStatus(repositoryName, initialStatusParameterName, initialStatus, typeDef, methodName); /* * Validation complete, ok to create new instance * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Create requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; ClassificationErrorException classificationErrorException = null; StatusNotSupportedException statusNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.addEntity(userId, entityTypeGUID, initialProperties, initialClassifications, initialStatus); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (ClassificationErrorException error) { classificationErrorException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (StatusNotSupportedException error) { statusNotSupportedException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedClassificationErrorException(classificationErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedStatusNotSupportedException(statusNotSupportedException); throwCapturedInvalidParameterException(invalidParameterException); return null; } /** * Create an entity proxy in the metadata collection. This is used to store relationships that span metadata * repositories. * * @param userId unique identifier for requesting user. * @param entityProxy details of entity to add. * @throws FunctionNotSupportedException the repository does not support entity proxies as first class elements. */ public void addEntityProxy(String userId, EntityProxy entityProxy) throws FunctionNotSupportedException { final String methodName = "addEntityProxy"; throwNotEnterpriseFunction(methodName); } /** * Update the status for a specific entity. * * @param userId unique identifier for requesting user. * @param entityGUID unique identifier (guid) for the requested entity. * @param newStatus new InstanceStatus for the entity. * @return EntityDetail showing the current entity header, properties and classifications. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection. * @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support * the requested status. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail updateEntityStatus(String userId, String entityGUID, InstanceStatus newStatus) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, StatusNotSupportedException, UserNotAuthorizedException { final String methodName = "updateEntityStatus"; final String entityGUIDParameterName = "entityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().updateEntityStatus(userId, entityGUID, newStatus); } /** * Update selected properties in an entity. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier (guid) for the entity. * @param properties a list of properties to change. * @return EntityDetail showing the resulting entity header, properties and classifications. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this entity's type * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail updateEntityProperties(String userId, String entityGUID, InstanceProperties properties) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, PropertyErrorException, UserNotAuthorizedException { final String methodName = "updateEntityProperties"; final String entityGUIDParameterName = "entityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().updateEntityProperties(userId, entityGUID, properties); } /** * Undo the last update to an entity and return the previous content. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier (guid) for the entity. * @return EntityDetail showing the resulting entity header, properties and classifications. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection. * @throws FunctionNotSupportedException the repository does not support undo. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail undoEntityUpdate(String userId, String entityGUID) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "undoEntityUpdate"; final String entityGUIDParameterName = "entityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().undoEntityUpdate(userId, entityGUID); } /** * Delete an entity. The entity is soft deleted. This means it is still in the graph but it is no longer returned * on queries. All relationships to the entity are also soft-deleted and will no longer be usable. * To completely eliminate the entity from the graph requires a call to the purgeEntity() method after the delete call. * The restoreEntity() method will switch an entity back to Active status to restore the entity to normal use. * * @param userId unique identifier for requesting user. * @param typeDefGUID unique identifier of the type of the entity to delete. * @param typeDefName unique name of the type of the entity to delete. * @param obsoleteEntityGUID String unique identifier (guid) for the entity * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection. * @throws FunctionNotSupportedException the metadata repository hosting the metadata collection does not support * soft-deletes (use purgeEntity() to remove the entity permanently). * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail deleteEntity(String userId, String typeDefGUID, String typeDefName, String obsoleteEntityGUID) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "deleteEntity"; final String typeDefGUIDParameterName = "typeDefGUID"; final String typeDefNameParameterName = "typeDefName"; final String entityGUIDParameterName = "obsoleteEntityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeDefIds(repositoryName, typeDefGUIDParameterName, typeDefNameParameterName, typeDefGUID, typeDefName, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, obsoleteEntityGUID, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, obsoleteEntityGUID); repositoryValidator.validateEntityFromStore(repositoryName, obsoleteEntityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, obsoleteEntityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().deleteEntity(userId, typeDefGUID, typeDefName, obsoleteEntityGUID); } /** * Permanently removes a deleted entity from the metadata collection. This request can not be undone. * * @param userId unique identifier for requesting user. * @param typeDefGUID unique identifier of the type of the entity to purge. * @param typeDefName unique name of the type of the entity to purge. * @param deletedEntityGUID String unique identifier (guid) for the entity. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws EntityNotDeletedException the entity is not in DELETED status and so can not be purged * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public void purgeEntity(String userId, String typeDefGUID, String typeDefName, String deletedEntityGUID) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, EntityNotDeletedException, UserNotAuthorizedException { final String methodName = "purgeEntity"; final String typeDefGUIDParameterName = "typeDefGUID"; final String typeDefNameParameterName = "typeDefName"; final String entityGUIDParameterName = "deletedEntityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeDefIds(repositoryName, typeDefGUIDParameterName, typeDefNameParameterName, typeDefGUID, typeDefName, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, deletedEntityGUID, methodName); /* * Validation complete, ok to purge the instance * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Purge requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; EntityNotKnownException entityNotKnownException = null; EntityNotDeletedException entityNotDeletedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ metadataCollection.purgeEntity(userId, typeDefGUID, typeDefName, deletedEntityGUID); return; } catch (InvalidParameterException error) { invalidParameterException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (EntityNotDeletedException error) { entityNotDeletedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedEntityNotDeletedException(entityNotDeletedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedEntityNotKnownException(entityNotKnownException); throwCapturedInvalidParameterException(invalidParameterException); return; } /** * Restore the requested entity to the state it was before it was deleted. * * @param userId unique identifier for requesting user. * @param deletedEntityGUID String unique identifier (guid) for the entity. * @return EntityDetail showing the restored entity header, properties and classifications. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws EntityNotDeletedException the entity is currently not in DELETED status and so it can not be restored * @throws FunctionNotSupportedException the repository does not support soft-deletes. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail restoreEntity(String userId, String deletedEntityGUID) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, EntityNotDeletedException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "restoreEntity"; final String entityGUIDParameterName = "deletedEntityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, deletedEntityGUID, methodName); /* * Locate entity */ EntityDetail entity = this.isEntityKnown(userId, deletedEntityGUID); repositoryValidator.validateEntityFromStore(repositoryName, deletedEntityGUID, entity, methodName); repositoryValidator.validateEntityIsDeleted(repositoryName, entity, methodName); /* * Validation is complete. It is ok to restore the entity. * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Restore requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; EntityNotKnownException entityNotKnownException = null; EntityNotDeletedException entityNotDeletedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; FunctionNotSupportedException functionNotSupportedException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.restoreEntity(userId, deletedEntityGUID); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (EntityNotDeletedException error) { entityNotDeletedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedEntityNotDeletedException(entityNotDeletedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedEntityNotKnownException(entityNotKnownException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } /** * Add the requested classification to a specific entity. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier (guid) for the entity. * @param classificationName String name for the classification. * @param classificationProperties list of properties to set in the classification. * @return EntityDetail showing the resulting entity header, properties and classifications. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws ClassificationErrorException the requested classification is either not known or not valid * for the entity. * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this classification type * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail classifyEntity(String userId, String entityGUID, String classificationName, InstanceProperties classificationProperties) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, ClassificationErrorException, PropertyErrorException, UserNotAuthorizedException { final String methodName = "classifyEntity"; final String entityGUIDParameterName = "entityGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().classifyEntity(userId, entityGUID, classificationName, classificationProperties); } /** * Remove a specific classification from an entity. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier (guid) for the entity. * @param classificationName String name for the classification. * @return EntityDetail showing the resulting entity header, properties and classifications. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws ClassificationErrorException the requested classification is not set on the entity. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail declassifyEntity(String userId, String entityGUID, String classificationName) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, ClassificationErrorException, UserNotAuthorizedException { final String methodName = "declassifyEntity"; final String entityGUIDParameterName = "entityGUID"; final String classificationParameterName = "classificationName"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); repositoryValidator.validateClassificationName(repositoryName, classificationParameterName, classificationName, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().declassifyEntity(userId, entityGUID, classificationName); } /** * Update one or more properties in one of an entity's classifications. * * @param userId unique identifier for requesting user. * @param entityGUID String unique identifier (guid) for the entity. * @param classificationName String name for the classification. * @param properties list of properties for the classification. * @return EntityDetail showing the resulting entity header, properties and classifications. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection * @throws ClassificationErrorException the requested classification is not attached to the classification. * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this classification type * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public EntityDetail updateEntityClassification(String userId, String entityGUID, String classificationName, InstanceProperties properties) throws InvalidParameterException, RepositoryErrorException, EntityNotKnownException, ClassificationErrorException, PropertyErrorException, UserNotAuthorizedException { final String methodName = "updateEntityClassification"; final String entityGUIDParameterName = "entityGUID"; final String classificationParameterName = "classificationName"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName); repositoryValidator.validateClassificationName(repositoryName, classificationParameterName, classificationName, methodName); /* * Locate entity */ EntitySummary entity = this.getEntitySummary(userId, entityGUID); repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().updateEntityClassification(userId, entityGUID, classificationName, properties); } /** * Add a new relationship between two entities to the metadata collection. * * @param userId unique identifier for requesting user. * @param relationshipTypeGUID unique identifier (guid) for the new relationship's type. * @param initialProperties initial list of properties for the new entity, null means no properties. * @param entityOneGUID the unique identifier of one of the entities that the relationship is connecting together. * @param entityTwoGUID the unique identifier of the other entity that the relationship is connecting together. * @param initialStatus initial status. This is typically DRAFT, PREPARED or ACTIVE. * @return Relationship structure with the new header, requested entities and properties. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws TypeErrorException the requested type is not known, or not supported in the metadata repository * hosting the metadata collection. * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this relationship's type. * @throws EntityNotKnownException one of the requested entities is not known in the metadata collection. * @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support * the requested status. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship addRelationship(String userId, String relationshipTypeGUID, InstanceProperties initialProperties, String entityOneGUID, String entityTwoGUID, InstanceStatus initialStatus) throws InvalidParameterException, RepositoryErrorException, TypeErrorException, PropertyErrorException, EntityNotKnownException, StatusNotSupportedException, UserNotAuthorizedException { final String methodName = "addRelationship"; final String guidParameterName = "relationshipTypeGUID"; final String propertiesParameterName = "initialProperties"; final String initialStatusParameterName = "initialStatus"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateTypeGUID(repositoryName, guidParameterName, relationshipTypeGUID, methodName); TypeDef typeDef = repositoryHelper.getTypeDef(repositoryName, guidParameterName, relationshipTypeGUID, methodName); repositoryValidator.validateTypeDefForInstance(repositoryName, guidParameterName, typeDef, methodName); repositoryValidator.validatePropertiesForType(repositoryName, propertiesParameterName, typeDef, initialProperties, methodName); repositoryValidator.validateInstanceStatus(repositoryName, initialStatusParameterName, initialStatus, typeDef, methodName); /* * Validation complete, ok to create new instance * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Create requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; EntityNotKnownException entityNotKnownException = null; TypeErrorException typeErrorException = null; PropertyErrorException propertyErrorException = null; StatusNotSupportedException statusNotSupportedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.addRelationship(userId, relationshipTypeGUID, initialProperties, entityOneGUID, entityTwoGUID, initialStatus); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (EntityNotKnownException error) { entityNotKnownException = error; } catch (TypeErrorException error) { typeErrorException = error; } catch (StatusNotSupportedException error) { statusNotSupportedException = error; } catch (PropertyErrorException error) { propertyErrorException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedEntityNotKnownException(entityNotKnownException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedTypeErrorException(typeErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedStatusNotSupportedException(statusNotSupportedException); throwCapturedInvalidParameterException(invalidParameterException); return null; } /** * Update the status of a specific relationship. * * @param userId unique identifier for requesting user. * @param relationshipGUID String unique identifier (guid) for the relationship. * @param newStatus new InstanceStatus for the relationship. * @return Resulting relationship structure with the new status set. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support * the requested status. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship updateRelationshipStatus(String userId, String relationshipGUID, InstanceStatus newStatus) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, StatusNotSupportedException, UserNotAuthorizedException { final String methodName = "updateRelationshipStatus"; final String guidParameterName = "relationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, relationshipGUID); repositoryValidator.validateInstanceType(repositoryName, relationship); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, relationshipGUID, relationship.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().updateRelationshipStatus(userId, relationshipGUID, newStatus); } /** * Update the properties of a specific relationship. * * @param userId unique identifier for requesting user. * @param relationshipGUID String unique identifier (guid) for the relationship. * @param properties list of the properties to update. * @return Resulting relationship structure with the new properties set. * @throws InvalidParameterException one of the parameters is invalid or null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws PropertyErrorException one or more of the requested properties are not defined, or have different * characteristics in the TypeDef for this relationship's type. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship updateRelationshipProperties(String userId, String relationshipGUID, InstanceProperties properties) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, PropertyErrorException, UserNotAuthorizedException { final String methodName = "updateRelationshipProperties"; final String guidParameterName = "relationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, relationshipGUID); repositoryValidator.validateInstanceType(repositoryName, relationship); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, relationshipGUID, relationship.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().updateRelationshipProperties(userId, relationshipGUID, properties); } /** * Undo the latest change to a relationship (either a change of properties or status). * * @param userId unique identifier for requesting user. * @param relationshipGUID String unique identifier (guid) for the relationship. * @return Relationship structure with the new current header, requested entities and properties. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws FunctionNotSupportedException the repository does not support undo. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship undoRelationshipUpdate(String userId, String relationshipGUID) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "undoRelationshipUpdate"; final String guidParameterName = "relationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, relationshipGUID); repositoryValidator.validateInstanceType(repositoryName, relationship); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, relationshipGUID, relationship.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } return homeRepositoryConnector.getMetadataCollection().undoRelationshipUpdate(userId, relationshipGUID); } /** * Delete a specific relationship. This is a soft-delete which means the relationship's status is updated to * DELETED and it is no longer available for queries. To remove the relationship permanently from the * metadata collection, use purgeRelationship(). * * @param userId unique identifier for requesting user. * @param typeDefGUID unique identifier of the type of the relationship to delete. * @param typeDefName unique name of the type of the relationship to delete. * @param obsoleteRelationshipGUID String unique identifier (guid) for the relationship. * @return delete relationship * @throws InvalidParameterException one of the parameters is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws FunctionNotSupportedException the metadata repository hosting the metadata collection does not support * soft-deletes. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship deleteRelationship(String userId, String typeDefGUID, String typeDefName, String obsoleteRelationshipGUID) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "deleteRelationship"; final String guidParameterName = "typeDefGUID"; final String nameParameterName = "typeDefName"; final String relationshipParameterName = "obsoleteRelationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, relationshipParameterName, obsoleteRelationshipGUID, methodName); repositoryValidator.validateTypeDefIds(repositoryName, guidParameterName, nameParameterName, typeDefGUID, typeDefName, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, obsoleteRelationshipGUID); repositoryValidator.validateTypeForInstanceDelete(repositoryName, typeDefGUID, typeDefName, relationship, methodName); /* * Validation complete, ok to make changes */ OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName); if (homeRepositoryConnector == null) { OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, obsoleteRelationshipGUID, relationship.getMetadataCollectionId()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } /* * A delete is a soft-delete that updates the status to DELETED. */ return homeRepositoryConnector.getMetadataCollection().deleteRelationship(userId, typeDefGUID, typeDefName, obsoleteRelationshipGUID); } /** * Permanently delete the relationship from the repository. There is no means to undo this request. * * @param userId unique identifier for requesting user. * @param typeDefGUID unique identifier of the type of the relationship to purge. * @param typeDefName unique name of the type of the relationship to purge. * @param deletedRelationshipGUID String unique identifier (guid) for the relationship. * @throws InvalidParameterException one of the parameters is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws RelationshipNotDeletedException the requested relationship is not in DELETED status. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public void purgeRelationship(String userId, String typeDefGUID, String typeDefName, String deletedRelationshipGUID) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, RelationshipNotDeletedException, UserNotAuthorizedException { final String methodName = "purgeRelationship"; final String guidParameterName = "typeDefGUID"; final String nameParameterName = "typeDefName"; final String relationshipParameterName = "deletedRelationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, relationshipParameterName, deletedRelationshipGUID, methodName); repositoryValidator.validateTypeDefIds(repositoryName, guidParameterName, nameParameterName, typeDefGUID, typeDefName, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, deletedRelationshipGUID); repositoryValidator.validateTypeForInstanceDelete(repositoryName, typeDefGUID, typeDefName, relationship, methodName); repositoryValidator.validateRelationshipIsDeleted(repositoryName, relationship, methodName); /* * Validation is complete. It is ok to purge the relationship. * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Restore requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; RelationshipNotKnownException relationshipNotKnownException = null; RelationshipNotDeletedException relationshipNotDeletedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ metadataCollection.purgeRelationship(userId, typeDefGUID, typeDefName, deletedRelationshipGUID); return; } catch (InvalidParameterException error) { invalidParameterException = error; } catch (RelationshipNotKnownException error) { relationshipNotKnownException = error; } catch (RelationshipNotDeletedException error) { relationshipNotDeletedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRelationshipNotDeletedException(relationshipNotDeletedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedRelationshipNotKnownException(relationshipNotKnownException); throwCapturedInvalidParameterException(invalidParameterException); return; } /** * Restore a deleted relationship into the metadata collection. The new status will be ACTIVE and the * restored details of the relationship are returned to the caller. * * @param userId unique identifier for requesting user. * @param deletedRelationshipGUID String unique identifier (guid) for the relationship. * @return Relationship structure with the restored header, requested entities and properties. * @throws InvalidParameterException the guid is null. * @throws RepositoryErrorException there is a problem communicating with the metadata repository where * the metadata collection is stored. * @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection. * @throws RelationshipNotDeletedException the requested relationship is not in DELETED status. * @throws FunctionNotSupportedException the repository does not support soft-deletes. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ public Relationship restoreRelationship(String userId, String deletedRelationshipGUID) throws InvalidParameterException, RepositoryErrorException, RelationshipNotKnownException, RelationshipNotDeletedException, FunctionNotSupportedException, UserNotAuthorizedException { final String methodName = "restoreRelationship"; final String guidParameterName = "deletedRelationshipGUID"; /* * Validate parameters */ this.validateRepositoryConnector(methodName); parentConnector.validateRepositoryIsActive(methodName); repositoryValidator.validateUserId(repositoryName, userId, methodName); repositoryValidator.validateGUID(repositoryName, guidParameterName, deletedRelationshipGUID, methodName); /* * Locate relationship */ Relationship relationship = this.getRelationship(userId, deletedRelationshipGUID); repositoryValidator.validateRelationshipIsDeleted(repositoryName, relationship, methodName); /* * Validation is complete. It is ok to restore the relationship. * * The list of cohort connectors are retrieved for each request to ensure that any changes in * the shape of the cohort are reflected immediately. */ List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName); /* * Ready to process the request. Restore requests occur in the first repository that accepts the call. * Some repositories may produce exceptions. These exceptions are saved and will be returned if * there are no positive results from any repository. */ InvalidParameterException invalidParameterException = null; RelationshipNotKnownException relationshipNotKnownException = null; RelationshipNotDeletedException relationshipNotDeletedException = null; UserNotAuthorizedException userNotAuthorizedException = null; RepositoryErrorException repositoryErrorException = null; FunctionNotSupportedException functionNotSupportedException = null; Throwable anotherException = null; /* * Loop through the metadata collections extracting the typedefs from each repository. */ for (OMRSRepositoryConnector cohortConnector : cohortConnectors) { if (cohortConnector != null) { OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection(); validateMetadataCollection(metadataCollection, methodName); try { /* * Issue the request and return if it succeeds */ return metadataCollection.restoreRelationship(userId, deletedRelationshipGUID); } catch (InvalidParameterException error) { invalidParameterException = error; } catch (FunctionNotSupportedException error) { functionNotSupportedException = error; } catch (RelationshipNotKnownException error) { relationshipNotKnownException = error; } catch (RelationshipNotDeletedException error) { relationshipNotDeletedException = error; } catch (RepositoryErrorException error) { repositoryErrorException = error; } catch (UserNotAuthorizedException error) { userNotAuthorizedException = error; } catch (Throwable error) { anotherException = error; } } } throwCapturedRelationshipNotDeletedException(relationshipNotDeletedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedThrowableException(anotherException, methodName); throwCapturedRelationshipNotKnownException(relationshipNotKnownException); throwCapturedInvalidParameterException(invalidParameterException); throwCapturedFunctionNotSupportedException(functionNotSupportedException); return null; } /* ====================================================================== * Group 5: Change the control information in entities and relationships */ /** * Change the guid of an existing entity to a new value. This is used if two different * entities are discovered to have the same guid. This is extremely unlikely but not impossible so * the open metadata protocol has provision for this. * * @param userId unique identifier for requesting user. * @param typeDefGUID the guid of the TypeDef for the entity used to verify the entity identity. * @param typeDefName the name of the TypeDef for the entity used to verify the entity identity. * @param entityGUID the existing identifier for the entity. * @param newEntityGUID new unique identifier for the entity. * @return entity new values for this entity, including the new guid. * @throws FunctionNotSupportedException the repository does not support the re-identification of instances. */ public EntityDetail reIdentifyEntity(String userId, String typeDefGUID, String typeDefName, String entityGUID, String newEntityGUID) throws FunctionNotSupportedException { final String methodName = "reIdentifyEntity()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the type of an existing entity. Typically this action is taken to move an entity's * type to either a super type (so the subtype can be deleted) or a new subtype (so additional properties can be * added.) However, the type can be changed to any compatible type and the properties adjusted. * * @param userId unique identifier for requesting user. * @param entityGUID the unique identifier for the entity to change. * @param currentTypeDefSummary the current details of the TypeDef for the entity used to verify the entity identity * @param newTypeDefSummary details of this entity's new TypeDef. * @return entity new values for this entity, including the new type information. * @throws FunctionNotSupportedException the repository does not support the re-typing of instances. */ public EntityDetail reTypeEntity(String userId, String entityGUID, TypeDefSummary currentTypeDefSummary, TypeDefSummary newTypeDefSummary) throws FunctionNotSupportedException { final String methodName = "reTypeEntity()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the home of an existing entity. This action is taken for example, if the original home repository * becomes permanently unavailable, or if the user community updating this entity move to working * from a different repository in the open metadata repository cohort. * * @param userId unique identifier for requesting user. * @param entityGUID the unique identifier for the entity to change. * @param typeDefGUID the guid of the TypeDef for the entity used to verify the entity identity. * @param typeDefName the name of the TypeDef for the entity used to verify the entity identity. * @param homeMetadataCollectionId the existing identifier for this entity's home. * @param newHomeMetadataCollectionId unique identifier for the new home metadata collection/repository. * @return entity new values for this entity, including the new home information. * @throws FunctionNotSupportedException the repository does not support the re-homing of instances. */ public EntityDetail reHomeEntity(String userId, String entityGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId, String newHomeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "reHomeEntity()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the guid of an existing relationship. This is used if two different * relationships are discovered to have the same guid. This is extremely unlikely but not impossible so * the open metadata protocol has provision for this. * * @param userId unique identifier for requesting user. * @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity. * @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity. * @param relationshipGUID the existing identifier for the relationship. * @param newRelationshipGUID the new unique identifier for the relationship. * @return relationship new values for this relationship, including the new guid. * @throws FunctionNotSupportedException the repository does not support the re-identification of instances. */ public Relationship reIdentifyRelationship(String userId, String typeDefGUID, String typeDefName, String relationshipGUID, String newRelationshipGUID) throws FunctionNotSupportedException { final String methodName = "reIdentifyRelationship()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the type of an existing relationship. Typically this action is taken to move a relationship's * type to either a super type (so the subtype can be deleted) or a new subtype (so additional properties can be * added.) However, the type can be changed to any compatible type. * * @param userId unique identifier for requesting user. * @param relationshipGUID the unique identifier for the relationship. * @param currentTypeDefSummary the details of the TypeDef for the relationship used to verify the relationship identity. * @param newTypeDefSummary details of this relationship's new TypeDef. * @return relationship new values for this relationship, including the new type information. * @throws FunctionNotSupportedException the repository does not support the re-typing of instances. */ public Relationship reTypeRelationship(String userId, String relationshipGUID, TypeDefSummary currentTypeDefSummary, TypeDefSummary newTypeDefSummary) throws FunctionNotSupportedException { final String methodName = "reTypeRelationship()"; throwNotEnterpriseFunction(methodName); return null; } /** * Change the home of an existing relationship. This action is taken for example, if the original home repository * becomes permanently unavailable, or if the user community updating this relationship move to working * from a different repository in the open metadata repository cohort. * * @param userId unique identifier for requesting user. * @param relationshipGUID the unique identifier for the relationship. * @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity. * @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity. * @param homeMetadataCollectionId the existing identifier for this relationship's home. * @param newHomeMetadataCollectionId unique identifier for the new home metadata collection/repository. * @return relationship new values for this relationship, including the new home information. * @throws FunctionNotSupportedException the repository does not support the re-homing of instances. */ public Relationship reHomeRelationship(String userId, String relationshipGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId, String newHomeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "reHomeRelationship()"; throwNotEnterpriseFunction(methodName); return null; } /* ====================================================================== * Group 6: Local house-keeping of reference metadata instances * These methods are not supported by the EnterpriseOMRSRepositoryConnector */ /** * Save the entity as a reference copy. The id of the home metadata collection is already set up in the * entity. * * @param userId unique identifier for requesting server. * @param entity details of the entity to save * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void saveEntityReferenceCopy(String userId, EntityDetail entity) throws FunctionNotSupportedException { final String methodName = "saveEntityReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /** * Remove a reference copy of the the entity from the local repository. This method can be used to * remove reference copies from the local cohort, repositories that have left the cohort, * or entities that have come from open metadata archives. * * @param userId unique identifier for requesting server. * @param entityGUID the unique identifier for the entity. * @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity. * @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity. * @param homeMetadataCollectionId identifier of the metadata collection that is the home to this entity. * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void purgeEntityReferenceCopy(String userId, String entityGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "purgeEntityReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /** * The local repository has requested that the repository that hosts the home metadata collection for the * specified entity sends out the details of this entity so the local repository can create a reference copy. * * @param userId unique identifier for requesting server. * @param entityGUID unique identifier of requested entity * @param typeDefGUID unique identifier of requested entity's TypeDef * @param typeDefName unique name of requested entity's TypeDef * @param homeMetadataCollectionId identifier of the metadata collection that is the home to this entity. * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void refreshEntityReferenceCopy(String userId, String entityGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "refreshEntityReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /** * Save the relationship as a reference copy. The id of the home metadata collection is already set up in the * relationship. * * @param userId unique identifier for requesting server. * @param relationship relationship to save * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void saveRelationshipReferenceCopy(String userId, Relationship relationship) throws FunctionNotSupportedException { final String methodName = "saveRelationshipReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /** * Remove the reference copy of the relationship from the local repository. This method can be used to * remove reference copies from the local cohort, repositories that have left the cohort, * or relationships that have come from open metadata archives. * * @param userId unique identifier for requesting server. * @param relationshipGUID the unique identifier for the relationship. * @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity. * @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity. * @param homeMetadataCollectionId unique identifier for the home repository for this relationship. * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void purgeRelationshipReferenceCopy(String userId, String relationshipGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "purgeRelationshipReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /** * The local repository has requested that the repository that hosts the home metadata collection for the * specified relationship sends out the details of this relationship so the local repository can create a * reference copy. * * @param userId unique identifier for requesting user. * @param relationshipGUID unique identifier of the relationship * @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity. * @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity. * @param homeMetadataCollectionId unique identifier for the home repository for this relationship. * @throws FunctionNotSupportedException the repository does not support reference copies of instances. */ public void refreshRelationshipReferenceCopy(String userId, String relationshipGUID, String typeDefGUID, String typeDefName, String homeMetadataCollectionId) throws FunctionNotSupportedException { final String methodName = "refreshRelationshipReferenceCopy()"; throwNotEnterpriseFunction(methodName); } /* * ================================================= * Private validation and processing methods */ /** * Build a combined list of AttributeTypeDefs. * * @param accumulatedResults current accumulated AttributeTypeDefs * @param newResults newly received AttributeTypeDefs * @param serverName name of the server that provided the new AttributeTypeDefs * @param metadataCollectionId unique identifier for metadata collection that provided the new AttributeTypeDefs * @param methodName method name that returned the new AttributeTypeDefs * @return combined results */ private Map<String, AttributeTypeDef> addUniqueAttributeTypeDefs(Map<String, AttributeTypeDef> accumulatedResults, List<AttributeTypeDef> newResults, String serverName, String metadataCollectionId, String methodName) { Map<String, AttributeTypeDef> combinedResults = new HashMap<>(accumulatedResults); if (newResults != null) { for (AttributeTypeDef attributeTypeDef : newResults) { if (attributeTypeDef != null) { combinedResults = addUniqueAttributeTypeDef(combinedResults, attributeTypeDef, serverName, metadataCollectionId, methodName); } } } return combinedResults; } /** * Build a combined list of AttributeTypeDefs. * * @param accumulatedResults current accumulated AttributeTypeDefs * @param attributeTypeDef newly received AttributeTypeDef * @param serverName name of the server that provided the new AttributeTypeDef * @param metadataCollectionId unique identifier for metadata collection that provided the new AttributeTypeDef * @param methodName method name that returned the new AttributeTypeDef * @return combined results */ private Map<String, AttributeTypeDef> addUniqueAttributeTypeDef(Map<String, AttributeTypeDef> accumulatedResults, AttributeTypeDef attributeTypeDef, String serverName, String metadataCollectionId, String methodName) { Map<String, AttributeTypeDef> combinedResults = new HashMap<>(accumulatedResults); if (attributeTypeDef != null) { AttributeTypeDef existingAttributeTypeDef = combinedResults.put(attributeTypeDef.getGUID(), attributeTypeDef); // todo validate that existing attributeTypeDef and the new one are copies } return combinedResults; } /** * Build a combined list of TypeDefs. * * @param accumulatedResults current accumulated TypeDefs * @param returnedTypeDefs newly received TypeDefs * @param serverName name of the server that provided the new TypeDefs * @param metadataCollectionId unique identifier for metadata collection that provided the new TypeDefs * @param methodName method name that returned the new TypeDefs * @return combined results */ private Map<String, TypeDef> addUniqueTypeDefs(Map<String, TypeDef> accumulatedResults, List<TypeDef> returnedTypeDefs, String serverName, String metadataCollectionId, String methodName) { Map<String, TypeDef> combinedResults = new HashMap<>(accumulatedResults); if (returnedTypeDefs != null) { for (TypeDef returnedTypeDef : returnedTypeDefs) { combinedResults = this.addUniqueTypeDef(combinedResults, returnedTypeDef, serverName, metadataCollectionId, methodName); } } return combinedResults; } /** * Build a combined list of TypeDefs. * * @param accumulatedResults current accumulated TypeDefs * @param typeDef newly received TypeDef * @param serverName name of the server that provided the new TypeDef * @param metadataCollectionId unique identifier for metadata collection that provided the new TypeDef * @param methodName method name that returned the new TypeDef * @return combined results */ private Map<String, TypeDef> addUniqueTypeDef(Map<String, TypeDef> accumulatedResults, TypeDef typeDef, String serverName, String metadataCollectionId, String methodName) { Map<String, TypeDef> combinedResults = new HashMap<>(accumulatedResults); if (typeDef != null) { TypeDef existingTypeDef = combinedResults.put(typeDef.getGUID(), typeDef); // todo validate that existing typeDef and the new one are copies } return combinedResults; } /** * Build a combined list of entities. * * @param accumulatedResults current accumulated entities * @param results newly received list of entities * @param serverName name of the server that provided the new entity * @param metadataCollectionId unique identifier for metadata collection that provided the new entity * @param methodName method name that returned the new entity * @return combined results */ private Map<String, EntityDetail> addUniqueEntities(Map<String, EntityDetail> accumulatedResults, List<EntityDetail> results, String serverName, String metadataCollectionId, String methodName) { Map<String, EntityDetail> combinedResults = new HashMap<>(accumulatedResults); if (results != null) { for (EntityDetail returnedEntity : results) { combinedResults = this.addUniqueEntity(combinedResults, returnedEntity, serverName, metadataCollectionId, methodName); } } return combinedResults; } /** * Build a combined list of entities. * * @param accumulatedResults current accumulated entities * @param entity newly received entity * @param serverName name of the server that provided the new entity * @param metadataCollectionId unique identifier for metadata collection that provided the new entity * @param methodName method name that returned the new entity * @return combined results */ private Map<String, EntityDetail> addUniqueEntity(Map<String, EntityDetail> accumulatedResults, EntityDetail entity, String serverName, String metadataCollectionId, String methodName) { Map<String, EntityDetail> combinedResults = new HashMap<>(accumulatedResults); if (entity != null) { EntityDetail existingEntity = combinedResults.put(entity.getGUID(), entity); // todo validate that existing entity and the new one are copies } return combinedResults; } /** * Build a combined list of relationships. * * @param accumulatedResults current accumulated relationships * @param results newly received list of relationships * @param serverName name of the server that provided the new relationship * @param metadataCollectionId unique identifier for metadata collection that provided the new relationship * @param methodName method name that returned the new relationship * @return combined results */ private Map<String, Relationship> addUniqueRelationships(Map<String, Relationship> accumulatedResults, List<Relationship> results, String serverName, String metadataCollectionId, String methodName) { Map<String, Relationship> combinedResults = new HashMap<>(accumulatedResults); if (results != null) { for (Relationship returnedRelationship : results) { combinedResults = this.addUniqueRelationship(combinedResults, returnedRelationship, serverName, metadataCollectionId, methodName); } } return combinedResults; } /** * Build a combined list of relationships. * * @param accumulatedResults current accumulated relationships * @param relationship newly received relationship * @param serverName name of the server that provided the new relationship * @param metadataCollectionId unique identifier for metadata collection that provided the new relationship * @param methodName method name that returned the new relationship * @return combined results */ private Map<String, Relationship> addUniqueRelationship(Map<String, Relationship> accumulatedResults, Relationship relationship, String serverName, String metadataCollectionId, String methodName) { Map<String, Relationship> combinedResults = new HashMap<>(accumulatedResults); if (relationship != null) { Relationship existingRelationship = combinedResults.put(relationship.getGUID(), relationship); // todo validate that existing relationship and the new one are copies } return combinedResults; } /** * Verify that a cohort member's metadata collection is not null. * * @param cohortMetadataCollection metadata collection * @param methodName name of method * @throws RepositoryErrorException null metadata collection */ private void validateMetadataCollection(OMRSMetadataCollection cohortMetadataCollection, String methodName) throws RepositoryErrorException { /* * The cohort metadata collection should not be null. It is in a real mess if this fails. */ if (cohortMetadataCollection == null) { /* * A problem in the set up of the metadata collection list. Repository connectors implemented * with no metadata collection are tested for in the OMRSEnterpriseConnectorManager so something * else has gone wrong. */ OMRSErrorCode errorCode = OMRSErrorCode.NULL_ENTERPRISE_METADATA_COLLECTION; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } /** * Indicates to the caller that the method called is not supported by the enterprise connector. * * @param methodName name of the method that was called * @throws FunctionNotSupportedException resulting exception */ private void throwNotEnterpriseFunction(String methodName) throws FunctionNotSupportedException { OMRSErrorCode errorCode = OMRSErrorCode.ENTERPRISE_NOT_SUPPORTED; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName); throw new FunctionNotSupportedException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } /** * Throw a TypeDefNotKnownException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws TypeDefNotKnownException the type definition is not known in any of the federated repositories */ private void throwCapturedTypeDefNotKnownException(TypeDefNotKnownException exception) throws TypeDefNotKnownException { if (exception != null) { throw exception; } } /** * Throw a InvalidParameterException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws InvalidParameterException one of the parameters is invalid */ private void throwCapturedInvalidParameterException(InvalidParameterException exception) throws InvalidParameterException { if (exception != null) { throw exception; } } /** * Throw a TypeErrorException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws TypeErrorException the type definition of the instance is not known in any of the federated repositories */ private void throwCapturedTypeErrorException(TypeErrorException exception) throws TypeErrorException { if (exception != null) { throw exception; } } /** * Throw a StatusNotSupportedException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws StatusNotSupportedException the status is not known in any of the federated repositories */ private void throwCapturedStatusNotSupportedException(StatusNotSupportedException exception) throws StatusNotSupportedException { if (exception != null) { throw exception; } } /** * Throw a ClassificationErrorException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws ClassificationErrorException the classification is not known */ private void throwCapturedClassificationErrorException(ClassificationErrorException exception) throws ClassificationErrorException { if (exception != null) { throw exception; } } /** * Throw a PropertyErrorException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws PropertyErrorException the properties are not valid for the call */ private void throwCapturedPropertyErrorException(PropertyErrorException exception) throws PropertyErrorException { if (exception != null) { throw exception; } } /** * Throw a EntityNotKnownException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws EntityNotKnownException the entity is not known in any of the federated repositories */ private void throwCapturedEntityNotKnownException(EntityNotKnownException exception) throws EntityNotKnownException { if (exception != null) { throw exception; } } /** * Throw a EntityNotDeletedException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws EntityNotDeletedException the entity is not in deleted status */ private void throwCapturedEntityNotDeletedException(EntityNotDeletedException exception) throws EntityNotDeletedException { if (exception != null) { throw exception; } } /** * Throw a EntityProxyOnlyException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws EntityProxyOnlyException only entity proxies have been found in the available federated repositories */ private void throwCapturedEntityProxyOnlyException(EntityProxyOnlyException exception) throws EntityProxyOnlyException { if (exception != null) { throw exception; } // todo add audit log call as this exception may indicate one of the repositories in the // todo may be in trouble. } /** * Throw a RelationshipNotKnownException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws RelationshipNotKnownException the relationship is not known in any of the federated repositories */ private void throwCapturedRelationshipNotKnownException(RelationshipNotKnownException exception) throws RelationshipNotKnownException { if (exception != null) { throw exception; } } /** * Throw a RelationshipNotDeletedException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws RelationshipNotDeletedException the relationship is not in deleted status */ private void throwCapturedRelationshipNotDeletedException(RelationshipNotDeletedException exception) throws RelationshipNotDeletedException { if (exception != null) { throw exception; } } /** * Throw a UserNotAuthorizedException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws TypeDefNotSupportedException the type definition is not supported in any of the federated repositories */ private void throwCapturedTypeDefNotSupportedException(TypeDefNotSupportedException exception) throws TypeDefNotSupportedException { if (exception != null) { throw exception; } } /** * Throw a FunctionNotSupportedException if it was returned by all of the calls to the cohort connectors. * * @param exception captured exception * @throws FunctionNotSupportedException the requested function is not supported in any of the federated repositories */ private void throwCapturedFunctionNotSupportedException(FunctionNotSupportedException exception) throws FunctionNotSupportedException { if (exception != null) { throw exception; } } /** * Throw a UserNotAuthorizedException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws UserNotAuthorizedException the userId is not authorized in the server */ private void throwCapturedUserNotAuthorizedException(UserNotAuthorizedException exception) throws UserNotAuthorizedException { if (exception != null) { throw exception; } } /** * Throw a RepositoryErrorException if it was returned by one of the calls to a cohort connector. * * @param exception captured exception * @throws RepositoryErrorException there was an error in the repository */ private void throwCapturedRepositoryErrorException(RepositoryErrorException exception) throws RepositoryErrorException { if (exception != null) { throw exception; } } /** * Throw a RepositoryErrorException if an unexpected Throwable exception was returned by one of the calls * to a cohort connector. * * @param exception captured exception * @throws RepositoryErrorException there was an unexpected error in the repository */ private void throwCapturedThrowableException(Throwable exception, String methodName) throws RepositoryErrorException { if (exception != null) { OMRSErrorCode errorCode = OMRSErrorCode.UNEXPECTED_EXCEPTION_FROM_COHORT; String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName, exception.getMessage()); throw new RepositoryErrorException(errorCode.getHTTPErrorCode(), this.getClass().getName(), methodName, errorMessage, errorCode.getSystemAction(), errorCode.getUserAction()); } } /** * Take the results of the federated connectors and combine them into a valid TypeDef gallery or an * exception. * * @param repositoryName the name of this repository * @param combinedTypeDefResults TypeDefs returned by the federated connectors * @param combinedAttributeTypeDefResults AttributeTypeDefs returned by the federated connectors * @param userNotAuthorizedException captured user not authorized exception * @param repositoryErrorException captured repository error exception * @param anotherException captured Throwable * @param methodName name of the method issuing the request * @return TypeDefGallery * @throws RepositoryErrorException there is a problem communicating with the metadata repository. * @throws UserNotAuthorizedException the userId is not permitted to perform this operation. */ private TypeDefGallery validatedTypeDefGalleryResults(String repositoryName, Map<String, TypeDef> combinedTypeDefResults, Map<String, AttributeTypeDef> combinedAttributeTypeDefResults, UserNotAuthorizedException userNotAuthorizedException, RepositoryErrorException repositoryErrorException, Throwable anotherException, String methodName) throws RepositoryErrorException, UserNotAuthorizedException { int resultCount = (combinedTypeDefResults.size() + combinedAttributeTypeDefResults.size()); /* * Return any results, or exception if nothing is found. */ if (resultCount > 0) { TypeDefGallery typeDefGallery = new TypeDefGallery(); List<AttributeTypeDef> attributeTypeDefs = new ArrayList<>(combinedAttributeTypeDefResults.values()); List<TypeDef> typeDefs = new ArrayList<>(combinedTypeDefResults.values()); repositoryValidator.validateEnterpriseTypeDefs(repositoryName, typeDefs, methodName); typeDefGallery.setAttributeTypeDefs(attributeTypeDefs); typeDefGallery.setTypeDefs(typeDefs); return typeDefGallery; } else { throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedThrowableException(anotherException, methodName); /* * Nothing went wrong, there are just no results. */ return null; } } /** * Take the results of the federated connectors and combine them into a valid TypeDef list or an * exception. * * @param repositoryName the name of this repository * @param combinedTypeDefResults TypeDefs returned by the federated connectors * @param userNotAuthorizedException captured user not authorized exception * @param repositoryErrorException captured repository error exception * @param anotherException captured Throwable * @param methodName name of the method issuing the request * @return list of TypeDefs * @throws RepositoryErrorException problem in one of the federated connectors * @throws UserNotAuthorizedException user not recognized or not granted access to the TypeDefs */ private List<TypeDef> validatedTypeDefListResults(String repositoryName, Map<String, TypeDef> combinedTypeDefResults, UserNotAuthorizedException userNotAuthorizedException, RepositoryErrorException repositoryErrorException, Throwable anotherException, String methodName) throws RepositoryErrorException, UserNotAuthorizedException { /* * Return any results, or null if nothing is found. */ if (! combinedTypeDefResults.isEmpty()) { List<TypeDef> typeDefs = new ArrayList<>(combinedTypeDefResults.values()); repositoryValidator.validateEnterpriseTypeDefs(repositoryName, typeDefs, methodName); return typeDefs; } else { throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedThrowableException(anotherException, methodName); /* * Nothing went wrong, there are just no results. */ return null; } } /** * Take the results of the federated connectors and combine them into a valid AttributeTypeDef list or an * exception. * * @param repositoryName the name of this repository * @param combinedAttributeTypeDefResults AttributeTypeDefs returned by the federated connectors * @param userNotAuthorizedException captured user not authorized exception * @param repositoryErrorException captured repository error exception * @param anotherException captured Throwable * @param methodName name of the method issuing the request * @return list of AttributeTypeDefs * @throws RepositoryErrorException problem in one of the federated connectors * @throws UserNotAuthorizedException user not recognized or not granted access to the TypeDefs */ private List<AttributeTypeDef> validatedAttributeTypeDefListResults(String repositoryName, Map<String, AttributeTypeDef> combinedAttributeTypeDefResults, UserNotAuthorizedException userNotAuthorizedException, RepositoryErrorException repositoryErrorException, Throwable anotherException, String methodName) throws RepositoryErrorException, UserNotAuthorizedException { /* * Return any results, or null if nothing is found. */ if (! combinedAttributeTypeDefResults.isEmpty()) { List<AttributeTypeDef> attributeTypeDefs = new ArrayList<>(combinedAttributeTypeDefResults.values()); repositoryValidator.validateEnterpriseAttributeTypeDefs(repositoryName, attributeTypeDefs, methodName); return attributeTypeDefs; } else { throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedThrowableException(anotherException, methodName); /* * Nothing went wrong, there are just no results. */ return null; } } /** * Return a validated, sorted list of search results. * * @param repositoryName name of this repository * @param combinedResults results from all cohort repositories * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @param methodName name of method called * @return list of entities * @throws RepositoryErrorException there is a problem with the results */ private List<EntityDetail> validatedEntityListResults(String repositoryName, Map<String, EntityDetail> combinedResults, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize, String methodName) throws RepositoryErrorException { if (combinedResults.isEmpty()) { return null; } List<EntityDetail> actualResults = new ArrayList<>(combinedResults.values()); // todo: sort results and crop to max page size return actualResults; } /** * Return a validated, sorted list of search results. * * @param repositoryName name of this repository * @param combinedResults relationships from all cohort repositories * @param sequencingProperty String name of the property that is to be used to sequence the results. * Null means do not sequence on a property name (see SequencingOrder). * @param sequencingOrder Enum defining how the results should be ordered. * @param pageSize the maximum number of result entities that can be returned on this request. Zero means * unrestricted return results size. * @param methodName name of the method called * @return list of relationships * @throws RepositoryErrorException there is a problem with the results */ private List<Relationship> validatedRelationshipResults(String repositoryName, Map<String, Relationship> combinedResults, String sequencingProperty, SequencingOrder sequencingOrder, int pageSize, String methodName) throws RepositoryErrorException { if (combinedResults.isEmpty()) { return null; } List<Relationship> actualResults = new ArrayList<>(combinedResults.values()); // todo, sort results and crop to max page size return actualResults; } /** * Return a validated InstanceGraph. * * @param repositoryName name of this repository * @param accumulatedEntityResults list of returned entities * @param accumulatedRelationshipResults list of returned relationships * @param userNotAuthorizedException captured exception * @param propertyErrorException captured exception * @param functionNotSupportedException captured exception * @param entityNotKnownException captured exception * @param repositoryErrorException captured exception * @param anotherException captured Throwable exception * @param methodName name of calling method * @return InstanceGraph */ private InstanceGraph validatedInstanceGraphResults(String repositoryName, Map<String, EntityDetail> accumulatedEntityResults, Map<String, Relationship> accumulatedRelationshipResults, UserNotAuthorizedException userNotAuthorizedException, PropertyErrorException propertyErrorException, FunctionNotSupportedException functionNotSupportedException, EntityNotKnownException entityNotKnownException, RepositoryErrorException repositoryErrorException, Throwable anotherException, String methodName) throws UserNotAuthorizedException, PropertyErrorException, FunctionNotSupportedException, EntityNotKnownException, RepositoryErrorException { int resultCount = (accumulatedEntityResults.size() + accumulatedRelationshipResults.size()); /* * Return any results, or exception if nothing is found. */ if (resultCount > 0) { InstanceGraph instanceGraph = new InstanceGraph(); List<EntityDetail> entityDetails = new ArrayList<>(accumulatedEntityResults.values()); List<Relationship> relationships = new ArrayList<>(accumulatedRelationshipResults.values()); // todo Validate the entities and relationships instanceGraph.setEntities(entityDetails); instanceGraph.setRelationships(relationships); return instanceGraph; } else { throwCapturedUserNotAuthorizedException(userNotAuthorizedException); throwCapturedRepositoryErrorException(repositoryErrorException); throwCapturedPropertyErrorException(propertyErrorException); throwCapturedThrowableException(anotherException, methodName); throwCapturedFunctionNotSupportedException(functionNotSupportedException); throwCapturedEntityNotKnownException(entityNotKnownException); /* * Nothing went wrong, there are just no results. */ return null; } } }
14c73d3b984e4a84888c313fef94f918be47c167
db51942fe4ef8c2c7a474b65c47a984b2005a179
/2nd assigment/Spotihy11/app/src/main/java/com/example/spotihy11/MyApplication.java
fc57cc7aa58da69edae5519e30f7c98f33c31afa
[]
no_license
HerculesChrysanthos/Distributed-Systems-Music-streaming-Service
f7f3ec6156b75507b0598e7d7266d34b8d141f64
d929ec0d51796a78ab4c257ba6cb2e255437ddfe
refs/heads/master
2023-04-20T10:35:54.112189
2021-05-20T11:32:06
2021-05-20T11:32:06
369,178,566
0
1
null
null
null
null
UTF-8
Java
false
false
5,116
java
package com.example.spotihy11; import android.app.Application; import android.os.AsyncTask; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; public final class MyApplication extends Application { private Socket socket; private ObjectInputStream in; private ObjectOutputStream out; private ArrayList<String> totalArtistList; public ArrayList<String> songs; public Socket getSocket(){ return socket; } public void setSocket(Socket socket){ this.socket = socket; } public ObjectInputStream getIn() { return in; } public void setIn(ObjectInputStream in) { this.in = in; } public ObjectOutputStream getOut() { return out; } public void setOut(ObjectOutputStream out) { this.out = out; } public ArrayList<String> getTotalArtistList() { return totalArtistList; } public void addTotalArtistList(String artist) { totalArtistList.add(artist); } public void setTotalArtistList(ArrayList<String> totalArtistList) { this.totalArtistList = totalArtistList; } public ArrayList<String> getSongs() { return songs; } public void setSongs(ArrayList<String> songs) { this.songs = songs; } @Override public void onCreate() { super.onCreate(); AsyncTaskRunner runner = new AsyncTaskRunner(); runner.execute("192.168.1.68", "4321","true","false"); } public void Redirect(String ip,int port,boolean check,String username,String artistName){ songs = new ArrayList<>(); AsyncTaskRunner redirect = new AsyncTaskRunner(); redirect.execute(ip,String.valueOf(port),String.valueOf(check),"false",username,artistName); } public void CloseSocket(){ AsyncTaskRunner bye = new AsyncTaskRunner(); bye.execute("","","","true","",""); } private class AsyncTaskRunner extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... strings) { if( Boolean.parseBoolean(strings[3])){ try{ out.writeObject(false); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { in.close(); out.close(); socket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } else { boolean check = Boolean.parseBoolean(strings[2]); if (!check) { try { socket.close(); //an allksei server kleinei to socket kai ta streams tou prohgoumenou in.close(); out.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } try { socket = new Socket(strings[0], Integer.parseInt(strings[1])); in = new ObjectInputStream(socket.getInputStream()); out = new ObjectOutputStream(socket.getOutputStream()); getOut().writeObject("Consumer"); getOut().writeObject(check); if (check) { totalArtistList = new ArrayList<String>(); int artistsSize = (int) in.readObject(); for (int i = 0; i < artistsSize; i++) { String message = (String) in.readObject(); totalArtistList.add(message); } } else { getOut().writeObject(strings[4]); //stelnei username an kanei redirect getOut().flush(); getOut().writeObject(strings[5]);//stelnei artistname an kanei redirect getOut().flush(); boolean findCorrectBroker = (boolean) in.readObject(); if (findCorrectBroker) { int songsAmount = (int) in.readObject(); for (int i = 0; i < songsAmount; i++) { String tempString = (String) in.readObject(); songs.add(tempString); } } } } catch (IOException | ClassNotFoundException unknownHost) { System.err.println("You are trying to connect to an unknown host!"); } } return null; } } }
e079de54977d28ae4c48fca8d8919eae2962b6bf
9d73d5bacee97acce69d8f423807b81ee62cfe18
/day6/MethodLab5.java
75bbb52932d7ca30ad5ebe2d1ca36da58ecda803
[]
no_license
AnabolicAction/JavaStudy
89c8c50a1cdcda0a64a05d1fd8d3c149dac26b08
968ac319fd8e14fff580a509a756d9f6768ffc60
refs/heads/master
2020-03-09T02:05:38.811336
2018-07-08T08:46:32
2018-07-08T08:46:32
128,532,263
0
0
null
null
null
null
UHC
Java
false
false
803
java
package day6; public class MethodLab5 { public static void main(String[] args) { int r1[] = powerArray(2); int r2[] = powerArray(3); int r3[] = powerArray(4); for (int i = 0; i < 10; i++) System.out.print(r1[i] + " "); System.out.println(); for (int i = 0; i < 10; i++) System.out.print(r2[i] + " "); System.out.println(); for (int i = 0; i < 10; i++) System.out.print(r3[i] + " "); System.out.println(); } /* * public static int getRandom(int n) 1 부터 n 까지 범위의 난수 리턴 public static int * getRandom(int n1, int n2) n1 부터 n2 범위의 난수 리턴 */ public static int[] powerArray(int nums) { int arr[] = new int[10]; for (int i = 0; i < 10; i++) arr[i] = (i + 1) * nums; return arr; } }
8041a103a4fd225eff33dd8c59804fb6ee1e71e8
8e7199dcb9d15155acad762ff506609129487cec
/tect/src/test/java/TEst/tect/AppTest.java
cafb69f81a880b51193f3280a4778c54a123bc4c
[]
no_license
pooja-tester/automationscripts
6faaacf4783624663b7fec904ff7b30b818ade10
9518d8e6ad48874669d620abad74a72240174c19
refs/heads/master
2021-04-28T13:51:13.423343
2019-09-03T07:04:40
2019-09-03T07:04:40
121,951,024
0
0
null
null
null
null
UTF-8
Java
false
false
675
java
package TEst.tect; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
052d7e424f25e699dceee14578aab57256c87f64
5b06ed7fd0bfda05c572722af3c7ed36cdbc32c5
/ChatEE2/src/JsonMessages.java
071b32180af97c64232751ddc24c8401ebf85cdd
[]
no_license
KanivetsAlexey/chatEE
2be72ac226ab97afb833a186f347d7775f32ba0c
d90913b11580770633fa6808adb6890bfc500400
refs/heads/master
2021-01-17T08:25:22.164491
2017-03-04T17:01:41
2017-03-04T17:01:41
83,909,359
0
0
null
null
null
null
UTF-8
Java
false
false
779
java
import java.util.ArrayList; import java.util.List; public class JsonMessages { private final List<Message> list; public JsonMessages(List<Message> sourceList, int fromIndex, String to, String room) { this.list = new ArrayList<>(); Message result = null; for(int i = fromIndex; i < sourceList.size(); i++){ result = sourceList.get(i); if(result != null){ if(result.getTo().equals(Constants.TO_ALL) || (result.getTo().equals(to))){ if(result.getRoom().equals(Constants.MAIN_ROOM)||result.getRoom().equals(room)){ list.add(result); } }else{ list.add(null); } } } } }
8c498f4767b4574bcd8663ebd23768dcef0f8f49
4616476edc1ec184af03779e4562ac31037a387c
/Informatik/PhytonEinführung/src/Aufgabe1.java
6b34b726d67f01dec4d6e640a9297574724e708f
[]
no_license
Lukas-AI-Project/programming
b197478ffd7125e9735b78637c15076af21c969c
4ba18dab06b332edfbdd1678b5f58a45afcd274c
refs/heads/master
2021-06-10T01:15:56.976709
2017-01-18T19:22:05
2017-01-18T19:22:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
import java.util.Scanner; public class Aufgabe1 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.println("Bitte geben sie ihren Namen ein: "); String name = sc.next(); System.out.println("Guten Tag "+name+"!"); sc.close(); } }
17465e6b7746a42d148d8c0587bfaa7dd9ef1150
af2fee288a263cd55aaecdefb249d5c8b7bfb11b
/app/src/main/java/com/example/android/finalapp/MessagesMan.java
6bcf3466f943e59087a2b37285e858a2238d317a
[]
no_license
dHRUSHIT/MECO
2d000bcc31d72b7df8d2d9f89bf7cda03ac28779
ab1581a158a3e6decba97d7c3a8df234fd80c1f0
refs/heads/master
2016-09-13T09:23:49.693012
2016-05-21T17:24:36
2016-05-21T17:24:36
57,521,558
0
0
null
null
null
null
UTF-8
Java
false
false
1,767
java
package com.example.android.finalapp; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.provider.Telephony; import android.telephony.SmsManager; import java.util.Calendar; /** * Created by dhrushit.s on 2/17/2016. */ public class MessagesMan { private boolean allowFeature = false; public static String fetchNotifications(String contents, Context context) { return null; } public static String getMessages(String content, Context context) { SmsManager smsManager = SmsManager.getDefault(); Calendar calendar = Calendar.getInstance(); calendar.add(calendar.DATE,-1); String[] args = {String.valueOf(calendar.getTime())}; // String[] args = {String.valueOf(calendar.getTime()),"0"}; ContentResolver contentResolver = context.getContentResolver(); /*please uncomment in the next line for the final app*/ // Cursor cursor = contentResolver.query(Telephony.Sms.Inbox.CONTENT_URI, null, Telephony.Sms.Inbox.DATE + ">= ?", args, null); // Cursor cursor = contentResolver.query(Telephony.Sms.Inbox.CONTENT_URI, null, "date>= ? AND read = ?", args, null); Cursor cursor = contentResolver.query(Telephony.Sms.Inbox.CONTENT_URI, null, null, null, null); int numberOfMessages = cursor.getCount(); cursor.moveToFirst(); String ret=""; while (cursor.moveToNext()){ ret = ret + cursor.getString(cursor.getColumnIndex("address")) + ":\n"; ret = ret + cursor.getString(cursor.getColumnIndex("body")) + "\n\n"; } cursor.close(); return ret; } }
17f41041d2e1eacc7aac4b1178362069fce9434c
eb993770c0b2f352a79d55ad5e6fc8e00b854b12
/src/com/zaren/HdhomerunSignalMeterLib/data/HdhomerunDevice.java
aaea1ed775ddf256991c4dd04666e5737b30e7a5
[]
no_license
cfraser/HdhomerunSignalMeterLib
0a568395de83b9d288cf5beee39189455edc9ecc
51f0db13a58fdf95c65f5f8ca33da02a4b84c753
refs/heads/master
2021-01-16T21:20:21.346251
2013-06-14T15:18:52
2013-06-14T15:18:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
21,775
java
package com.zaren.HdhomerunSignalMeterLib.data; import com.zaren.HdhomerunSignalMeterLib.util.ErrorHandler; import com.zaren.HdhomerunSignalMeterLib.util.HDHomerunLogger; import com.zaren.HdhomerunSignalMeterLib.util.Utils; import java.io.Serializable; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import java.util.StringTokenizer; public class HdhomerunDevice implements Serializable { private static final long serialVersionUID = 1942906208628106963L; public static final String DEVICE_CABLECARD = "cablecard"; public static final String DEVICE_ATSC = "atsc"; //reset constants public static final String SELF = "self"; public static final String CABLECARD = "cablecard"; private int cPointer; private long deviceId; private int ipAddr; private int tuner; private String[] channelMaps; private String deviceName; private TunerStatus prevTunerStatus; private String prevChannelMap; private String deviceType; private transient ChannelList channelList = new ChannelList(); //this is transient because it is not serializable /* * this is used to load the native library on application startup. The * library has already been unpacked into /data/data/PROJECT/lib/C-FILE.so at * installation time by the package manager. */ static { System.loadLibrary("hdhomerun"); } public HdhomerunDevice(long deviceId_val, int ipAddr_val, int tuner_val ) throws HdhomerunCommErrorException { String supportedString; this.deviceId = deviceId_val; this.ipAddr = ipAddr_val; this.tuner = tuner_val; cPointer = JNIcreateNewDevice(deviceId_val, ipAddr_val, tuner_val); deviceName = Long.toHexString(deviceId_val) + "-" + tuner_val; HDHomerunLogger.d("Device created id:" + deviceName); // Now Lets collect the supported channelmaps supportedString = JNIgetSupported(cPointer); HDHomerunLogger.d(supportedString); StringTokenizer st = new StringTokenizer(supportedString, "\n"); while (st.hasMoreTokens() == true) { processSupportedString(st.nextToken()); } //now the device type String deviceModel = getModel(); HDHomerunLogger.d("Device model " + deviceModel); if(deviceModel.contains("cablecard")) { deviceType = DEVICE_CABLECARD; } else { deviceType = DEVICE_ATSC; } HDHomerunLogger.d("Device type " + deviceType); } private void processSupportedString(String token) { StringTokenizer st = new StringTokenizer(token); // need at least two tokens, one for the key and 1 for the value, if not // at least 2 its worthless if (st.countTokens() > 1) { String key = st.nextToken(); if (key.equals("channelmap:")) { int i = 0; // just a counter channelMaps = new String[st.countTokens()]; while (st.hasMoreTokens() == true) { channelMaps[i] = st.nextToken(); i++; } } else if (key.equals("modulation:")) { // don't care about this yet } else if (key.equals("auto-modulation:")) { // don't care about this yet } else { HDHomerunLogger.w("Unhandled token type: " + key); } } } public void destroy() { HDHomerunLogger.d("Destroying device " + deviceName); JNIdestroy(cPointer); cPointer = -1; } synchronized public int setChannelMap(String channelMap) { HDHomerunLogger.d("Set ChannelMap to " + channelMap + " for device " + deviceName); int status = JNIsetChannelMap(this.cPointer, channelMap); //TODO need to recalc channellist return status; } private native int JNIgetTunerChannel( int aCPointer, JniString aChannel ); public int getTunerChannel( JniString aChannel ) { int theRetVal = JNIgetTunerChannel( cPointer, aChannel ); HDHomerunLogger.d("getTunerChannel: return val " + theRetVal + " channel: " + aChannel.getString()); return theRetVal; } synchronized public int setTunerChannel(String channel) { HDHomerunLogger.d("Set Channel to " + channel + " for device " + deviceName); int status; status = JNIsetTunerChannel(cPointer, channel); //TODO for some reason this is crashing when we hit the end of a channel scan for the cable channelmaps //checkForError(status, "SetTunerChannel"); if (status == -1) { // network error, we need to give up } return status; } synchronized public TunerStatus getTunerStatus() { TunerStatus tunerStatus = JNIgetTunerStatus(cPointer); boolean error = checkForError(tunerStatus.returnStatus, "GetTunerStatus"); if (error == false) { prevTunerStatus = tunerStatus; return tunerStatus; } else { return prevTunerStatus; } } public synchronized int updateTunerStatus(TunerStatus tunerStatus) { int status = JNIupdateTunerStatus(cPointer, tunerStatus); checkForError(status, "UpdateTunerStatus"); return status; } private synchronized native int JNIcreateNewDevice(long deviceId, long ipAddr, int tuner); private synchronized native int JNIsetChannelMap(int cPointer, String channelMap); private synchronized native int JNIsetTunerChannel(int cPointer, String channel); private synchronized native int JNIsetTunerVChannel(int cPointer, String channel); private synchronized native int JNIwaitForLock(int cPointer, TunerStatus tunerStatus); synchronized public int waitForLock(TunerStatus tunerStatus) { int retVal = JNIwaitForLock(cPointer, tunerStatus); ErrorHandler.HandleError(retVal, "Wait for Lock"); return retVal; } private synchronized native int JNIgetTunerStreamInfo(int cPointer, JniString streamInfo); synchronized public int getTunerStreamInfo(ProgramsList thePrograms) { JniString streamInfo = new JniString(); int retVal = JNIgetTunerStreamInfo(cPointer, streamInfo); ErrorHandler.HandleError(retVal, "Get Tuner Stream Info"); if(retVal > 0) { convertStreamInfoToPrograms(streamInfo.getString(), thePrograms); } return retVal; } private void convertStreamInfoToPrograms( String streamInfo, ProgramsList thePrograms) { StringTokenizer theProgramStrings = new StringTokenizer(streamInfo,"\n"); while(theProgramStrings.hasMoreTokens()) { try { String theProgramString = ""; if( theProgramStrings.hasMoreTokens() ) { theProgramString = theProgramStrings.nextToken(); } HDHomerunLogger.d( "Parsing program string: " + theProgramString ); StringTokenizer theProgNumAndName = new StringTokenizer( theProgramString, ":" ); ChannelScanProgram theProgram = new ChannelScanProgram(); theProgram.programString = theProgramString; while( theProgNumAndName.hasMoreTokens() ) { theProgram.programNumber = Integer.parseInt( theProgNumAndName.nextToken() ); processProgramName( theProgNumAndName.nextToken(), theProgram ); } thePrograms.append( theProgram.programNumber, theProgram ); } catch( NumberFormatException e ) { HDHomerunLogger.e( "Error Parsing String: " + e ); } catch( NoSuchElementException e ) { HDHomerunLogger.e( "NoSuchElementException: " + e ); } } } private static final String[] theTypes = new String[]{ "control", "encrypted", "no data", "internet"}; private void processProgramName( String aProgramName, ChannelScanProgram aProgram ) { int theOpeningParen = aProgramName.indexOf( "(" ); int theClosingParen = aProgramName.indexOf( ")" ); String theJustProgramName = aProgramName; if( theOpeningParen != -1 && theClosingParen != -1 ) { //This is the string that says "control" or "encrypted" or "no data" String theTypeString = aProgramName.substring( theOpeningParen + 1, theClosingParen ); List< String > theTypeStrings = Arrays.asList( theTypes ); if( theTypeStrings.contains( theTypeString ) ) { aProgram.type = theTypeString; theJustProgramName = aProgramName.substring( 0, theOpeningParen ); } } StringTokenizer theStrings = new StringTokenizer( theJustProgramName, " " ); String theChannelNumbers = theStrings.nextToken(); StringTokenizer theChannelStrings = new StringTokenizer( theChannelNumbers, "." ); aProgram.virtualMajor = Integer.parseInt( theChannelStrings.nextToken() ); if( theChannelStrings.hasMoreTokens() ) { aProgram.virtualMinor = Integer.parseInt( theChannelStrings.nextToken() ); } StringBuilder theNameStringBuilder = new StringBuilder(); while( theStrings.hasMoreTokens() ) { String theString = theStrings.nextToken(); if( theNameStringBuilder.length() > 0 ) { theNameStringBuilder.append( " " ); } theNameStringBuilder.append( theString ); } aProgram.name = theNameStringBuilder.toString(); } private synchronized native TunerStatus JNIgetTunerStatus(int cPointer); private synchronized native String JNIgetSupported(int cPointer); private synchronized native void JNIdestroy(int cPointer); private synchronized native String JNIgetChannelMap(int cPointer); private synchronized native int JNIupdateTunerStatus(int cPointer, TunerStatus tunerStatus); private synchronized native int JNIupdateTunerVStatus(int cPointer, TunerVStatus tunerVStatus); public int updateTunerVStatus(TunerVStatus tunerVStatus) { int status = JNIupdateTunerVStatus(cPointer, tunerVStatus); checkForError(status, "UpdateTunerVStatus"); return status; } private synchronized native TunerVStatus JNIgetTunerVStatus(int cPointer); public TunerVStatus getTunerVStatus() { TunerVStatus tunerVStatus = JNIgetTunerVStatus(cPointer); return tunerVStatus; } private synchronized native String JNIgetModel(int cPointer); public String getModel() throws HdhomerunCommErrorException { String retVal = JNIgetModel(cPointer); if(retVal == null) { throw new HdhomerunCommErrorException("Failed to get model information"); } return retVal; } private synchronized native int JNIcreateChannelList(String channelMap, ChannelList channelList); public int createChannelList(String channelMap, ChannelList channelList) { int status = JNIcreateChannelList(channelMap, channelList); this.channelList = channelList; return status; } /** * @return the channelMaps */ public String[] getChannelMaps() { return channelMaps; } synchronized public String getCurrentChannelMap() { String channelMap = JNIgetChannelMap(cPointer); boolean error = checkForError(channelMap, "GetCurrentChannelMap"); if (error == false) { prevChannelMap = channelMap; return channelMap; } else { return prevChannelMap; } } private boolean checkForError(int returnStatus, String message) { //ErrorHandler.HandleError(returnStatus, message); if (returnStatus == 0) { return true; } else if (returnStatus == -1) { return true; } return false; } private boolean checkForError(String returnString, String message) { if (returnString.equals("rejected")) { //ErrorHandler.HandleError(0, message); return true; } else if (returnString.equals("Network failure")) { //ErrorHandler.HandleError(-1, message); return true; } return false; } public int getCurrentChannel() { TunerStatus tunerStatus = getTunerStatus(); String channelString = tunerStatus.channel; if (channelString.equals("none")) { return -1; } else { String[] splitString = channelString.split(":"); return Integer.parseInt(splitString[1]); } } String buildChannelStringFromTunerStatus(String channel, String lockStr) { HDHomerunLogger.v("BuildChannelString: "+channel + " " + lockStr); if(channel.equals("none")) { return channel; } else { String[] splitString = channel.split(":"); if(splitString.length > 1) { int channel_int = Integer.parseInt(splitString[1]); if(channel_int > 1000) { //this must be a frequency value channel_int = frequencyToChannelNumber(channel_int); if(channel_int == 0) { //for some reason we couldn't match up the frequency to channel number, just return the frequency return lockStr + ":" + splitString[1]; } return lockStr + ":" + channel_int; } else { return lockStr + ":" + splitString[1]; } } else { //something was wrong with the channel from the device return "none"; } } } protected String getChannelNumberFromChannelString(String channelString) { HDHomerunLogger.v("getChannelNumberFromChannelString(): " + channelString); if(channelString.equals("none")) { return ""; } //first split on a comma, sometimes the channelString comes back as two different channelmaps, not sure why String channelMapstrings[] = channelString.split(","); //just use the first one String strings[] = channelMapstrings[0].split(":"); //if it didn't return more than two results that means for some reason we don't have a channel number if(strings.length < 2) { return ""; } int channelInt = Integer.parseInt(strings[1]); if(channelInt > 1000) { //this must be a frequency value int convertedChannelInt = frequencyToChannelNumber(channelInt); if(convertedChannelInt == 0) { //for some reason we couldn't match up the frequency to channel number, just return the frequency return ""+channelInt; } return ""+convertedChannelInt; } else { return ""+channelInt; } } public int frequencyToChannelNumber(int frequency) { return channelList.frequencyToNumber(frequency); } /** * @return the cPointer */ public int getcPointer() { return cPointer; } /** * @return the deviceName */ public String getDeviceName() { return deviceName; } /** * @return the deviceId */ public long getDeviceId() { return deviceId; } /** * @return the ipAddr */ public int getIpAddr() { return ipAddr; } /** * @return the ipAddr as a byte array */ public byte[] getIpAddrArray() { return Utils.HdHrIpAddressToByteArray(ipAddr); } /** * @return the tuner */ public int getTuner() { return tuner; } /** * @return the deviceType */ public String getDeviceType() { return deviceType; } public int setTunerVChannel(String channel) { HDHomerunLogger.d("Set Virtual Channel to " + channel + " for device " + deviceName); int status; status = JNIsetTunerVChannel(cPointer, channel); //TODO for some reason this is crashing when we hit the end of a channel scan for the cable channelmaps //checkForError(status, "SetTunerChannel"); if (status == -1) { // network error, we need to give up } return status; } private native int JNIgetTunerVChannel( int aCPointer, JniString aVChannel ); public int getTunerVChannel( JniString aVChannel ) { int theRetVal = JNIgetTunerVChannel( cPointer, aVChannel ); HDHomerunLogger.d("getTunerVChannel: return val " + theRetVal + " program: " + aVChannel.getString()); return theRetVal; } private native String JNIgetFirmwareVersion(int cPointer2); public String getFirmwareVersion() { return JNIgetFirmwareVersion(cPointer); } private native String JNIgetLockkeyOwner(int cPointer2); public String getLockkeyOwner() { return JNIgetLockkeyOwner(cPointer); } private native String JNIgetTunerTarget(int cPointer2); public String getTargetIp() { return JNIgetTunerTarget(cPointer); } private native int JNIsetVar(int cPointer, String var, String value); public int setVar(String var, String value) { return JNIsetVar(cPointer, var, value); } private native int JNIgetVar(int cPointer, String var, JniString aValue, JniString aError); public int getVar(String var, JniString aValue, JniString aError) { return JNIgetVar(cPointer, var, aValue, aError); } private native int JNItunerLockeyRequest(int cPointer, JniString error); public int tunerLockeyRequest(JniString error) { int retVal = JNItunerLockeyRequest(cPointer, error); HDHomerunLogger.d("tunerLockeyRequest: return val " + retVal + " error: " + error.getString()); return retVal; } private native int JNItunerLockeyRelease(int cPointer); public int tunerLockeyRelease() { int retVal = JNItunerLockeyRelease(cPointer); HDHomerunLogger.d("tunerLockeyRelease: return val " + retVal); return retVal; } private native int JNItunerLockeyForce(int cPointer); public int tunerLockeyForce() { int retVal = JNItunerLockeyForce(cPointer); HDHomerunLogger.d("tunerLockeyForce: return val " + retVal); return retVal; } private native int JNIgetTunerProgram(int cPointer, JniString program); public int getTunerProgram(JniString program) { int retVal = JNIgetTunerProgram(cPointer, program); //HDHomerunLogger.d("getTunerProgram: return val " + retVal + " program: " + program.getString()); return retVal; } private native int JNIsetTunerProgram(int cPointer, String progNumber); public int setTunerProgram(String progNumber) { int retVal = JNIsetTunerProgram(cPointer, progNumber); HDHomerunLogger.d("setTunerProgram: return val " + retVal); return retVal; } private native int JNIsetTunerTarget(int cPointer, String targetString); public int setTargetIP(String targetString) { int retVal = JNIsetTunerTarget(cPointer, targetString); HDHomerunLogger.d("setTargetIP: " + targetString + " return val " + retVal); return retVal; } private native void JNIstreamStop(int cPointer); public void stopStreaming() { HDHomerunLogger.d("Device: stopStreaming"); JNIstreamStop(cPointer); } public CableCardStatus getCardStatus() { JniString theValue = new JniString(); JniString theError = new JniString(); int theStatus = getVar( "/card/status", theValue, theError ); HDHomerunLogger.d( "getCardStatus: theStatus = " + theStatus + " theValue = " + theValue + " theError = " + theError ); CableCardStatus theReturn = new CableCardStatus(); if( theStatus == DeviceResponse.SUCCESS ) { //process response processCardStatus( theValue, theReturn ); } return theReturn; } private void processCardStatus( JniString aValue, CableCardStatus aReturn ) { StringTokenizer theKeyValPairs = new StringTokenizer( aValue.getString(), " " ); while( theKeyValPairs.hasMoreTokens() ) { String theKeyVal = theKeyValPairs.nextToken(); int theEqualsIndex = theKeyVal.indexOf( '=' ); if( theEqualsIndex != -1 ) { String theKey = theKeyVal.substring( 0, theEqualsIndex ); String theVal = theKeyVal.substring( theEqualsIndex + 1, theKeyVal.length() ); if( theKey.equals("card") ) { aReturn.setCard( theVal ); } else if( theKey.equals("auth") ) { aReturn.setAuth( theVal ); } else if( theKey.equals("oob") ) { aReturn.setOob( theVal ); } else if( theKey.equals("act") ) { aReturn.setAct( theVal ); } } } } } //end class HdhomerunDevice
f3722a7b130b28b3a9e8a0a52b57d67c28414a85
acbf25323a68b1eec69fab0e3b104faff265e863
/src/main/java/com/nowcoder/community/config/ConfigAlpha.java
d4506c576aacd9f9c5806520b2908ee754d59659
[]
no_license
wsnd123/community
418d80543963431d802075f37bcf96bcd97d21cf
128ca0af1a4615839a8762716e65a8100e97b318
refs/heads/master
2023-08-22T08:07:43.092693
2021-09-25T08:07:38
2021-09-25T08:07:38
409,911,190
0
0
null
null
null
null
UTF-8
Java
false
false
508
java
package com.nowcoder.community.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.text.SimpleDateFormat; @Configuration//表示这是一个配置类 与配置类相关的扫描组件 public class ConfigAlpha { @Bean//方法名就是Bean的名字 这个方法返回的值将会被装配到容器中 public SimpleDateFormat simpleDateFormat(){ return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }
74e93be3ed81a4c717e3a2d221fe77527217faf9
600a80b2e378985e7cf5d6035834697b24a873b0
/src/test/java/org/springframework/samples/petclinic/web/PrescriptionControllerTests.java
e6ec563b0660892bcd0a742f2a5f3518554e8726
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
mancanjua/DP2-1920-GI-01
8f93fdc843dfe5b6ac0609e5510df8c026f12136
ba81993acfe303cb2eb7983075b75606b803a5f3
refs/heads/master
2022-09-29T22:10:39.301759
2020-06-05T19:36:04
2020-06-05T19:36:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,849
java
package org.springframework.samples.petclinic.web; import static org.mockito.BDDMockito.given; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.samples.petclinic.configuration.SecurityConfiguration; import org.springframework.samples.petclinic.model.MedicalRecord; import org.springframework.samples.petclinic.model.Medicine; import org.springframework.samples.petclinic.model.Owner; import org.springframework.samples.petclinic.model.Pet; import org.springframework.samples.petclinic.model.PetType; import org.springframework.samples.petclinic.model.Visit; import org.springframework.samples.petclinic.service.MedicalRecordService; import org.springframework.samples.petclinic.service.MedicineService; import org.springframework.samples.petclinic.service.PrescriptionService; import org.springframework.samples.petclinic.web.formatters.MedicineFormatter; import org.springframework.security.config.annotation.web.WebSecurityConfigurer; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest(value = PrescriptionController.class, includeFilters = @ComponentScan.Filter(value = MedicineFormatter.class, type = FilterType.ASSIGNABLE_TYPE), excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebSecurityConfigurer.class), excludeAutoConfiguration= SecurityConfiguration.class) class PrescriptionControllerTests { @MockBean private MedicineService medicineService; @MockBean private MedicalRecordService medicalRecordService; @MockBean private PrescriptionService prescriptionService; @Autowired private MockMvc mockMvc; @BeforeEach void setup() { Owner owner; Pet pet; Visit visit; MedicalRecord medicalRecord; Medicine medicine; PetType petType; owner = new Owner(); pet = new Pet(); visit = new Visit(); medicalRecord = new MedicalRecord(); medicine = new Medicine(); petType = new PetType(); petType.setName("Test"); petType.setId(1); owner.addPet(pet); owner.setId(1); pet.setType(petType); pet.setId(1); visit.setPet(pet); visit.setId(1); medicalRecord.setVisit(visit); medicine.setName("Cat medicine"); medicine.setPetType(petType); given(medicineService.findManyAll()).willReturn(Lists.newArrayList(medicine)); given(medicalRecordService.findMedicalRecordById(1)).willReturn(medicalRecord); given(medicineService.findByPetType(null)).willReturn(Lists.newArrayList(medicine)); } @WithMockUser(value = "spring") @Test void testInitCreationForm() throws Exception { mockMvc.perform(get("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1)) .andExpect(status().isOk()) .andExpect(view().name("prescription/form")) .andExpect(model().attributeExists("prescription")) .andExpect(model().attributeExists("medicines")); } @WithMockUser(value = "spring") @Test void testProccessCreationFormSuccess() throws Exception { mockMvc.perform(post("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1) .with(csrf()) .queryParam("dose", "Test") .queryParam("medicine", "Cat medicine")) .andExpect(status().is3xxRedirection()) .andExpect(view().name("redirect:/owners/1/pets/1/visits/1/medical-record/show?id=1")); } @WithMockUser(value = "spring") @Test void testProccessCreationFormHasErrors() throws Exception { mockMvc.perform(post("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1) .with(csrf()) .queryParam("dose", "Test") .queryParam("medicine", "")) .andExpect(status().isOk()) .andExpect(view().name("prescription/form")) .andExpect(model().hasErrors()) .andExpect(model().attributeHasErrors("prescription")) .andExpect(model().attributeExists("prescription")); } }
fae700630af5c5fca7e3ddc545d5206509a35f45
3b33d6e3c2067446ecb2475f68de74328a6ea66a
/DeveloperStudioWorkspace/quick-daan-project-workspace/modules/crowd-funding-database/crowd-funding-database-api/src/main/java/com/crowd/funding/database/service/DonorRegistrationServiceWrapper.java
362fc0e514bdd1490ef020d1d1c7fc8120fa7291
[]
no_license
Sumit9727/QuickDaan_LifeRay1
bbeced3e386f732be861073106848b4237e967ba
96320146033f182ab32f13a54bdc7a2306986b53
refs/heads/master
2020-09-18T11:21:16.519127
2019-11-26T09:04:17
2019-11-26T09:04:17
224,142,985
0
0
null
null
null
null
UTF-8
Java
false
false
1,724
java
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library 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 2.1 of the License, or (at your option) * any later version. * * This library 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. */ package com.crowd.funding.database.service; import aQute.bnd.annotation.ProviderType; import com.liferay.portal.kernel.service.ServiceWrapper; /** * Provides a wrapper for {@link DonorRegistrationService}. * * @author Brian Wing Shun Chan * @see DonorRegistrationService * @generated */ @ProviderType public class DonorRegistrationServiceWrapper implements DonorRegistrationService, ServiceWrapper<DonorRegistrationService> { public DonorRegistrationServiceWrapper( DonorRegistrationService donorRegistrationService) { _donorRegistrationService = donorRegistrationService; } /** * Returns the OSGi service identifier. * * @return the OSGi service identifier */ @Override public String getOSGiServiceIdentifier() { return _donorRegistrationService.getOSGiServiceIdentifier(); } @Override public DonorRegistrationService getWrappedService() { return _donorRegistrationService; } @Override public void setWrappedService( DonorRegistrationService donorRegistrationService) { _donorRegistrationService = donorRegistrationService; } private DonorRegistrationService _donorRegistrationService; }
cde71c75f49fe1adea195bac5185703cb82571ec
9f6884be098fc8ea0623f738eb5fcae121074ddd
/app/src/main/java/com/example/administrator/newcityselect/citypicker/util/ScreenUtil.java
1b82ee39bdc0f072df12351b862a7b05d9c33593
[]
no_license
wuqiuyun/citySelect
5dc08f74b61f3d2e907d1118e7217b8f0f479bd0
1092ebffb96e076e18e00563ea54609a2da60723
refs/heads/master
2021-05-24T10:32:34.217062
2020-04-06T14:27:46
2020-04-06T14:27:46
253,521,085
0
0
null
null
null
null
UTF-8
Java
false
false
3,099
java
package com.example.administrator.newcityselect.citypicker.util; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Build; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; /** * @Author: Bro0cL * @Date: 2018/12/4 11:35 * @Discription: */ public class ScreenUtil { private static int getInternalDimensionSize(Context context, String key) { int result = 0; try { int resourceId = context.getResources().getIdentifier(key, "dimen", "android"); if (resourceId > 0) { result = Math.round(context.getResources().getDimensionPixelSize(resourceId) * Resources.getSystem().getDisplayMetrics().density / context.getResources().getDisplayMetrics().density); } } catch (Resources.NotFoundException ignored) { return 0; } return result; } public static int getStatusBarHeight(Context context) { return getInternalDimensionSize(context, "status_bar_height"); } public static int getNavigationBarHeight(Context context) { boolean mInPortrait = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (hasNavBar((Activity) context)) { String key; if (mInPortrait) { key = "navigation_bar_height"; } else { key = "navigation_bar_height_landscape"; } return getInternalDimensionSize(context, key); } } return result; } private static boolean hasNavBar(Activity activity) { //判断小米手机是否开启了全面屏,开启了,直接返回false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (Settings.Global.getInt(activity.getContentResolver(), "force_fsg_nav_bar", 0) != 0) { return false; } } //其他手机根据屏幕真实高度与显示高度是否相同来判断 WindowManager windowManager = activity.getWindowManager(); Display d = windowManager.getDefaultDisplay(); DisplayMetrics realDisplayMetrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { d.getRealMetrics(realDisplayMetrics); } int realHeight = realDisplayMetrics.heightPixels; int realWidth = realDisplayMetrics.widthPixels; DisplayMetrics displayMetrics = new DisplayMetrics(); d.getMetrics(displayMetrics); int displayHeight = displayMetrics.heightPixels; int displayWidth = displayMetrics.widthPixels; return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0; } }
4f1ce828b39e8739edb8aa56d3526991e7f44919
1e67a0851d3a1ca55cb814d05d6248d5e8e7aa24
/code/projects_2018/project_03/P0305c_005_Counter_Inheritance_accessor/src/counter/SimpleCounter.java
d3addb29afb46148f2bb2b5af291947026b072ac
[]
no_license
iijima-lab/Lecture_2018_Soft_Eng_Practice
95bdf3011774d325d918b6ca3e980f0bc02845df
1bd694c2922c7b078ee4e0edd54a3d03bfa12d77
refs/heads/master
2020-03-09T08:18:22.812055
2018-05-14T06:52:32
2018-05-14T06:52:32
128,686,062
0
0
null
null
null
null
UTF-8
Java
false
false
6,957
java
// ============================================================================= // 45678901234567890123456789012345678901234567890123456789012345678901234567890 // ============================================================================= // 慶應義塾大学・理工学部・飯島研究室 // 2018年度・ソフトウェア工学実習 // Counter 2018-04 飯島 正 ([email protected]) // ============================================================================= package counter; // ============================================================================= /** * カウンタ(SimpleCounter): モデル(単純なカウンタ). * @author 飯島 正 ([email protected]) * @version <br> * ---- 0305c-005-20180423a [iijima] カウンタ(Counter) △継承の導入(メソッドのオーバーライド; アクセッサによるアクセス)<br> * ---- 0305b-005-20180423a [iijima] カウンタ(Counter) 継承の導入(メソッドのオーバーライド; 属性をpublicに変更)<br> * ---- 0305a-005-20180423a [iijima] カウンタ(Counter) △継承の導入(属性/メソッドの追加)<br> * ---- 0304a-004-20180423a [iijima] カウンタ(Counter) 進捗バーを追加し多重ビューを実現する<br> * ---- 0303b-003-20180420a [iijima] カウンタ(Counter) モデルに限界値を格納し,上限値もチェックする<br> * ---- 0303a-003-20180420a [iijima] カウンタ(Counter) エラーを例外で識別する<br> * ---- 0302f-002-20180420a [iijima] カウンタ(Counter) パッケージの導入<br> * ---- 0302e-002-20180420a [iijima] カウンタ(Counter) JOptionPaneによるエラーメッセージの表示<br> * ---- 0302d-002-20180420a [iijima] カウンタ(Counter) JDialogによるエラーメッセージの表示<br> * ---- 0302b-002-20180416a [iijima] カウンタ(Counter) エラーメッセージを配列で管理する<br> * ---- 0302a-002-20180416a [iijima] カウンタ(Counter) エラーコードでエラーを識別する<br> * ---- 0301c-001-20180416a [iijima] カウンタ(Counter) 共通部分をprivateの下請けメソッドに抽出する<br> * ---- 0301b-001-20180416a [iijima] カウンタ(Counter) モデルを抽出する(MVCの分離)<br> * ---- 0301a-001-20180413a [iijima] カウンタ(Counter) モデル抽出前の準備(0201a-001のコピー) */ // ============================================================================= public class SimpleCounter { // ========================================================================= // ///////////////////////////////////////////////////////////////////////// // ///// 属性(カウンターの内部状態) //////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// // ========================================================================= /** * [値属性] カウント値. */ // ========================================================================= private int count = 0; // <----- private // ========================================================================= // ///////////////////////////////////////////////////////////////////////// // ///// コンストラクタ (初期化) /////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// // ========================================================================= /** * [コンストラクタ] 初期化する. */ // ========================================================================= public SimpleCounter() { // --------------------------------------------------------------------- count = 0; // --------------------------------------------------------------------- } // ========================================================================= // ///////////////////////////////////////////////////////////////////////// // ///// インスタンスメソッド ////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// // ========================================================================= /** * カウントアップする. */ // ========================================================================= public void up() { // --------------------------------------------------------------------- count++; // --------------------------------------------------------------------- } // ========================================================================= /** * カウントダウンする. */ // ========================================================================= public void down() { // --------------------------------------------------------------------- count--; // --------------------------------------------------------------------- } // ========================================================================= /** * カウントをリセットする. */ // ========================================================================= public void reset() { // --------------------------------------------------------------------- count = 0; // --------------------------------------------------------------------- } // ========================================================================= // ///////////////////////////////////////////////////////////////////////// // ///// インスタンスメソッド: アクセッサ ////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// // ========================================================================= /** * [getter] カウント値を返す. * * @return カウント値. */ // ========================================================================= public int getCount() { // --------------------------------------------------------------------- return (count); // --------------------------------------------------------------------- } // ========================================================================= /** * [setter] カウント値を設定する. * * @param count 設定するカウント値. */ // ========================================================================= public void setCount(int count) { // --------------------------------------------------------------------- this.count = count; // --------------------------------------------------------------------- } // ========================================================================= } // =============================================================================
e032eb7750a9e58830986eeb589c84d2c98c8a2d
f80ced44f41091f5cc030d9f2908b70e719d2e14
/src/zoneserver/src/test/java/bronzethistle/zoneserver/dao/ZoneDaoTest.java
48041ea61c2738eebb9d289b912a992ae1530f87
[]
no_license
trasa/BronzeThistle
cede793b4fdd0f951729d49544b398c1e9385897
30396f41395d7c87cb33248efeb692a86913b182
refs/heads/master
2023-04-30T07:39:59.178998
2022-11-18T18:59:38
2022-11-18T18:59:38
2,722,900
0
0
null
2023-04-17T17:43:54
2011-11-06T22:59:41
Java
UTF-8
Java
false
false
883
java
package bronzethistle.zoneserver.dao; import bronzethistle.zoneserver.Zone; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ZoneDaoTest { private ZoneDao zoneDao; @Before public void setUp() { zoneDao = new ZoneDao(); zoneDao.init(); } @Test public void zerothZoneIsTheLobby() { Zone z = zoneDao.getZoneById(ZoneDao.LOBBY_ZONE_ID); assertEquals(ZoneDao.LOBBY_ZONE_ID, z.getZoneId()); assertEquals("Lobby", z.getName()); } @Test @Ignore("not implemented yet") public void create_a_zone() { // needs to not overwrite the existing 0th zone, // start numbering from 1, etc. assertTrue("todo", false); } }
c48ad0d5cbe176d15c4b3d2e82dab030668b3c2f
18f5ebbb2ede8c9d0501f09430e294b2232e2535
/app/src/main/java/com/app/cpk/adapter/PelSupAdapter.java
80141810f95e8cdd5aee7e70289ccb9f2705d75d
[]
no_license
healer32/cpk
9e3c9cea6cae0ae5a45c8f2774acb1d7799d2e2c
1ed5e8cd056bf3998a6a0b7ca18a58a836984200
refs/heads/master
2020-12-03T15:26:29.670781
2020-01-02T11:55:21
2020-01-02T11:55:21
231,371,687
0
0
null
null
null
null
UTF-8
Java
false
false
3,932
java
package com.app.cpk.adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.app.cpk.R; import com.app.cpk.activity.BayarPembelianActivity; import com.app.cpk.activity.ListPelSupActivity; import com.app.cpk.activity.PelSupSelectedActivity; import com.app.cpk.model.PelSup; import java.util.ArrayList; import java.util.List; public class PelSupAdapter extends RecyclerView.Adapter<PelSupAdapter.HolderData> { private List<PelSup> pelSupList; private Activity activity; private String jenis; public PelSupAdapter(ArrayList<PelSup> pelSupList, Activity activity, String jenis) { this.pelSupList = pelSupList; this.activity = activity; this.jenis = jenis; } @Override public HolderData onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pelsup, parent, false); HolderData holderData = new HolderData(v); return holderData; } @Override public void onBindViewHolder(HolderData holder, int position) { PelSup pelSup = pelSupList.get(position); holder.txNick.setText(pelSup.getNama().substring(0,1)); holder.txNama.setText(pelSup.getNama().toString()); holder.txNoTelp.setText(pelSup.getTelephone()); holder.id = pelSup.getId(); holder.tipe = pelSup.getTipe(); holder.alamat = pelSup.getAlamat(); holder.pos = String.valueOf(position); } @Override public int getItemCount() { return pelSupList.size(); } public class HolderData extends RecyclerView.ViewHolder implements View.OnClickListener { TextView txNama, txNoTelp, txNick; String id,tipe,alamat,pos; public HolderData(View itemView) { super(itemView); itemView.setOnClickListener(this); txNama = (TextView)itemView.findViewById(R.id.tx_namaps); txNoTelp = (TextView)itemView.findViewById(R.id.tx_notelpps); txNick = (TextView)itemView.findViewById(R.id.tx_nickps); } @Override public void onClick(View v) { Context context = v.getContext(); if (jenis.equals("0")||jenis.equals("1")){ Intent intent = new Intent(context, PelSupSelectedActivity.class); intent.putExtra("id",id); intent.putExtra("nama",txNama.getText().toString()); intent.putExtra("alamat",alamat); intent.putExtra("notelp",txNoTelp.getText().toString()); intent.putExtra("tipe",tipe); intent.putExtra("flag","0"); context.startActivity(intent); }else if (jenis.equals("3")){ Intent returnIntent = new Intent(); returnIntent.putExtra("result",String.valueOf(pos)); returnIntent.putExtra("id_pelsup",id); returnIntent.putExtra("nama",txNama.getText().toString()); ((ListPelSupActivity)activity).setResult(Activity.RESULT_OK,returnIntent); ((ListPelSupActivity)activity).setFinish(); }else if(jenis.equals("4")){ ((BayarPembelianActivity)activity).setSupplier(Integer.parseInt(pos)); } } } // Clean all elements of the recycler public void clear() { pelSupList.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<PelSup> list) { pelSupList.addAll(list); notifyDataSetChanged(); } public void updateList(List<PelSup> list){ pelSupList = list; notifyDataSetChanged(); } }
c85b792c0b1a698ad06b65c332845e7667be2886
961c1e82b1b1e58b6d34388209ed8aa8adad0e05
/src/test/java/uk/gov/hmcts/probate/businessrule/PA16FormBusinessRuleTest.java
ca55e52dfb81706b01c3ebf56e7d5e9b2d0b8227
[ "MIT" ]
permissive
hmcts/probate-back-office
3f838cfde035e7ea4b0c02168d2ad99a731dcfc2
09f3b8502a4bcc7db31838981ba28e1af4578dcd
refs/heads/master
2023-08-18T04:32:09.797012
2023-08-16T13:05:35
2023-08-16T13:05:35
128,388,317
5
10
MIT
2023-09-14T01:57:05
2018-04-06T11:50:57
Java
UTF-8
Java
false
false
2,766
java
package uk.gov.hmcts.probate.businessrule; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import uk.gov.hmcts.probate.model.ccd.raw.request.CaseData; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; import static uk.gov.hmcts.probate.model.Constants.NO; import static uk.gov.hmcts.probate.model.Constants.YES; class PA16FormBusinessRuleTest { @InjectMocks private PA16FormBusinessRule underTest; @Mock private CaseData mockCaseData; @BeforeEach public void setup() { openMocks(this); } @Test void shouldBeApplicableForChildAdoptedNoApplicantSiblingsRenouncing() { when(mockCaseData.getSolsApplicantRelationshipToDeceased()).thenReturn("ChildAdopted"); when(mockCaseData.getSolsApplicantSiblings()).thenReturn(NO); when(mockCaseData.getSolsSpouseOrCivilRenouncing()).thenReturn(YES); assertTrue(underTest.isApplicable(mockCaseData)); } @Test void shouldBeApplicableForChildNoApplicantSiblingsYesRenouncing() { when(mockCaseData.getSolsApplicantRelationshipToDeceased()).thenReturn("Child"); when(mockCaseData.getSolsApplicantSiblings()).thenReturn(NO); when(mockCaseData.getSolsSpouseOrCivilRenouncing()).thenReturn(YES); assertTrue(underTest.isApplicable(mockCaseData)); } @Test void shouldNOTBeApplicableForNotChildAdoptedNoApplicantSiblingsNoRenouncing() { when(mockCaseData.getSolsApplicantRelationshipToDeceased()).thenReturn("SpouseOrCivil"); when(mockCaseData.getSolsApplicantSiblings()).thenReturn(NO); when(mockCaseData.getSolsSpouseOrCivilRenouncing()).thenReturn(YES); assertFalse(underTest.isApplicable(mockCaseData)); } @Test void shouldNOTBeApplicableForChildAdoptedYesApplicantSiblingsYesRenouncing() { when(mockCaseData.getSolsApplicantRelationshipToDeceased()).thenReturn("ChildAdopted"); when(mockCaseData.getSolsApplicantSiblings()).thenReturn(YES); when(mockCaseData.getSolsSpouseOrCivilRenouncing()).thenReturn(YES); assertFalse(underTest.isApplicable(mockCaseData)); } @Test void shouldNOTBeApplicableForChildAdoptedNoApplicantSiblingsNoRenouncing() { when(mockCaseData.getSolsApplicantRelationshipToDeceased()).thenReturn("ChildAdopted"); when(mockCaseData.getSolsApplicantSiblings()).thenReturn(NO); when(mockCaseData.getSolsSpouseOrCivilRenouncing()).thenReturn(NO); assertFalse(underTest.isApplicable(mockCaseData)); } }
f77d0aa50aa312bf6907d13a5463558dbdb3a531
5275bc4932db32eb7f2e06b799e7f124c2f06181
/cis/src/main/java/cn/haohao/cis/notice/vo/NoticeQueryObj.java
901c6a655b620b2901aa459314c0b51fb63342e4
[]
no_license
liyl1991/commission-info-system
7a93dae3d180537f9ff708ce9ea3648970ef6965
ceaa3c47813268eca1fce7b5b0eef180c838cd48
refs/heads/master
2021-01-23T02:30:03.393207
2015-08-27T03:01:36
2015-08-27T03:01:36
31,420,391
0
1
null
null
null
null
UTF-8
Java
false
false
2,163
java
package cn.haohao.cis.notice.vo; //j-import-b import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; import cn.haohao.vas.core.vo.IPageable; import cn.haohao.cis.notice.model.Notice; //j-import-e /** * VO */ public class NoticeQueryObj extends Notice implements IPageable{ private static final long serialVersionUID = 1L; /** * 名字匹配 */ private String titleMatch; /** * 访问者id */ private Integer visitorId; /** * 页面大小 */ private int pageSize = 10; /** * 当前页 */ private int currentPage = 1; /** * 排序 */ private Sort sort; public Integer getVisitorId() { return visitorId; } public void setVisitorId(Integer visitorId) { this.visitorId = visitorId; } public String getTitleMatch() { return titleMatch; } public void setTitleMatch(String titleMatch) { this.titleMatch = titleMatch; } public Integer getStartRowNum() { if (currentPage < 1) currentPage = 1; return (currentPage - 1) * pageSize; } public Integer getEndRowNum() { if (currentPage < 1) currentPage = 1; return (currentPage) * pageSize; } public int getPageNumber() { return this.currentPage; } public int getPageSize() { return this.pageSize; } public int getOffset() { return currentPage*pageSize; } public Sort getSort() { return this.sort; } public NoticeQueryObj next() { this.currentPage += 1; return this; } public NoticeQueryObj previousOrFirst() { if(currentPage != 1) this.currentPage -= 1; return this; } public NoticeQueryObj first() { this.currentPage = 1; return this; } public boolean hasPrevious() { return this.currentPage>1; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setSort(Sort sort){ this.sort = sort; } public void setSort(List<Order> orders){ this.sort = new Sort(orders); } }
0478db1e6d3009dff1fc39d321584f49daf0a5c9
c6d7b5092c710002a9bf213b8ca01b48b935e17a
/petPetBoot/src/main/java/com/petAdopt/springboot/controller/Basic.java
d9d767e03d6b38468799f34822701991dce7e039
[]
no_license
roger0968672/TEST
eea9ceafb4feb42cb818e91e0ea4fcf37ef6e87f
d02fe085d05ddabe5495981d2f4d7cb184e074d3
refs/heads/main
2023-08-05T06:45:41.773271
2021-09-13T13:13:29
2021-09-13T13:13:29
389,244,382
0
0
null
null
null
null
UTF-8
Java
false
false
696
java
package com.petAdopt.springboot.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class Basic { @GetMapping("/Test") public String testajax() { return"TestAjax"; } @GetMapping("/hello") public String hello( @RequestParam(value="name",required=false) String vis ,Model m) { String mes=vis !=null ? vis+"您好" : "訪客,您好"; m.addAttribute("hellomsg", mes); return "greeting"; } }
[ "Student@DESKTOP-EKRVM5K" ]
Student@DESKTOP-EKRVM5K
722477b8582d082cc51799235c2a6d8d9dd6b4a8
de911552d30f5b640987ff8387163205e6ea6ea3
/app/src/main/java/com/newsdemo/model/http/response/GoldHttpResponse.java
5e27775965127fbf5050c80093a9ad4031e4e7b8
[]
no_license
MrHuJianQiang/NewsDemo
d170b8639df243129223ed469caa0519937196aa
bdab42e59cb4a36d8d2f74c06cde7ab91ff45c4c
refs/heads/master
2021-01-20T16:27:29.851681
2017-06-09T08:11:21
2017-06-09T08:11:21
90,842,185
2
0
null
null
null
null
UTF-8
Java
false
false
286
java
package com.newsdemo.model.http.response; /** * Created by jianqiang.hu on 2017/5/11. */ public class GoldHttpResponse<T> { private T results; public T getResults(){ return results; } public void setResults(T results){ this.results=results; } }
c4822722367f57513fd28d7dd01b23822cb3fbe8
78bdc24b10434008c4361ae104e8338146515eb0
/src/main/java/br/com/alura/forum/Models/Topico.java
603b38360277a3079e2367d717ed2fbdb0e70a84
[]
no_license
gabrielpoke/Spring-boot-API-REST
6913b4010c96da72a986ae7fe65031e0669020f5
0a3dc519fa1e882526752da015e028e03e2907d6
refs/heads/main
2023-05-28T21:44:27.218015
2021-06-15T21:34:32
2021-06-15T21:34:32
376,944,628
0
0
null
null
null
null
UTF-8
Java
false
false
2,284
java
package br.com.alura.forum.Models; import javax.persistence.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Entity public class Topico { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String titulo; private String mensagem; private LocalDateTime dataCriacao = LocalDateTime.now(); @Enumerated(EnumType.STRING) private StatusTopico status = StatusTopico.NAO_RESPONDIDO; @ManyToOne private Usuario autor; @ManyToOne private Curso curso; @OneToMany(mappedBy = "topico") private List<Resposta> respostas = new ArrayList<>(); public Topico(){} public Topico(String titulo, String mensagem, Curso curso) { this.titulo = titulo; this.mensagem = mensagem; this.curso = curso; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Topico other = (Topico) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getMensagem() { return mensagem; } public void setMensagem(String mensagem) { this.mensagem = mensagem; } public LocalDateTime getDataCriacao() { return dataCriacao; } public void setDataCriacao(LocalDateTime dataCriacao) { this.dataCriacao = dataCriacao; } public StatusTopico getStatus() { return status; } public void setStatus(StatusTopico status) { this.status = status; } public Usuario getAutor() { return autor; } public void setAutor(Usuario autor) { this.autor = autor; } public Curso getCurso() { return curso; } public void setCurso(Curso curso) { this.curso = curso; } public List<Resposta> getRespostas() { return respostas; } public void setRespostas(List<Resposta> respostas) { this.respostas = respostas; } }
c92a0c2a4716d530af36c145d8e5de1143ec08f2
6eb86b69c3057d853daac3002ff4fa5e5dcadb36
/src/view/javafx/MVVMDemoJFXController.java
c09d8d753021050cbd3b724471c5c8c6b4496c1f
[]
no_license
EWCMF/MVVMDemoJFX
5fbd1ddfbc8620d47a36ef8bfb70326be8ae2943
3cfb52fb5500436c290b3be85a77f337b7b3bc22
refs/heads/master
2021-01-02T18:15:53.338663
2020-02-15T11:11:27
2020-02-15T11:11:27
239,739,384
0
0
null
null
null
null
UTF-8
Java
false
false
1,203
java
package view.javafx; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import persistence.SQLiteDBJava; import view.TrueCasePresenter; import java.util.Observable; import java.util.Observer; public class MVVMDemoJFXController { @FXML private TextField textField; @FXML private Label label; @FXML private Button button; SQLiteDBJava db; TrueCasePresenter trueCasePresenter; public void initialize() { db = new SQLiteDBJava(null); trueCasePresenter = new TrueCasePresenter(db.getModel()); label.setText(trueCasePresenter.getString()); button.setOnAction(event -> changeText()); trueCasePresenter.addObserver(new Observer() { @Override public void update(Observable observable, Object o) { if (observable instanceof TrueCasePresenter) { String string = ((TrueCasePresenter) observable).getString(); label.setText(string); } } }); } public void changeText() { trueCasePresenter.setString(textField.getText()); } }
2d4363fa211868212897f245a7a13933c4bd546f
dbe40c665f11ecfc3349bd84d7629f1e13720ac4
/src/com/company/Main.java
f04f53d037c8d669540c996f7f11d74fb729eb70
[]
no_license
SakanaKoi/NDrop
3163183499d15d64463b5dcef9dccd1e14df6d78
252845fec77791fce689a1c18096277cfe45d2bb
refs/heads/master
2023-01-05T16:28:21.740413
2020-11-03T07:07:47
2020-11-03T07:07:47
309,602,516
0
0
null
null
null
null
UTF-8
Java
false
false
993
java
package com.company; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //проблема: прямой доступ к полям класса. Такое нежелательно. NDrob fract1 = new NDrob(); //fract1.num = 3; //fract1.denom = 5; fract1.setNum(3); fract1.setDenom(5); NDrob fract2 = new NDrob(); //fract2.num = sc.nextInt(); //fract2.denom = sc.nextInt(); fract2.setNum(sc.nextInt()); fract2.setDenom(sc.nextInt()); fract1.print(); System.out.println(fract2); System.out.println(fract1.multi(fract2).evqleed(fract1.multi(fract2))); System.out.println(fract1.div(fract2).evqleed(fract1.div(fract2))); System.out.println(fract1.sum(fract2).evqleed(fract1.sum(fract2))); System.out.println(fract1.differ(fract2).evqleed(fract1.differ(fract2))); } }
c36dd33a2516edaae9c400a9434832b004ac811f
545ed699c8fcf2f77e38c8978f70bef74c4d0b4c
/app/src/main/java/appewtc/masterung/bookmeetingpbru/MyOpenHelper.java
ebf41ed647d0dff8851964aa30eaa89fe8868e4f
[]
no_license
kayapon/Book-Meeting-PBRU
4a4fb1b4f72c06f13308ebbaeb3d0da0a8577501
c61cebccc7c0736994f273d3475a3f3f3886980c
refs/heads/master
2016-09-13T11:36:20.281841
2016-05-25T11:43:17
2016-05-25T11:43:17
59,450,212
0
0
null
null
null
null
UTF-8
Java
false
false
1,048
java
package appewtc.masterung.bookmeetingpbru; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by masterUNG on 5/24/16 AD. */ public class MyOpenHelper extends SQLiteOpenHelper{ //Explicit public static final String database_name = "Pbru.db"; private static final int database_version = 1; private static final String create_user_table = "create table userTABLE (" + "_id integer primary key," + "Name text," + "Surname text," + "IDcard text," + "Office text," + "User text," + "Password text);"; public MyOpenHelper(Context context) { super(context, database_name, null,database_version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(create_user_table); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } } // Main Class
574a628a8b050d0379f4e643d4b345b1b8188472
389e2751dc19c8e6213ae566e6fbd70fff820de9
/tropicraft/1.6.2/src/packages/CoroUtil/util/CoroUtilNBT.java
89a42b2a4c3374e2cd25ecee127df58c0c3edbd8
[]
no_license
Cojomax99/Tropicraft-Archive
9bbb47da5e00bf45ed1397fea1db9d45b546294c
130497ac9cd146af3a6f6c800474e382c909b710
refs/heads/master
2021-01-13T02:24:11.791169
2014-11-06T16:54:06
2014-11-06T16:54:06
26,279,814
0
2
null
null
null
null
UTF-8
Java
false
false
2,413
java
package CoroUtil.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChunkCoordinates; import CoroUtil.OldUtil; public class CoroUtilNBT { public static NBTTagCompound copyOntoNBT(NBTTagCompound nbtSource, NBTTagCompound nbtDest) { NBTTagCompound newNBT = (NBTTagCompound) nbtDest.copy(); //do magic try { Collection dataCl = nbtSource.getTags(); Iterator it = dataCl.iterator(); while (it.hasNext()) { NBTBase data = (NBTBase)it.next(); newNBT.setTag(data.getName(), data); } } catch (Exception ex) { ex.printStackTrace(); } return newNBT; } /*private static NBTTagCompound copyOntoNBTTagCompound nbtSource, NBTTagCompound nbtDest) { NBTTagCompound }*/ //this should probably be recursive /*private static NBTTagCompound copyOntoRecursive(NBTTagCompound nbtSource, NBTTagCompound nbttagcompound) { try { Collection dataCl = nbtSource.getTags(); Iterator it = dataCl.iterator(); while (it.hasNext()) { NBTBase data = (NBTBase)it.next(); if (data instanceof NBTTagCompound) { NBTTagCompound resultCopy = copyOntoRecursive((NBTTagCompound)data, nbttagcompound); } String entryName = data.getName(); } //nbttagcompound = new NBTTagCompound(this.getName()); Map tagMap = (Map)c_CoroAIUtil.getPrivateValueSRGMCP(NBTTagCompound.class, nbtSource, "tagMap", "tagMap"); Iterator iterator = tagMap.entrySet().iterator(); while (iterator.hasNext()) { String s = (String)iterator.next(); nbttagcompound.setTag(s, ((NBTBase)tagMap.get(s)).copy()); } } catch (Exception ex) { ex.printStackTrace(); } return nbttagcompound; }*/ public static void writeCoords(String name, ChunkCoordinates coords, NBTTagCompound nbt) { nbt.setInteger(name + "X", coords.posX); nbt.setInteger(name + "Y", coords.posY); nbt.setInteger(name + "Z", coords.posZ); } public static ChunkCoordinates readCoords(String name, NBTTagCompound nbt) { if (nbt.hasKey(name + "X")) { return new ChunkCoordinates(nbt.getInteger(name + "X"), nbt.getInteger(name + "Y"), nbt.getInteger(name + "Z")); } else { return null; } } }
57a41308edfbe04022f042da1715f107d652aa4b
fda2971901092ec64e0ad508459bac688b796ceb
/src/main/java/com/win/payrollproject/PayRoll/EmployeeNotFoundAdvice.java
5b94b37481ac0bfd01afd0886dd71e30cdce5c4e
[]
no_license
aprajitayadav/SpringBoot_PayRoll_HW0625_AY
df436326c78a52f8dbabac49331e0178b2ced2b8
5ae2bf371b10943399faa54d8c8f5374d4c8f9b5
refs/heads/master
2022-11-07T09:33:12.558451
2020-06-26T02:40:03
2020-06-26T02:40:03
275,058,596
0
0
null
null
null
null
UTF-8
Java
false
false
611
java
package com.win.payrollproject.PayRoll; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice class EmployeeNotFoundAdvice { @ResponseBody @ExceptionHandler(EmployeeNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) String employeeNotFoundHandler(EmployeeNotFoundException ex) { return ex.getMessage(); } }
762cafb5802901505b18b533b9ce3b20d473ee29
28a6fc8602b1f1dc8bde851838836988309ff967
/src/main/java/com/hzy/config/SwaggerConfig.java
a621c7dd80cbe3133b5cee0510efe3391f436012
[]
no_license
sunyaohui/springboot-admin
536f88185682c0560ca6892bbbb72db11adbdfe4
8040f483e5ae9db504ae6e0656b55c55c309d2f2
refs/heads/master
2022-07-01T03:43:02.527731
2019-05-30T01:28:58
2019-05-30T01:28:58
189,323,899
0
1
null
2020-07-01T18:47:51
2019-05-30T01:27:32
Java
UTF-8
Java
false
false
2,565
java
package com.hzy.config; import java.util.ArrayList; import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.base.Predicates; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.ApiSelectorBuilder; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { private static final String TITLE = "api文档"; private static final String VERSION = "1.0"; //监控所有的url private static final String INTERCEPT_URL = "/.*"; //参数:token private static final String HEADER_NAME = "token"; //参数备注信息 private static final String HEADER_DESCRIPTION = "请求头信息"; //请求参数类型,header private static final String HEADER_PAR_TYPE = "header"; //是否必填:非必填 private static final Boolean HEADER_PAR_REQUIRED = false; //参数数据类型,String private static final String DATA_TYPE = "string"; @SuppressWarnings("unchecked") @Bean public Docket api() { ApiSelectorBuilder asb = new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo(TITLE)) .pathMapping("/") .select(); List<String> list = YmlConfigStore.getBaseYmls().getSwagger().getSwaggerFilterUrl(); for (int i = 0; i < list.size(); i++) { asb.paths(Predicates.not(PathSelectors.regex(list.get(i)))); } return asb.paths(PathSelectors.regex(INTERCEPT_URL)) .build() .globalOperationParameters(parameterBuilder()); } private List<Parameter> parameterBuilder() { ParameterBuilder tokenPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<Parameter>(); tokenPar.name(HEADER_NAME) .description(HEADER_DESCRIPTION) .modelRef(new ModelRef(DATA_TYPE)) .parameterType(HEADER_PAR_TYPE) .required(HEADER_PAR_REQUIRED) .build(); pars.add(tokenPar.build()); return pars; } private ApiInfo apiInfo(String desc) { return new ApiInfoBuilder() .title(desc) .version(VERSION) .build(); } }
5ce1bb693040191086fc8c0d607534b925c9b846
19ca16ce5f224da01df497e73f5f6a83fca9b781
/src/main/java/com/zxh/springbootl/mapper/UserMapper.java
d880177888db8b475fdb14f0612ea368472b8e38
[]
no_license
zxhzxhtest/Community
c2208b8fe3064c012445feff1def8805074c0a0f
c70ecc89f098f2d2d30f8f643205b3e51978a5aa
refs/heads/master
2022-06-26T12:56:23.144656
2019-12-26T13:40:36
2019-12-26T13:40:36
230,090,761
0
0
null
2022-06-17T02:46:52
2019-12-25T11:08:54
Java
UTF-8
Java
false
false
488
java
package com.zxh.springbootl.mapper; import com.zxh.springbootl.model.User; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface UserMapper { // @Select("select * from user where id=#{id}") @Insert("insert into User (name,account_id,token,gmt_create,gmt_modified) values (#{name},#{accountId},#{token},#{gmtCreate},#{gmtModified})") void insertUser(User user); }
0e43b55767c6d116184615d16ba5621ba25077fd
8cc604d67d76f07a5c43926d56f5db42d64c6879
/weixiao/weixiao/weixiao-entity/src/main/java/com/zjw/graduation/enums/EnumStatusType.java
4aec02fbf0ee81f0bda22e699e633318bc516839
[]
no_license
small-little-time/weixiao-center
7b702aa83a94c20bd263d756e86ebe55bd68e28b
f7f60de9b4551b2e93647b6bd79085e4621b81c2
refs/heads/master
2022-12-16T03:13:49.684757
2020-09-11T07:14:52
2020-09-11T07:14:52
293,831,699
1
0
null
null
null
null
UTF-8
Java
false
false
581
java
package com.zjw.graduation.enums; public enum EnumStatusType { ERROR(-1,"数据异常"),LOSE(-2, "token失效"),NOTALLOW(-3, "没有权限"); private Integer value; private String type; EnumStatusType(Integer value, String type) { this.value = value; this.type = type; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
92b6c78f2c09da464e075fbed76960b71c237c66
c309d18e695caf34b40efff3db98e75542071042
/src/controller/TelaEditaAviaoController.java
921191046b7e4537a7a22c2dc7a6e7e80f91522b
[]
no_license
LucasGuasselli/Venda_Passagem_Aerea_FX
0c18e108fcdaaac9927d4099f40560174998c543
b3409414eece96965d1f792216e488aad63ee303
refs/heads/master
2021-01-21T15:06:58.211799
2017-07-13T19:59:05
2017-07-13T19:59:05
95,376,330
0
0
null
null
null
null
UTF-8
Java
false
false
8,935
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import DAO.AviaoDAO; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.util.Callback; import model.Aviao; import util.Digita; /** * * @author Lucas Guasselli * @since 03/07/2017 * @version 3.2 * */ public class TelaEditaAviaoController implements Initializable { @FXML AnchorPane telaEditaAviao; @FXML private TextField tfCodigo_alterar; @FXML private TextField tfCodigo; @FXML private TextField tfNome; @FXML private TextField tfQtdeAssentos; @FXML private TableView<Aviao> tableViewAviao; @FXML private TableColumn<Aviao, String> tableColumnCodigo; @FXML private TableColumn<Aviao, String> tableColumnNome; @FXML private TableColumn<Aviao, String> tableColumnQtdeAssentos; private List<Aviao> listaAvioes; private ObservableList<Aviao> observableListAvioes; private AviaoDAO aDAO = new AviaoDAO(); private Digita d = new Digita(); private Aviao avi = null; @FXML private void onActionEditar(ActionEvent event) throws ClassNotFoundException, SQLException { if(verificaCamposVazios() == true){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("CAMPOS VAZIOS"); alert.setHeaderText(null); alert.setContentText("Voce deve preencher todos os campos!!"); alert.showAndWait(); }else{ if(validaCampos() == false){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("CAMPOS CHEIOS"); alert.setHeaderText(null); alert.setContentText("Voce excedeu a quantidade de caracteres de algum campo!!"); alert.showAndWait(); }else{ if(aDAO.verificaAviaoByCod(Integer.parseInt(tfCodigo_alterar.getText())) == true){ editarAviao(); }else{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("ERRO"); alert.setHeaderText(null); alert.setContentText("Aviao nao cadastrado!!"); alert.showAndWait(); }//fecha if-else }//fecha if-else }//fecha if-else }//fecha handle event @Override public void initialize(URL url, ResourceBundle rb) { try{ listaAvioes = aDAO.retornaListaAvioes(); carregaTableViewAvioes(); }catch(Exception e){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("EXCEÇÃO"); alert.setHeaderText(null); alert.setContentText("erro ao receber avioes do banco!"); alert.showAndWait(); }//try-catch }//fecha initialize private void carregaTableViewAvioes() { tableColumnCodigo.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<Aviao,String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<Aviao, String> linha) { final Aviao aviao = linha.getValue(); final SimpleObjectProperty<String> simpleObject = new SimpleObjectProperty( Integer.toString(aviao.getCodigo()) ); return simpleObject; } }); tableColumnNome.setCellValueFactory(new PropertyValueFactory<>("nome")); tableColumnQtdeAssentos.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<Aviao,String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<Aviao, String> linha) { final Aviao aviao = linha.getValue(); final SimpleObjectProperty<String> simpleObject = new SimpleObjectProperty( Integer.toString(aviao.getQtdeAssentos()) ); return simpleObject; } }); observableListAvioes = FXCollections.observableArrayList(listaAvioes); tableViewAviao.setItems(observableListAvioes); }//fecha metodo carregaTableView private void editarAviao(){ Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacao"); alert.setHeaderText(null); alert.setContentText("Voce tem certeza sobre editar este aviao?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ try{ avi = (aDAO.retornaAviaoByCod(Integer.parseInt(tfCodigo_alterar.getText()))); String nome = tfNome.getText(); nome = nome.toLowerCase(); nome = nome.substring(0,1).toUpperCase().concat(nome.substring(1)); aDAO.editarAviao(new Aviao(avi.getId(),Integer.parseInt(tfCodigo.getText()), nome, Integer.parseInt(tfQtdeAssentos.getText()))); alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("SUCESSO!"); alert.setHeaderText(null); alert.setContentText("Aviao editado com sucesso!"); alert.showAndWait(); } catch (Exception e){ alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("EXCEÇÃO"); alert.setHeaderText(null); alert.setContentText("erro ao editar aviao!"); alert.showAndWait(); }//try-catch } else { alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("CANCELADO!"); alert.setHeaderText(null); alert.setContentText("edicao cancelada com sucesso!"); alert.showAndWait(); }//fecha if-else }//fecha editar Aviao @FXML private void onActionLimpar(ActionEvent event){ limpar(); }//fecha onActionLimpar @FXML private void tratarBotaoVoltar(ActionEvent event) throws IOException { System.out.println("Voltar"); Stage stage = (Stage) telaEditaAviao.getScene().getWindow(); stage.close(); }//fecha botao voltar private void limpar(){ tfCodigo_alterar.setText(""); tfCodigo.setText(""); tfNome.setText(""); tfQtdeAssentos.setText(""); }//fecha limpar private boolean verificaCamposVazios() { if(tfCodigo_alterar.getText().isEmpty() || tfCodigo.getText().isEmpty() || tfNome.getText().isEmpty() || tfQtdeAssentos.getText().isEmpty()){ return true; }//fecha if return false; }//fecha verificaCampos Vazios private boolean validaCampos(){ try{ if(d.validaCodigo(tfCodigo_alterar.getText()) && d.validaCodigo(tfCodigo.getText()) == true && d.validaNome(tfNome.getText()) == true && d.validaQtdeAssentos(tfQtdeAssentos.getText()) == true){ return true; } }catch(Exception e){ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("EXCEÇÃO"); alert.setHeaderText(null); alert.setContentText("DIGITE UM NUMERO INTEIRO"); alert.showAndWait(); }//fecha try-catch return false; }//fecha validaCampos }//fecha classe
91dadae1de7e68b36a24eac6287b6a97d5b441a8
944900e3d66eb8ce606c791239ed90dbe04de05d
/SistemaPontoAcesso/src/main/java/com/dio/live/swagger/SwaggerConfig.java
17450cb3abdc5e27daf5dd83f8a68c2f93edfd9e
[]
no_license
gerson002/controle-acesso-spring-boot
64030469c2da43fd310bb054380cc906bb5a3540
7784f607b0fbc67541ce00d371988fe787abda87
refs/heads/main
2023-07-08T16:27:34.198426
2021-08-11T01:46:31
2021-08-11T01:46:31
394,825,971
0
0
null
null
null
null
UTF-8
Java
false
false
2,125
java
package com.dio.live.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Collections; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket apiAdmin() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.dio.live")) .paths(PathSelectors.ant("/**")) .build() .apiInfo(apiInfo()) .globalOperationParameters( Collections.singletonList( new ParameterBuilder() .name("Authorization") .description("Header para Token JWT") .modelRef(new ModelRef("string")) .parameterType("header") .required(false) .build())); } @Bean public ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API-REST") .description("super live code") .version("1.0.0") .license("Apache License Version 2.0") .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0") .contact(new Contact("DIO", "https://web.digitalinnovation.one", "[email protected]")) .build(); } }
8173677f39ccd29502adb4bbdf817a035110832a
792c024f4917fcaeccd7a4dfacf4f3e30fbaeab9
/src/ua/artcode/week6/ex/TestUncheckedEx.java
e171f0432d3f54b223ab8cd918ffcff657f851cb
[]
no_license
presly808/ACO4
96db9134c3826bf2147c25927e698e81fa4c504b
0cd4500c9dafac056ad1026ad112ac198ec8cc9e
refs/heads/master
2021-01-02T09:19:46.728536
2015-04-04T11:56:19
2015-04-04T11:56:19
30,460,700
0
0
null
null
null
null
UTF-8
Java
false
false
301
java
package ua.artcode.week6.ex; import java.util.Arrays; /** * Created by serhii on 21.03.15. */ public class TestUncheckedEx { public static void main(String[] args) { int a = 8; int b = 10; int res = b / a; System.out.println("res = " + res); } }
0e7453189d6bd704a37e6050d9d0863c7c2e05eb
b96ee7ae537733dba2046c13b053067b2845dee4
/play-form/app/services/MyService.java
ab51259b2c397adf4390e4386d439046b3889941
[ "Apache-2.0" ]
permissive
sangth95/play-service-ebean
2ce7f093f57ac1e82730efe5ecadbdf8f1a19797
beaffccee0cf3cdcc15662f9c345d371f5b61476
refs/heads/master
2020-06-17T14:42:44.906368
2016-11-30T10:57:12
2016-11-30T10:57:12
74,994,039
0
0
null
null
null
null
UTF-8
Java
false
false
649
java
package services; import java.util.List; import com.fasterxml.jackson.databind.node.ArrayNode; import models.*; public interface MyService { //Course CRUD Course createCourse(Course course); Course readCourse(Integer id); Course updateCourse(Course course); Boolean deleteProject(Integer id); List<Course> allCourse(); ArrayNode allStudentInCourse(Integer id); Integer countCourse(); //Student CRUD Student createStudent(Student student); Student readStudent(Integer id); Student updateStudent(Student student); Boolean deleteStudent(Integer id); List<Student> allStudent(); Integer countStudent(); }
5e0005c4be6ee09086a8df11b987f28b190b7c9c
b6f5d180d2366dfd9a6b42e9465612a1faa99455
/DistWrapper/src/main/java/ash/nazg/dist/Main.java
c1b16714d4a7fb1a109f5d96996910359d22a0f6
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
d3v3l0/OneRing
830fe43870be409edea58a2425ad5dfb42f41477
c301dfa6880c844ee2c02f0170258302d54f2539
refs/heads/master
2022-11-09T08:59:26.772117
2020-06-17T20:09:11
2020-06-17T20:09:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,406
java
/** * Copyright (C) 2020 Locomizer team and Contributors * This project uses New BSD license with do no evil clause. For full text, check the LICENSE file in the root directory. */ package ash.nazg.dist; import ash.nazg.config.TaskWrapperConfigBuilder; import ash.nazg.config.WrapperConfig; import ash.nazg.spark.WrapperBase; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; public class Main { public static void main(String[] args) { TaskWrapperConfigBuilder configBuilder = new TaskWrapperConfigBuilder(); JavaSparkContext context = null; try { configBuilder.addRequiredOption("c", "config", true, "Config file"); configBuilder.addOption("d", "direction", true, "Copy direction. Can be 'from', 'to', or 'nop' to just validate the config file and exit"); configBuilder.addOption("o", "output", true, "Path to output distcp.ini"); configBuilder.setCommandLine(args); SparkConf sparkConf = new SparkConf() .setAppName(WrapperBase.APP_NAME) .set("spark.serializer", org.apache.spark.serializer.KryoSerializer.class.getCanonicalName()); if (configBuilder.hasOption("local")) { sparkConf .setMaster("local[*]") .set("spark.network.timeout", "10000"); if (configBuilder.hasOption("driverMemory")) { sparkConf .set("spark.driver.memory", configBuilder.getOptionValue("driverMemory")); } } context = new JavaSparkContext(sparkConf); context.hadoopConfiguration().set(FileInputFormat.INPUT_DIR_RECURSIVE, Boolean.TRUE.toString()); WrapperConfig config = configBuilder.build(context); configBuilder.overrideFromCommandLine("distcp.ini", "o"); configBuilder.overrideFromCommandLine("distcp.wrap", "d"); configBuilder.overrideFromCommandLine("distcp.store", "S"); new DistWrapper(context, config) .go(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } finally { if (context != null) { context.stop(); } } } }
7d6258441b1a4edef472ec55cc230a40a48d2fe4
dd3fc6592c58341d8a2364d9f9a1695f59c9009a
/JDBCproject/src/com/ltts/dao/Playerdao.java
e8c8585fa8ee7a7193c68302c31010d6582f8a19
[]
no_license
shreyansh1406/shareshadow
820c36f47358a26ddaad8c58e501f631e2f2ad6f
88906b977a9cf71b245eefcc0b39cd2db9023f28
refs/heads/main
2023-05-13T10:34:34.137908
2021-05-23T12:00:50
2021-05-23T12:00:50
345,407,548
0
0
null
null
null
null
UTF-8
Java
false
false
2,379
java
package com.ltts.dao; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.ltts.configuration.Connect; import com.ltts.model.Player; public class Playerdao { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public void add() throws Exception { Connection con=Connect.getConnection(); PreparedStatement pst=con.prepareStatement("insert into Player values(?,?,?,?)"); System.out.println("enter id,name ,skill,nom"); int id=Integer.parseInt(br.readLine()); String name=br.readLine(); String skill=br.readLine(); int nom=Integer.parseInt(br.readLine()); Player p=new Player(id,name,skill,nom); pst.setInt(1,id); pst.setString(2,name); pst.setString(3,skill); pst.setInt(4,nom); pst.executeUpdate(); System.out.println("record is inserted"); } public void delete() throws Exception { Connection con2=Connect.getConnection(); PreparedStatement pst2=con2.prepareStatement("delete from Player where Id=?"); System.out.println("enter the id to delete"); int id2=Integer.parseInt(br.readLine()); pst2.setInt(1,id2); pst2.executeUpdate(); System.out.println("record is deleted"); } public void getall() throws Exception { Connection con1=Connect.getConnection(); String query = "select * from Player"; PreparedStatement ps = con1.prepareStatement(query); ResultSet rs = ps.executeQuery(); // List<Player> ls = new ArrayList(); // while (rs.next()) { // Player emp = new Player(); // emp.setId(rs.getInt("Id")); // emp.setName(rs.getString("name")); // emp.setSkill(rs.getString("skill")); // emp.setId(rs.getInt("numberofmatches")); // // ls.add(emp); // } // return ls; while(rs.next()){ System.out.println(rs.getInt(1)+" " + rs.getString(2)+" " + rs.getString(3)+" " + rs.getInt(4)); } } public void update() throws Exception { Connection con1=Connect.getConnection(); PreparedStatement pst1=con1.prepareStatement("update Player set id=? "); System.out.println("enter the id to update"); int id1=Integer.parseInt(br.readLine()); pst1.setInt(1,id1); pst1.executeUpdate(); System.out.println("record is updated"); } }
6ceb23b900c3907d7865fb63308d172226b67b1f
fe0cf4ebaef708d5f47bf8401887f38132221a2e
/SJmp3/src/SJmp3/video/AviSampleReader.java
9c81033330f5cadb7d0785187a51f03203b14fc3
[]
no_license
Ygarr/sjmp3
f78392a716537e83ca292af38532abd29bb3a0c7
7b2d99ac260487e4eec27a447a28eda7e78eedd2
refs/heads/master
2021-01-20T01:17:10.586579
2017-04-24T14:20:39
2017-04-24T14:20:39
89,249,348
0
0
null
null
null
null
UTF-8
Java
false
false
7,852
java
package SJmp3.video; import java.io.IOException; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import net.sourceforge.parser.avi.Utils; import net.sourceforge.parser.avi.type.AviIndexChunk; import net.sourceforge.parser.avi.type.AviIndexIDX1; import net.sourceforge.parser.avi.type.AviStandardIndex; import net.sourceforge.parser.avi.type.AviStreamFormat; import net.sourceforge.parser.avi.type.List; import net.sourceforge.parser.util.ByteStream; import net.sourceforge.parser.util.TreeNode; public class AviSampleReader extends Thread { private boolean release_flag = false; private BlockingQueue<byte[]> videoSampleQueue; private AviParserWrapper wrapper; private PipedInputStream audio_stream; private PipedOutputStream audio_out; public AviSampleReader(AviParserWrapper wrapper, BlockingQueue<byte[]> videoSampleQueue) throws IOException { this(wrapper, videoSampleQueue, null); } public AviSampleReader(AviParserWrapper wrapper, BlockingQueue<byte[]> videoSampleQueue, InputStream audio_stream) throws IOException { this.wrapper = wrapper; this.videoSampleQueue = videoSampleQueue; if (audio_stream != null) { this.audio_out = new PipedOutputStream((PipedInputStream)audio_stream); this.audio_stream = (PipedInputStream)audio_stream; } start(); } public void run() { while(!release_flag) { try { readSamples(); release_flag = true; } catch (Exception e) { e.printStackTrace(); release_flag = true; } } } public void release() { release_flag = true; try { if (videoSampleQueue.remainingCapacity() == 0) videoSampleQueue.take(); videoSampleQueue.clear(); } catch (InterruptedException e) { e.printStackTrace(); } } public void readSamples() throws Exception { ByteStream stream = wrapper.getParser().getByteStream(); AviStreamFormat strf = (AviStreamFormat)wrapper.findChildByName("strf", wrapper.getVideoTrack(0)); AviIndexChunk video_super_index = (AviIndexChunk)wrapper.findChildByName("indx", wrapper.getVideoTrack(0)); AviIndexChunk audio_super_index = (AviIndexChunk)wrapper.findChildByName("indx", wrapper.getAudioTrack(0)); if (video_super_index == null || audio_super_index == null) { readSamplesIDX1(); return; } nextVideoStdIndex(video_super_index, stream); nextAudioStdIndex(audio_super_index, stream); boolean video_end = false; boolean audio_end = false; while(!release_flag || (video_end && audio_end)) { long video_offset = nextVideoOffset(video_super_index, stream); long audio_offset = nextAudioOffset(audio_super_index, stream); video_end = video_offset == -1; audio_end = audio_offset == -1; video_offset += video_std_index.qwBaseOffset; audio_offset += audio_std_index.qwBaseOffset; if (video_offset < audio_offset) { if (video_end) continue; video_index++; int sample_size = video_std_index.idx.get(video_index++); boolean key_frame = sample_size > 0; if (!key_frame) sample_size ^= (1 << 31); byte[] sample_data = new byte[sample_size]; stream.position(video_offset); stream.read(sample_data); //VideoSample sample = new VideoSample(sample_data, strf.format, 0); if(!release_flag) videoSampleQueue.offer(sample_data, 1 << 25, TimeUnit.MILLISECONDS); } else { if (audio_end) continue; audio_index++; int sample_size = audio_std_index.idx.get(audio_index++); boolean key_frame = sample_size > 0; if (!key_frame) sample_size ^= (1 << 31); if (audio_stream != null) { byte[] sample_data = new byte[sample_size]; stream.position(audio_offset); stream.read(sample_data); audio_out.write(sample_data); } } } } private int video_index; private int audio_index; private AviStandardIndex video_std_index; private AviStandardIndex audio_std_index; private long nextVideoOffset(AviIndexChunk video_super_index, ByteStream stream) throws IOException { if (video_index >= video_std_index.idx.capacity()) { nextVideoStdIndex(video_super_index, stream); if (video_std_index == null) return -1; video_index = 0; } return video_std_index.idx.get(video_index); } private void nextVideoStdIndex(AviIndexChunk video_super_index, ByteStream stream) throws IOException { long dwOffset = video_super_index.idx.get(); if (dwOffset == 0) { video_std_index = null; } else { long dwSize_dwDuration = video_super_index.idx.get(); stream.position(dwOffset); int type = (int)Utils.bytesToLong(stream, 4); long size = (int) Utils.bytesToLongLE(stream, 4); video_std_index = new AviStandardIndex(type, size); video_std_index.readData(stream); } } private long nextAudioOffset(AviIndexChunk audio_super_index, ByteStream stream) throws IOException { if (audio_index >= audio_std_index.idx.capacity()) { nextAudioStdIndex(audio_super_index, stream); if (audio_std_index == null) return -1; audio_index = 0; } return audio_std_index.idx.get(audio_index); } private void nextAudioStdIndex(AviIndexChunk audio_super_index, ByteStream stream) throws IOException { long dwOffset = audio_super_index.idx.get(); if (dwOffset == 0) { audio_std_index = null; } else { long dwSize_dwDuration = audio_super_index.idx.get(); stream.position(dwOffset); int type = (int)Utils.bytesToLong(stream, 4); long size = (int) Utils.bytesToLongLE(stream, 4); audio_std_index = new AviStandardIndex(type, size); audio_std_index.readData(stream); } } private boolean new_index = false; private int index = 0; public synchronized void setIndex(int index) { this.index = index; this.new_index = true; videoSampleQueue.clear(); } private static final int xt = 0x7874; private static final int bw = 0x6277; private static final int cd = 0x6364; private static final int bd = 0x6264; private static final int xi = 0x7869; public void readSamplesIDX1() throws Exception { List movie = (List)wrapper.findNode("LIST-movi"); AviStreamFormat strf = (AviStreamFormat)wrapper.findChildByName("strf", wrapper.getVideoTrack(0)); TreeNode node = wrapper.findNode("idx1"); AviIndexIDX1 avi_index = (AviIndexIDX1)node; boolean rel_pos = true; while(index < avi_index.idx1.capacity()) { if (release_flag) return; int ckid = avi_index.idx1.get(index++); int dwFlags = avi_index.idx1.get(index++); int dwChunkOffset = avi_index.idx1.get(index++); int dwChunkLength = avi_index.idx1.get(index++); if (index == 4 && (dwChunkOffset == movie.offset)) rel_pos = false; if (rel_pos) { wrapper.getParser().getByteStream().position((int)movie.offset + dwChunkOffset+4); } else wrapper.getParser().getByteStream().position(dwChunkOffset+8); if ((ckid >>> 16) == cd) { byte[] sample_data = new byte[dwChunkLength]; wrapper.getParser().getByteStream().read(sample_data); //VideoSample sample = new VideoSample(sample_data, strf.format, 0); videoSampleQueue.offer(sample_data, 1<<25, TimeUnit.MILLISECONDS); } else if ((ckid >>> 16) == bd) { byte[] sample_data = new byte[dwChunkLength]; wrapper.getParser().getByteStream().read(sample_data); //VideoSample sample = new VideoSample(sample_data, strf.format, 0); videoSampleQueue.offer(sample_data, 1<<25, TimeUnit.MILLISECONDS); } else if ((ckid >>> 16) == bw) { if (audio_stream != null) { byte[] sample_data = new byte[dwChunkLength]; wrapper.getParser().getByteStream().read(sample_data); audio_out.write(sample_data); } } else if ((ckid >>> 16) == xt) {} } } }
[ "Urbanterror1" ]
Urbanterror1
e1122aefe57ba1facf22041eae9a0d9da7b037ae
e801e0c3be2aabd014c57c722cf2b8e7260b4c36
/src/com/gmail/at/kevinburnseit/organizer/gui/DataFolderDialog.java
772d9a1b3410d677f93368ff23bce270488b14c2
[]
no_license
kjburns/task-calendar
c15c095b4ac1db7f6f5b7ba980d0d69c194bc580
2715ea3ed21022e9494421bf01e0016586ed0509
refs/heads/master
2020-04-18T01:14:46.985442
2015-10-18T14:43:39
2015-10-18T14:43:39
42,716,031
0
0
null
null
null
null
UTF-8
Java
false
false
5,494
java
package com.gmail.at.kevinburnseit.organizer.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JLabel; import com.gmail.at.kevinburnseit.organizer.Organizer; import com.gmail.at.kevinburnseit.swing.DialogResult; import com.gmail.at.kevinburnseit.swing.NewDialog; import com.gmail.at.kevinburnseit.swing.ValidatingTextBox; import com.gmail.at.kevinburnseit.swing.ValidatingTextBoxAction; import com.gmail.at.kevinburnseit.swing.ValidatingTextBoxValidator; public class DataFolderDialog extends NewDialog { private enum FolderValidationFailReasonEnum { READ_ONLY("Selected folder is read-only."), IS_NOT_DIRECTORY("Selection is not a folder."), PARENT_DNE("Parent of proposed folder does not exist."), PARENT_READ_ONLY("Parent of proposed folder is read-only."), PARENT_IS_NOT_DIRECTORY("Parent of proposed folder is not a folder."), EMPTY("Folder path cannot be empty."), ILLEGAL("Path name is not valid."); private String message; private FolderValidationFailReasonEnum(String msg) { this.message = msg; } /** * @return the message */ public String getMessage() { return message; } } private static final long serialVersionUID = 704172727734836624L; private static FolderValidationFailReasonEnum pathFailureReason = null; private static final ValidatingTextBoxValidator pathValidator = new ValidatingTextBoxValidator() { @Override public boolean validate(String newValue) { if (newValue == null) { pathFailureReason = FolderValidationFailReasonEnum.EMPTY; return false; } if (newValue.trim().length() == 0) { pathFailureReason = FolderValidationFailReasonEnum.EMPTY; return false; } File f = new File(newValue); if (f.exists()) { if (!f.isDirectory()) { pathFailureReason = FolderValidationFailReasonEnum.IS_NOT_DIRECTORY; return false; } if (!f.canWrite()) { pathFailureReason = FolderValidationFailReasonEnum.READ_ONLY; return false; } return true; } File parent = f.getParentFile(); if (parent == null) { pathFailureReason = FolderValidationFailReasonEnum.PARENT_DNE; return false; } if (!parent.exists()) { pathFailureReason = FolderValidationFailReasonEnum.PARENT_DNE; return false; } if (!parent.isDirectory()) { pathFailureReason = FolderValidationFailReasonEnum.PARENT_IS_NOT_DIRECTORY; return false; } if (!parent.canWrite()) { pathFailureReason = FolderValidationFailReasonEnum.PARENT_READ_ONLY; return false; } return true; } }; private Organizer org; private ValidatingTextBox dataPathTextBox; private JLabel failureLabel; private JButton browseButton; private JButton okButton; private JButton cancelBtn; public DataFolderDialog(Organizer app) { this.org = app; this.buildUI(); this.failureLabel.setVisible(false); } private void buildUI() { BoxLayout layout = new BoxLayout(this.contentPanel, BoxLayout.PAGE_AXIS); this.contentPanel.setLayout(layout); this.setTitle("Select Data Storage Folder"); JLabel label = new JLabel("Select folder to store program data:"); this.contentPanel.add(label); this.dataPathTextBox = new ValidatingTextBox(); this.dataPathTextBox.setValidationKey("path-text-box"); this.dataPathTextBox.addValidationListener(pathValidator); this.dataPathTextBox.setColumns(30); this.dataPathTextBox.setText(this.org.getAppDataPath()); this.contentPanel.add(this.dataPathTextBox); ImageIcon errorIcon = new ImageIcon( this.getClass().getClassLoader().getResource("res/error.png")); this.failureLabel = new JLabel(" "); this.failureLabel.setIcon(errorIcon); this.contentPanel.add(this.failureLabel); this.dataPathTextBox.addAfterValidationAction(new ValidatingTextBoxAction() { @Override public void afterValidation(boolean ok) { if (ok) failureLabel.setVisible(false); else { failureLabel.setText(pathFailureReason.getMessage()); failureLabel.setVisible(true); } } }); this.browseButton = this.addButton( "Browse for Folder...", null, ButtonTypeEnum.NONE); this.browseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { showFolderChooser(); } }); this.okButton = this.addButton("OK", DialogResult.OK, ButtonTypeEnum.DEFAULT); this.okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { org.setAppDataPath(dataPathTextBox.getText()); setVisible(false); } }); this.cancelBtn = this.addButton("Cancel", DialogResult.CANCEL, ButtonTypeEnum.CANCEL); this.cancelBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); } }); this.pack(); } protected void showFolderChooser() { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); File initFolder = new File(this.org.getAppDataPath()); if (!initFolder.exists()) initFolder = initFolder.getParentFile(); fc.setSelectedFile(initFolder); int ret = fc.showOpenDialog(this.org); if (ret == JFileChooser.APPROVE_OPTION) { this.dataPathTextBox.setText(fc.getSelectedFile().getAbsolutePath()); } } }
aa21135a5ecfeb4f58f360e239f607ba4a33849f
9d6cca167c6ed884130b78e7867454cd2f2ad9c8
/admin/src/main/java/com/wupaas/boot/admin/config/ShiroConfig.java
d1efa1c39756ad7395e5fcd860c14cdc8d9931f9
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-mulanpsl-1.0-en", "MulanPSL-1.0" ]
permissive
jueyue/windbell
470f6e7ad92d3b13dfa8df6afa0481bb34230bde
8af280adcac4da0d96801999a667935871b5bdd1
refs/heads/master
2022-11-01T02:26:09.168901
2021-04-14T15:40:23
2021-04-14T15:40:23
196,199,062
5
2
NOASSERTION
2022-10-12T20:29:03
2019-07-10T12:13:13
Java
UTF-8
Java
false
false
5,608
java
package com.wupaas.boot.admin.config; import com.wupaas.boot.core.business.security.shiro.*; import com.wupaas.boot.core.business.security.shiro.cache.RedisCacheManager; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.realm.Realm; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.web.filter.DelegatingFilterProxy; import javax.servlet.Filter; import java.util.*; /** * shiro的控制类 * Created by jeelus */ @Configuration public class ShiroConfig { @Bean public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public JwtAuthorizingRealm getJwtAuthorizingRealm() { return new JwtAuthorizingRealm(); } @Bean public RedisCacheManager getRedisCacheManager() { return new RedisCacheManager(); } /** * 并发登录控制 * * @return */ @Bean public LimitConcurrentSessionControlFilter limitConcurrentSessionControlFilter(CacheManager cacheManager) { LimitConcurrentSessionControlFilter limitConcurrentSessionControlFilter = new LimitConcurrentSessionControlFilter(); //使用cacheManager获取相应的cache来缓存用户登录的会话;用于保存用户—会话之间的关系的; limitConcurrentSessionControlFilter.setCacheManager(cacheManager); //是否踢出后来登录的,默认是false;即后者登录的用户踢出前者登录的用户; limitConcurrentSessionControlFilter.setKickoutAfter(false); return limitConcurrentSessionControlFilter; } @Bean("shiroFilter") public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager, IShiroPermissionsHandler permissionsHandler) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); Map<String, Filter> filterMap = new HashMap<>(); filterMap.put("restAuth", new RestUrlAuthorizationFilter()); filterMap.put("jwtAuth", new JwtAuthenticationFilter()); factoryBean.setFilters(filterMap); factoryBean.setSecurityManager(securityManager); factoryBean.setUnauthorizedUrl("/401"); Map<String, String> filterRuleMap = new LinkedHashMap<>(); permissionsHandler.getNotNeedPermissions().forEach(p -> filterRuleMap.put(p, "anon")); filterRuleMap.put("/admin/userAuth/login", "anon"); filterRuleMap.put("/**", "jwtAuth,restAuth"); factoryBean.setFilterChainDefinitionMap(filterRuleMap); return factoryBean; } @Bean(name = "basicHttpAuthenticationFilter") public BasicHttpAuthenticationFilter casFilter() { BasicHttpAuthenticationFilter basicHttpAuthenticationFilter = new BasicHttpAuthenticationFilter(); basicHttpAuthenticationFilter.setLoginUrl("/login"); return basicHttpAuthenticationFilter; } @Bean(name = "securityManager") public DefaultWebSecurityManager defaultWebSecurityManager( JwtAuthorizingRealm authorizingRealm, CacheManager cacheManager) { DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); defaultWebSecurityManager.setCacheManager(cacheManager); Collection<Realm> typeRealms = new ArrayList<>(); typeRealms.add(authorizingRealm); defaultWebSecurityManager.setRealms(typeRealms); return defaultWebSecurityManager; } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistration = new FilterRegistrationBean(); filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter")); filterRegistration.addInitParameter("targetFilterLifecycle", "true"); filterRegistration.setEnabled(true); filterRegistration.setOrder(2); filterRegistration.addUrlPatterns("/*"); return filterRegistration; } @Bean(name = "lifecycleBeanPostProcessor") public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean @DependsOn("lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); defaultAdvisorAutoProxyCreator.setProxyTargetClass(true); return defaultAdvisorAutoProxyCreator; } }
8dd1e3538650722eadd3fdde46afd100f35b7ce6
7ee56c8f8c1f34926107e00fb0abd3737dc4bcde
/ApplicationProgramming/src/Alphabet1.java
d2eb913008b058cc0392cdf19f18a436fb0a5f72
[]
no_license
lamin1990/java_encoding
ee1ffbb930e1eaf800a7b02449902add1bb86f51
90bc110f79918993ea9ee60397a4928bd7f5365d
refs/heads/master
2020-03-10T00:52:06.069019
2018-04-11T12:32:16
2018-04-11T12:32:16
129,093,504
0
0
null
null
null
null
UTF-8
Java
false
false
679
java
public class Alphabet1 { public static void main(String[] args) { // 1. Write the shortest possible program that outputs the numbers between 0 and 100 to the console. hint: use a loop. for(int i=1; i < 100; i++) System.out.println(i); // 2. Write the shortest possible program that outputs all the lower case letters of the alphabet to the console. hint: use a loop with a 'char' type variable. for(char c='a'; c <= 'z'; c++) System.out.println(c); // 3. Write the shortest possible program that outputs all the upper case letters of the alphabet, in reverse order, to the console. for(char c='Z'; c >= 'A'; c--) System.out.println(c); } }
d64076cd2e249ba50fe8329dfd6ac5038685c03a
392d8ef9b7d8762f1b30fb55786cb9a2f04b34ae
/Sharif/src/test1.java
6ec9cd66910888a86c0e8aaf86ffe35041ba4193
[]
no_license
sharifulgeo/repo1
9945cb4dfea73e36979f6c8d18565e29b8b5f37e
b6cb517a1874ec54806821c13145c1f8b5e10ff0
refs/heads/master
2020-05-20T06:04:06.860272
2013-07-09T08:45:17
2013-07-09T08:45:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
183
java
public class test1 { public test1() { // TODO Auto-generated constructor stub } public static void main(String[] args) { System.out.println("Im Bakul"); } }
[ "msig301331" ]
msig301331
2cca43f24792b57eb3937d9e45576ae102c82710
83d781a9c2ba33fde6df0c6adc3a434afa1a7f82
/MarketBackend/src/com/newco/marketplace/business/businessImpl/so/pdf/TermsConditionsPDFTemplateImpl.java
d8734d3d3eed9054ca3cc1caab4fcf94a11b8308
[]
no_license
ssriha0/sl-b2b-platform
71ab8ef1f0ccb0a7ad58b18f28a2bf6d5737fcb6
5b4fcafa9edfe4d35c2dcf1659ac30ef58d607a2
refs/heads/master
2023-01-06T18:32:24.623256
2020-11-05T12:23:26
2020-11-05T12:23:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,713
java
package com.newco.marketplace.business.businessImpl.so.pdf; import java.io.StringReader; import org.apache.log4j.Logger; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Image; import com.lowagie.text.List; import com.lowagie.text.PageSize; import com.lowagie.text.Phrase; import com.lowagie.text.html.simpleparser.StyleSheet; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import com.newco.marketplace.util.constants.SOPDFConstants; import com.newco.marketplace.utils.ServiceLiveStringUtils; public class TermsConditionsPDFTemplateImpl implements PDFTemplate{ private Logger logger = Logger.getLogger(TermsConditionsPDFTemplateImpl.class); private Image logoImage; private String termsCond; public void execute(PdfWriter pdfWriter, Document document) throws DocumentException { float pageWidth = PageSize.LETTER.getWidth(); float[] termsConditionsTableWidths = { 180, 180, 180 }; PdfPTable termsConditionsTable = new PdfPTable(termsConditionsTableWidths); termsConditionsTable.setSplitLate(false); PdfPCell cell = null; termsConditionsTable.getDefaultCell().setBorder(0); termsConditionsTable.setHorizontalAlignment(Element.ALIGN_CENTER); termsConditionsTable.setTotalWidth(pageWidth - 72); termsConditionsTable.setLockedWidth(true); //adding terms and conditions PdfPTable tableTermsCond = this.addTermsAndConditionsTable(); cell = new PdfPCell(tableTermsCond); cell.setColspan(3); cell.setMinimumHeight(300); termsConditionsTable.addCell(cell); // Empty Rows SOPDFUtils.addEmptyRow(3, 0, -1, termsConditionsTable); SOPDFUtils.addEmptyRow(3, 0, -1, termsConditionsTable); document.newPage(); document.add(termsConditionsTable); } /** * Method for adding terms and conditions to table * @param so * @return */ @SuppressWarnings("unchecked") private PdfPTable addTermsAndConditionsTable() { float[] tableTermsCondWidth = { 550 }; PdfPTable tableTermsCond = new PdfPTable(tableTermsCondWidth); tableTermsCond.getDefaultCell().setBorder(1); tableTermsCond.setHorizontalAlignment(Element.ALIGN_LEFT); PdfPCell cellTermsCond = null; StringReader strTermsCond = new StringReader(termsCond); StyleSheet style = new StyleSheet(); cellTermsCond = new PdfPCell(new Phrase(SOPDFConstants.BUYER_TERMS_COND, SOPDFConstants.FONT_HEADER)); cellTermsCond.setBorder(0); cellTermsCond.setHorizontalAlignment(Element.ALIGN_LEFT); tableTermsCond.addCell(cellTermsCond); //SL-20728 List termsAndConditions = null; String terms = termsCond; try { //replace html character entities terms = SOPDFUtils.getHtmlContent(terms); //Convert the html content to rich text termsAndConditions = SOPDFUtils.getRichText(terms, SOPDFConstants.FONT_LABEL_SMALL, null, SOPDFConstants.SPACE); } catch (Exception e) { logger.error("Error while converting rich text for " + SOPDFConstants.BUYER_TERMS_COND + e); termsAndConditions = null; } if(null != termsAndConditions && !termsAndConditions.isEmpty()){ cellTermsCond = new PdfPCell(); cellTermsCond.addElement(termsAndConditions); cellTermsCond.setBorder(0); tableTermsCond.addCell(cellTermsCond); } else{ terms = termsCond; //Remove the html tags terms = ServiceLiveStringUtils.removeHTML(terms); cellTermsCond = new PdfPCell(new Phrase(terms, SOPDFConstants.FONT_LABEL_SMALL)); cellTermsCond.setBorder(0); tableTermsCond.addCell(cellTermsCond); /*java.util.List<Paragraph> parasList = null; try { parasList = (java.util.List<Paragraph>)HTMLWorker.parseToList(strTermsCond, style); } catch (IOException ioEx) { logger.error("Unexpected IO Error while converting terms conditions HTML into list of iText Paragraphs", ioEx); } if (parasList != null) { for(Paragraph para : parasList) { cellTermsCond = new PdfPCell(new Phrase(para.getContent(), SOPDFConstants.FONT_LABEL_SMALL)); cellTermsCond.setBorder(0); tableTermsCond.addCell(cellTermsCond); } }*/ } cellTermsCond = new PdfPCell(new Phrase(" ")); cellTermsCond.setBorder(0); tableTermsCond.addCell(cellTermsCond); return tableTermsCond; } public Image getLogoImage() { return logoImage; } public void setLogoImage(Image logoImage) { this.logoImage = logoImage; } public String getTermsCond() { return termsCond; } public void setTermsCond(String termsCond) { this.termsCond = termsCond; } }
3a89da85294a11fd0737d077020915ea3ebfc9ce
166faa6f61e46955cda483af43ac77b01454ec52
/sportify-v1/src/main/java/caa/sportify/utility/CustomJList.java
1868d048e2aa958efe5b2b7b641b02928acc4368
[]
no_license
crispinakomea/sportify-v1
791122ee410f6987f32f24730ef20a7f3de64941
0881368de18b9cf169958290979ea892de8b4e8c
refs/heads/master
2021-04-29T16:03:40.516068
2018-10-06T20:37:51
2018-10-06T20:37:51
121,806,817
0
0
null
null
null
null
UTF-8
Java
false
false
444
java
package caa.sportify.utility; import java.awt.Color; import javax.swing.JList; import javax.swing.ListSelectionModel; /** * @author Crispin A. * */ @SuppressWarnings("serial") public class CustomJList extends JList<String> { public CustomJList(String[] array) { super(array); setFixedCellWidth(175); setFixedCellHeight(22); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setSelectionBackground(Color.darkGray); } }
3d317427879ad3b325cd541b5e98390f5a2a0d4d
ed3b5db79f904540bb8538b047d53f144f8ae3c5
/src/ssm170730/Timer.java
dbaf221650b1d4a0f171d6f7482b86b8ba7729ef
[]
no_license
maneshreyash/SkipList
9071530613d88514a7e22838682a09612a926a0e
3a74dbe8de529f3b803e13120ae2dc8293ad5566
refs/heads/master
2020-03-31T10:39:52.405061
2018-10-15T01:47:09
2018-10-15T01:47:09
152,143,602
0
2
null
null
null
null
UTF-8
Java
false
false
939
java
/** Timer class for roughly calculating running time of programs * @author rbk * Usage: Timer timer = new Timer(); * timer.start(); * timer.end(); * System.out.println(timer); // output statistics */ package ssm170730; public class Timer { long startTime, endTime, elapsedTime, memAvailable, memUsed; public Timer() { startTime = System.currentTimeMillis(); } public void start() { startTime = System.currentTimeMillis(); } public Timer end() { endTime = System.currentTimeMillis(); elapsedTime = endTime-startTime; memAvailable = Runtime.getRuntime().totalMemory(); memUsed = memAvailable - Runtime.getRuntime().freeMemory(); return this; } public String toString() { return "Time: " + elapsedTime + " msec.\n" + "Memory: " + (memUsed/1048576) + " MB / " + (memAvailable/1048576) + " MB."; } }
f13b3df1fab6e7d8967d085519e8a53cd72c75f7
f572e0ede050be232751940439b83a05f98273c0
/src/main/java/br/com/vagas/service/mapper/CursoMapper.java
e5e5e5d00be56312c9436507f98e1ff3d36cf9ab
[]
no_license
adailtonlima/portal-vagas-bt
8c4ba96115de6c387828a0be4f6fb98b341639cc
1c2389881366f2ecc7f885e1c9b058497379636e
refs/heads/main
2023-05-08T17:32:02.077641
2021-06-01T11:32:26
2021-06-01T11:32:26
372,805,501
0
0
null
2021-06-01T11:32:27
2021-06-01T11:28:34
Java
UTF-8
Java
false
false
455
java
package br.com.vagas.service.mapper; import br.com.vagas.domain.*; import br.com.vagas.service.dto.CursoDTO; import org.mapstruct.*; /** * Mapper for the entity {@link Curso} and its DTO {@link CursoDTO}. */ @Mapper(componentModel = "spring", uses = { PessoaMapper.class }) public interface CursoMapper extends EntityMapper<CursoDTO, Curso> { @Mapping(target = "pessoa", source = "pessoa", qualifiedByName = "nome") CursoDTO toDto(Curso s); }
90a6e58ad37c1633d2b613c934887b487ee0e003
73c99cac5b77da4dbaa8ac4731adf4d8e0d724f1
/Snatch/app/src/main/java/cl/snatch/snatch/receivers/PhoneObserver.java
b4b19f97ec2b88561a24d166155af10c1ae30589
[]
no_license
rmujica/snatch-android
91ad3aee554e4ec4783c28d705b6f1d4cf438993
fc3020e838ad3cfaab3210c554af1cc4ee8ca02b
refs/heads/master
2021-01-15T12:32:28.679270
2015-03-25T22:40:00
2015-03-25T22:40:00
29,935,736
0
0
null
null
null
null
UTF-8
Java
false
false
657
java
package cl.snatch.snatch.receivers; import android.database.ContentObserver; import android.net.Uri; import android.os.Handler; import android.util.Log; public class PhoneObserver extends ContentObserver { /** * Creates a content observer. * * @param handler The handler to run {@link #onChange} on, or null if none. */ public PhoneObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { onChange(selfChange, null); } @Override public void onChange(boolean selfChange, Uri uri) { Log.d("cl.snatch.snatch", "change happened"); } }
5e6fd514ae79064d8f7eff6626f0ec214df653da
42ead296aaa99e5448032e5e91f61048185aa993
/src/main/java/CalorieCalculator/model/service/UserDetailsServiceModel.java
1790c2dddccece70017a59cd16dea9c47594ca10
[]
no_license
Fatme98/calorie-calculator
bddb9f80b2a456ddf34e1e6d8a0464cd6c7539f1
b700813066c53d2f3bbee247331ff4f90e40fa4a
refs/heads/master
2023-05-03T04:51:14.442237
2021-05-14T11:45:30
2021-05-14T11:45:30
326,731,861
0
0
null
null
null
null
UTF-8
Java
false
false
1,623
java
package CalorieCalculator.model.service; public class UserDetailsServiceModel { private String id; private String username; private String password; private int age; private PhotoProfileServiceModel photoProfileServiceModel; private String wantedEffect; private double totalCalories; public UserDetailsServiceModel() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public PhotoProfileServiceModel getPhotoProfileServiceModel() { return photoProfileServiceModel; } public void setPhotoProfileServiceModel(PhotoProfileServiceModel photoProfileServiceModel) { this.photoProfileServiceModel = photoProfileServiceModel; } public String getWantedEffect() { return wantedEffect; } public void setWantedEffect(String wantedEffect) { this.wantedEffect = wantedEffect; } public double getTotalCalories() { return totalCalories; } public void setTotalCalories(double totalCalories) { this.totalCalories = totalCalories; } }
d2de571fdc58c2c9831fe38c4b16e6f64371c4bf
4890ef94b1cb226a51e3f43edfac43b4f64ad2c2
/src/main/java/Pages/HomePage/HomePage.java
8dab179b0f7045d036ca343e76650ae8160a8188
[]
no_license
eldadco/Java---selenium-project-using-testNG
fda578f5a3231a572cb61c2eb891cdb4ec8f58ed
821505beec85be13ca3ecdcc4c3fd505e27002b3
refs/heads/main
2023-04-04T03:25:13.819479
2021-04-19T18:06:10
2021-04-19T18:06:10
310,059,751
0
0
null
null
null
null
UTF-8
Java
false
false
243
java
package Pages.HomePage; import Pages.BasePage; import org.openqa.selenium.By; public class HomePage extends BasePage { public static final By featureTitles = By.cssSelector("#gatsby-focus-wrapper > div > section h2 span"); }
a711fb192aa3b6fd408fb8de4087e44f12033b90
3a359498e646a0202d498fe67c3f5a2af1e0bf3e
/springboot/20200325/springboot-start/src/main/java/com/jikaigg/springbootstart/SpringbootStartApplication.java
c6d5c03e509a6bd2e34f6237fd77e9a3add8f3ff
[]
no_license
jikaigggg/Frame
d1172919612b2ed643bd784043ed274b47b62ee6
0afb9b972e1c3719564f4da1e63b0837cee02adf
refs/heads/master
2023-01-11T02:49:19.685934
2020-05-07T10:21:52
2020-05-07T10:21:52
241,066,743
0
0
null
2022-12-27T14:46:53
2020-02-17T09:25:19
Java
UTF-8
Java
false
false
426
java
package com.jikaigg.springbootstart; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationProperties; @SpringBootApplication public class SpringbootStartApplication { public static void main(String[] args) { SpringApplication.run(SpringbootStartApplication.class, args); } }
11c81d26cb78b5dc935c0b1cffb5b57f83c5b138
e5e18e0421eb0f67ff7b297e21081e933a18768c
/app/src/main/java/com/dlvs/monstereditor/editor/RichTextEditorManager.java
6e17d82628fc794f11ad3261865f071713636eff
[]
no_license
LaxusJie/MonsterEditor
aa8ff96d288dc510719b75ebefe6980c06650854
3c2ccb3391cf23eb060c2419376cdbaa55fa3eaf
refs/heads/master
2021-01-22T21:17:23.977453
2017-08-18T09:18:08
2017-08-18T09:18:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,723
java
package com.dlvs.monstereditor.editor; import android.content.Context; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Looper; import android.widget.EditText; import com.bumptech.glide.Glide; import com.dlvs.monstereditor.Network; import com.dlvs.monstereditor.R; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * desc:编辑器管理类 * author:mgq * date:2017-06-06 */ public class RichTextEditorManager { /*编辑器所展示数据的集合*/ private List<EditorDataEntity> editShowList = new ArrayList<>(); /*编辑器中多媒体数据集合*/ private List<EditorDataEntity> editorDataList = new ArrayList<>(); /*富文本编辑器*/ private RichTextEditor editor; /*上下文*/ private Context mContext; /*标签长度*/ private int tagLength = -8; private boolean richEditorStatus = true; public int editorBackground = 0; public RichTextEditorManager(Context mContext) { this.mContext = mContext; } public RichTextEditorManager(RichTextEditor editor, Context mContext) { this.editor = editor; this.mContext = mContext; } public boolean isRichEditorStatus() { return richEditorStatus; } public void setRichEditorStatus(boolean richEditorStatus) { this.richEditorStatus = richEditorStatus; } /*回显数据*/ private void showData(boolean status) { int k = 0; for (int i = 0; i < editShowList.size(); i++) { if (editShowList.get(i).getType().equals(RichTextEditor.TYPE_TEXT) || editShowList.get(i).getType().equals(RichTextEditor.TYPE_ALINK)) { if (editShowList.get(i).getText().trim().length() <= 0) { continue; } editor.addEditTextAtIndex(k, editShowList.get(i).getText(), editShowList.get(i).getType()); } else if (editShowList.get(i).getType().equals(RichTextEditor.TYPE_AUDIO)) { // editor.addAudioViewAtIndex(k, editShowList.get(i)); } else if (editShowList.get(i).getType().equals(RichTextEditor.TYPE_VIDEO)) { editor.addImageViewAtIndex(k, editShowList.get(i)); } else { editor.addImageViewAtIndex(k, editShowList.get(i)); } k++; } } /*过滤html数据*/ public void filterHtml(final String htmlStr) { //过滤 filterData(htmlStr); //排序 sortMediaPosition(); } /** * 过滤数据 * * @param htmlStr * @return */ public String filterData(String htmlStr) { // 替换换行 htmlStr = htmlStr.replace("<br>", "\n"); htmlStr = htmlStr.replace("</p>", "\n"); // 过滤script标签 htmlStr = getHtmlFilterString(EditorConstants.REGEX_SCRIPT, htmlStr); // 过滤style标签 htmlStr = getHtmlFilterString(EditorConstants.REGEX_STYLE, htmlStr); // 过滤html标签 htmlStr = getHtmlFilterString(EditorConstants.REGEX_HTML, htmlStr); //过滤多媒体标签之前拆分数据 splitTextData(htmlStr); //过滤附件a标签 htmlStr = getMediaFilterString(EditorConstants.REGEX_ATTACHMENT, htmlStr, RichTextEditor.TYPE_ALINK); //过滤图片 htmlStr = getMediaFilterString(EditorConstants.REGEX_IMG, htmlStr, RichTextEditor.TYPE_IMAGE); //过滤音频 htmlStr = getMediaFilterString(EditorConstants.REGEX_AUDIO, htmlStr, RichTextEditor.TYPE_AUDIO); //过滤视频 htmlStr = getMediaFilterString(EditorConstants.REGEX_VEDIO, htmlStr, RichTextEditor.TYPE_VIDEO); ensureMediaTagPosition(htmlStr, RichTextEditor.TYPE_ALINK); ensureMediaTagPosition(htmlStr, RichTextEditor.TYPE_IMAGE); ensureMediaTagPosition(htmlStr, RichTextEditor.TYPE_AUDIO); ensureMediaTagPosition(htmlStr, RichTextEditor.TYPE_VIDEO); htmlStr = replaceTagByUrl(htmlStr, RichTextEditor.TYPE_ALINK); htmlStr = replaceTagByUrl(htmlStr, RichTextEditor.TYPE_IMAGE); htmlStr = replaceTagByUrl(htmlStr, RichTextEditor.TYPE_AUDIO); htmlStr = replaceTagByUrl(htmlStr, RichTextEditor.TYPE_VIDEO); return htmlStr; } /*将tag标签替换为对应的url*/ private String replaceTagByUrl(String htmlStr, String tag) { for (int i = 0; i < editorDataList.size(); i++) { if (tag.equals(editorDataList.get(i).getType())) { if (tag.equals(RichTextEditor.TYPE_ALINK)) { htmlStr = htmlStr.replaceFirst(tag, editorDataList.get(i).getText()); } else { htmlStr = htmlStr.replaceFirst(tag, editorDataList.get(i).getUrl()); } } } return htmlStr; } /** * 确定多媒体标签的位置 * * @param htmlStr */ public void ensureMediaTagPosition(String htmlStr, String tag) { int position = tagLength; for (int i = 0; i < editorDataList.size(); i++) { position = htmlStr.indexOf(tag, position + 8); for (int k = 0; k < editorDataList.size(); k++) { if (editorDataList.get(k).getPosition() == 0 && tag.equals(editorDataList.get(k).getType())) { editorDataList.get(k).setPosition(position); break; } } } } /** * 获取过滤多媒体标签后的数据 */ public String getMediaFilterString(String reg, String htmlStr, String tag) { EditorDataEntity editorDataEntity; //过滤标签 Pattern p_img = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); Matcher m_img = p_img.matcher(htmlStr); while (m_img.find()) { editorDataEntity = new EditorDataEntity(); if (tag.equals(RichTextEditor.TYPE_ALINK)) { editorDataEntity.setText(m_img.group(1)); } else { editorDataEntity.setUrl(m_img.group(1)); } editorDataEntity.setType(tag); if (tag.equals(RichTextEditor.TYPE_AUDIO) || tag.equals(RichTextEditor.TYPE_VIDEO)) { editorDataEntity.setName(m_img.group(3)); editorDataEntity.setPath(m_img.group(5)); editorDataEntity.setAliasname(m_img.group(7)); } if (tag.equals(RichTextEditor.TYPE_VIDEO)) { editorDataEntity.setPoster(m_img.group(9)); } editorDataList.add(editorDataEntity); } htmlStr = m_img.replaceAll(tag); return htmlStr; } /** * 过滤普通Html标签 */ public String getHtmlFilterString(String reg, String htmlStr) { Pattern p_html = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); Matcher m_html = p_html.matcher(htmlStr); htmlStr = m_html.replaceAll(""); return htmlStr; } /*拆分文本数据*/ public void splitTextData(String htmlStr) { String data = htmlStr; data = insertSplitTag(data, EditorConstants.REGEX_ATTACHMENT); data = insertSplitTag(data, EditorConstants.REGEX_IMG); data = insertSplitTag(data, EditorConstants.REGEX_AUDIO); data = insertSplitTag(data, EditorConstants.REGEX_VEDIO); addTextToEditList(data); } /*插入拆分标签*/ public String insertSplitTag(String data, String reg) { Pattern p_img = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); Matcher m_img = p_img.matcher(data); data = m_img.replaceAll(EditorConstants.SPLITTAG); return data; } /*将文本数据装载到编辑器集合中*/ public void addTextToEditList(String data) { String filterData = getHtmlFilterString(EditorConstants.REGEX_AA,data); String[] textData = filterData.split(EditorConstants.SPLITTAG); for (int i = 0; i < textData.length; i++) { editShowList.add(new EditorDataEntity(RichTextEditor.TYPE_TEXT, textData[i])); } } /** * 对多媒体资源位置进行排序 */ private void sortMediaPosition() { Collections.sort(editorDataList, new Comparator<EditorDataEntity>() { @Override public int compare(EditorDataEntity lhs, EditorDataEntity rhs) { return lhs.getPosition() - rhs.getPosition(); } }); setMediaBitmap(); } /*设置bitmap*/ private void setMediaBitmap() { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { if (Looper.myLooper() == null) { Looper.prepare(); } try { for (int i = 0; i < editorDataList.size(); i++) { if (editorDataList.get(i).getType().equals(RichTextEditor.TYPE_IMAGE)) { String url = editorDataList.get(i).getUrl(); if(!url.contains("http")){ url = Network.FILE_SERVER_COMMON_URL + url; } editorDataList.get(i).setBitmapResource(Glide.with(mContext).load(url).asBitmap().into(500, 500).get()); } else if (editorDataList.get(i).getType().equals(RichTextEditor.TYPE_VIDEO) || editorDataList.get(i).getType().equals(RichTextEditor.TYPE_AUDIO)) { editorDataList.get(i).setBitmapResource(Glide.with(mContext).load(Network.FILE_SERVER_COMMON_URL + editorDataList.get(i).getPoster()).asBitmap().into(500, 500).get()); } } } catch (InterruptedException e) { e.printStackTrace(); return false; } catch (ExecutionException e) { e.printStackTrace(); return false; } return true; } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); //组合文本数据和多媒体数据 for (int i = 0; i < editorDataList.size(); i++) { if (editorDataList.get(i).getBitmapResource() == null) { editorDataList.get(i).setBitmapResource(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.default_bg)); } EditorDataEntity editData = new EditorDataEntity(editorDataList.get(i).getText(), editorDataList.get(i).getType(), editorDataList.get(i).getUrl(), editorDataList.get(i).getBitmapResource()); editData.setMediaPath(editData.getUrl()); int number = 2 * i + 1; if (number > editShowList.size()) { editShowList.add(editData); } else { editShowList.add(number, editData); } } showData(isRichEditorStatus()); } }.execute(); } /** * 添加图片到富文本剪辑器 */ public void insertBitmap(EditorDataEntity editorDataEntity) { editor.insertImage(editorDataEntity); } /** * 获得多媒体个数 * * @param type * @return */ public int getMediaCount(String type) { int audioCount = 0; int videoCount = 0; List<EditorDataEntity> editorDataEntityList = editor.buildEditData(); for (int i = 0; i < editorDataEntityList.size(); i++) { if (editorDataEntityList.get(i).getType().equals(RichTextEditor.TYPE_AUDIO)) { audioCount++; continue; } if (editorDataEntityList.get(i).getType().equals(RichTextEditor.TYPE_VIDEO)) { videoCount++; } } if (type.equals(RichTextEditor.TYPE_AUDIO)) { return audioCount; } else { return videoCount; } } public void setEditorHint(String hint) { editor.setEditHint(hint); } public List<EditorDataEntity> getEditorDataList() { return editorDataList; } public List<EditorDataEntity> getEditShowList() { return editShowList; } public EditText setEditTextFocus(){ return editor.setEditTextFocus(); } }
88a76683bdd3e74377b7efdd92964029926d7aa7
b248accc100195100a05b3470c6dd87e881bc1fb
/espacedev.gaml.extensions.genstar/src/core/metamodel/attribute/emergent/filter/GSMatchFilter.java
80fa1d4d159ce7fcb7a6ff05212ff5d19455b6c8
[]
no_license
gama-platform/gama.experimental
e59df86a518295d3b4408b2ebe3e8ab343f27951
f27c88cbe53a8850dc203b588b597f4162210774
refs/heads/GAMA_1.9.0
2023-08-06T14:58:18.989889
2023-07-14T10:25:27
2023-07-14T10:25:27
59,318,904
19
7
null
2023-05-04T07:43:24
2016-05-20T18:53:28
Java
UTF-8
Java
false
false
1,784
java
package core.metamodel.attribute.emergent.filter; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonTypeName; import core.metamodel.attribute.EmergentAttribute; import core.metamodel.attribute.IAttribute; import core.metamodel.entity.IEntity; import core.metamodel.entity.matcher.IGSEntityMatcher; import core.metamodel.entity.matcher.MatchType; import core.metamodel.value.IValue; /** * Filter entity by matching at least one attribute with vector matcher. * * @author kevinchapuis * */ @JsonTypeName(GSMatchFilter.SELF) public class GSMatchFilter<T> extends AGSEntitySelector<Collection<IEntity<? extends IAttribute<? extends IValue>>>, T> { public static final String SELF = "MATCH FILTER"; public GSMatchFilter(IGSEntityMatcher<T> matcher, MatchType match) { super(matcher, match); } public GSMatchFilter(IGSEntityMatcher<T> matcher) { super(matcher); } @Override public Collection<IEntity<? extends IAttribute<? extends IValue>>> apply(IEntity<? extends IAttribute<? extends IValue>> superEntity) { return superEntity.getChildren().stream() .filter(e -> this.validate(super.getMatchType(), e)) .sorted(super.getComparator()) .collect(Collectors.toCollection(this.getSupplier())); } // TODO : turn this and IEntity parametric references to Map<Attribute,Value> abstract representation // FIXME : this wont work because it make a reference to an EmergentAttribute that encapsulate a collection of Entity (rather than entities) @Override public <V extends IValue> Map<IAttribute<? extends IValue>, IValue> reverse( EmergentAttribute<V, Collection<IEntity<? extends IAttribute<? extends IValue>>>, T> attribute, V value) { return null; } }
df629d4c703d41f15de5e7ea09d5019d787a7252
bec1efb7d98851d1e274283ae1539b6e0cec3d83
/client/app/src/main/java/ir/mohammadpour/app/ui/widget/slider/Transformers/ForegroundToBackgroundTransformer.java
295b461ee939b5a99f2552daa53b20469d28cdce
[]
no_license
aminm1993/MultiCriteriaRecommendationSystem
55f4632b6afe4cba0b2fec25cecdb67de1dbb18a
54cfd6c18f4ee12dcdcf5813c1c57a0a4f84d12a
refs/heads/master
2020-04-20T17:40:35.957789
2019-02-08T08:31:41
2019-02-08T08:31:41
168,995,816
0
0
null
null
null
null
UTF-8
Java
false
false
810
java
package ir.mohammadpour.app.ui.widget.slider.Transformers; import android.view.View; import com.nineoldandroids.view.ViewHelper; public class ForegroundToBackgroundTransformer extends BaseTransformer { @Override protected void onTransform(View view, float position) { final float height = view.getHeight(); final float width = view.getWidth(); final float scale = min(position > 0 ? 1f : Math.abs(1f + position), 0.5f); ViewHelper.setScaleX(view,scale); ViewHelper.setScaleY(view,scale); ViewHelper.setPivotX(view,width * 0.5f); ViewHelper.setPivotY(view,height * 0.5f); ViewHelper.setTranslationX(view,position > 0 ? width * position : -width * position * 0.25f); } private static final float min(float val, float min) { return val < min ? min : val; } }
fda2ee58a166f29daad08849f77485ef9d86772e
adcea0d809a9307117bd2d6d7259c96efc88fc42
/mm-core/src/main/java/com/wasu/springboot/integration/utils/DateUtils.java
00b224abeb2639711f0155619084d4155ca652cc
[]
no_license
kalegege/springboot-integration
b72ef0a75a442beaff46d3b32c4d65f92aa50221
07f6e11acad5c486d6a4df82f3234e2e8cee5344
refs/heads/master
2022-10-27T11:47:06.600116
2019-11-29T07:19:22
2019-11-29T07:19:22
163,186,910
1
0
null
2022-10-12T20:28:12
2018-12-26T14:12:12
Java
UTF-8
Java
false
false
7,608
java
package com.wasu.springboot.integration.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class DateUtils { private static final String[] DAYNAMES = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final List<String> DATE_FORMATE_LIST = new ArrayList<>(Arrays.asList( "yyyy-MM-dd", "yyyy/MM/dd", "yyyy/MM/dd", "yyyyMMdd" )); public static final String DATE_FORMATE_1 = "yyyy-MM-dd"; public static final String DATE_FORMATE_2 = "yyyy/MM/dd"; public static final String DATE_FORMATE_3 = "yyyy/MM/dd"; public static final String DATE_FORMATE_4 = "yyyyMMdd"; public static Date getNow() { return new Date(); } public static String formate(Date date){ return formatDateTime(date,"yyy-MM-dd HH:mm:ss"); } public static Date parseDate(String dateTime) { return parse(dateTime, DATE_FORMATE_1); } public static Date getAfterMonth(Date date, int month) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(2, month); return c.getTime(); } public static Date getLastDay(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); c.set(5, 1); c.add(2, 1); c.add(5, -1); return c.getTime(); } public static int getDiffMonth(Date startDate, Date endDate) { Calendar cStart = Calendar.getInstance(); Calendar cEnd = Calendar.getInstance(); cStart.setTime(startDate); cEnd.setTime(endDate); int mStart = cStart.get(2) + 1; int mEnd = cEnd.get(2) + 1; int checkMonth = mEnd - mStart + (cEnd.get(1) - cStart.get(1)) * 12; return checkMonth; } /** * @param dateTime * @return */ public static Boolean isDate(String dateTime) { try { parse(dateTime, DATE_FORMATE_1); } catch (Exception ex) { try { parse(dateTime, DATE_FORMATE_2); } catch (Exception ex1) { try { parse(dateTime, DATE_FORMATE_3); } catch (Exception ex2) { try { parse(dateTime, DATE_FORMATE_4); } catch (Exception ex3) { return Boolean.valueOf(false); } } } } return Boolean.valueOf(true); } /** * * @param date * @return */ public static Date getDate(String date) { for (int i = 0; i < DATE_FORMATE_LIST.size(); i++) { Date d = parse(date, DATE_FORMATE_LIST.get(i)); if(null == d){ continue; }else{ return d; } } return null; } public static Date parseDateTime(String dateTime) { return parse(dateTime, DATE_TIME_FORMAT); } public static Date parseDateTimeForUK(String dateTime) throws ParseException, RuntimeException { DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK); return dateFormat.parse(dateTime); } public static Date parse(String dateTime, String formate) { if (StringUtils.isBlank(dateTime)) return null; DateFormat dateFormat = new SimpleDateFormat(formate); try { return dateFormat.parse(dateTime); } catch (ParseException e) { throw new RuntimeException("formate date error!", e); } } public static String formatDateTime(Date date, String format) { if (date == null) return null; DateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } /** * 获取两个日期之间的年份和月份 * * @param minDate * @param maxDate * @return */ public static List<String> getMonthBetween(String minDate, String maxDate) { List<String> result = new ArrayList<>(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM"); Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); try { min.setTime(simpleDateFormat.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(simpleDateFormat.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(simpleDateFormat.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } } catch (ParseException e) { e.printStackTrace(); } return result; } public static int getValidMonthInternal(Date fromDate, Date toDate) { if (fromDate.after(toDate)) { Date t = fromDate; fromDate = toDate; toDate = t; } Calendar fromCalender = Calendar.getInstance(); fromCalender.setTime(fromDate); int fromYear = fromCalender.get(Calendar.YEAR); int fromMonth = fromCalender.get(Calendar.MONTH); Calendar toCalender = Calendar.getInstance(); toCalender.setTime(fromDate); int toYear = toCalender.get(Calendar.YEAR); int toMonth = toCalender.get(Calendar.MONTH); int internal = (toYear - fromYear) * 12 + (toMonth - fromMonth); return internal > 0 ? internal : 0; } public static int getSubDay(Date first, Date second) { Calendar firstCalendar=Calendar.getInstance(); firstCalendar.setTime(first); Calendar secondCalendar=Calendar.getInstance(); secondCalendar.setTime(second); StringBuilder sbFirst=new StringBuilder(); sbFirst.append(firstCalendar.get(Calendar.YEAR)); sbFirst.append("-"); sbFirst.append(firstCalendar.get(Calendar.MONTH) + 1); sbFirst.append("-"); sbFirst.append(firstCalendar.get(Calendar.DAY_OF_MONTH)); StringBuilder sbSecond=new StringBuilder(); sbSecond.append(secondCalendar.get(Calendar.YEAR)); sbSecond.append("-"); sbSecond.append(secondCalendar.get(Calendar.MONTH) + 1); sbSecond.append("-"); sbSecond.append(secondCalendar.get(Calendar.DAY_OF_MONTH)); Date firstYmd=parse(sbFirst.toString(),"yyyy-M-dd"); Date secondYmd=parse(sbSecond.toString(),"yyyy-MM-dd"); return getDiffDay(firstYmd,secondYmd); } private static Integer getDiffDay(Date start, Date end) { if(start.after(end)){ Date temp=start; start=end; end=temp; } Calendar startCalendar=Calendar.getInstance(); startCalendar.setTime(start); Calendar endCalendar=Calendar.getInstance(); endCalendar.setTime(end); Integer len=Integer.valueOf((endCalendar.get(1)-startCalendar.get(1)) * 12 + endCalendar.get(2) - startCalendar.get(2)); if(endCalendar.get(5) < startCalendar.get(5)){ len=Integer.valueOf(len.intValue() - 1); } return len; } public static Date addOrSubDay(Date date, int day) { Calendar calendar=Calendar.getInstance(); calendar.setTime(date); calendar.add(5,day); return calendar.getTime(); } }
b690fbf7f23435afe6327e52b440cc7604d380cb
e3209724b56526e3981f5315cc8c959fdc3534ee
/src/main/java/com/edsonr/cursomc/domain/Categoria.java
82cd60e1a8bb3d62511b4285b6dfea5c9948f547
[]
no_license
EdsonRCJ/cursomc
36a0dd66ffd8b6f7c23dfca5b3e864787afc0f74
887b8215c0e3cb7060c199a3f1e85bc372ad38af
refs/heads/master
2020-03-20T19:09:34.832462
2018-06-24T04:04:10
2018-06-24T04:04:10
137,624,293
0
0
null
null
null
null
UTF-8
Java
false
false
1,659
java
package com.edsonr.cursomc.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import com.fasterxml.jackson.annotation.JsonManagedReference; @Entity public class Categoria implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String nome; @JsonManagedReference @ManyToMany(mappedBy="categorias") private List<Produto> produtos = new ArrayList<>(); public Categoria() { } public Categoria(Integer id, String nome) { super(); this.id = id; this.nome = nome; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public List<Produto> getProdutos() { return produtos; } public void setProdutos(List<Produto> produtos) { this.produtos = produtos; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Categoria other = (Categoria) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
793db8240de8497b5951823f271a426536b160db
fd3cd767e56750d2cf8e1b177deb4f4495dbe8bf
/src/downloader/DownloadTableModel.java
572f883dfc015d3cb2ba3c1666d9e9cf7ad42ad8
[]
no_license
jiashuo/downloader
bed3c9b348e6b16240d65c2461d87a2897caa452
f9c161e05254738d482ba3d9c29188a8f8564895
refs/heads/master
2016-09-16T11:02:52.051511
2013-04-10T01:43:23
2013-04-10T01:43:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,389
java
package downloader; import java.awt.EventQueue; import java.util.Observable; import java.util.Observer; import javax.swing.JProgressBar; import javax.swing.table.AbstractTableModel; /** * This class manages the download table's data. * */ public class DownloadTableModel extends AbstractTableModel implements Observer { private final DownloadManager downloadManager; public DownloadTableModel(DownloadManager downloadManager) { this.downloadManager=downloadManager; } // These are the names for the table's columns. private static final String[] columnNames = {"URL", "Size (KB)", "Progress", "Status","Priority"}; // These are the classes for each column's values. @SuppressWarnings("rawtypes") private static final Class[] columnClasses = {String.class, String.class, JProgressBar.class, String.class,String.class}; /** * Add a new download to the table. */ public void addNewDownload(SingleTask download) { // Register to be notified when the download changes. download.addObserver(this); // Fire table row insertion notification to table. fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1); } /** * Remove a download from the list. */ public void clearDownload(int row) { // Fire table row deletion notification to table. fireTableRowsDeleted(row, row); } /** * Get table's column count. */ public int getColumnCount() { return columnNames.length; } /** * Get a column's name. */ public String getColumnName(int col) { return columnNames[col]; } /** * Get a column's class. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Class getColumnClass(int col) { return columnClasses[col]; } /** * Get table's row count. */ public int getRowCount() { return downloadManager.getDownloadList().size(); } /** * Get value for a specific row and column combination. */ public Object getValueAt(int row, int col) { // Get download from download list SingleTask download = downloadManager.getDownloadList().get(row); switch (col) { case 0: // URL return download.getURL(); case 1: // Size long size = download.getFileSize(); return (size == -1) ? "" : (Long.toString(size/1000)); case 2: // Progress return new Float(download.getProgress()); case 3: // Status return SingleTask.STATUSES[download.getState()]; case 4: //priority return SingleTask.PRIORITIES[download.getPriority()]; } return ""; } /** * Update is called when a Download notifies its observers of any changes */ public void update(Observable o, Object arg) { final int index = downloadManager.getDownloadList().indexOf(o); // Fire table row update notification to table. EventQueue.invokeLater(new Runnable() { public void run() { fireTableRowsUpdated(index, index); } } ); } }
d8f19f20a9fdf732f166306ab75714977007e38f
2ef47520194f98c3e905cf24be193c32b49990c6
/proj13DeGrawHang/bantam/ast/ConstBooleanExpr.java
977ac6c3feec8741a5ca16242a01ee0c0a805e78
[]
no_license
jackiehang/proj13
15b0011934ad663475472c4869f5c8cfa7117265
4e6cf5a7291360ffeff56eb6adee70f90b864262
refs/heads/master
2020-04-26T21:10:30.119232
2019-03-08T06:00:10
2019-03-08T06:00:10
173,834,452
0
0
null
null
null
null
UTF-8
Java
false
false
1,969
java
/* Bantam Java Compiler and Language Toolset. Copyright (C) 2009 by Marc Corliss ([email protected]) and David Furcy ([email protected]) and E Christopher Lewis ([email protected]). ALL RIGHTS RESERVED. The Bantam Java toolset is distributed under the following conditions: You may make copies of the toolset for your own use and modify those copies. All copies of the toolset must retain the author names and copyright notice. You may not sell the toolset or distribute it in conjunction with a commerical product or service without the expressed written consent of the authors. THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ package proj13DeGrawHang.bantam.ast; import proj13DeGrawHang.bantam.visitor.Visitor; /** * The <tt>ConstBooleanExpr</tt> class represents a boolean constant expression. * It extends constant expressions so it containts a constant value (represented * as a String). Since this class is similar to other subclasses most of the * functionality can be implemented in the bantam.visitor method for the parent class. * * @see ASTNode * @see ConstExpr */ public class ConstBooleanExpr extends ConstExpr { /** * ConstBooleanExpr constructor * * @param lineNum source line number corresponding to this AST node * @param constant constant value (as a String) */ public ConstBooleanExpr(int lineNum, int colPos, String constant) { super(lineNum,colPos, constant); } /** * Visitor method * * @param v bantam.visitor object * @return result of visiting this node * @see proj13DeGrawHang.bantam.visitor.Visitor */ public Object accept(Visitor v) { return v.visit(this); } }
df67251e23a933947bd121ae64546cb006cc1a30
c212cdc56883b887e4e427475c8e24a72e4cd3d8
/src/main/java/com/weiwudev/models/User.java
b14607dbeb49c69ac950ecb01f2a5e66246bf35e
[]
no_license
weiwuDev/AuthService-JWT
209cd87bd998b6ea05413deda9b41b756f10ed67
a77c90e56ca7fe2f765d0aed169e3f6f07024f15
refs/heads/master
2022-11-23T01:15:38.208776
2020-07-31T18:48:10
2020-07-31T18:48:10
283,006,117
0
0
null
null
null
null
UTF-8
Java
false
false
736
java
package com.weiwudev.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.userdetails.UserDetails; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor @Document(collection = "login") public class User { @Id private String id; @Indexed(unique=true) private String username; private String password; private List<String> roles; public UserDetails toUserDetails(){ return new MyUserDetails(username,password, roles); } }
ab7c024fba42b67c51d6a8cfe024d6e819dea545
4a6454a57012326f41336bd291ef196f23ef90be
/XMISA/src/com/nti56/xmisa/adapter/MyListView.java
94637fc2c9a3c9cef2fdfd28a45582afb281e312
[]
no_license
chenchengtyh/XMISA
1f121f00cf27fe52707afa9c7fa71f72f40057b4
7f4d7afa8f166f3b4b22e5e4593b0929cf573d94
refs/heads/master
2021-09-01T13:07:31.615630
2017-12-27T05:21:05
2017-12-27T05:21:05
115,484,212
0
0
null
null
null
null
UTF-8
Java
false
false
12,854
java
package com.nti56.xmisa.adapter; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.nti56.xmisa.MyApplication; import com.nti56.xmisa.R; import com.nti56.xmisa.util.Content; import com.nti56.xmisa.util.MyLog; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences.Editor; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.AbsListView.OnScrollListener; public class MyListView extends ListView implements OnScrollListener { private Context mContext; private int state; private final static int CLOSE = 0; private final static int OPENING = 1; // 下拉过程中 private final static int OPEN = 2;// 下拉完成 private final static int LOADING = 3;// 正在刷新的状态值 private int mMode; private final static int NONE = 0; private final static int VERTICAL = 5;// 垂直移动 private final static int HORIZONTAL = 10;// 水平移动 private final static int RATIO = 3;// 实际的padding的距离与界面上偏移距离的比例 private int headerContentHeight;// 定义头部下拉刷新的布局的高度 private int startX, startY; private LayoutInflater inflater; // ListView头部下拉刷新的布局 private LinearLayout headerView; private TextView lvHeaderTipsTv; private TextView lvHeaderLastUpdatedTv; private ImageView lvHeaderArrowIv; private ProgressBar lvHeaderProgressBar; private RotateAnimation animation; private RotateAnimation reverseAnimation; private boolean isBack; public boolean isOnMeasure; private boolean Refreshable = false; private int mListCode; // private Editor editor; private String TAG = "MyListView"; private OnRefreshListener refreshListener; public interface OnRefreshListener { public void onRefresh(); } public MyListView(Context context) { super(context); mContext = context; } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { isOnMeasure = true; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public void onLayout(boolean changed, int l, int t, int r, int b) { isOnMeasure = false; super.onLayout(changed, l, t, r, b); } @Override public boolean onTouchEvent(MotionEvent ev) { if (Refreshable) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: MyLog.e(TAG, "onTouchEvent", "MotionEvent.ACTION_DOWN"); mMode = NONE; startX = (int) ev.getX();// 手指按下时记录当前位置 startY = (int) ev.getY();// 手指按下时记录当前位置 break; case MotionEvent.ACTION_MOVE: MyLog.d(TAG, "onTouchEvent", "MotionEvent.ACTION_MOVE"); int DifValueX = ((int) ev.getX() - startX) / RATIO;// Y轴移动距离 int DifValueY = ((int) ev.getY() - startY) / RATIO;// Y轴移动距离 if (mMode == NONE && (Math.abs(DifValueX) > 2 || Math.abs(DifValueY) > 2)) { if (Math.abs(DifValueX) > Math.abs(DifValueY)) { mMode = HORIZONTAL;// 水平模式 } else { mMode = VERTICAL;// 垂直模式 } } if (mMode == VERTICAL && state != LOADING) {// 当未正在刷新时 if (DifValueY <= 0) {// 关闭 if (state != CLOSE) { state = CLOSE; isBack = false; changeHeaderViewByState(); } } else if (DifValueY < headerContentHeight && state != OPENING) {// 正在下拉 state = OPENING; changeHeaderViewByState(); } else if (DifValueY >= headerContentHeight && state != OPEN) {// 下拉完成 state = OPEN; isBack = true; changeHeaderViewByState(); } if (state != CLOSE) {// 动态改变界面高度 headerView.setPadding(0, DifValueY - headerContentHeight, 0, 0); } } break; case MotionEvent.ACTION_UP: MyLog.e(TAG, "onTouchEvent", "MotionEvent.ACTION_UP"); if (state == OPEN) { state = LOADING; changeHeaderViewByState(); onLvRefresh(); } else if (state == OPENING) { state = CLOSE; changeHeaderViewByState(); } break; default: break; } } return super.onTouchEvent(ev); } @Override public void setAdapter(ListAdapter adapter) { if (Refreshable) { initHeaderView(); UpdateLastTime();//TODO 此处要从MyApplication.mySharedPreferences获得上次刷新时间写入 } super.setAdapter(adapter); } private void InitSharedPreferences(){ if (MyApplication.mySharedPreferences == null) { MyApplication.mySharedPreferences = mContext.getSharedPreferences("mysharepreferences", Activity.MODE_PRIVATE); } if(MyApplication.editor == null){ MyApplication.editor = MyApplication.mySharedPreferences.edit(); } } private void UpdateLastTime(){ InitSharedPreferences(); String lastUpdate= ""; switch (mListCode) { case Content.LIST_RECEIVE: lastUpdate = MyApplication.mySharedPreferences.getString("rec_update", ""); break; case Content.LIST_INPUT: lastUpdate = MyApplication.mySharedPreferences.getString("ipt_update", ""); break; case Content.LIST_OUTPUT: lastUpdate = MyApplication.mySharedPreferences.getString("opt_update", ""); break; case Content.LIST_INVENTORY: lastUpdate = MyApplication.mySharedPreferences.getString("ivt_update", ""); break; case Content.LIST_ASSIGN: lastUpdate = MyApplication.mySharedPreferences.getString("asg_update", ""); break; case Content.LIST_EXAMINE: lastUpdate = MyApplication.mySharedPreferences.getString("exm_update", ""); break; case Content.LIST_SURVEY: lastUpdate = MyApplication.mySharedPreferences.getString("sur_update", ""); break; case Content.LIST_FUMIGATE: lastUpdate = MyApplication.mySharedPreferences.getString("fmg_update", ""); break; case Content.LIST_PESTS: lastUpdate = MyApplication.mySharedPreferences.getString("pts_update", ""); break; case Content.LIST_PATROL: lastUpdate = MyApplication.mySharedPreferences.getString("ptl_update", ""); break; default: break; } lvHeaderLastUpdatedTv.setText("上次更新时间:" + lastUpdate); } public void setOnRefreshListener(OnRefreshListener refreshListener, int listCode) { this.Refreshable = true; this.refreshListener = refreshListener; mListCode = listCode; } public void onRefreshComplete(boolean Success, int listCode) { state = CLOSE; if(Success){//TODO 此处要将时间写入 MyApplication.mySharedPreferences DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.getDefault()); String updateTime = format.format(new Date()); lvHeaderLastUpdatedTv.setText("上次更新时间:" + updateTime); InitSharedPreferences(); switch (listCode) { case Content.LIST_RECEIVE: MyApplication.editor.putString("rec_update", updateTime); break; case Content.LIST_INPUT: MyApplication.editor.putString("ipt_update", updateTime); break; case Content.LIST_OUTPUT: MyApplication.editor.putString("opt_update", updateTime); break; case Content.LIST_INVENTORY: MyApplication.editor.putString("ivt_update", updateTime); break; case Content.LIST_ASSIGN: MyApplication.editor.putString("asg_update", updateTime); break; case Content.LIST_EXAMINE: MyApplication.editor.putString("exm_update", updateTime); break; case Content.LIST_SURVEY: MyApplication.editor.putString("sur_update", updateTime); break; case Content.LIST_FUMIGATE: MyApplication.editor.putString("fmg_update", updateTime); break; case Content.LIST_PESTS: MyApplication.editor.putString("pts_update", updateTime); break; case Content.LIST_PATROL: MyApplication.editor.putString("ptl_update", updateTime); break; default: break; } MyApplication.editor.commit(); } changeHeaderViewByState(); } @Override public Drawable getDivider() { return super.getDivider(); } @Override public int getDividerHeight() { return super.getDividerHeight(); } private void initHeaderView() { MyLog.e(TAG, "initHeaderView"); setCacheColorHint(mContext.getResources().getColor(R.color.yellow)); inflater = LayoutInflater.from(mContext); headerView = (LinearLayout) inflater.inflate(R.layout.listview_header, null); lvHeaderTipsTv = (TextView) headerView.findViewById(R.id.lvHeaderTipsTv); lvHeaderLastUpdatedTv = (TextView) headerView.findViewById(R.id.lvHeaderLastUpdatedTv); lvHeaderArrowIv = (ImageView) headerView.findViewById(R.id.lvHeaderArrowIv); // 设置下拉刷新图标的最小高度和宽度 lvHeaderArrowIv.setMinimumWidth(70); lvHeaderArrowIv.setMinimumHeight(50); lvHeaderProgressBar = (ProgressBar) headerView.findViewById(R.id.lvHeaderProgressBar); measureView(headerView); headerContentHeight = headerView.getMeasuredHeight(); // 设置内边距,正好距离顶部为一个负的整个布局的高度,正好把头部隐藏 headerView.setPadding(0, -1 * headerContentHeight, 0, 0); // 头部存在时会有间隙,去掉此间隙 setY(0 - getDividerHeight()); // 重绘一下 headerView.invalidate(); // 将下拉刷新的布局加入ListView的顶部 addHeaderView(headerView, null, true);//第三参数设置为false会导致headerView与itemView的分割线为透明 setOnScrollListener(this); // 设置旋转动画事件 animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); animation.setInterpolator(new LinearInterpolator()); animation.setDuration(250); animation.setFillAfter(true); reverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); reverseAnimation.setInterpolator(new LinearInterpolator()); reverseAnimation.setDuration(200); reverseAnimation.setFillAfter(true); } // 当状态改变时候,调用该方法,以更新界面 private void changeHeaderViewByState() { switch (state) { case CLOSE: headerView.setPadding(0, 0 - headerContentHeight, 0, 0); lvHeaderTipsTv.setText("下拉刷新"); lvHeaderProgressBar.setVisibility(View.GONE); lvHeaderArrowIv.setVisibility(View.VISIBLE); lvHeaderArrowIv.clearAnimation(); lvHeaderArrowIv.setImageResource(R.drawable.arrow); break; case OPENING: lvHeaderTipsTv.setText("下拉刷新"); if (isBack) {// 是由OPEN状态转变来的 isBack = false; lvHeaderArrowIv.clearAnimation(); lvHeaderArrowIv.startAnimation(reverseAnimation); } break; case OPEN: lvHeaderTipsTv.setText("松开刷新"); lvHeaderProgressBar.setVisibility(View.GONE); lvHeaderArrowIv.clearAnimation();// 清除动画 lvHeaderArrowIv.startAnimation(animation);// 开始动画效果 break; case LOADING: headerView.setPadding(0, 0, 0, 0); lvHeaderTipsTv.setText("正在刷新..."); lvHeaderProgressBar.setVisibility(View.VISIBLE); lvHeaderArrowIv.clearAnimation(); lvHeaderArrowIv.setVisibility(View.GONE); break; } } // 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及height private void measureView(View child) { ViewGroup.LayoutParams params = child.getLayoutParams(); if (params == null) { params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, params.width); int lpHeight = params.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private void onLvRefresh() { if (refreshListener != null) { refreshListener.onRefresh(); } } public boolean isOnMeasure() { return isOnMeasure; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }
d2e3c7fb6a8b871b8a05f3d21e0b7aeaf7b9cc11
4ec1401e1c2a0a049cdb8733bb02d922d64723eb
/app/src/main/java/com/wteam/carkeeper/map/NaviActivity.java
2c1387716e420293788a2867188438250080cef4
[]
no_license
LHBGit/Carkeeper
6c4b4c5ada1a52929e7c158607e7e8f3b2e2e7fd
db415ab6e61820a0551e8dfa32339a95ba899379
refs/heads/master
2021-01-21T15:04:41.265781
2016-06-12T03:15:58
2016-06-12T03:15:58
58,925,118
1
1
null
null
null
null
UTF-8
Java
false
false
7,993
java
package com.wteam.carkeeper.map; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Window; import android.widget.Toast; import com.amap.api.navi.AMapNavi; import com.amap.api.navi.AMapNaviListener; import com.amap.api.navi.AMapNaviView; import com.amap.api.navi.AMapNaviViewListener; import com.amap.api.navi.enums.NaviType; import com.amap.api.navi.enums.PathPlanningStrategy; import com.amap.api.navi.model.AMapLaneInfo; import com.amap.api.navi.model.AMapNaviCross; import com.amap.api.navi.model.AMapNaviInfo; import com.amap.api.navi.model.AMapNaviLocation; import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo; import com.amap.api.navi.model.AimLessModeCongestionInfo; import com.amap.api.navi.model.AimLessModeStat; import com.amap.api.navi.model.NaviInfo; import com.amap.api.navi.model.NaviLatLng; import com.amap.api.services.core.LatLonPoint; import com.autonavi.tbt.TrafficFacilityInfo; import com.wteam.carkeeper.R; import com.wteam.carkeeper.util.TTSController; import java.util.ArrayList; import java.util.List; /** * Created by lhb on 2016/5/23. */ public class NaviActivity extends AppCompatActivity implements AMapNaviListener, AMapNaviViewListener { private AMapNaviView mAMapNaviView; private AMapNavi mAMapNavi; private TTSController mTtsManager; private List<NaviLatLng> mStartList = new ArrayList<NaviLatLng>(); private List<NaviLatLng> mEndList = new ArrayList<NaviLatLng>(); private List<NaviLatLng> mWayPointList = new ArrayList<NaviLatLng>(); private int wayFlag; private int naviType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); for(int i=0;i<5;i++) { LatLonPoint latLonPoint = (LatLonPoint) getIntent().getExtras().get("point_" + i); if(i == 0) { mStartList.add(new NaviLatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude())); } else if(i == 4) { mEndList.add(new NaviLatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude())); } else { if(latLonPoint != null) { mWayPointList.add(new NaviLatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude())); } } } wayFlag = (int) getIntent().getExtras().get("wayFlag"); naviType = (int) getIntent().getExtras().get("naviType"); mTtsManager = TTSController.getInstance(getApplicationContext()); mTtsManager.init(); mTtsManager.startSpeaking(); mAMapNavi = AMapNavi.getInstance(getApplicationContext()); mAMapNavi.startGPS(); mAMapNavi.addAMapNaviListener(this); mAMapNavi.addAMapNaviListener(mTtsManager); mAMapNavi.setEmulatorNaviSpeed(200); setContentView(R.layout.activity_navi); mAMapNaviView = (AMapNaviView) findViewById(R.id.navi_view); mAMapNaviView.onCreate(savedInstanceState); mAMapNaviView.setAMapNaviViewListener(this); } @Override protected void onResume() { super.onResume(); mAMapNaviView.onResume(); /* mStartList.add(mStartLatlng); mEndList.add(mEndLatlng);*/ mAMapNaviView.setNaviMode(AMapNaviView.CAR_UP_MODE); } @Override protected void onPause() { super.onPause(); mAMapNaviView.onPause(); // 仅仅是停止你当前在说的这句话,一会到新的路口还是会再说的 mTtsManager.stopSpeaking(); // // 停止导航之后,会触及底层stop,然后就不会再有回调了,但是讯飞当前还是没有说完的半句话还是会说完 // mAMapNavi.stopNavi(); } @Override protected void onDestroy() { super.onDestroy(); mAMapNaviView.onDestroy(); //since 1.6.0 //不再在naviview destroy的时候自动执行AMapNavi.stopNavi(); //请自行执行 mAMapNavi.stopNavi(); mAMapNavi.stopGPS(); mAMapNavi.destroy(); mTtsManager.destroy(); } @Override public void onInitNaviFailure() { Toast.makeText(this, "init navi Failed", Toast.LENGTH_SHORT).show(); } @Override public void onInitNaviSuccess() { if(wayFlag == RouteSelectActivity.WAY_FLAG_DRIVE) { mAMapNavi.calculateDriveRoute(mStartList, mEndList, mWayPointList, PathPlanningStrategy.DRIVING_DEFAULT); } if(wayFlag == RouteSelectActivity.WAT_FLAG_WALK) { mAMapNavi.calculateWalkRoute(mStartList.get(0), mEndList.get(0)); } } @Override public void onStartNavi(int type) { Log.e("tag","onStartNavi"); } @Override public void onTrafficStatusUpdate() { Log.e("tag","onTrafficStatusUpdate"); } @Override public void onLocationChange(AMapNaviLocation location) { Toast.makeText(this,"onLocationChange",Toast.LENGTH_LONG).show(); } @Override public void onGetNavigationText(int type, String text) { Log.e("tag","onGetNavigationText"); } @Override public void onEndEmulatorNavi() { Log.e("tag","onEndEmulatorNavi"); } @Override public void onArriveDestination() { Log.e("tag","onArriveDestination"); } @Override public void onCalculateRouteSuccess() { if(naviType == NaviType.EMULATOR) { mAMapNavi.startNavi(NaviType.EMULATOR); } if(naviType == NaviType.GPS) { mAMapNavi.startNavi(NaviType.GPS); } } @Override public void onCalculateRouteFailure(int errorInfo) { } @Override public void onReCalculateRouteForYaw() { } @Override public void onReCalculateRouteForTrafficJam() { } @Override public void onArrivedWayPoint(int wayID) { } @Override public void onGpsOpenStatus(boolean enabled) { } @Override public void onNaviSetting() { } @Override public void onNaviMapMode(int isLock) { } @Override public void onNaviCancel() { finish(); } @Override public void onNaviTurnClick() { } @Override public void onNextRoadClick() { } @Override public void onScanViewButtonClick() { } @Deprecated @Override public void onNaviInfoUpdated(AMapNaviInfo naviInfo) { } @Override public void onNaviInfoUpdate(NaviInfo naviinfo) { } @Override public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) { } @Override public void showCross(AMapNaviCross aMapNaviCross) { } @Override public void hideCross() { } @Override public void showLaneInfo(AMapLaneInfo[] laneInfos, byte[] laneBackgroundInfo, byte[] laneRecommendedInfo) { } @Override public void hideLaneInfo() { } @Override public void onCalculateMultipleRoutesSuccess(int[] ints) { } @Override public void notifyParallelRoad(int i) { } @Override public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) { } @Override public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) { } @Override public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) { } @Override public void onLockMap(boolean isLock) { } @Override public void onNaviViewLoaded() { Log.d("wlx", "导航页面加载成功"); Log.d("wlx", "请不要使用AMapNaviView.getMap().setOnMapLoadedListener();会overwrite导航SDK内部画线逻辑"); } @Override public boolean onNaviBackClick() { return false; } }
c753da3d8d22168960af89ea93bd946f8df28770
10a9cf79e5a4a0a12cc4eda75e9bc25d778c75b0
/378_convert-binary-search-tree-to-doubly-linked-list/convert-binary-search-tree-to-doubly-linked-list.java
788593eac47859883fdaff06a0cca6d0e0b9c295
[]
no_license
SilverDestiny/LintCode
d1cd06bf7c218e61a9410dadbf03bbb47f0ce167
eb4e3ba601675e37511635c0be307706db4f19c4
refs/heads/master
2020-12-02T18:10:48.963573
2017-07-07T15:45:55
2017-07-07T15:45:55
96,489,141
0
4
null
null
null
null
UTF-8
Java
false
false
1,971
java
/* @Copyright:LintCode @Author: yun16 @Problem: http://www.lintcode.com/problem/convert-binary-search-tree-to-doubly-linked-list @Language: Java @Datetime: 16-12-20 16:30 */ /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } * Definition for Doubly-ListNode. * public class DoublyListNode { * int val; * DoublyListNode next, prev; * DoublyListNode(int val) { * this.val = val; * this.next = this.prev = null; * } * } */ public class Solution { /** * @param root: The root of tree * @return: the head of doubly list node */ class ResultType { DoublyListNode first, last; ResultType(DoublyListNode first, DoublyListNode last) { first = this.first; last = this.last; } } public DoublyListNode bstToDoublyList(TreeNode root) { // Write your code here if (root == null) { return null; } ResultType result = helper(root); return result.first; } private ResultType helper(TreeNode root) { if (root == null) { return null; } ResultType left = helper(root.left); ResultType right = helper(root.right); DoublyListNode node = new DoublyListNode(root.val); ResultType result = new ResultType(null, null); if (left == null) { result.first = node; } else { result.first = left.first; node.prev = left.last; left.last.next = node; } if (right == null) { result.last = node; } else { result.last = right.last; node.next = right.first; right.first.prev = node; } return result; } }
c69811b6d8a3203e4768e32bc37563aff0fdc723
3b51cf95fc110510d269cd98a68e3f107de40e39
/src/BinarySearchRecursive.java
bcda2f5ce8804410ef14520318c943005c5da158
[]
no_license
khoand10/pf-java-algorithm-binary-search-recursive
7b1b34371974f3f22e749ee8fe29337653b4e1ae
06c0720efea61f57afe362ebe0ca205a4e0f59b2
refs/heads/master
2020-03-09T09:24:04.543247
2018-04-09T03:56:31
2018-04-09T03:56:31
128,712,003
0
0
null
null
null
null
UTF-8
Java
false
false
624
java
public class BinarySearchRecursive { static int binarySearch(int[] arr, int row, int high, int value) { if (high >= row) { int mid = (row + high) / 2; if (value == arr[mid]) return mid; if (value > arr[mid]) return binarySearch(arr, mid + 1, high, value); return binarySearch(arr, row, mid - 1, value); } return -1; } public static void main(String[] args) { int[] numbers = {1, 4, 6, 8, 10, 13, 44}; int index = binarySearch(numbers, 0, numbers.length - 1, 45); System.out.println(index); } }
a79f13481948e637c44c03242d329e5101924975
410c3edff13b40190e3ef38aa60a42a4efc4ad67
/base/src/main/java/io/vproxy/base/util/ringbuffer/ProxyOutputRingBuffer.java
9b5b9979c33d703d13f00fa3e1d739936f116971
[ "MIT" ]
permissive
wkgcass/vproxy
f3d783531688676932f60f3df57e89ddabf3f720
6c891d43d6b9f2d2980a7d4feee124b054fbfdb5
refs/heads/dev
2023-08-09T04:03:10.839390
2023-07-31T08:28:56
2023-08-04T12:04:11
166,255,932
129
53
MIT
2022-09-15T08:35:53
2019-01-17T16:14:58
Java
UTF-8
Java
false
false
5,254
java
package io.vproxy.base.util.ringbuffer; import io.vproxy.base.util.Logger; import io.vproxy.base.util.RingBuffer; import io.vproxy.base.util.RingBufferETHandler; import io.vproxy.vfd.ReadableByteStream; import io.vproxy.vfd.WritableByteStream; import java.io.IOException; public class ProxyOutputRingBuffer extends AbstractRingBuffer { private class DefaultBufferETHandler implements RingBufferETHandler { @Override public void readableET() { triggerReadable(); } @Override public void writableET() { // dose not care, because this buffer is only used as output buffer } } private class ProxiedETHandler implements RingBufferETHandler { @Override public void readableET() { if (isProxy) { triggerReadable(); } } @Override public void writableET() { // does not care, because this buffer is only used as output buffer } } public interface ProxyDoneCallback { void proxyDone(); } private final ProxiedETHandler proxiedETHandler = new ProxiedETHandler(); private boolean isProxy = false; // true = write data from attached, false = write data from private final SimpleRingBuffer defaultBuffer; private final int cap; private RingBuffer proxied; private int proxyLen; private ProxyDoneCallback proxyDoneCallback; private ProxyOutputRingBuffer(SimpleRingBuffer defaultBuffer) { this.defaultBuffer = defaultBuffer; this.cap = defaultBuffer.capacity(); defaultBuffer.addHandler(new DefaultBufferETHandler()); } public static ProxyOutputRingBuffer allocateDirect(int cap) { return new ProxyOutputRingBuffer(SimpleRingBuffer.allocateDirect(cap)); } public void proxy(RingBuffer proxied, int proxyLen, ProxyDoneCallback cb) { if (this.proxied != null) throw new IllegalStateException("has a proxied buffer, with proxyLen = " + proxyLen); assert Logger.lowLevelDebug("get a buffer to proxy, data length is " + proxyLen); this.proxied = proxied; this.proxyLen = proxyLen; this.proxyDoneCallback = cb; this.proxied.addHandler(proxiedETHandler); if (defaultBuffer.used() == 0) { assert Logger.lowLevelDebug("the defaultBuffer is empty now, switch to proxy mode"); isProxy = true; triggerReadable(); } else { assert Logger.lowLevelDebug("still have data in the defaultBuffer"); } } public void newDataFromProxiedBuffer() { if (proxied == null) throw new IllegalStateException("no buffer to proxy but alarmed with 'new data from proxied buffer'"); if (isProxy) { triggerReadable(); } } @Override public int storeBytesFrom(ReadableByteStream channel) throws IOException { if (proxied != null) throw new IllegalStateException("has a proxied buffer, with proxyLen = " + proxyLen); return defaultBuffer.storeBytesFrom(channel); } @Override public int writeTo(WritableByteStream channel, int maxBytesToWrite) throws IOException { if (isProxy) { int toWrite = Math.min(maxBytesToWrite, proxyLen); int wrote = proxied.writeTo(channel, toWrite); proxyLen -= wrote; if (proxyLen == 0) { isProxy = false; proxied.removeHandler(proxiedETHandler); proxied = null; ProxyDoneCallback cb = proxyDoneCallback; proxyDoneCallback = null; assert Logger.lowLevelDebug("proxy end, calling proxy done callback"); cb.proxyDone(); } return wrote; } else { int wrote = defaultBuffer.writeTo(channel, maxBytesToWrite); if (wrote == maxBytesToWrite) return wrote; if (proxied == null) return wrote; assert Logger.lowLevelDebug("wrote all data from defaultBuffer, switch to proxy mode"); isProxy = true; return wrote + writeTo(channel, maxBytesToWrite - wrote); } } @Override public int free() { return cap - used(); } @Override public int used() { int proxyPart = 0; if (proxied != null) { int ret = cap; if (ret > proxyLen) ret = proxyLen; int foo = proxied.used(); if (ret > foo) ret = foo; return ret; // the minimum of cap, proxyLen, and proxied.used() } if (isProxy) { return proxyPart; } else { return Math.min(cap, defaultBuffer.used() + proxyPart); } } @Override public int capacity() { return cap; } @Override public void clean() { if (proxied != null) { proxied.removeHandler(proxiedETHandler); proxied = null; proxyLen = 0; proxyDoneCallback = null; } defaultBuffer.clean(); } @Override public void clear() { defaultBuffer.clear(); } }
389b42e91fb4f0fcc16bf268c2b0d7203eb91623
5f3814219da2f88325491e29c993b1a511e2002d
/src/service/MemberService.java
e4b2bf1cce66e23c10fb182ef4032e4c46077749
[]
no_license
JuveAlle/CatSoftVer2
def3c8380cf945474e30260d3140c1fddc6791dd
9bf57b0da8e4c5de385bc06df16196f289d464dc
refs/heads/master
2021-07-12T05:27:35.768867
2017-10-10T11:54:18
2017-10-10T11:54:18
105,760,265
2
0
null
null
null
null
UTF-8
Java
false
false
467
java
package service; import java.util.List; import domain.Member; public interface MemberService { //회원 등록 int createMember(Member member); //회원 반환하기 Member loginMember(String id); //아이디 찾기(중복) Boolean findMember(String id); //회원 목록 List<Member> memberList(); //회원정보 수정 void ModifyMember(String id, String password); //회원 삭제 void deleteMember(String id); }
d9033ea900725cf9405512d524f087db347712b9
84325f97bb51a75378491508d22b1610b7a0f526
/src/main/java/com/lagopusempire/zmessages/commands/MsgCommand.java
d5fa5572a745e44e3e6894d659aee557dc785ff5
[ "ISC" ]
permissive
ZorasOldBukkitPlugins/ZMessages
bce51d95fdc64c8e7750074493a6256ec9c1dac5
2e0167995f80af77c577e0e5af326df3392f22d4
refs/heads/master
2020-05-20T06:03:21.164304
2015-03-01T22:30:04
2015-03-01T22:30:04
31,493,899
0
0
null
null
null
null
UTF-8
Java
false
false
1,543
java
package com.lagopusempire.zmessages.commands; import com.lagopusempire.zmessages.MessageFormatter; import com.lagopusempire.zmessages.MessageSystem; import com.lagopusempire.zmessages.Messages; import com.lagopusempire.zmessages.Utils; import java.util.Arrays; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; /** * * @author MrZoraman */ public class MsgCommand extends CommandBase { public MsgCommand(MessageSystem messageSystem, Messages messages) { super(messageSystem, messages); } @Override public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) { if(args.length < 1) { Utils.sendMessage(sender, MessageFormatter.create(messages.get("error.noTarget")).colorize()); return false; } if(args.length < 2) { Utils.sendMessage(sender, MessageFormatter.create(messages.get("error.noMessage")).colorize()); return false; } CommandSender target = Utils.matchCommandSender(args[0]); if(target == null) { Utils.sendMessage(sender, MessageFormatter.create(messages.get("notFound.general")).replace("receiver", args[0]).colorize()); return true; } String message = Utils.toMessage(Arrays.copyOfRange(args, 1, args.length)); messageSystem.sendMessage(sender, target, message); return true; } }
c0ff1bcb5ed32c38d9e7a9775d3dd382fe0f1f87
5b2bc6e368a5357d009db3e1ded1967869c62900
/src/main/java/com/luckydog/mapper/WyCleanPlanMapper.java
bd8db18cff04b968d33cbf82f08bac35accf470d
[]
no_license
wzy1142552920/family_service_platform
0d68e1b0f884e970ec55505970f53340a3082409
5a68167215072baa1314faa6853f3b7d526c811f
refs/heads/master
2023-02-05T04:14:51.623473
2020-11-22T15:50:47
2020-11-22T15:50:47
315,075,371
0
0
null
null
null
null
UTF-8
Java
false
false
294
java
package com.luckydog.mapper; import com.luckydog.bean.WyCleanPlan; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * 清洁安排 Mapper 接口 * </p> * * @author luckydog * @since 2020-07-14 */ public interface WyCleanPlanMapper extends BaseMapper<WyCleanPlan> { }
2eb0cef4d361f39e7ae2c15e9640aa8e19bca29c
30c417ec27ea21ef65fedfd44a07c85d0205e8d9
/src/main/java/com/example/demo/service/UserService.java
7523d70d5ae19a57fdb2a3cea33cda42ce91c50f
[]
no_license
fjborquez/tutorial-aspectj-springboot
c1804d5ea48ddf025cc1da29205264df97b5eb68
b60a3d493b8edf90e95b94139a7ba71c81532d1e
refs/heads/master
2022-11-16T10:15:48.177009
2020-07-05T22:33:49
2020-07-05T22:33:49
276,540,051
0
0
null
null
null
null
UTF-8
Java
false
false
156
java
package com.example.demo.service; import com.example.demo.dto.User; import java.util.List; public interface UserService { List<User> getAllUsers(); }
d07166f244fef79166906b862dfe8fb7c468f159
72003cab6711efe96e7080599376d758e065fc33
/PCLApp/JavaSource/com/citibank/ods/modules/product/player/functionality/PlayerDetailFnc.java
3778d11e6aefba40f75410fcfad9abd8a2258b38
[]
no_license
mv58799/PCLApp
39390b8ff5ccaf95c654f394e32ed03b7713e8ad
2f8772a60fee035104586bbbf2827567247459c4
refs/heads/master
2020-03-19T09:06:30.870074
2018-06-06T03:10:07
2018-06-06T03:10:07
136,260,531
0
0
null
null
null
null
ISO-8859-1
Java
false
false
29,784
java
package com.citibank.ods.modules.product.player.functionality; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.struts.action.ActionForm; import com.citibank.ods.Globals; import com.citibank.ods.common.entity.BaseODSEntity; import com.citibank.ods.common.functionality.ODSDetailFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.common.util.ODSConstraintDecoder; import com.citibank.ods.entity.pl.BaseTplPlayerRoleEntity; import com.citibank.ods.entity.pl.TplPlayerEntity; import com.citibank.ods.entity.pl.TplPlayerMovEntity; import com.citibank.ods.entity.pl.TplPlayerRoleMovEntity; import com.citibank.ods.entity.pl.TplShortNamePlayerMovEntity; import com.citibank.ods.entity.pl.valueobject.TplPlayerEntityVO; import com.citibank.ods.entity.pl.valueobject.TplPlayerRoleMovEntityVO; import com.citibank.ods.modules.product.player.form.PlayerDetailForm; import com.citibank.ods.modules.product.player.functionality.valueobject.PlayerDetailFncVO; import com.citibank.ods.modules.product.player.functionality.valueobject.ShortNameVO; import com.citibank.ods.persistence.pl.dao.BaseTplPlayerDAO; import com.citibank.ods.persistence.pl.dao.BaseTplPlayerRoleDAO; import com.citibank.ods.persistence.pl.dao.TplPlayerDAO; import com.citibank.ods.persistence.pl.dao.TplPlayerMovDAO; import com.citibank.ods.persistence.pl.dao.TplPlayerRoleDAO; import com.citibank.ods.persistence.pl.dao.TplPlayerRoleMovDAO; import com.citibank.ods.persistence.pl.dao.TplProdPlayerRoleDAO; import com.citibank.ods.persistence.pl.dao.TplShortNamePlayerDAO; import com.citibank.ods.persistence.pl.dao.TplShortNamePlayerMovDAO; import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory; /** * @author angelica.almeida * */ public class PlayerDetailFnc extends BasePlayerDetailFnc implements ODSDetailFnc { private static final String C_ASSOCIATION = "Associações"; private static final String C_PLYR_ROLE = "Papel Player"; private static final String C_PLAYER = "Player"; /** * * @see com.citibank.ods.common.functionality.ODSDetailFnc#insert(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void insert( BaseFncVO fncVO_ ) { BaseTplPlayerRoleEntity baseTplPlayerRoleEntity; TplPlayerRoleMovEntity playerRoleMovEntity; this.validateInsert( fncVO_ ); if ( !fncVO_.hasErrors() ) { PlayerDetailFncVO detailFncVO = ( PlayerDetailFncVO ) fncVO_; TplPlayerEntity tplPlayerEntity = ( TplPlayerEntity ) detailFncVO.getBaseTplPlayerEntity(); tplPlayerEntity.getData().setLastUpdDate( new Date() ); tplPlayerEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); TplPlayerMovEntity tplPlayerMovEntity = new TplPlayerMovEntity( tplPlayerEntity, TplPlayerMovEntity.C_OPERN_CODE_INSERT ); TplPlayerMovDAO tplPlayerMovDAO = ODSDAOFactory.getInstance().getTplPlayerMovDAO(); tplPlayerMovDAO.insert( tplPlayerMovEntity ); TplPlayerRoleMovDAO tplPlayerRoleMovDAO = ODSDAOFactory.getInstance().getTplPlayerRoleMovDAO(); ArrayList playerRoleNames = detailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames(); for ( int i = 0; i < playerRoleNames.size(); i++ ) { baseTplPlayerRoleEntity = ( BaseTplPlayerRoleEntity ) playerRoleNames.get( i ); playerRoleMovEntity = new TplPlayerRoleMovEntity(); playerRoleMovEntity.getData().setPlyrCnpjNbr( baseTplPlayerRoleEntity.getData().getPlyrCnpjNbr() ); playerRoleMovEntity.getData().setPlyrRoleTypeCode( baseTplPlayerRoleEntity.getData().getPlyrRoleTypeCode() ); playerRoleMovEntity.getData().setLastUpdDate( new Date() ); playerRoleMovEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); ( ( TplPlayerRoleMovEntityVO ) playerRoleMovEntity.getData() ).setOpernCode( TplPlayerRoleMovEntity.C_OPERN_CODE_INSERT ); tplPlayerRoleMovDAO.insert( playerRoleMovEntity ); } //Insere lista de Mnemonicos ShortNameVO shortNameVO; TplShortNamePlayerMovEntity tplShortNamePlayerMovEntity; TplShortNamePlayerMovDAO tplShortNamePlayerMovDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerMovDAO(); List<ShortNameVO> shortNameList = detailFncVO.getIssueShortNameList(); for(int i=0;i<shortNameList.size();i++){ shortNameVO = shortNameList.get(i); shortNameVO.setOpernCode(BaseODSEntity.C_OPERN_CODE_INSERT); shortNameVO.setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : ""); shortNameVO.setLastUpdDate(new Date()); tplShortNamePlayerMovEntity = new TplShortNamePlayerMovEntity(shortNameVO); tplShortNamePlayerMovDAO.insert(tplShortNamePlayerMovEntity); } } } /** * * @see com.citibank.ods.common.functionality.ODSDetailFnc#update(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void update( BaseFncVO fncVO_ ) { BaseTplPlayerRoleEntity baseTplPlayerRoleEntity; TplPlayerRoleMovEntity playerRoleMovEntity; this.validateUpdate( fncVO_ ); if ( !fncVO_.hasErrors() ) { PlayerDetailFncVO detailFncVO = ( PlayerDetailFncVO ) fncVO_; TplPlayerEntity tplPlayerEntity = ( TplPlayerEntity ) detailFncVO.getBaseTplPlayerEntity(); tplPlayerEntity.getData().setLastUpdDate( new Date() ); tplPlayerEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); TplPlayerMovEntity tplPlayerMovEntity = new TplPlayerMovEntity( tplPlayerEntity, TplPlayerMovEntity.C_OPERN_CODE_UPDATE ); TplPlayerMovDAO tplPlayerMovDAO = ODSDAOFactory.getInstance().getTplPlayerMovDAO(); tplPlayerMovDAO.insert( tplPlayerMovEntity ); //Inserir papéis do player TplPlayerRoleMovDAO tplPlayerRoleMovDAO = ODSDAOFactory.getInstance().getTplPlayerRoleMovDAO(); ArrayList playerRoleNames = detailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames(); for ( int i = 0; i < playerRoleNames.size(); i++ ) { baseTplPlayerRoleEntity = ( BaseTplPlayerRoleEntity ) playerRoleNames.get( i ); playerRoleMovEntity = new TplPlayerRoleMovEntity(); playerRoleMovEntity.getData().setPlyrCnpjNbr( baseTplPlayerRoleEntity.getData().getPlyrCnpjNbr() ); playerRoleMovEntity.getData().setPlyrRoleTypeCode( baseTplPlayerRoleEntity.getData().getPlyrRoleTypeCode() ); playerRoleMovEntity.getData().setLastUpdDate( new Date() ); playerRoleMovEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); ( ( TplPlayerRoleMovEntityVO ) playerRoleMovEntity.getData() ).setOpernCode( TplPlayerMovEntity.C_OPERN_CODE_UPDATE ); tplPlayerRoleMovDAO.insert( playerRoleMovEntity ); } //Insere lista de Mnemonicos ShortNameVO shortNameVO; TplShortNamePlayerMovEntity tplShortNamePlayerMovEntity; TplShortNamePlayerMovDAO tplShortNamePlayerMovDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerMovDAO(); List<ShortNameVO> shortNameList = detailFncVO.getIssueShortNameList(); for(int i=0;i<shortNameList.size();i++){ shortNameVO = shortNameList.get(i); shortNameVO.setOpernCode(BaseODSEntity.C_OPERN_CODE_UPDATE); shortNameVO.setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : ""); shortNameVO.setLastUpdDate(new Date()); tplShortNamePlayerMovEntity = new TplShortNamePlayerMovEntity(shortNameVO); tplShortNamePlayerMovDAO.insert(tplShortNamePlayerMovEntity); } } } /** * * @see com.citibank.ods.common.functionality.ODSDetailFnc#delete(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void delete( BaseFncVO fncVO_ ) { BaseTplPlayerRoleEntity baseTplPlayerRoleEntity; TplPlayerRoleMovEntity playerRoleMovEntity; PlayerDetailFncVO detailFncVO = ( PlayerDetailFncVO ) fncVO_; validateDelete( detailFncVO ); if ( !detailFncVO.hasErrors() ) { TplPlayerDAO tplPlayerDAO = ODSDAOFactory.getInstance().getTplPlayerDAO(); TplPlayerEntity tplPlayerEntity = ( TplPlayerEntity ) tplPlayerDAO.find( detailFncVO.getBaseTplPlayerEntity() ); tplPlayerEntity.getData().setLastUpdDate( new Date() ); tplPlayerEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); TplPlayerMovEntity tplPlayerMovEntity = new TplPlayerMovEntity( tplPlayerEntity, TplPlayerMovEntity.C_OPERN_CODE_DELETE ); TplPlayerMovDAO tplPlayerMovDAO = ODSDAOFactory.getInstance().getTplPlayerMovDAO(); tplPlayerMovDAO.insert( tplPlayerMovEntity ); //Papéis do player TplPlayerRoleMovDAO tplPlayerRoleMovDAO = ODSDAOFactory.getInstance().getTplPlayerRoleMovDAO(); TplPlayerRoleDAO tplPlayerRoleDAO = ODSDAOFactory.getInstance().getTplPlayerRoleDAO(); ArrayList playerRoleNames = tplPlayerRoleDAO.selectByPk( tplPlayerEntity.getData().getPlyrCnpjNbr() ); for ( int i = 0; i < playerRoleNames.size(); i++ ) { baseTplPlayerRoleEntity = ( BaseTplPlayerRoleEntity ) playerRoleNames.get( i ); playerRoleMovEntity = new TplPlayerRoleMovEntity(); playerRoleMovEntity.getData().setPlyrCnpjNbr( baseTplPlayerRoleEntity.getData().getPlyrCnpjNbr() ); playerRoleMovEntity.getData().setPlyrRoleTypeCode( baseTplPlayerRoleEntity.getData().getPlyrRoleTypeCode() ); playerRoleMovEntity.getData().setLastUpdDate( new Date() ); playerRoleMovEntity.getData().setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : "" ); ( ( TplPlayerRoleMovEntityVO ) playerRoleMovEntity.getData() ).setOpernCode( TplPlayerMovEntity.C_OPERN_CODE_DELETE ); tplPlayerRoleMovDAO.insert( playerRoleMovEntity ); } //Mnemonicos ShortNameVO shortNameVO; TplShortNamePlayerMovEntity tplShortNamePlayerMovEntity; TplShortNamePlayerMovDAO tplShortNamePlayerMovDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerMovDAO(); List<ShortNameVO> shortNameList = detailFncVO.getIssueShortNameList(); for(int i=0;i<shortNameList.size();i++){ shortNameVO = shortNameList.get(i); shortNameVO.setOpernCode(BaseODSEntity.C_OPERN_CODE_DELETE); shortNameVO.setLastUpdUserId( fncVO_.getLoggedUser() != null ? fncVO_.getLoggedUser().getUserID() : ""); shortNameVO.setLastUpdDate(new Date()); tplShortNamePlayerMovEntity = new TplShortNamePlayerMovEntity(shortNameVO); tplShortNamePlayerMovDAO.insert(tplShortNamePlayerMovEntity); } } } /** * Realiza as validações de inserção * @see com.citibank.ods.common.functionality.ODSDetailFnc#validateInsert(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateInsert( BaseFncVO fncVO_ ) { PlayerDetailFncVO playerDetailFncVO = ( PlayerDetailFncVO ) fncVO_; TplPlayerEntityVO tplPlayerEntityVO = ( TplPlayerEntityVO ) playerDetailFncVO.getBaseTplPlayerEntity().getData(); //Validar Campos Obrigatórios if ( tplPlayerEntityVO.getPlyrCnpjNbr() == null || tplPlayerEntityVO.getPlyrCnpjNbr().equals( "" ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_CNPJ_NBR ); } if ( tplPlayerEntityVO.getPlyrName() == null || tplPlayerEntityVO.getPlyrName().equals( "" ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_NAME ); } if ( playerDetailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames() == null || playerDetailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames().size() < 1 ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_ROLE ); } if ( !fncVO_.hasErrors() ) { //Validar se já existe um registro com este codigo na "Current", if ( this.existsActive( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_DUPLICATE_PK ); } //Validar se já existe movimento com este codigo if ( this.existsInMovement( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IN_MOVEMENT ); } //validar se já existe um mnemonico cadastrado com o este valor if(this.existsInIssue( playerDetailFncVO )!= null){ fncVO_.addError(PlayerDetailFncVO.C_INVALID_ISSUE,this.existsInIssue( playerDetailFncVO )); } } } /** * Realiza as validações de alteração * @see com.citibank.ods.common.functionality.ODSDetailFnc#validateUpdate(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateUpdate( BaseFncVO fncVO_ ) { PlayerDetailFncVO playerDetailFncVO = ( PlayerDetailFncVO ) fncVO_; TplPlayerEntityVO tplPlayerEntityVO = ( TplPlayerEntityVO ) playerDetailFncVO.getBaseTplPlayerEntity().getData(); //Validar Campos Obrigatórios if ( tplPlayerEntityVO.getPlyrCnpjNbr() == null || tplPlayerEntityVO.getPlyrCnpjNbr().equals( "" ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_CNPJ_NBR ); } if ( tplPlayerEntityVO.getPlyrName() == null || tplPlayerEntityVO.getPlyrName().equals( "" ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_NAME ); } if ( playerDetailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames() == null || playerDetailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames().size() < 1 ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_PLYR_ROLE ); } if ( !fncVO_.hasErrors() ) { //Validar se existe um registro com este codigo na "Current", if ( !this.existsActive( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_PK_NOT_FOUND ); } //Validar se já existe movimento com este codigo if ( this.existsInMovement( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IN_MOVEMENT ); } //Validar se existem associações relacionadas a algum dos papéis // excluidos ArrayList listRoleTypes = new ArrayList(); listRoleTypes = this.verifyAssociations( tplPlayerEntityVO.getPlyrCnpjNbr(), playerDetailFncVO.getBaseTplPlayerEntity().getPlyrRoleNames() ); if ( listRoleTypes != null && listRoleTypes.size() > 0 ) { for ( int i = 0; i < listRoleTypes.size(); i++ ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IS_REFERENCED, C_PLYR_ROLE + " " + listRoleTypes.get( i ), " " + C_ASSOCIATION ); } } if ( this.existsInIssue(playerDetailFncVO) != null) { fncVO_.addError( PlayerDetailFncVO.C_INVALID_ISSUE, this.existsInIssue( playerDetailFncVO ) ); } } } /** * Realiza as validações de exclusão * @see com.citibank.ods.common.functionality.ODSDetailFnc#validateDelete(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateDelete( BaseFncVO fncVO_ ) { PlayerDetailFncVO playerDetailFncVO = ( PlayerDetailFncVO ) fncVO_; if ( !fncVO_.hasErrors() ) { //Validar se existe um registro com este codigo na "Current", if ( !this.existsActive( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_PK_NOT_FOUND ); } //Validar se já existe movimento com este codigo if ( this.existsInMovement( playerDetailFncVO ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IN_MOVEMENT ); } if ( this.existsAssociation( playerDetailFncVO.getBaseTplPlayerEntity().getData().getPlyrCnpjNbr() ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IS_REFERENCED, C_PLAYER, C_ASSOCIATION ); } } } /** * Carregamento inicial - detalhe * @see com.citibank.ods.common.functionality.ODSDetailFnc#loadForConsult(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void loadForConsult( BaseFncVO fncVO_ ) { super.load( ( PlayerDetailFncVO ) fncVO_ ); super.loadDomains( ( PlayerDetailFncVO ) fncVO_ ); } /** * Carregamento inicial - inserção * @see com.citibank.ods.common.functionality.ODSDetailFnc#loadForInsert(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void loadForInsert( BaseFncVO fncVO_ ) { PlayerDetailFncVO detailFncVO = ( PlayerDetailFncVO ) fncVO_; TplPlayerEntityVO tplPlayerEntityVO = ( TplPlayerEntityVO ) detailFncVO.getBaseTplPlayerEntity().getData(); tplPlayerEntityVO.setPlyrCnpjNbr( null ); tplPlayerEntityVO.setPlyrName( null ); tplPlayerEntityVO.setPlyrAddrText( null ); tplPlayerEntityVO.setPlyrDueDlgDate( null ); tplPlayerEntityVO.setPlyrDueDlgExecInd( null ); tplPlayerEntityVO.setPlyrDueDlgEndDate( null ); tplPlayerEntityVO.setPlyrDueDlgRnwDate( null ); tplPlayerEntityVO.setPlyrInvstCmtteApprvDate( null ); tplPlayerEntityVO.setPlyrApprvRstrnText( null ); tplPlayerEntityVO.setPlyrSuplServText( null ); tplPlayerEntityVO.setPlyrCmntText( null ); detailFncVO.getBaseTplPlayerEntity().setPlyrRoleNames( null ); detailFncVO.setIssueShortNameList(new ArrayList<ShortNameVO>()); detailFncVO.setIssueShortNameText(null); } /** * Carregamento inicial - alteração * @see com.citibank.ods.common.functionality.ODSDetailFnc#loadForUpdate(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void loadForUpdate( BaseFncVO fncVO_ ) { if ( this.existsInMovement( ( PlayerDetailFncVO ) fncVO_ ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IN_MOVEMENT ); } else { super.load( ( PlayerDetailFncVO ) fncVO_ ); super.loadDomains( ( PlayerDetailFncVO ) fncVO_ ); } } /** * Carregamento inicial - exclusão * @see com.citibank.ods.common.functionality.ODSDetailFnc#loadForDelete(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void loadForDelete( BaseFncVO fncVO_ ) { if ( this.existsInMovement( ( PlayerDetailFncVO ) fncVO_ ) ) { fncVO_.addError( PlayerDetailFncVO.C_ERROR_IN_MOVEMENT ); } else { super.load( ( PlayerDetailFncVO ) fncVO_ ); super.loadDomains( ( PlayerDetailFncVO ) fncVO_ ); } } /** * Verifica se existe um registro na tabela de movimento com os critérios * passados */ private boolean existsInMovement( PlayerDetailFncVO playerDetailFncVO_ ) { TplPlayerMovDAO tplPlayerMovDAO = ODSDAOFactory.getInstance().getTplPlayerMovDAO(); TplPlayerMovEntity tplPlayerMovEntity = new TplPlayerMovEntity(); tplPlayerMovEntity.getData().setPlyrCnpjNbr( playerDetailFncVO_.getBaseTplPlayerEntity().getData().getPlyrCnpjNbr() ); return tplPlayerMovDAO.exists( tplPlayerMovEntity ); } /** * Verifica se já existe um registro na tabela de "Current" com o código * passado e o seu status é "Ativo" */ private boolean existsActive( PlayerDetailFncVO playerDetailFncVO_ ) { TplPlayerDAO tplPlayerDAO = ODSDAOFactory.getInstance().getTplPlayerDAO(); return tplPlayerDAO.existsActive( ( TplPlayerEntity ) playerDetailFncVO_.getBaseTplPlayerEntity() ); } /** * Retorna uma instancia do FncVO * @see com.citibank.ods.common.functionality.BaseFnc#createFncVO() */ public BaseFncVO createFncVO() { return new PlayerDetailFncVO(); } /** * Retorna uma instancia do DAO da Current */ protected BaseTplPlayerDAO getDAO() { return ODSDAOFactory.getInstance().getTplPlayerDAO(); } /** * Retorna o DAO do Player Role * @see com.citibank.ods.modules.product.player.functionality.BasePlayerDetailFnc#getPlayerRoleDAO() */ protected BaseTplPlayerRoleDAO getPlayerRoleDAO() { return ODSDAOFactory.getInstance().getTplPlayerRoleDAO(); } /** * Seta na Form os campos específicos de current */ public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ ) { super.updateFormFromFncVO( form_, fncVO_ ); PlayerDetailFncVO detailfncVO = ( PlayerDetailFncVO ) fncVO_; PlayerDetailForm detailForm = ( PlayerDetailForm ) form_; TplPlayerEntityVO tplPlayerEntityVO = ( TplPlayerEntityVO ) detailfncVO.getBaseTplPlayerEntity().getData(); SimpleDateFormat dateFormat = new SimpleDateFormat( Globals.FuncionalityFormatKeys.C_FORMAT_DATE_DDMMYYYY ); detailForm.setLastAuthUserId( tplPlayerEntityVO.getLastAuthUserId() ); if ( tplPlayerEntityVO.getLastAuthDate() != null && !tplPlayerEntityVO.getLastAuthDate().equals( "" ) ) { detailForm.setLastAuthDate( dateFormat.format( tplPlayerEntityVO.getLastAuthDate() ) ); } else { detailForm.setLastAuthDate( null ); } String recStatCode = ( ( TplPlayerEntityVO ) ( detailfncVO.getBaseTplPlayerEntity().getData() ) ).getRecStatCode(); if ( recStatCode != null && !"".equals( recStatCode ) ) { String strRecStatCode = ODSConstraintDecoder.decodeRecStatus( recStatCode ); detailForm.setRecStatCode( strRecStatCode ); } if(this.existsActive( detailfncVO )){ if(detailForm.getLoadIssue().equals("S")){ TplShortNamePlayerDAO tplShortNamePlayerDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerDAO(); List<ShortNameVO> shortNameList = tplShortNamePlayerDAO.selectByPlyr(detailfncVO.getBaseTplPlayerEntity().getData().getPlyrCnpjNbr()); detailForm.setIssueShortNameList(shortNameList); detailfncVO.setLoadIssue("N"); } } } private ArrayList verifyAssociations( String plyrCnpjNbr_, ArrayList listPlayerRole_ ) { BaseTplPlayerRoleEntity tplPlayerRoleEntity; ArrayList list = new ArrayList(); list = listPlayerRole_; String roleTypes = ""; if ( list != null && list.size() > 0 ) { for ( int i = 0; i < list.size(); i++ ) { tplPlayerRoleEntity = ( BaseTplPlayerRoleEntity ) list.get( i ); roleTypes = roleTypes + ",'" + tplPlayerRoleEntity.getData().getPlyrRoleTypeCode() + "'"; } } roleTypes = roleTypes.substring( 1 ); TplProdPlayerRoleDAO tplProdPlayerRoleDAO = ODSDAOFactory.getInstance().getTplProdPlayerRoleDAO(); list = tplProdPlayerRoleDAO.getRoleTypes( plyrCnpjNbr_, roleTypes ); return list; } private boolean existsAssociation( String plyrCnpjNbr_ ) { ArrayList listAssociation = new ArrayList(); TplProdPlayerRoleDAO tplProdPlayerRoleDAO = ODSDAOFactory.getInstance().getTplProdPlayerRoleDAO(); listAssociation = tplProdPlayerRoleDAO.selectByPlyr( plyrCnpjNbr_ ); if ( listAssociation.size() > 0 ) { return true; } else { return false; } } public void insertIssue(BaseFncVO fncVO_){ PlayerDetailFncVO detailfncVO = ( PlayerDetailFncVO ) fncVO_; if(detailfncVO.getIssueShortNameText() != null && !detailfncVO.getIssueShortNameText().equals("")){ if(validateIssue(fncVO_)){ ShortNameVO shortNameVO = new ShortNameVO(); shortNameVO.setPlyrCnpjNbr(detailfncVO.getBaseTplPlayerEntity().getData().getPlyrCnpjNbr()); shortNameVO.setLastUpdUserId(detailfncVO.getBaseTplPlayerEntity().getData().getLastUpdUserId()); shortNameVO.setIssueShortName(detailfncVO.getIssueShortNameText().toUpperCase().trim()); detailfncVO.getIssueShortNameList().add(shortNameVO); fncVO_.clearErrors(); } }else{ fncVO_.addError( PlayerDetailFncVO.C_ERROR_MANDATORY_FIELD, C_DISPLAY_ISSUE ); } } public void deleteIssue(BaseFncVO fncVO_){ PlayerDetailFncVO detailfncVO = ( PlayerDetailFncVO ) fncVO_; List<ShortNameVO> shortNameList = detailfncVO.getIssueShortNameList(); ShortNameVO shortNameVO = shortNameList.get(detailfncVO.getShortNameIdx()); shortNameList.remove(shortNameVO); detailfncVO.setIssueShortNameList(shortNameList); } public boolean validateIssue(BaseFncVO fncVO_){ PlayerDetailFncVO detailfncVO = ( PlayerDetailFncVO ) fncVO_; if(detailfncVO.getIssueShortNameList().size() > 0){ List<ShortNameVO> shortNameList = detailfncVO.getIssueShortNameList(); for(int i=0; i< shortNameList.size(); i++){ ShortNameVO shortNameVO = shortNameList.get(i); if(shortNameVO.getIssueShortName().equals(detailfncVO.getIssueShortNameText().toUpperCase().trim())){ fncVO_.addError(BaseODSFncVO.C_INVALID_ISSUE,detailfncVO.getIssueShortNameText().toUpperCase()); return false; } } } return true; } private String existsInIssue( PlayerDetailFncVO playerDetailFncVO ){ //Lista valores contidos no objeto a ser inserido List<ShortNameVO> shortNameObjList = playerDetailFncVO.getIssueShortNameList(); //Lista valores contidos na base tpl_short_name_player TplShortNamePlayerDAO tplShortNamePlayerDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerDAO(); List<ShortNameVO> shortNameDataList = tplShortNamePlayerDAO.selectByPlyrCnpj(playerDetailFncVO.getBaseTplPlayerEntity().getData().getPlyrCnpjNbr());; //Lista valores contidos na base tpl_short_name_player_mov TplShortNamePlayerMovDAO tplShortNamePlayerMovDAO = ODSDAOFactory.getInstance().getTplShortNamePlayerMovDAO(); List<ShortNameVO> shortNameDataMovList = tplShortNamePlayerMovDAO.selectByPlyr(null); for(int indexObj = 0;indexObj< shortNameObjList.size();indexObj++){ ShortNameVO shortNameObjVO = shortNameObjList.get(indexObj); //Verifica se o valor do obj se encontra na base for(int indexData = 0;indexData< shortNameDataList.size();indexData++){ ShortNameVO shortNameDataVO = shortNameDataList.get(indexData); if(shortNameObjVO.getIssueShortName().equals(shortNameDataVO.getIssueShortName())){ return shortNameDataVO.getIssueShortName(); } } //Verifica se o valor do obj se encontra na base mov for(int indexDataMov = 0;indexDataMov< shortNameDataMovList.size();indexDataMov++){ ShortNameVO shortNameDataMovVO = shortNameDataMovList.get(indexDataMov); if(shortNameObjVO.getIssueShortName().equals(shortNameDataMovVO.getIssueShortName())){ return shortNameDataMovVO.getIssueShortName(); } } } return null; } }
8f3e120e0a9bdc81f19051104aba6c053a0b7879
cfc894ac317799b5bb997dff83465c056b740167
/app/src/main/java/com/bryanrady/ui/view/paint/filter/ColorMatrixFilterOther.java
b912746d121539f9866b65e8e08e4cfab500916a
[]
no_license
bryanrady/UI
b3f919deeec7719bcce251898c91fb3440032ebf
edd8fb1c0069cfc7fc23a6f1421cd4a87dae87c4
refs/heads/master
2021-06-28T12:59:07.065515
2020-09-13T08:10:28
2020-09-13T08:10:28
139,309,123
0
0
null
null
null
null
UTF-8
Java
false
false
3,429
java
package com.bryanrady.ui.view.paint.filter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.RectF; import android.view.MotionEvent; import android.view.View; import com.bryanrady.ui.R; /** * 颜色矩阵的一些其他效果 * Created by wqb on 2018/6/26. */ public class ColorMatrixFilterOther extends View { private Paint mPaint; private Bitmap mBitmap; private int progress1; private int progress2; public ColorMatrixFilterOther(Context context) { super(context); setLayerType(LAYER_TYPE_SOFTWARE,null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.xyjy2); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); RectF rectF = new RectF(100,100,mBitmap.getWidth(),mBitmap.getHeight()); canvas.drawBitmap(mBitmap, null , rectF , mPaint); //1.设置矩阵缩放 setScale RectF rectF1 = new RectF(100+mBitmap.getWidth(),100,mBitmap.getWidth()*2,mBitmap.getHeight()); ColorMatrix colorMatrix = new ColorMatrix(); //图片变亮了 colorMatrix.setScale(1.2f,1.2f,1.2f,1); mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); canvas.drawBitmap(mBitmap, null , rectF1 , mPaint); mPaint.setColorFilter(null); // 2.设置饱和度 setSaturation 图片能变深沉 RectF rectF2 = new RectF(100,mBitmap.getHeight()+100,mBitmap.getWidth(),mBitmap.getHeight()*2); ColorMatrix colorMatrix2 = new ColorMatrix(); colorMatrix2.setSaturation(progress1); mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix2)); canvas.drawBitmap(mBitmap,null,rectF2,mPaint); mPaint.setColorFilter(null); //3.设置旋转 setRotate 颜色变换 RectF rectF3 = new RectF(100+mBitmap.getWidth(),mBitmap.getHeight()+100,mBitmap.getWidth()*2,mBitmap.getHeight()*2); ColorMatrix colorMatrix3 = new ColorMatrix(); //aixs-- 0 红色轴,1,绿色,2,蓝色 // degrees -- 旋转的角度 colorMatrix3.setRotate(0,progress2); mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix3)); canvas.drawBitmap(mBitmap,null, rectF3, mPaint); mPaint.setColorFilter(null); //4.两个矩阵组合 setConcat RectF rectF4 = new RectF(100,mBitmap.getHeight()*2+100,mBitmap.getWidth(),mBitmap.getHeight()*3); ColorMatrix colorMatrix4 = new ColorMatrix(); colorMatrix4.setConcat(colorMatrix2,colorMatrix3); mPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix4)); canvas.drawBitmap(mBitmap,null, rectF4, mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //progress1 += 1f; progress1 += 20f; progress2 = 0xff0000; invalidate(); break; case MotionEvent.ACTION_UP: progress2 = 0x000000; invalidate(); break; } return true; } }
bab015856bf60af25d7cbb306ed9262fe9e6521a
307791dc81ec099b906bc6eef3d9eb70a92b65e9
/NewsApp/app/src/androidTest/java/com/example/android/newsapp/ExampleInstrumentedTest.java
61977e2f7c4ed89ace1c2675171ea8c0983099ea
[]
no_license
karthik-panambur/AndroidApps
4d44b4d836da99c703430b5a31bc1aeaf41972a5
d5592c354ba15fffa51ed5d129b584aff5b44f85
refs/heads/master
2022-09-03T23:20:09.502275
2020-05-26T17:18:53
2020-05-26T17:18:53
266,230,507
1
0
null
null
null
null
UTF-8
Java
false
false
770
java
package com.example.android.newsapp; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.android.newsapp", appContext.getPackageName()); } }
ac516d9e90992615e63e0869d516f62553a26aa3
dee8cddb2f465ca99a628825b2f7e1efe974fb87
/app/src/main/java/com/sahni/rahul/ieee_niec/activity/SignInActivity.java
fdc29c97db6a4016f8b77c121d2a19e1fe3b0c92
[]
no_license
rahulsahni06/IEEE-NIEC-Android-app
0b11a9f121b2502ef3b880e439c00fef981ffd9b
eca8ccc0de321354441c99673f92da2a575cf54b
refs/heads/master
2021-03-31T01:05:53.750358
2018-04-06T06:36:31
2018-04-06T06:36:31
111,327,642
2
0
null
null
null
null
UTF-8
Java
false
false
15,745
java
package com.sahni.rahul.ieee_niec.activity; import android.content.Intent; import android.content.IntentSender; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.sahni.rahul.ieee_niec.R; import com.sahni.rahul.ieee_niec.helpers.ContentUtils; import com.sahni.rahul.ieee_niec.models.User; import static com.sahni.rahul.ieee_niec.helpers.ContentUtils.STATE_RESOLVING_ERROR; public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener ,GoogleApiClient.ConnectionCallbacks { private static final String TAG = "SignInActivity"; private static final int RC_GET_USER_DETAILS = 600; private GoogleApiClient mGoogleApiClient; private int RC_SIGN_IN = 1; private ProgressBar mProgressBar; private SignInButton mSignInButton; private AlertDialog mAlertDialog; private FirebaseAuth mAuth; private int REQUEST_RESOLVE_ERROR = 1001; private String mAction; private boolean mResolvingError = false; private CollectionReference mUsersCollection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mResolvingError = savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false); } setContentView(R.layout.activity_sign_in); mUsersCollection = FirebaseFirestore.getInstance().collection("users"); Intent intent = getIntent(); mAction = intent.getStringExtra(ContentUtils.ACTION_SIGN); mAuth = FirebaseAuth.getInstance(); mProgressBar = findViewById(R.id.sign_in_progress); mProgressBar.getIndeterminateDrawable().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN); ImageView closeImageView = findViewById(R.id.close_image_view); closeImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mSignInButton = findViewById(R.id.sign_in_button); mSignInButton.setSize(SignInButton.SIZE_WIDE); mSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); if (mAction != null && mAction.equals(ContentUtils.SIGNED_OUT)) { mSignInButton.setEnabled(false); View dialogView = getLayoutInflater().inflate(R.layout.progress_dialog_layout, null); TextView progressTextView = dialogView.findViewById(R.id.progress_text_view); progressTextView.setText("Signing out..."); mAlertDialog = new AlertDialog.Builder(this) .setView(dialogView) .setCancelable(false) .create(); mAlertDialog.show(); } else if (mAction != null && mAction.equals(ContentUtils.DELETE_ACCOUNT)) { mSignInButton.setEnabled(false); View dialogView = getLayoutInflater().inflate(R.layout.progress_dialog_layout, null); TextView progressTextView = dialogView.findViewById(R.id.progress_text_view); progressTextView.setText("Deleting..."); mAlertDialog = new AlertDialog.Builder(this) .setView(dialogView) .setCancelable(false) .create(); mAlertDialog.show(); } } private void signIn() { mProgressBar.setVisibility(View.VISIBLE); Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); } else if (requestCode == REQUEST_RESOLVE_ERROR) { mResolvingError = false; if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } } else if(requestCode == RC_GET_USER_DETAILS){ if(resultCode == RESULT_OK){ User user = data.getParcelableExtra(ContentUtils.USER_KEY); saveDetails(user); } else { mProgressBar.setVisibility(View.INVISIBLE); mSignInButton.setEnabled(true); Snackbar.make(mProgressBar, "Sign in failed!, Try Again", Snackbar.LENGTH_SHORT).show(); } } } private void handleSignInResult(GoogleSignInResult result) { if (result.isSuccess()) { mSignInButton.setEnabled(false); final GoogleSignInAccount acct = result.getSignInAccount(); firebaseAuthWithGoogle(acct); } else { mProgressBar.setVisibility(View.INVISIBLE); } } private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) { AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseUser firebaseUser = mAuth.getCurrentUser(); checkForUserDetailsOnline(firebaseUser); } else { mProgressBar.setVisibility(View.INVISIBLE); mSignInButton.setEnabled(true); Toast.makeText(SignInActivity.this, "Login failed, try again", Toast.LENGTH_SHORT).show(); } } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } private void checkForUserDetailsOnline(final FirebaseUser firebaseUser) { mUsersCollection.document(firebaseUser.getUid()) .get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document.exists()) { User user = document.toObject(User.class); Toast.makeText(SignInActivity.this, "Welcome back, " + user.getName() + "!", Toast.LENGTH_SHORT).show(); saveDetailsLocally(user); } else { User user = new User( firebaseUser.getUid(), firebaseUser.getDisplayName(), firebaseUser.getEmail(), firebaseUser.getPhotoUrl().toString() ); getAdditionalDetailsFromUser(user); } } else { mProgressBar.setVisibility(View.INVISIBLE); mSignInButton.setEnabled(true); Snackbar.make(mProgressBar, "Sign in failed!, Try Again", Snackbar.LENGTH_SHORT).show(); } } }); } @Override protected void onStart() { mGoogleApiClient.connect(); if (mAuth == null) { mAuth = FirebaseAuth.getInstance(); } super.onStart(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient) .setResultCallback( new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { FirebaseAuth.getInstance().signOut(); ContentUtils.deleteUserDataFromSharedPref(SignInActivity.this); Snackbar.make(mProgressBar, "Goodbye!", Snackbar.LENGTH_LONG).show(); mAlertDialog.dismiss(); mSignInButton.setEnabled(true); } } ); } private void deleteAccount() { final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { if (status.isSuccess()) { mUsersCollection.document(firebaseUser.getUid()) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { ContentUtils.deleteUserDataFromSharedPref(SignInActivity.this); Snackbar.make(mProgressBar, "Goodbye!", Snackbar.LENGTH_LONG).show(); mAlertDialog.dismiss(); mSignInButton.setEnabled(true); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } } }); } private void saveDetails(final User user) { mProgressBar.setVisibility(View.VISIBLE); mSignInButton.setEnabled(false); mUsersCollection.document(user.getuId()) .set(user) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(SignInActivity.this, "Welcome, " + user.getName() + "!", Toast.LENGTH_SHORT).show(); saveDetailsLocally(user); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mProgressBar.setVisibility(View.INVISIBLE); mSignInButton.setEnabled(true); Snackbar.make(mProgressBar, "Sign in failed!, Try Again", Snackbar.LENGTH_SHORT).show(); } }); } private void saveDetailsLocally(User user) { ContentUtils.saveUserDataInSharedPref(user, this); Intent intent = new Intent(); intent.putExtra(ContentUtils.USER_KEY, user); setResult(RESULT_OK, intent); finish(); } private void getAdditionalDetailsFromUser(User user) { Intent intent = new Intent(this, GetUserDetailsActivity.class); intent.putExtra(ContentUtils.USER_KEY, user); startActivityForResult(intent, RC_GET_USER_DETAILS); } @Override public void onBackPressed() { startActivity(new Intent(this, MainActivity.class)); } @Override public void onConnected(@Nullable Bundle bundle) { if (mAction != null && mAction.equals(ContentUtils.SIGNED_OUT)) { signOut(); } else if (mAction != null && mAction.equals(ContentUtils.DELETE_ACCOUNT)) { deleteAccount(); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { if (mResolvingError) { return; } else if (connectionResult.hasResolution()) { try { mResolvingError = true; connectionResult.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); } catch (IntentSender.SendIntentException e) { mGoogleApiClient.connect(); } } else { GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), REQUEST_RESOLVE_ERROR).show(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError); } }
ad84963fc84a8f7f5db56bf3e6851a55533d7a48
180e78725121de49801e34de358c32cf7148b0a2
/dataset/protocol1/yauaa/learning/1231/UselessMatcherException.java
3fc01b70d8d59038acfac05fd45a47b9d09936ed
[]
no_license
ASSERT-KTH/synthetic-checkstyle-error-dataset
40e8d1e0a7ebe7f7711def96a390891a6922f7bd
40c057e1669584bfc6fecf789b5b2854660222f3
refs/heads/master
2023-03-18T12:50:55.410343
2019-01-25T09:54:39
2019-01-25T09:54:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
822
java
/* * Yet Another UserAgent Analyzer * Copyright (C) 2013-2018 Niels Basjes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.basjes.parse.useragent.analyze; public class UselessMatcherException extends Exception { public UselessMatcherException(String message) { super(message); } }
a59ba2807015e9eefe757909c2abcb0b57353604
e1e664b8783962091771e7de8ebe7dcb32e18767
/joe-program/src/main/java/com/joe/qiao/domain/headfirst/command/undo/Command.java
1e183331184bff98005717df931e8c2395cede0c
[]
no_license
qiaoyunlai66/butterfly
4b76fc8a32f11b66d93e9fcd873eb537d80a4880
eda50a90ff4102601a254e93a37c79407f6a1380
refs/heads/master
2020-03-10T22:17:59.831745
2018-04-21T05:32:39
2018-04-21T05:32:39
129,592,162
0
0
null
null
null
null
UTF-8
Java
false
false
127
java
package com.joe.qiao.domain.headfirst.command.undo; public interface Command { public void execute(); public void undo(); }
f1312a362635881f7943746df754b3132301d523
9ab0308e383dd05dcd405f7ff1541b00f21736e5
/utilities/src/main/java/com/gravity/utilities/MD5Hash.java
d80618f12986a8f37d8890699e6b8af79078ead0
[ "Apache-2.0" ]
permissive
BenLloydPearson/common-libs
3492a18dd7cc70627589a0036695ea8d63bfba7a
82c4c5db4750be6a4d9d07d932598e0604eca0b4
refs/heads/master
2020-04-02T15:42:06.249110
2017-08-07T19:27:42
2017-08-07T19:27:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,723
java
package com.gravity.utilities; /** * User: chris * Date: Sep 1, 2010 * Time: 9:45:58 PM */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Hash { private static final Logger logger = LoggerFactory.getLogger(MD5Hash.class); public static BigInteger hashString(String data) { try { MessageDigest instance = MessageDigest.getInstance("MD5"); instance.update(data.getBytes("UTF-8")); byte[] bytes = instance.digest(); instance.reset(); BigInteger bi = new BigInteger(bytes); return bi; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) { buf.append((char) ('0' + halfbyte)); } else { buf.append((char) ('a' + (halfbyte - 10))); } halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } public static String MD5(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] md5hash; md.update(text.getBytes()); md5hash = md.digest(); return convertToHex(md5hash); } }
f1704a7bfbcac77da025d4d44160af354b6b46c6
62d079c0cda5a5eec28aa9f39d1305aa6fac22cc
/soa-parent/soa-trade/soa-trade-api/src/main/java/com/soa/trade/facade/TradeFacade.java
1781a6d0bc0be2722ecd26af638c0557a91b9d95
[]
no_license
liyinyong/dubbo
735118b8b98dccde259bc8b19650ba4c6c3d7696
3542b26202398d60435085615018e9e043be4e87
refs/heads/master
2020-05-07T21:37:53.535640
2019-04-12T02:20:22
2019-04-12T02:20:22
180,912,182
1
0
null
null
null
null
UTF-8
Java
false
false
153
java
package com.soa.trade.facade; import com.soa.trade.domain.Trade; public interface TradeFacade { public void createTrade(Trade obj); }
4ce29a80e427ee1c08ae6ec2a9d356b06afb1f42
b822ed0b104a2379c9f404cc69afda4bb1955f8c
/siweimapsdk/src/main/java/org/oscim/layers/tile/bitmap/BitmapTileLayer.java
e992eb5310d7fc68d27820189db74d525b1176c5
[]
no_license
LonelyPluto/SiweidgMapSDK-V3.0.0
a4a269a8663f770519f597430a36376f7fc4d3ef
c10514c1c29f997299f70a12b1e55e8372bf19de
refs/heads/master
2022-12-02T19:30:02.727651
2020-08-13T07:51:46
2020-08-13T07:51:46
287,214,472
1
0
null
null
null
null
UTF-8
Java
false
false
7,774
java
/* * Copyright 2013 Hannes Janetzek * Copyright 2017 Andrey Novikov * Copyright 2017-2018 devemux86 * Copyright 2019 Gustl22 * * This file is part of the OpenScienceMap project (http://www.opensciencemap.org). * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.layers.tile.bitmap; import org.oscim.core.MapPosition; import org.oscim.event.Event; import org.oscim.layers.tile.TileLayer; import org.oscim.layers.tile.TileLoader; import org.oscim.layers.tile.TileManager; import org.oscim.layers.tile.VectorTileRenderer; import com.siweidg.siweimapsdk.map.SiweidgMap; import com.siweidg.siweimapsdk.map.Viewport; import org.oscim.renderer.bucket.TextureItem.TexturePool; import org.oscim.tiling.TileSource; import org.oscim.utils.FastMath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BitmapTileLayer extends TileLayer { protected static final Logger log = LoggerFactory.getLogger(BitmapTileLayer.class); private static final int CACHE_LIMIT = 40; protected TileSource mTileSource; /** * Bitmap alpha in range 0 to 1. */ private float mBitmapAlpha = 1.0f; public static class FadeStep { public final double scaleStart, scaleEnd; public final double zoomStart, zoomEnd; public final float alphaStart, alphaEnd; /** * @param zoomStart the zoom start in range {@value Viewport#MIN_ZOOM_LEVEL} to {@value Viewport#MAX_ZOOM_LEVEL} * @param zoomEnd the zoom end, must be greater than zoom start * @param alphaStart the alpha start value in range 0 to 1 * @param alphaEnd the alpha end value in range 0 to 1 */ public FadeStep(int zoomStart, int zoomEnd, float alphaStart, float alphaEnd) { if (zoomEnd < zoomStart) throw new IllegalArgumentException("zoomEnd must be larger than zoomStart"); this.scaleStart = 1 << zoomStart; this.scaleEnd = 1 << zoomEnd; this.zoomStart = zoomStart; this.zoomEnd = zoomEnd; this.alphaStart = alphaStart; this.alphaEnd = alphaEnd; } public FadeStep(double scaleStart, double scaleEnd, float alphaStart, float alphaEnd) { if (scaleEnd < scaleStart) throw new IllegalArgumentException("scaleEnd must be larger than scaleStart"); this.scaleStart = scaleStart; this.scaleEnd = scaleEnd; this.zoomStart = Math.log(scaleStart) / Math.log(2); this.zoomEnd = Math.log(scaleEnd) / Math.log(2); this.alphaStart = alphaStart; this.alphaEnd = alphaEnd; } } public BitmapTileLayer(SiweidgMap map, TileSource tileSource) { this(map, tileSource, CACHE_LIMIT); } public BitmapTileLayer(SiweidgMap map, TileSource tileSource, float bitmapAlpha) { this(map, tileSource, CACHE_LIMIT, bitmapAlpha); } public BitmapTileLayer(SiweidgMap map, TileSource tileSource, int cacheLimit) { this(map, tileSource, cacheLimit, tileSource.getAlpha()); } public BitmapTileLayer(SiweidgMap map, TileSource tileSource, int cacheLimit, float bitmapAlpha) { super(map, new TileManager(map, cacheLimit), new VectorTileRenderer()); mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), tileSource.getZoomLevelMax()); mTileSource = tileSource; setBitmapAlpha(bitmapAlpha, false); initLoader(getNumLoaders()); setFade(map.getMapPosition()); } public void setBitmapAlpha(float bitmapAlpha, boolean redraw) { mBitmapAlpha = FastMath.clamp(bitmapAlpha, 0f, 1f); tileRenderer().setBitmapAlpha(mBitmapAlpha); if (redraw) map().updateMap(true); } @Override public void onMapEvent(Event event, MapPosition pos) { super.onMapEvent(event, pos); if (event != SiweidgMap.POSITION_EVENT) return; setFade(pos); } private void setFade(MapPosition pos) { FadeStep[] fade = mTileSource.getFadeSteps(); if (fade == null) { //mRenderLayer.setBitmapAlpha(1); return; } float alpha = mBitmapAlpha; for (FadeStep f : fade) { if (pos.scale < f.scaleStart || pos.scale > f.scaleEnd) continue; if (f.alphaStart == f.alphaEnd) { alpha = f.alphaStart; break; } // interpolate alpha between start and end alpha = (float) (f.alphaStart + (pos.getZoom() - f.zoomStart) * (f.alphaEnd - f.alphaStart) / (f.zoomEnd - f.zoomStart)); break; } alpha = FastMath.clamp(alpha, 0f, 1f) * mBitmapAlpha; tileRenderer().setBitmapAlpha(alpha); } @Override protected TileLoader createLoader() { return new BitmapTileLoader(this, mTileSource); } @Override public void onDetach() { super.onDetach(); if (mTileSource != null) { mTileSource.close(); } pool.clear(); } static final int POOL_FILL = 20; /** * pool shared by TextLayers */ final TexturePool pool = new TexturePool(POOL_FILL) { // int sum = 0; // // public TextureItem release(TextureItem item) { // log.debug(getFill() + " " + sum + " release tex " + item.id); // return super.release(item); // }; // // public synchronized TextureItem get() { // log.debug(getFill() + " " + sum + " get tex "); // // return super.get(); // }; // // protected TextureItem createItem() { // log.debug(getFill() + " " + (sum++) + " create tex "); // // return super.createItem(); // }; // // protected void freeItem(TextureItem t) { // log.debug(getFill() + " " + (sum--) + " free tex "); // super.freeItem(t); // // }; }; /** * Sets the {@link TileSource} used by {@link TileLoader}. * * @return true when new TileSource was set (has changed) */ public boolean setTileSource(TileSource tileSource) { pauseLoaders(true); mTileManager.clearJobs(); if (mTileSource != null) { mTileSource.close(); mTileSource = null; } TileSource.OpenResult msg = tileSource.open(); if (msg != TileSource.OpenResult.SUCCESS) { log.debug(msg.getErrorMessage()); return false; } mTileSource = tileSource; mTileManager.setZoomLevel(tileSource.getZoomLevelMin(), tileSource.getZoomLevelMax()); for (TileLoader l : mTileLoader) ((BitmapTileLoader) l).setDataSource(tileSource.getDataSource()); mMap.clearMap(); resumeLoaders(); return true; } }
9140b80ef8d9888f700e4560f7fb09121e16f974
769f22ae2ac7cf3f0903ebefcf21fd8ce04d4879
/src/main/java/com/mastery/java/task/rest/EmployeeNotFoundAdvice.java
f432cb230bbfb954acfaad97e96979dc55c48751
[]
no_license
kunavich/Java-Mastery
d8b9f2b2e0007f61147d8a313b1f20cf87612049
1a33cec69ee6afe739b100a945cbd8181d67f886
refs/heads/main
2023-04-21T12:55:52.782440
2021-04-19T00:43:05
2021-04-19T00:43:05
359,284,851
0
0
null
null
null
null
UTF-8
Java
false
false
624
java
package com.mastery.java.task.rest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice class EmployeeNotFoundAdvice { @ResponseBody @ExceptionHandler(EmployeeNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) String employeeNotFoundHandler(EmployeeNotFoundException ex) { return ex.getMessage(); } }
2b97c0819b898c9e3d4dd9da95438104728817da
aea1e1f753124c936e7a5f9e0f7e65766e8db70b
/app/src/main/java/com/wishland/www/aicaipiao2/utils/SPUtils.java
82f8527d2b1df220fcc1af2b4b7df624dabae589
[]
no_license
RightManCode/myProject
0371a0aa8a62ee3502e25891026163f886aad611
d28fed9e157338d16c02c2b6cb83846b6894b54e
refs/heads/master
2021-07-05T14:15:04.386969
2017-09-27T05:45:56
2017-09-27T05:45:56
103,805,460
0
0
null
null
null
null
UTF-8
Java
false
false
8,689
java
package com.wishland.www.aicaipiao2.utils; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import java.util.LinkedHashSet; import java.util.Set; /** * Created by admin on 2017/9/12. */ public class SPUtils { private static SharedPreferences sharedPreferences; private static final String preferencesName = "preferences"; private static final String LENGTH = "_length"; private static final String DEFAULT_STRING_VALUE = ""; private static final int DEFAULT_INT_VALUE = -1; private static final double DEFAULT_DOUBLE_VALUE = -1d; private static final float DEFAULT_FLOAT_VALUE = -1f; private static final long DEFAULT_LONG_VALUE = -1L; private static final boolean DEFAULT_BOOLEAN_VALUE = false; public static Context context; private static SharedPreferences getSharedPreferences() { if (sharedPreferences == null) { sharedPreferences = context .getApplicationContext().getSharedPreferences( preferencesName, Context.MODE_PRIVATE ); } return sharedPreferences; } /** * @param what * @return Returns the stored value of 'what' */ public static String getString(String what) { return getSharedPreferences().getString(what, DEFAULT_STRING_VALUE); } /** * @param what * @param defaultString * @return Returns the stored value of 'what' */ public static String getString(String what, String defaultString) { return getSharedPreferences().getString(what, defaultString); } /** * @param where * @param what */ public static void putString(String where, String what) { getSharedPreferences().edit().putString(where, what).apply(); } // int related methods /** * @param what * @return Returns the stored value of 'what' */ public static int getInt(String what) { return getSharedPreferences().getInt(what, DEFAULT_INT_VALUE); } /** * @param what * @param defaultInt * @return Returns the stored value of 'what' */ public static int getInt(String what, int defaultInt) { return getSharedPreferences().getInt(what, defaultInt); } /** * @param where * @param what */ public static void putInt(String where, int what) { getSharedPreferences().edit().putInt(where, what).apply(); } // double related methods /** * @param what * @return Returns the stored value of 'what' */ public static double getDouble(String what) { if (!contains(what)) return DEFAULT_DOUBLE_VALUE; return Double.longBitsToDouble(getLong(what)); } /** * @param what * @param defaultDouble * @return Returns the stored value of 'what' */ public double getDouble(String what, double defaultDouble) { if (!contains(what)) return defaultDouble; return Double.longBitsToDouble(getLong(what)); } /** * @param where * @param what */ public void putDouble(String where, double what) { putLong(where, Double.doubleToRawLongBits(what)); } // float related methods /** * @param what * @return Returns the stored value of 'what' */ public float getFloat(String what) { return getSharedPreferences().getFloat(what, DEFAULT_FLOAT_VALUE); } /** * @param what * @param defaultFloat * @return Returns the stored value of 'what' */ public float getFloat(String what, float defaultFloat) { return getSharedPreferences().getFloat(what, defaultFloat); } /** * @param where * @param what */ public void putFloat(String where, float what) { getSharedPreferences().edit().putFloat(where, what).apply(); } // long related methods /** * @param what * @return Returns the stored value of 'what' */ public static long getLong(String what) { return getSharedPreferences().getLong(what, DEFAULT_LONG_VALUE); } /** * @param what * @param defaultLong * @return Returns the stored value of 'what' */ public static long getLong(String what, long defaultLong) { return getSharedPreferences().getLong(what, defaultLong); } /** * @param where * @param what */ public static void putLong(String where, long what) { getSharedPreferences().edit().putLong(where, what).apply(); } // boolean related methods /** * @param what * @return Returns the stored value of 'what' */ public static boolean getBoolean(String what) { return getSharedPreferences().getBoolean(what, DEFAULT_BOOLEAN_VALUE); } /** * @param what * @param defaultBoolean * @return Returns the stored value of 'what' */ public static boolean getBoolean(String what, boolean defaultBoolean) { return getSharedPreferences().getBoolean(what, defaultBoolean); } /** * @param where * @param what */ public static void putBoolean(String where, boolean what) { getSharedPreferences().edit().putBoolean(where, what).apply(); } // String set methods /** * @param key * @param value */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void putStringSet(final String key, final Set<String> value) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getSharedPreferences().edit().putStringSet(key, value).apply(); } else { // Workaround for pre-HC's lack of StringSets putOrderedStringSet(key, value); } } /** * @param key * @param value */ public static void putOrderedStringSet(String key, Set<String> value) { int stringSetLength = 0; if (getSharedPreferences().contains(key + LENGTH)) { // First getString what the value was stringSetLength = getInt(key + LENGTH); } putInt(key + LENGTH, value.size()); int i = 0; for (String aValue : value) { putString(key + "[" + i + "]", aValue); i++; } for (; i < stringSetLength; i++) { // Remove any remaining values remove(key + "[" + i + "]"); } } /** * @param key * @param defValue * @return Returns the String Set with HoneyComb compatibility */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public Set<String> getStringSet(final String key, final Set<String> defValue) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return getSharedPreferences().getStringSet(key, defValue); } else { // Workaround for pre-HC's missing getStringSet return getOrderedStringSet(key, defValue); } } /** * @param key * @param defValue * @return Returns the ordered String Set */ public Set<String> getOrderedStringSet(String key, final Set<String> defValue) { if (contains(key + LENGTH)) { LinkedHashSet<String> set = new LinkedHashSet<>(); int stringSetLength = getInt(key + LENGTH); if (stringSetLength >= 0) { for (int i = 0; i < stringSetLength; i++) { set.add(getString(key + "[" + i + "]")); } } return set; } return defValue; } // end related methods /** * @param key */ public static void remove(final String key) { if (contains(key + LENGTH)) { // Workaround for pre-HC's lack of StringSets int stringSetLength = getInt(key + LENGTH); if (stringSetLength >= 0) { getSharedPreferences().edit().remove(key + LENGTH).apply(); for (int i = 0; i < stringSetLength; i++) { getSharedPreferences().edit().remove(key + "[" + i + "]").apply(); } } } getSharedPreferences().edit().remove(key).apply(); } /** * @param key * @return Returns if that key exists */ public static boolean contains(final String key) { return getSharedPreferences().contains(key); } /** * Clear all the preferences */ public static void clear() { getSharedPreferences().edit().clear().apply(); } }
4edb0ba5b7e9055fbd81815707d0564475136b7c
6ef239bc1f3a4bb90a6e6d77bb54946b2e477dd9
/WebTools_e-Med_Hospital Management System/Final_PatientCentricHealthCare/src/main/java/org/healthcare/hospitalapp/model/employee/PersistentObject.java
1b60ae3367a62ab04592c240e16571576673a447
[]
no_license
PraneethVellaboyana/Academic_Projects
96699663ab0b7f53a2d56729ea4189afdf811eb2
9fbaf5773216cf1a80bb2de1f7b5b7e31c2ec140
refs/heads/master
2016-08-12T14:47:47.929506
2016-03-29T20:46:25
2016-03-29T20:46:25
46,273,587
0
0
null
null
null
null
UTF-8
Java
false
false
142
java
package org.healthcare.hospitalapp.model.employee; import java.io.Serializable; public interface PersistentObject extends Serializable { }
0239fff7e1bbd3d6570ca570be8d60a52acb23b5
a5a2c13cd166e72461d4c4ced88c735df2f7b020
/info2/contract/Date.java
462cec3782ec8169370d979a24ae836ac0cc0ec6
[]
no_license
dvdhrm/uni
98916787a331218fd98a08c654d2fecbfde87b22
740137ee580e5137628578ea34818549b311d236
refs/heads/master
2020-05-14T21:20:58.377919
2012-01-29T21:01:57
2012-01-29T21:01:57
1,653,767
2
2
null
null
null
null
UTF-8
Java
false
false
727
java
// David Herrmann // Single date public class Date { // Year (eg. 2011, 1991, 2000) int year; // Month (1-12) int month; // Day (1-31) int day; public Date(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public boolean isEarlierThan(Date date) { if (this.year < date.year) return true; else if (this.year > date.year) return false; else if (this.month < date.month) return true; else if (this.month > date.month) return false; else if (this.day < date.day) return true; else return false; } }
38a40b82b5c78b5db4485f7bc0047a6cf6ac4480
977d55bf914e439ffcc88b5974fc1c484eea0e66
/src/test/java/TestBusStop.java
e1373eee04573235b380434990e423b739e625c9
[]
no_license
philm1873/Week06_Day02_Bus_Lab
73efc58aca92011997110e304ea665e32565317c
bfe9caf631c403e8d9169c829a2ace2185eef118
refs/heads/master
2021-08-23T15:51:18.437177
2017-12-05T14:11:03
2017-12-05T14:11:03
113,190,539
0
1
null
null
null
null
UTF-8
Java
false
false
605
java
import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestBusStop { Bus testBus; Person dave; BusStop lothianRoad; @Before public void before(){ testBus = new Bus("Stockbridge"); dave = new Person("Dave"); lothianRoad = new BusStop("Lothian Road"); } @Test public void queueStartsEmpty(){ assertEquals(0, lothianRoad.queueLength()); } @Test public void canAddToQueue(){ lothianRoad.addPerson(dave); assertEquals(1, lothianRoad.queueLength()); } }
891aae968321728f9d3586fd4b4a75b869cb62c6
c557833ee5de95b7cb34b0c32739e52257beb922
/src/main/java/com/huangning/java/spark/Day01java.java
a7458da833889e762ba8345bcc5393df66cd1a9b
[]
no_license
HuangNing616/neo_spark
431b0ac857f61bb21224a58e344d68fbc69bab93
af35349426a0de3c81cb582b9676494e6cec5fd6
refs/heads/master
2023-07-28T17:59:00.775841
2021-09-12T07:21:21
2021-09-12T07:21:21
338,257,901
0
0
null
null
null
null
UTF-8
Java
false
false
5,510
java
package com.huangning.java.spark; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.*; import scala.Tuple2; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * 1. java 里面没有sortBy算子,只有sortByKey * 2. JavaPairRDD<String, String> 叫k,v格式的rdd, 而JavaRDD<Tuple2<String, String>>只叫做tuple类型的rdd * 3. transformation 算子中的sample中的fraction只代表大约的数量,即百分之10左右的数据 * 但是如果输入大于1的数,比如5:那么就会抽出当前样本量5倍的数据,但是scala中只代表抽出5条数据 */ public class Day01java { public static void main(String[] args) { SparkConf conf = new SparkConf(); conf.setAppName("test"); conf.setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> lines = sc.textFile("./data/words"); sc.setLogLevel("Error"); JavaRDD<String> sample = lines.sample(true, 0.1, 100L); sample.foreach(new VoidFunction<String>() { @Override public void call(String s) throws Exception { System.out.println(s); } }); // // return the first five item of the data // List<String> take = lines.take(4); // System.out.println(take); // // return the first item of the data // String first = lines.first(); // System.out.println(first); // // count 算子 // long count = lines.count(); // System.out.println(count); // // collect 算子 // List<String> collect = lines.collect(); // for(String one: collect){ // System.out.println(one); // } // // 按照提示来传递function, s.split(" ")是一个字符串数组,Arrays.asList是将String数组转成了一个list, // // 然后可以通过List的iterator方法将其转换成Iterator // JavaPairRDD<String, Integer> reduceRDD = lines.flatMap(new FlatMapFunction<String, String>() { // @Override // public Iterator<String> call(String s) throws Exception { // List<String> list = Arrays.asList(s.split(" ")); // System.out.println("****" + list.iterator() + "****"); // return list.iterator(); // } // }).mapToPair(new PairFunction<String, String, Integer>() { // // @Override // public Tuple2<String, Integer> call(String s) throws Exception { // return new Tuple2<>(s, 1); // } // }).reduceByKey(new Function2<Integer, Integer, Integer>() { // @Override // public Integer call(Integer v1, Integer v2) throws Exception { // return v1 + v2; // } // }); // // // 想要转出一对一格式的数据,并且转出来的还得是tuple类型 // reduceRDD.mapToPair(new PairFunction<Tuple2<String, Integer>, Integer, String>() { // @Override // public Tuple2<Integer, String> call(Tuple2<String, Integer> t2) throws Exception { // return t2.swap(); // } // }).sortByKey(false).mapToPair(new PairFunction<Tuple2<Integer, String>, String, Integer>() { // @Override // public Tuple2<String, Integer> call(Tuple2<Integer, String> t3) throws Exception { // return t3.swap(); // } // }).foreach(new VoidFunction<Tuple2<String, Integer>>() { // @Override // public void call(Tuple2<String, Integer> t4) throws Exception { // System.out.println(t4); // } // }); // // 转成k,v格式的时候用mapToPair,不转成k,v格式的时候用map // JavaPairRDD<String, String> stringStringJavaPairRDD = lines.mapToPair(new PairFunction<String, String, String>() { // @Override // public Tuple2<String, String> call(String s) throws Exception { // return new Tuple2<String, String>(s, s + "#"); // } // }); // // JavaRDD<Tuple2<String, String>> map = lines.map(new Function<String, Tuple2<String, String>>() { // @Override // public Tuple2<String, String> call(String line) throws Exception { // return new Tuple2<>(line, line + "*"); // } // }); // map.foreach(new VoidFunction<String>() { // @Override // public void call(String s) throws Exception { // System.out.println(s); // } // }); // // String 表示进来的当前行数据,boolean表示返回的值类型 // JavaRDD<String> result = lines.filter(new Function<String, Boolean>() { // @Override // public Boolean call(String s) throws Exception { // // return "hello spark".equals(s); // } // }); // // long count = result.count(); // System.out.println(count); // result.foreach(new VoidFunction<String>() { // @Override // public void call(String s) throws Exception { // System.out.println(s); // } // }); // stop and close have the same meaning // sc.close(); sc.stop(); } }
7fab215bf0b25b7898b03aba4922d0057df582bb
39e074c9f61026a83701783237a4dbde047c3d0a
/src/main/java/com/tourism/datamodel/repository/UserRepository.java
7bd336010bbe088a443bc32122727e02e993110e
[]
no_license
ganeshallampalli/tourism-service
6770289b92efaf0571435246d65002d6461fe72f
c57f392066761a42409944da9bbc95b825da16b5
refs/heads/master
2021-06-19T13:31:05.892337
2019-07-25T08:00:14
2019-07-25T08:00:14
188,469,578
0
0
null
2021-03-31T21:18:50
2019-05-24T18:27:17
Java
UTF-8
Java
false
false
435
java
package com.tourism.datamodel.repository; import com.tourism.datamodel.User; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository<User, Integer> { @SuppressWarnings("unchecked") User save(User user); User findByEmailId(String emailId); List<User> findAllByRoleId(Integer id); }
2e010d30d9fd3495e6059daae196fa3591052769
232cd9491237f5d9ef6e0274898bdb906ae44c7f
/Velopatrol/app/src/main/java/ua/in/velopatrol/velopatrol/entities/UserPhotos.java
b3d9dfa6e102176950774ecd7a6b1fe77a3c9e7a
[]
no_license
avtehnik/velopatrol-app
160432d5d914743e856ee7ccfb0f7c67d165a136
f52314a5df06c85e767fc0638c25528030dbf0c6
refs/heads/master
2016-09-02T00:24:41.671386
2015-08-09T16:25:27
2015-08-09T16:25:27
40,442,477
0
0
null
null
null
null
UTF-8
Java
false
false
1,376
java
package ua.in.velopatrol.velopatrol.entities; import org.codehaus.jackson.annotate.JsonProperty; /** * Created by Anton on 1/31/2015. */ public class UserPhotos { @JsonProperty("profile_thumb") private String profileThumb; @JsonProperty("profile_small_thumb") private String profileSmallThumb; @JsonProperty("profile_chat_thumb") private String profileChatThumb; public UserPhotos() { } public UserPhotos(String profileThumb, String profileSmallThumb, String profileChatThumb) { this.profileThumb = profileThumb; this.profileSmallThumb = profileSmallThumb; this.profileChatThumb = profileChatThumb; } @Override public String toString() { return "UserPhotos{" + "profileThumb='" + profileThumb + '\'' + ", profileSmallThumb='" + profileSmallThumb + '\'' + ", profileChatThumb='" + profileChatThumb + '\'' + '}'; } public String getProfileThumb() { return profileThumb; } public void setProfileThumb(String profileThumb) { this.profileThumb = profileThumb; } public String getProfileSmallThumb() { return profileSmallThumb; } public void setProfileSmallThumb(String profileSmallThumb) { this.profileSmallThumb = profileSmallThumb; } public String getProfileChatThumb() { return profileChatThumb; } public void setProfileChatThumb(String profileChatThumb) { this.profileChatThumb = profileChatThumb; } }
f96124439a4a4d63866c0d4b0593f9c5148a4226
9f3aec95378f08de31c3bb2167587dcf4968094f
/vending.java
d578fe4136e1c190be7b6dee1b67fe930de34d8e
[]
no_license
muthubro/dash-challenge
b2d161f94adf548fcfbfbc1ad345a7f3e86806af
b1bd8342f96bcaff3584c6864bf7b9b186104a4f
refs/heads/master
2020-05-20T22:04:52.324691
2019-05-09T10:14:08
2019-05-09T10:14:08
185,775,239
0
0
null
null
null
null
UTF-8
Java
false
false
4,518
java
import java.util.HashMap; import java.util.Scanner; public class VendingMachine { private static HashMap<String, Integer> drinks; private static Integer minRequired; protected static class Coin { protected Integer value; protected Integer num; public Coin(Integer value) { this.value = value; } public Integer getValue() { return value; } public void setNum(Integer num) { this.num = num; } public Integer getAmount() { return value * num; } } private static class One extends Coin { public One(Integer value) { super(value); } } private static class Five extends Coin { public Five(Integer value) { super(value); } } private static class Ten extends Coin { public Ten(Integer value) { super(value); } } private static class TwentyFive extends Coin { public TwentyFive(Integer value) { super(value); } } public static void vending() { java.util.Scanner scanner = new Scanner(System.in); One ones = new One(1); Five fives = new Five(5); Ten tens = new Ten(10); TwentyFive twentyFives = new TwentyFive(25); Integer num; System.out.println("Enter number of 1s: "); num = scanner.nextInt(); ones.setNum(num); System.out.println("Enter number of 5s: "); num = scanner.nextInt(); fives.setNum(num); System.out.println("Enter number of 10s: "); num = scanner.nextInt(); tens.setNum(num); System.out.println("Enter number of 25s: "); num = scanner.nextInt(); twentyFives.setNum(num); Integer amount = ones.getAmount() + fives.getAmount() + tens.getAmount() + twentyFives.getAmount(); while (amount >= minRequired) { System.out.println("\nChoose an item (cash remaining: " + amount + ")"); Integer counter = 1; drinks.forEach((k, v) -> { System.out.println(String.format("%s (%d)", k, v)); }); System.out.println("Exit"); System.out.println("\nChoice: "); Integer choice; choice = scanner.nextInt(); if (choice == drinks.size() + 1) return; Integer used = 0; if (choice > drinks.size() + 1) System.out.println("Please enter a valid choice.\n"); else { Object key = drinks.keySet().toArray()[choice-1]; used = drinks.get(key); } amount -= used; } System.out.println("\nYou do not have enough balance to buy anything else.\nYour remaining balance is " + amount); } public static void addDrink() { System.out.println("Enter the name of the new drink: "); java.util.Scanner scanner = new Scanner(System.in); String name = scanner.nextLine(); if (drinks.containsKey(name)) System.out.println("This drink already exists."); else { System.out.println("Enter the cost of the new drink: "); Integer cost = scanner.nextInt(); drinks.put(name, cost); System.out.println("Drink successfully added."); if (cost < minRequired) minRequired = cost; } } public static void main(String[] args) { drinks = new HashMap<String, Integer>(); drinks.put("Coke", 25); drinks.put("Pepsi", 35); drinks.put("Soda", 45); minRequired = 25; System.out.println("Welcome to the Dash Vending Machine"); Scanner scanner = new Scanner(System.in); Integer choice = 1; while (choice != 3) { System.out.println("\nWhat do you want to do?\n1. Access Vending Machine\n2. Add a drink\n3. Go away"); System.out.println("\nYour choice: "); choice = scanner.nextInt(); if (choice == 1) vending(); else if (choice == 2) addDrink(); else if (choice == 3) return; else System.out.println("Please choose either 1 or 2.\n"); } } }
15f8ef73c1c8f904e3cd82d0366fc28cf35a95a7
9732150d3dedfc9a580046d80bf852fbb7175804
/app/src/main/java/org/wikipedia/search/RelatedPagesSearchClient.java
b491762a937bd5202d4e02b2170ab30718045ad7
[ "Apache-2.0" ]
permissive
lytellis/test
ea61fd6fb38215725163733657b16ed804b60667
8240be244d1bc98a3766d9f5498599eedd166fb0
refs/heads/master
2020-04-12T11:41:41.644842
2018-12-19T17:24:29
2018-12-19T17:24:29
162,467,837
0
0
null
null
null
null
UTF-8
Java
false
false
2,031
java
package org.wikipedia.search; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import org.wikipedia.dataclient.Service; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.restbase.RbRelatedPages; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import java.io.IOException; import java.util.List; import retrofit2.Call; import retrofit2.Response; public class RelatedPagesSearchClient { public interface Callback { void success(@NonNull Call<RbRelatedPages> call, @Nullable List<RbPageSummary> results); void failure(@NonNull Call<RbRelatedPages> call, @NonNull Throwable caught); } public Call<RbRelatedPages> request(@NonNull String title, @NonNull WikiSite wiki, int limit, @NonNull Callback cb) { return request(ServiceFactory.get(wiki), title, limit, cb); } @VisibleForTesting Call<RbRelatedPages> request(@NonNull Service service, @NonNull String title, int limit, @NonNull Callback cb) { Call<RbRelatedPages> call = service.getRelatedPages(title); call.enqueue(new retrofit2.Callback<RbRelatedPages>() { @Override public void onResponse(@NonNull Call<RbRelatedPages> call, @NonNull Response<RbRelatedPages> response) { if (response.body() != null && response.body().getPages() != null) { // noinspection ConstantConditions cb.success(call, limit < 0 ? response.body().getPages() : response.body().getPages(limit)); } else { cb.failure(call, new IOException("An unknown error occurred.")); } } @Override public void onFailure(@NonNull Call<RbRelatedPages> call, @NonNull Throwable t) { cb.failure(call, t); } }); return call; } }
3c589b8abad811354f8a6f94f947ca96aca7ebb8
635aa994ebc656d1db47bfeae7aa6fee56a12b98
/Workout-master/app/src/main/java/com/example/calvin/workout/MapActivity.java
19e4391bc23caeb772431646a20654fd26e1d75a
[]
no_license
FugiOP/CS4540
b628bcff6a3a6d7e352eeff9023728a519cde136
db58f963d461255d2fba55aa2c9258dc5a37e080
refs/heads/master
2021-01-01T19:18:40.119133
2018-09-30T03:00:07
2018-09-30T03:00:07
98,562,530
1
3
null
null
null
null
UTF-8
Java
false
false
13,816
java
package com.example.calvin.workout; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.os.CountDownTimer; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import android.widget.TextView; import android.widget.Toast; import com.example.calvin.workout.data.Contract; import com.example.calvin.workout.data.DBHelper; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; /** * Created by FugiBeast on 8/5/2017. */ public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { GoogleMap mMap; ArrayList<LatLng> points; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; Location oldLocation; double distance = 0d; double distanceCovered = 0; private Marker mCurrLocationMarker; private final LatLng mDefaultLocation = new LatLng(-122.084, 37.422); //Googleplex private boolean mLocationPermissionGranted; private boolean mRequestingLocationUpdates; private static final long LOCATION_REQUEST_INTERVAL = 2000; private static final long LOCATION_REQUEST_FASTEST_INTERVAL = 1000; private CountDownTimer mCDTimer; Chronometer myChronometer; DecimalFormat df; String date; ArrayList<LatLng> routePoints; private Polyline line; Button startBtn; TextView calcDist; TextView caloriesBurnt; double totalCalories = 0.00; double prevCalories; Cursor date_calorie_cursor; private SQLiteDatabase db_date_calorie; private DBHelper helper_date_calorie; public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); points = new ArrayList<LatLng>(); df = new DecimalFormat("0.00"); mRequestingLocationUpdates = true; startBtn = (Button) findViewById(R.id.startBtn); myChronometer = (Chronometer)findViewById(R.id.trackChrono); calcDist = (TextView)findViewById(R.id.calcDistance); calcDist.setText(".00 meters"); caloriesBurnt = (TextView)findViewById(R.id.caloriesBurnt); caloriesBurnt.setText("Calories Burned : "+totalCalories); oldLocation= new Location("dummy data"); helper_date_calorie = new DBHelper(this); db_date_calorie = helper_date_calorie.getReadableDatabase(); buildGoogleApiClient(); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; initMap(); mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); centerMap(); myChronometer.setOnChronometerTickListener( new Chronometer.OnChronometerTickListener(){ @Override public void onChronometerTick(Chronometer chronometer) { // TODO Auto-generated method stub addToPolyline(oldLocation); calcDist.setText(df.format(((distanceCovered*100.0)/100.0)*0.00062137119) + " miles"); caloriesBurnt.setText("Calories Burned: "+df.format((((distanceCovered*100.0)/100.0)*0.00062137119*0.76*200))); updateUserCalories(db_date_calorie,(((distanceCovered*100.0)/100.0)*0.00062137119*0.76*200),date); } } ); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addConnectionCallbacks(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(@Nullable Bundle bundle) { // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } private void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setSmallestDisplacement(20); mLocationRequest.setInterval(LOCATION_REQUEST_INTERVAL); mLocationRequest.setFastestInterval(LOCATION_REQUEST_FASTEST_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); } protected void startLocationUpdates() { if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } } protected void stopLocationUpdates() { LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this); } @Override public void onLocationChanged(Location location) { distanceCovered = distanceCovered + oldLocation.distanceTo(location); oldLocation = location; centerMap(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { initMap(); } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other permissions this app might request. //You can add here other case statements according to your requirement. } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==R.id.routine){ Intent intent = new Intent(this, RoutineActivity.class); startActivity(intent); } else if (item.getItemId() == R.id.music) { Intent intent = new Intent(this, MusicActivity.class); startActivity(intent); } else if (item.getItemId() == R.id.graph) { Intent intent = new Intent(this, GraphActivity.class); startActivity(intent); }else if (item.getItemId() == R.id.profile) { Intent intent = new Intent(this,UpdateProfile.class); startActivity(intent); }else if (item.getItemId() == R.id.calories) { Intent intent = new Intent(this,FoodActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } private void initMap() { if (mMap == null) { return; } //Request location permission from user so we can pull location if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLocationPermissionGranted = true; if (mRequestingLocationUpdates) { createLocationRequest(); startLocationUpdates(); } } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); } //Gets the most recent location of the device if (mLocationPermissionGranted) { oldLocation = LocationServices.FusedLocationApi .getLastLocation(mGoogleApiClient); mMap.setMyLocationEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); } else { mMap.setMyLocationEnabled(false); mMap.getUiSettings().setMyLocationButtonEnabled(false); oldLocation = null; } // Set the map's camera position to the current location of the device. // If it can't be found, defaults to GooglePlex if (oldLocation != null) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(oldLocation.getLatitude(), oldLocation.getLongitude()), 15)); } else { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, 15)); mMap.getUiSettings().setMyLocationButtonEnabled(false); } } //Centers the map on the device private void centerMap() { if (oldLocation != null) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(oldLocation.getLatitude(), oldLocation.getLongitude()), 15)); } } @Override protected void onPause() { super.onPause(); stopLocationUpdates(); } @Override protected void onResume() { super.onResume(); if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) { startLocationUpdates(); } } private void initPolyline() { if (line != null) { removePolyline(); } PolylineOptions pLineOptions = new PolylineOptions() .width(10) .color(Color.BLUE); line = mMap.addPolyline(pLineOptions); routePoints = new ArrayList<>(); line.setPoints(routePoints); } //adds coordinates to the arraylist that will form the polyline private void addToPolyline(Location location) { routePoints.add(new LatLng(location.getLatitude(), location.getLongitude())); line.setPoints(routePoints); } //clears existing polyline so there is no overlap private void removePolyline() { line.remove(); line = null; } //sorts between start and end tracking public void trackBtn(View view) { if(startBtn.getText().equals("Start")) startTracking(view); else endTracking(view); } public void startTracking(View view) { startBtn.setText("End"); initPolyline(); distanceCovered = 0; SimpleDateFormat sdf = new SimpleDateFormat("YYYY MMM d"); Calendar calendar = Calendar.getInstance(); date = sdf.format(calendar.getTime()); prevCalories = getPrevCalories(db_date_calorie, date); myChronometer.setBase(SystemClock.elapsedRealtime()); myChronometer.start(); } public void endTracking(View view) { startBtn.setText("Start"); caloriesBurnt.setText("Calories Burned: 0.00"); myChronometer.stop(); } public int updateUserCalories(SQLiteDatabase db, double calories,String date){ ContentValues cv = new ContentValues(); cv.put(Contract.TABLE_USER_CALORIES.COLUMN_NAME_DATE, date); cv.put(Contract.TABLE_USER_CALORIES.COLUMN_NAME_CALORIES,calories+prevCalories); return db.update(Contract.TABLE_USER_CALORIES.TABLE_NAME, cv,Contract.TABLE_USER_CALORIES.COLUMN_NAME_DATE + "='"+date+"'", null); } private double getPrevCalories(SQLiteDatabase db,String date){ double result = 0; Cursor cursor = db.query( Contract.TABLE_USER_CALORIES.TABLE_NAME, null, Contract.TABLE_USER_CALORIES.COLUMN_NAME_DATE+"='"+date+"'", null, null, null, null ); cursor.moveToFirst(); result = cursor.getDouble(cursor.getColumnIndex(Contract.TABLE_USER_CALORIES.COLUMN_NAME_CALORIES)); return result; } }
535d4cd92f7a6461dfb8287229ecb81606030b7b
472d7820a5f5d9d5ab2ec150eab0c9bdeb2008c7
/Protege-2000/source/Protege-2000/src/edu/stanford/smi/protege/util/ComponentUtilities.java
760d76b410921f96ea8b8e7ea9bd2452ceaa868e
[]
no_license
slacker247/GPDA
1ad5ebe0bea4528d9a3472d3c34580648ffb670e
fa9006d0877a691f1ddffe88799c844a3e8a669a
refs/heads/master
2022-10-08T07:39:09.786313
2020-06-10T22:22:58
2020-06-10T22:22:58
105,063,261
2
0
null
null
null
null
UTF-8
Java
false
false
20,013
java
/* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Original Code is Protege-2000. * * The Initial Developer of the Original Code is Stanford University. Portions * created by Stanford University are Copyright (C) 2001. All Rights Reserved. * * Protege-2000 was developed by Stanford Medical Informatics * (http://www.smi.stanford.edu) at the Stanford University School of Medicine * with support from the National Library of Medicine, the National Science * Foundation, and the Defense Advanced Research Projects Agency. Current * information about Protege can be obtained at http://protege.stanford.edu * * Contributor(s): */ package edu.stanford.smi.protege.util; import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.table.*; import javax.swing.tree.*; /** * Description of the class * * @author Ray Fergerson <[email protected]> */ public class ComponentUtilities { private static final int BORDER_SIZE = 50; private static final int STANDARD_ROW_HEIGHT = 60; private static final int STANDARD_COLUMN_WIDTH = 125; private static Collection _openWindows = new ArrayList(); public static void addColumn(JTable table, TableCellRenderer renderer) { addColumn(table, renderer, null); } public static void addColumn(JTable table, TableCellRenderer renderer, TableCellEditor editor) { int nColumns = table.getColumnCount(); TableColumn column = new TableColumn(nColumns); column.setCellRenderer(renderer); column.setCellEditor(editor); table.addColumn(column); } public static int addListValue(JList list, Object newValue) { return getModel(list).addValue(newValue); } public static void addListValue(JList list, Object newValue, int index) { getModel(list).addValue(newValue, index); } public static int addListValue(JList list, Object newValue, Comparator comparator) { int index = getPositionIndex(list, newValue, comparator); addListValue(list, newValue, index); return index; } public static void addListValues(JList list, Collection newValues) { if (!newValues.isEmpty()) { getModel(list).addValues(newValues); } } public static int addSelectedListValue(JList list, Object newValue) { int index = getModel(list).addValue(newValue); list.setSelectedIndex(index); return index; } public static void addSelectedListValues(JList list, Collection newValues) { if (!newValues.isEmpty()) { int index = getModel(list).addValues(newValues); list.setSelectionInterval(index, index + newValues.size() - 1); } } public static void addUniqueListValues(JList list, Collection newValues) { Collection uniqueValues = new HashSet(newValues); uniqueValues.removeAll(getModel(list).getValues()); addListValues(list, uniqueValues); } public static void apply(Component component, UnaryFunction f) { f.apply(component); applyToDescendents(component, f); } public static void applyToDescendents(Component component, UnaryFunction f) { if (component instanceof Container) { Container container = (Container) component; int count = container.getComponentCount(); for (int i = 0; i < count; ++i) { Component subComponent = container.getComponent(i); apply(subComponent, f); } } } public static void center(Component c) { Dimension screenSize = c.getToolkit().getScreenSize(); screenSize.width -= BORDER_SIZE; screenSize.height -= BORDER_SIZE; Dimension componentSize = c.getSize(); int xPos = (screenSize.width - componentSize.width) / 2; xPos = Math.max(xPos, 0); int yPos = (screenSize.height - componentSize.height) / 2; yPos = Math.max(yPos, 0); c.setLocation(new Point(xPos, yPos)); } public static void clearListValues(JList list) { getModel(list).clear(); } private static void clearSelectionIfNecessary(JList list, int count) { // Workaround for swing bug. Removing all elements from a list does not cause a selection event // to get fired. setSelectedIndex(-1) also does not cause an event to fire. Thus we clear the // selection manually if the result of the remove is that the list will be empty if (list.getModel().getSize() == count) { list.clearSelection(); } } public static void closeAllWindows() { Iterator i = new ArrayList(_openWindows).iterator(); while (i.hasNext()) { Window w = (Window) i.next(); closeWindow(w); } } public static void closeWindow(Window window) { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); } public static void deregisterWindow(Window window) { _openWindows.remove(window); } private static void disassemble(Component component) { if (component instanceof Container) { Container container = (Container) component; int nSubcomponents = container.getComponentCount(); for (int i = 0; i < nSubcomponents; ++i) { disassemble(container.getComponent(i)); } container.removeAll(); } } public static void dispose(Component component) { component.setVisible(false); UnaryFunction dispose = new UnaryFunction() { public Object apply(Object o) { if (o instanceof Disposable) { ((Disposable) o).dispose(); // Log.enter("ComponentUtilities.dispose", o.getClass().getName()); } return Boolean.TRUE; } }; apply(component, dispose); disassemble(component); } public static void ensureSelectionIsVisible(final JList list) { /* * SwingUtilities.invokeLater(new Runnable() { * public void run() { * int selection = list.getSelectedIndex(); * list.ensureIndexIsVisible(selection); * } * }); */ } public static void extendSelection(JTree tree, Object userObject) { LazyTreeNode selectedNode = (LazyTreeNode) tree.getLastSelectedPathComponent(); int index = selectedNode.getUserObjectIndex(userObject); TreeNode node = selectedNode.getChildAt(index); setSelectedNode(tree, node); } private static int fullExpand(JTree tree, TreePath parentPath, int nExpansions) { TreeNode parent = (TreeNode) parentPath.getLastPathComponent(); int count = parent.getChildCount(); for (int i = 0; i < count && nExpansions > 0; ++i) { TreeNode child = parent.getChildAt(i); TreePath childPath = parentPath.pathByAddingChild(child); nExpansions = fullExpand(tree, childPath, nExpansions); } tree.expandPath(parentPath); return --nExpansions; } public static void fullSelectionCollapse(JTree tree) { int startRow = tree.getLeadSelectionRow(); int stopRow = getStopRow(tree, startRow); for (int i = stopRow - 1; i >= startRow; --i) { tree.collapseRow(i); } } public static void fullSelectionExpand(JTree tree, int max_expansions) { TreePath topPath = tree.getLeadSelectionPath(); fullExpand(tree, topPath, max_expansions); } public static LazyTreeNode getChildNode(LazyTreeNode node, Object userObject) { LazyTreeNode childNode = null; int nChildren = node.getChildCount(); for (int i = 0; i < nChildren; ++i) { childNode = (LazyTreeNode) node.getChildAt(i); if (childNode.getUserObject() == userObject) { break; } } return childNode; } public static Component getDescendentOfClass(Class componentClass, Component root) { Collection c = getDescendentsOfClass(componentClass, root); Assert.assertTrue("max 1 descendent", c.size() == 0 || c.size() == 1); return (Component) CollectionUtilities.getFirstItem(c); } public static Collection getDescendentsOfClass(final Class componentClass, Component root) { final Collection results = new ArrayList(); UnaryFunction f = new UnaryFunction() { public Object result = null; public Object apply(Object o) { if (componentClass.isInstance(o)) { results.add(o); } return null; } }; apply(root, f); return results; } public static Dialog getDialog(Component c) { return (Dialog) SwingUtilities.windowForComponent(c); } public static Object getFirstSelectionParent(JTree tree) { Object parent; LazyTreeNode node = (LazyTreeNode) tree.getLastSelectedPathComponent(); if (node == null) { parent = null; } else { LazyTreeNode parentNode = node.getLazyTreeNodeParent(); if (parentNode instanceof LazyTreeRoot) { parent = null; } else { parent = parentNode.getUserObject(); } } return parent; } public static Frame getFrame(Component c) { Frame frame; if (c instanceof Frame) { frame = (Frame) c; } else { frame = (Frame) SwingUtilities.windowForComponent(c); } return frame; } public static Collection getListValues(JList list) { return getModel(list).getValues(); } private static SimpleListModel getModel(JList list) { ListModel model = list.getModel(); if (!(model instanceof SimpleListModel)) { model = new SimpleListModel(); list.setModel(model); } return (SimpleListModel) model; } private static int getPositionIndex(JList list, Object value, Comparator comparator) { int index = Collections.binarySearch(getModel(list).getValues(), value, comparator); if (index < 0) { index = -(index + 1); } return index; } public static Object getSelectedValue(JList list) { return CollectionUtilities.getFirstItem(getSelection(list)); } public static Collection getSelection(JList list) { return Arrays.asList(list.getSelectedValues()); } public static Collection getSelection(JTable table) { TableModel model = table.getModel(); int[] indices = table.getSelectedRows(); Collection selection = new ArrayList(); for (int i = 0; i < indices.length; ++i) { selection.add(model.getValueAt(indices[i], 0)); } return selection; } public static Collection getSelection(JTree tree) { return getSelection(tree, Object.class); } public static Collection getSelection(JTree tree, Class c) { Assert.assertNotNull("tree", tree); Collection selections = new HashSet(); TreePath[] paths = tree.getSelectionModel().getSelectionPaths(); if (paths != null) { for (int i = 0; i < paths.length; ++i) { Object o = paths[i].getLastPathComponent(); if (o instanceof LazyTreeNode) { o = ((LazyTreeNode) o).getUserObject(); } if (c == null || c.isInstance(o)) { selections.add(o); } } } return selections; } public static int getStandardColumnWidth() { return STANDARD_COLUMN_WIDTH; } public static int getStandardRowHeight() { return STANDARD_ROW_HEIGHT; } private static int getStopRow(JTree tree, int startRow) { int startDepth = tree.getPathForRow(startRow).getPathCount(); int last = tree.getRowCount(); int stopRow = last; for (int i = startRow + 1; i < last; ++i) { int depth = tree.getPathForRow(i).getPathCount(); if (depth <= startDepth) { stopRow = i; break; } } return stopRow; } public static TreePath getTreePath(JTree tree, Collection objectPath) { List nodePath = new LinkedList(); LazyTreeNode node = (LazyTreeNode) tree.getModel().getRoot(); nodePath.add(node); Iterator i = objectPath.iterator(); while (i.hasNext()) { Object userObject = i.next(); node = getChildNode(node, userObject); if (node == null) { Log.warning("no node for " + userObject, ComponentUtilities.class, "getTreePath", objectPath); break; } nodePath.add(node); } return new TreePath(nodePath.toArray()); } public static void hide(final Component c, final int delayInMillisec) { Thread t = new Thread() { public void run() { try { sleep(delayInMillisec); Component topComponent = SwingUtilities.getRoot(c); topComponent.setVisible(false); } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } public static boolean isDragAndDropEnabled(JComponent c) { Object o = c.getClientProperty(ComponentUtilities.class); return (o == null) ? true : ((Boolean) o).booleanValue(); } public static boolean listValuesContain(JList list, Object value) { return getModel(list).contains(value); } public static ImageIcon loadImageIcon(Class cls, String name) { ImageIcon icon = null; URL url = cls.getResource(name); if (url != null) { icon = new ImageIcon(url); if (icon.getIconWidth() == -1) { Log.error("failed to load", SystemUtilities.class, "loadImageIcon", cls, name); } } return icon; } // HACK: work around JDK1.2 swing layout bug by calling pack twice. public static void pack(Component c) { Window window = getFrame(c); window.pack(); window.pack(); } public static void paintImmediately(Component component) { Graphics g = component.getGraphics(); component.paint(g); g.dispose(); } public static void pressButton(Component c, final Icon icon) { Iterator i = getDescendentsOfClass(JButton.class, c).iterator(); while (i.hasNext()) { JButton button = (JButton) i.next(); if (button.getIcon() == icon) { button.doClick(); // Log.trace("doClick", ComponentUtilities.class, "pressButton", c, icon); } } } public static void registerWindow(Window window) { _openWindows.add(window); } public static void removeListValue(JList list, Object oldValue) { clearSelectionIfNecessary(list, 1); int selectedIndex = list.getSelectedIndex(); int index = getModel(list).removeValue(oldValue); if (selectedIndex == index) { setSelectedIndex(list, index); } } public static void removeListValues(JList list, Collection values) { clearSelectionIfNecessary(list, values.size()); int selectedIndex = list.getSelectedIndex(); int index = getModel(list).removeValues(values); if (selectedIndex == index) { setSelectedIndex(list, index); } } public static void removeSelection(JTree tree) { LazyTreeNode selectedNode = (LazyTreeNode) tree.getLastSelectedPathComponent(); LazyTreeNode parentNode = selectedNode.getLazyTreeNodeParent(); int index = parentNode.getUserObjectIndex(selectedNode.getUserObject()); int nChildren = parentNode.getChildCount(); TreeNode newSelection; if (index == nChildren - 1) { if (nChildren == 1) { newSelection = parentNode; } else { newSelection = parentNode.getChildAt(index - 1); } } else { newSelection = parentNode.getChildAt(index + 1); } setSelectedNode(tree, newSelection); } public static void replaceListValue(JList list, Object oldValue, Object newValue) { SimpleListModel model = getModel(list); int index = model.indexOf(oldValue); model.setValue(index, newValue); } public static void reposition(JList list, Object value, Comparator comparator) { int oldSelectionIndex = list.getSelectedIndex(); SimpleListModel model = getModel(list); int fromIndex = model.indexOf(value); model.removeValue(value); int toIndex = getPositionIndex(list, value, comparator); getModel(list).addValue(value, toIndex); if (oldSelectionIndex != -1) { int newSelectionIndex = oldSelectionIndex; if (fromIndex == oldSelectionIndex) { newSelectionIndex = toIndex; } else if (fromIndex < oldSelectionIndex && toIndex > oldSelectionIndex) { --newSelectionIndex; } else if (fromIndex > oldSelectionIndex && toIndex < oldSelectionIndex) { ++newSelectionIndex; } list.setSelectedIndex(newSelectionIndex); list.ensureIndexIsVisible(newSelectionIndex); } } public static void setDragAndDropEnabled(JComponent c, boolean enable) { c.putClientProperty(ComponentUtilities.class, new Boolean(enable)); } public static void setEnabled(Component component, final boolean enabled) { apply(component, new UnaryFunction() { public Object apply(Object o) { ((Component) o).setEnabled(enabled); return null; } } ); } public static void setExpanded(JTree tree, Collection objectPath, boolean expand) { TreePath path = getTreePath(tree, objectPath); if (expand) { tree.scrollPathToVisible(path); tree.expandPath(path); } else { tree.collapsePath(path); } } public static void setFrameTitle(Component c, String title) { getFrame(c).setTitle(title); } public static void setListValues(JList list, Collection values) { getModel(list).setValues(values); } private static void setSelectedIndex(JList list, int index) { int nElements = list.getModel().getSize(); index = Math.min(index, nElements - 1); list.setSelectedIndex(index); } public static void setSelectedNode(JTree tree, TreeNode node) { final TreePath path = new TreePath(((LazyTreeModel) tree.getModel()).getPathToRoot(node)); tree.scrollPathToVisible(path); tree.setSelectionPath(path); } public static void setSelectedObjectPath(JTree tree, Collection objectPath) { TreePath path = getTreePath(tree, objectPath); tree.scrollPathToVisible(path); tree.setSelectionPath(path); } }