How to mask out some field in grpc response when logging - java

I want to mask out some field when logging.
is there any good way to mask out?
after message is served to client.
I'm trying to mask out some field before logging
how do you mask out field?
--served to client
message {
id : "user",
phoneNumber : "12341234"
}
--logged response
message {
id : "user",
phoneNumber : "12******"
}

I don't think there is a way to alter the data like you mentioned, however there is a way to hide field that you don't want to print in the log (I assume its for security reasons). The way yo do that is with FieldMask.
So for the sake of the example I took the liberty of adding another field to the schema I assume you have:
message User {
string id = 1;
string name = 2;
string phone_number = 3;
}
So now let's say that I don't want to show the phone number of my users, I can use a FieldMask to keep only id and name. So first we build a FieldMask (you'll need to add this dependency for accessing FieldMaskUtil):
public static final FieldMask WITH_ID_AND_NAME =
FieldMaskUtil.fromFieldNumbers(User.class,
User.ID_FIELD_NUMBER,
User.NAME_FIELD_NUMBER);
then what I can do is merge this FieldMask with an existing object:
private static void log(User user, FieldMask fieldMask) {
User.Builder userWithMaskedFields = User.newBuilder();
FieldMaskUtil.merge(fieldMask, user, userWithMaskedFields);
System.out.println(userWithMaskedFields);
}
public static void main(String[] args) {
User user = User.newBuilder()
.setId("user")
.setName("a name")
.setPhoneNumber("12341234")
.build();
System.out.println("---Without FieldMask---");
System.out.println(user);
System.out.println("---With FieldMask---");
log(user, WITH_ID_AND_NAME);
}
This will give me the following output:
---Without FieldMask---
id: "user"
name: "a name"
phone_number: "12341234"
---With FieldMask---
id: "user"
name: "a name"
I hope that helps, let me know if you need more details, I can update my answer.

Related

UnrecognizedPropertyException map to JSONObject

currently I am programming a stocks project for my Bachelor degree, but I'm stuck.
For Frontend I use Angular and Backend Java with a Postgres DB.
I'm getting a 500 response when I try to update a row in my DB. The error is
org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "empty" (class org.json.JSONObject), not marked as ignorable (0 known properties: ])
In Angular I have a Watchlist Interface, which I want to update with an additional investment in it, send the new Watchlist to the backend, to store it in the db.
export interface Watchlist{
id?: number,
userid?: number,
watchlist?: any
}
on button click in the template I access the following method.
hinzufuegenWatchlist(){
this.mainComponent.watchlist.watchlist[this.isin] = this.investment;
this.watchlistService.sendRequestUpdateWatchlist(this.mainComponent.watchlist)
.subscribe(response => console.log('Investment zur Watchlist hinzugefügt'));
}
sendRequestUpdateWatchlist(watchlist : Watchlist){
return this.http
.put<Investment>(this.getServiceURL().concat("updateWatchlist"), JSON.stringify(watchlist),this.getOptions())
}
In the backend I use a JSONObject for the watchlist. The idea is to store every investment with its isin as an accessible key, to easily check whether its already stored or not. And easily store the whole watchlist in one row in the DB:
public class Watchlist {
private int id;
private int userid;
private JSONObject watchlist;
#PUT
#Path("updateWatchlist")
#Consumes({MediaType.APPLICATION_JSON})
public void updateWatchlist(Watchlist watchlist){
try {
String sql = "UPDATE watchlistdb set watchlist=? where id=?";
PreparedStatement ps = DatabaseHelper.connectDatabase().prepareStatement(sql);
ps.setString(1,watchlist.getWatchlist().toString());
ps.setInt(2,watchlist.getId());
ps.execute();
} catch (Exception e){
e.printStackTrace();
}
}
My first thoughts are, that it can't be mapped because it isn't a standard Java type like string or int. But how can I solve that problem?
Thank you for your time and help!

OSPermissionSubscriptionState : Cannot resolve symbol

I'm trying to add push notification to my mobile native chat app. I'm trying to use OneSignal.
I can send manual push notification, so I think gradle part is okay
idsAvaiable method is deprecated, I started to looking for how can I get userId.
OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
String userId = status.getSubscriptionStatus().getUserId();
In here, I'm trying to get userId with status, but it's saying:
Cannot resolve symbol 'OSPermissionSubscriptionState'
How can I get userId?
Root cause
From OneSignal API 4.0.0, there are many APIs that have been removed including OSPermissionSubscriptionState.
Solution 1
Use OneSignal.getDeviceState()
OSDeviceState device = OneSignal.getDeviceState();
String userId = device.getUserId();
Solution 2
Use OneSignal.addSubscriptionObserver()
OneSignal.addSubscriptionObserver(new OSSubscriptionObserver() {
#Override
public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
if (!stateChanges.getFrom().isSubscribed() && stateChanges.getTo().isSubscribed()) {
// Get user id
String userId = stateChanges.getTo().getUserId();
}
}
});
For more information, see the change log here.

Adding roles to a mentioned user in JDA

I want to be able to run a command that begins with !suspend, mentions a user, then determines a time length and adds a role named 'Suspended' to the mentioned user for the specified time length.
Message message = event.getMessage(); //Sets the message equal to the variable type 'Message' so it can be modified within the program.
String content = message.getContentRaw(); //Gets the raw content of the message and sets it equal to a string (best way to convert types Message to String).
MessageChannel channel = event.getChannel(); //Gets the channel the message was sent in (useful for sending error messages).
Guild guild = event.getGuild();
//Role group = content.matches("((Suspended))") ? guild.getRolesByName("Suspended", true).get(0) : null;
if(content.startsWith("!suspend"))//Pretty self explanatory. Enters the loop if the message begins with !suspend.
{
String[] spliced = content.split("\\s+"); //Splits the message into an array based on the spaces in the message.
TextChannel textChannel = event.getGuild().getTextChannelsByName("ranked-ms_punishments",true).get(0); //If there is a channel called ranked-ms_punishments which there should be set the value of it equal to the variable.
int length = spliced.length;//Sets 'length' equal to the number of items in the array.
if(length == 3)//If the number of items in the array is 3 then...
{
if(spliced[1].startsWith("<"))
{
list.add(spliced[1]);
String tempuser = spliced[1];
textChannel.sendMessage(tempuser + " you have been suspended for " + spliced[2] + " days.").queue();//Sends the message in the quotations.
//add role to the member
}
}else {
channel.sendMessage("Please use the following format for suspending a user: '!suspend' <#user> (length)").queue(); //If length doesn't equal 3 then it sends the message in quotations.
}
}
Not sure how to do this, as I'm too unfamiliar with JDA to make it work. I have everything working except for the actual addition of the role named 'Suspended'.
Adding a role to the mentioned members in a message can be done as follows:
Role role = event.getGuild().getRolesByName("Suspended", false).get(0);
List<Member> mentionedMembers = message.getMentionedMembers();
for (Member mentionedMember : mentionedMembers) {
event.getGuild().getController().addRolesToMember(mentionedMember, role).queue();
}
Note that your bot will need the MANAGE_ROLES permission to add roles.
You can do this: 👍
event.getGuild().addRoleToMember(memberId, jda.getRoleById(yourRole));
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(yourRole)).queue();

PASSWD_CANT_CHANGE flag not present in UserAccountControl attribute

I need to check through LDAP if an ActiveDirectory user has the PASSWD_CANT_CHANGE flag set. I found the UserAccountControl attribute (https://learn.microsoft.com/it-it/windows/desktop/ADSchema/a-useraccountcontrol): it works for all other flags but it doesn't work for this flag. I only need to read it, not to write.
I'm using Java with UnboundID LDAP SDK (https://ldap.com/unboundid-ldap-sdk-for-java/).
Here is my JUnit test code.
public static enum UACFlags {
SCRIPT(0x0001),
ACCOUNTDISABLE(0x0002),
HOMEDIR_REQUIRED(0x0008),
LOCKOUT(0x0010),
PASSWD_NOTREQD(0x0020),
PASSWD_CANT_CHANGE(0x0040),
ENCRYPTED_TEXT_PWD_ALLOWED(0x0080),
TEMP_DUPLICATE_ACCOUNT(0x0100),
NORMAL_ACCOUNT(0x0200),
INTERDOMAIN_TRUST_ACCOUNT(0x0800),
WORKSTATION_TRUST_ACCOUNT(0x1000),
SERVER_TRUST_ACCOUNT(0x2000),
DONT_EXPIRE_PASSWORD(0x10000),
MNS_LOGON_ACCOUNT(0x20000),
SMARTCARD_REQUIRED(0x40000),
TRUSTED_FOR_DELEGATION(0x80000),
NOT_DELEGATED(0x100000),
USE_DES_KEY_ONLY(0x200000),
DONT_REQ_PREAUTH(0x400000),
PASSWORD_EXPIRED(0x800000),
TRUSTED_TO_AUTH_FOR_DELEGATION(0x1000000);
private int flag;
private UACFlags(int flag) {
this.flag = flag;
}
}
#Test
public void testLDAP() throws LDAPException {
LDAPConnection connection = //GET CONNECTION
String username = "....";
String search = "(sAMAccountName=" + username + ")";
SearchRequest request = new SearchRequest("DC=....,DC=....", SearchScope.SUB, search, SearchRequest.ALL_USER_ATTRIBUTES);
SearchResult result = connection.search(request);
SearchResultEntry entry = result.getSearchEntries().get(0);
Attribute a = entry.getAttribute("userAccountControl");
int val = a.getValueAsInteger();
System.out.println(Integer.toHexString(val));
EnumSet<UACFlags> flags = EnumSet.noneOf(UACFlags.class);
for (UACFlags f : UACFlags.values()) {
if ((val & f.flag) == f.flag) {
flags.add(f);
}
}
System.out.println("FLAGS: " + flags);
}
I set up the flag on AD Users and Computers and it works as expected. I only want to check the flag programmatically, using Java and LDAP. Other solutions than UserAccountControl attribute are ok!
Thanks!!
That is, unfortunately, expected.
Microsoft uses the ADS_USER_FLAG_ENUM enumeration in a couple places:
The userAccountControl attribute when using LDAP, and
The userFlags property when using the WinNT provider.
The ADS_UF_PASSWD_CANT_CHANGE flag can only be used when using the WinNT provider, which I'm not sure you can do from Java.
When you click that 'User cannot change password' checkbox in AD Users and Computers, it doesn't actually change the userAccountControl attribute. In reality, it adds two permissions on the account:
Deny Change Password to 'Everyone'
Deny Change Password to 'SELF'
There is a description of how to look for those permissions here, but the examples are in C++ and VBScript. I don't know how to view the permissions in Java. It seems difficult and I can't find any real examples.
UPDATE
Appears from AD 2008 on that this is not a "real" value; but rather an ACE within the ACL of the entry.
THIS NO LONGER WORKS
As far as I can tell.
Microsoft Active Directory has a neat Extensible matching value that should work called LDAP_MATCHING_RULE_BIT_AND
So a simple LDAP Query Filter like:
(userAccountControl:1.2.840.113556.1.4.803:=64)
Should do the trick.

Salesforce: Birthday Apex Scheduler Questions

I have written an Apex Scheduler class to send an email when a colleagues Birthday is 2 days away. I have created a contact with a birthday 2 days away. The contact's birthday is the July 29, 2012. Today's date is July 27, 2012.
I'm stuck. I don't get an error message or anything. I have scheduled the class to run today at 12. I didn't get an email (either telling me it was someone's birthday (success) or an error message from Salesforce telling me my code could not run (failure)
To trouble shoot, I also tried if (contact.Next_Birthday__c = : system.Today().addDays(2)) for the email method and got an incompatible types error. Next_Birthday__c is a date field, so I'm unsure of why the types are incompatible or why this SOQL statement doesn't work.
Any advice would be appreciated. Here is my code.
global class BirthdayNameOptions implements Schedulable{
global void execute (SchedulableContext ctx)
{
sendBirthdayEmail();
}
public void sendBirthdayEmail()
{
for(Contact con : [SELECT Name FROM Contact WHERE Next_Birthday__c = : system.Today().addDays(2)])
{
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XJ0000000M31w');
mail.setTargetObjectId('005J0000000');
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail });
}
}
}
I believe you want to set the targetObjectId of your outbound email message to the Contact whose birthday it is, rather than hardcoding it...the value 005J0000000 in your code doesn't seem to be a valid ID either, which could be causing you to not receive the email. For testing purposes you'd want to make sure the Contact record's email is set to yours, so you receive the notification. Also, you only get 10 calls to Messaging.sendEmail() per execution, so I bulkified this a bit for you. Give this a shot:
global class BirthdayNameOptions implements Schedulable {
global void execute (SchedulableContext ctx) {
sendBirthdayEmail();
}
public void sendBirthdayEmail() {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for ( Contact con : [SELECT Id, Name FROM Contact WHERE Next_Birthday__c = : system.Today().addDays(2)] ) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XJ0000000M31w');
mail.setTargetObjectId(con.Id);
mail.setSaveAsActivity(false);
mails.add(mail);
}
if ( mails.size() > 0 )
Messaging.sendEmail(mails, false);
}
}

Categories

Resources