AuthTicketsHelper.getTicket() returns null - p4java

My company uses Perforce for version control and I'm writing software that automates use of Perforce using p4java. I'm running into a problem where my code can't connect to the Perforce server even though I am passing in valid information to use the p4tickets file on my computer.
First, I logged on to perforce to get a p4ticket by running "p4 login", which created the ~/.p4tickets file. But when I run my program that uses p4java to connect using the p4ticket file, it returns null.
AuthTicket auth = AuthTicketsHelper.getTicket(username, serverAddr, p4TicketsFilePath);
// auth == null
I've double checked that the username I'm passing in matches the $P4USER environment variable I had when I used "p4 login", as well as that serverAddr matched the host name that was referenced by my $P4PORT. The p4TicketsFilePath also exists and is the correct path to the .p4tickets file which has my ticket, which is not expired. I'm looking for the reason why getTicket still returns null.

You can debug this issue by copying the source code from AuthTicketsHelper and insert print statements. here's my logger:
private static final Logger logger = LoggerFactory.getLogger(YourClass.class);
(if you don't have a logger, you can do System.out.println() with String.format("... %s ... %s") instead.) Then, copy in this code.
AuthTicket auth;
{
AuthTicket foundTicket = null;
String serverAddress = serverAddr;
String ticketsFilePath = p4TicketsFilePath;
String userName = username;
if (serverAddress != null) {
logger.info("P4TICKETS 1");
if (serverAddress.indexOf(':') == -1) {
serverAddress += "localhost:" + serverAddress;
logger.info("P4TICKETS 2");
}
for (AuthTicket ticket : AuthTicketsHelper.getTickets(ticketsFilePath)) {
logger.info("P4TICKETS 3 {} - {} - {} - {}", serverAddress, ticket.getServerAddress(), userName, ticket.getUserName());
if (serverAddress.equals(ticket.getServerAddress())
&& (userName == null || userName.equals(ticket
.getUserName()))) {
logger.info("P4TICKETS 4");
foundTicket = ticket;
break;
}
}
logger.info("P4TICKETS 5");
}
auth = foundTicket;
}
Follow the code path in the output to see what went wrong. In my case, the server name was a hostname in the code, but my .p4tickets file had an IP address for the server name.

Related

How delete a channel with a specific command?

I made a code that closes the specific channel that you write the command in.
This is my code that redirects each command to its own folder and runs the code in it.
events\message.js
module.exports = (client, message) => {
// Ignore all bots
if (message.author.bot) return;
// Ignore messages not starting with the prefix (in config.json)
if (message.content.indexOf(client.config.prefix) !== 0) return;
// Our standard argument/command name definition.
const args = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
// Grab the command data from the client.commands Enmap
const cmd = client.commands.get(command);
// If that command doesn't exist, silently exit and do nothing
if (!cmd) return;
// Run the command
cmd.run(client, message, args);
};
And my code that deletes the channel the command is written in.
const ms = require('ms');
const Discord = require('discord.js');
const client = new Discord.Client();
exports.run = async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR", "Ticket Admin"))
return message.reply('You need a specify permission to setup a ticket!');
if (message.author.bot) return;
const msgargs = message.content.slice(client.config.prefix.length).trim().split(/ +/g);
const command = msgargs.shift().toLowerCase();
if(command == "close") {
if(!message.channel.name.includes("ticket-")) return message.channel.send("You cannot use that here!")
message.channel.delete();
}
};
but the problem is that it doesn't want to delete the channel with "ticket-" in his name and it's the channel that the command was written in.
any help will be appreciated.
your file name isn't the same ass your command.
so when you send the command $ticket-close it runs the ticket-close file but in the ticket-close file, you are verifying if the command was closed and not so it end it.
you need to have the same name for your file code and your command to verify,(if(command == "close")).
or just don't check what was the command.

How to redirect requests to another host using ZAP?

I'm new to ZAP and I don't know much about it's js/ecma scripting.
Basically, I was trying to redirect request to another host.
Say an application that is connected to the ZAP proxy makes a request in a URL:
http://www.somesite.com/path/to/a/file
but I want to change the hostname in the URL to:
another.site.com
so it will actually request to: http://www.anothersite.com/path/to/a/file
Here's the code that I was trying to work but the URL remains unchanged in the request.
function proxyRequest(msg) {
// Debugging can be done using println like this
var uri = msg.getRequestHeader().getURI().toString()
var host = msg.getRequestHeader().getURI().getHost().toString()
print('proxyResponse called for url=' + uri)
if (host == 'download.qt.io') {
uri = uri.replace('download.qt.io/online/', 'mirrors.ocf.berkeley.edu/qt/online/')
msg.getRequestHeader().setHeader('Location', uri)
print('proxyRequest changed to url=' + uri)
}
if (host == 'ftp.jaist.ac.jp') {
uri = uri.replace('ftp.jaist.ac.jp/pub/qtproject/online/', 'mirrors.ocf.berkeley.edu/qt/online/')
msg.getRequestHeader().setHeader('Location', uri)
print('proxyRequest changed to url=' + uri)
}
if (host == 'qtproject.mirror.liquidtelecom.com') {
uri = uri.replace('qtproject.mirror.liquidtelecom.com/online/', 'mirrors.ocf.berkeley.edu/qt/online/')
msg.getRequestHeader().setHeader('Location', uri)
print('proxyRequest changed to url=' + uri)
}
return true
}
Option 1: Replacer Rule
Install the Replacer addon, from the marketplace:
Goto the Tools menu and select 'Replacer Options'.
Setup a rule as shown in the following screenshot.
Save/Okay as appropriate.
Now when your browse etc all your traffic will be redirected/rewritten.
Option 2: HttpSender Script
Create a new HttpSender script, similar to the following example:
function sendingRequest(msg, initiator, helper) {
var host = msg.getRequestHeader().getURI().getHost();
if (host.equals("www.somesite.com")) {
uri = msg.getRequestHeader().getURI();
uri.setEscapedAuthority("www.anothersite.com");
msg.getRequestHeader().setURI(uri);
}
return msg;
}
function responseReceived(msg, initiator, helper) {}
Option 3: Hosts File Entry
Goto a command prompt and nslookup www.somesite.com, note the IP address (w.x.y.z).
In your hosts file, add an entry associating the noted IP (w.x.y.z) with www.anothersite.com.
(You may need to restart ZAP/browsers for this change to take effect. On linux you'll likely need to sudo to edit the file, on Windows you'll need to edit it as an admin user.)
(Further details WRT editing your hosts file: https://www.howtogeek.com/howto/27350/beginner-geek-how-to-edit-your-hosts-file/)

NOAUTH Authentication required when connecting to Redis Sentinel with LettuceConnectionFactory

I am trying to connect to a Redis server using sentinel with password. I got RedisCommandExecutionException: NOAUTH Authentication required when calling redisTemplate.opsForValue().get("key")
Exception in thread "Thread-6" org.springframework.data.redis.RedisConnectionFailureException: Unable to connect to Redis on localhost:6379; nested exception is com.lambdaworks.redis.RedisCommandExecutionException: NOAUTH Authentication required.
at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.createLettuceConnector(LettuceConnectionFactory.java:544)
at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.initConnection(LettuceConnectionFactory.java:213)
at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.getSharedConnection(LettuceConnectionFactory.java:517)
at org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory.getConnection(LettuceConnectionFactory.java:189)
This is how I configured the connection factory:
RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration().master("mymaster").sentinel("localhost", 26379);
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(sentinelConfiguration);
lettuceConnectionFactory.setDatabase(1);
lettuceConnectionFactory.setPassword("foobared");
When I tried using JedisConnectionFactory, it works.
It looks like the password is not set when using LettuceConnectionFactory with sentinel.
I'm using spring-data-redis 1.7.2.
UPDATE:
I checked the code in DefaultLettucePool and saw that the password is not used in generating RedisURI when sentinelConfiguration is involved. When I modified the code as following, it works now.
DefaultLettucePool:
private RedisURI getRedisURI() {
if (isRedisSentinelAware()) {
return LettuceConverters.sentinelConfigurationToRedisURI(sentinelConfiguration, password, getDatabase());
}
return createSimpleHostRedisURI();
}
And in LettuceConverters:
public static RedisURI sentinelConfigurationToRedisURI(RedisSentinelConfiguration sentinelConfiguration, String password, int database) {
Assert.notNull(sentinelConfiguration, "RedisSentinelConfiguration is required");
Set<RedisNode> sentinels = sentinelConfiguration.getSentinels();
RedisURI.Builder builder = null;
for (RedisNode sentinel : sentinels) {
if (builder == null) {
builder = RedisURI.Builder.sentinel(sentinel.getHost(), sentinel.getPort(), sentinelConfiguration.getMaster()
.getName());
}
else {
builder.withSentinel(sentinel.getHost(), sentinel.getPort());
}
}
if (password != null) {
builder = builder.withPassword(password);
}
builder.withDatabase(database);
return builder.build();
}

Why do I get an MSPL exception "ProxyRequest only valid for sipRequest"

I'm writing a Lync MSPL application using a manifest and a windows service. In my manifest.am I have the following code:
<?xml version="1.0"?>
<r:applicationManifest
r:appUri="http://www.company.no/LyncServerFilter"
xmlns:r="http://schemas.microsoft.com/lcs/2006/05">
<r:requestFilter methodNames="ALL"
strictRoute="true"
domainSupported="false"/>
<r:responseFilter reasonCodes="ALL"/>
<r:proxyByDefault action="true" />
<r:allowRegistrationBeforeUserServices action="true" />
<r:splScript>
<![CDATA[
callId = GetHeaderValues("Call-ID");
cseq = GetHeaderValues("CSeq");
content = "";
sstate = GetHeaderValues("subscription-state");
xevent = GetHeaderValues("Event");
xdir = GetHeaderValues("Direction");
xexp = GetHeaderValues("Session-Expires");
referto = GetHeaderValues("Refer-To");
if (sipRequest)
{
if (sipRequest.Method == "INVITE") {
if (ContainsString(sipRequest.Content, "m=audio", true)) {
content = "audio";
}
else if (ContainsString(sipRequest.Content, "m=video", true)) {
content = "video";
}
else if (ContainsString(sipRequest.Content, "m=message", true)) {
content = "message";
}
else if (ContainsString(sipRequest.Content, "m=application", true)) {
content = "application";
}
else {
content = "unknown";
}
}
else if (sipRequest.Method == "NOTIFY" || sipRequest.Method == "BENOTIFY") {
content = sipRequest.Content;
}
DispatchNotification("OnRequest", sipRequest.Method, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
if (sipRequest) {
ProxyRequest();
}
}
else if(sipResponse) {
DispatchNotification("OnResponse", sipResponse.StatusCode, sipResponse.StatusReasonPhrase, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
ProxyResponse();
}
]]></r:splScript>
</r:applicationManifest>
I'm getting the following errormessage in Eventlog on Lync Front End server:
Lync Server application MSPL script execution aborted because of an error
Application Uri at 'http://www.company.no/LyncServerFilter', at line 60
Error: 0x80070057 - The parameter is incorrect
Additional information: ProxyRequest only valid for sipRequest
Line 60 is where I call ProxyRequest:
if (sipRequest) {
ProxyRequest();
}
Questions:
Why does the errormessage say that ProxyRequest is only valid for a sipRequest? I'm checking that it is a sipMessage right?
Can I remove my call to ProxyRequest() since I have set proxyByDefault=true? Does the DistpathNotification-method "handle" the method (swallow it), or will the message be proxied by default? The code "works" when I remove the call to ProxyRequest(), but I'm not sure what the consequences are...
The ProxyRequest method takes a argument of the uri, which is why you are getting the compile error message.
So you should be calling it like:
ProxyRequest(""); // send to the URI specified in the request itself
Removing it effectivity does the same thing as per your proxyByDefault setting being set to true:
If true, the server automatically proxies any messages that are not handled by the application. If false, the message is dropped and applications that follow this application in the application execution order will not receive it. The default value is true.
As a side-note, you can use compilespl.exe, which comes as part of the Lync Server SDK to verify that your MSPL script is correct before trying to start it on the lync server.
Check out this link in the 'Compile the MSPL application separately' section.

RMI and 2 machines - two way communication

I've got problem with RMI comunication between 2 machines (win 7 and win xp VM). The exception with I have problem is:
java.rmi.ConnectException: Connection refused to host: 169.254.161.21; nested exception is:
java.net.ConnectException: Connection timed out: connect
It's really weired because during connection I use address 192.168.1.4 (server), but exception somehow show sth different. I disabled firewall on both side. Ping working to both side. I tried telnet to server and use server port:
telnet 192.168.1.4 1099 and it's working... I can't figure out where the problem is.
If I run this on host side (eg server side) everything works fine.
How is it look from SERVER:
public class Server
{
public static void main(String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String portNum, registryURL;
try{
System.out.println("Enter the RMIregistry port number:");
portNum = (br.readLine()).trim();
int RMIPortNum = Integer.parseInt(portNum);
startRegistry(RMIPortNum); // Registry registry = LocateRegistry.createRegistry(RMIPortNum);
ServerSide_Impl exportedObj = new ServerSide_Impl();
registryURL = "rmi://localhost:" + portNum + "/callback";
//registryURL = "rmi://192.168.1.4:" + portNum + "/callback";
Naming.rebind(registryURL, exportedObj);
System.out.println("Callback Server ready.");
}// end try
catch (Exception re) {
System.out.println(
"Exception in HelloServer.main: " + re);
} // end catch
} // end main
//This method starts a RMI registry on the local host, if
//it does not already exists at the specified port number.
private static void startRegistry(int RMIPortNum) throws RemoteException
{
try
{
Registry registry = LocateRegistry.getRegistry(RMIPortNum);
registry.list( );
// This call will throw an exception
// if the registry does not already exist
}
catch (RemoteException e)
{
Registry registry = LocateRegistry.createRegistry(RMIPortNum);
}
} // end startRegistry
} // end class
Client side is look like:
try
{
this.serverAd = serverAddress.getText();
String path = System.getProperty("user.dir");
String pathAfter = path.replace("\\", "/");
String pathFile = "file:/"+pathAfter + "/wideopen.policy";
System.setProperty("java.security.policy", pathFile);
System.setSecurityManager(new RMISecurityManager());
this.hostName = hostNameTextField.getText();
this.portNum = hostPortNumberTextField.getText();
RMIPort = Integer.parseInt(this.portNum);
this.time = Integer.parseInt(timeTextField.getText());
//this.registryURL = "rmi://localhost:" + this.portNum + "/callback";
String registryURLString = "rmi://"+this.serverAd+":" + this.portNum + "/callback";
this.registryURL = registryURLString;
ConsoleTextField.append("\n"+ this.registryURL + "\n");
// find the remote object and cast it to an
// interface object
obj = (ServerSide_Interface)Naming.lookup(this.registryURL);
boolean test = obj.Connect();
if(test)
{
callbackObj = new ClientSide_Impl();
// register for callback
obj.registerForCallback(callbackObj);
isConnected = true;
ConsoleTextField.append("Nawiązano połaczenie z serwerem\n");
TableModel modelTemp = obj.Server_GenerateStartValues();
myDataTable.setModel(modelTemp);
myDataTable.setEnabled(true);
}
else ConsoleTextField.append("Brak połączenia z serwerem\n");
}
catch (Exception ex ){
ConsoleTextField.append(ex + "\n");
System.out.println(ex);
}
This connection is working fine if I run client on host side. If I use VM and try connect between 2 different machines, I can;t figure out what did I do bad
There is something wrong with your etc/hosts file or your DNS setup. It is providing the wrong IP address to the server as the server's external IP address, so RMI embeds the wrong address into the stub, so the client attempts to connect to the wrong IP address.
If you can't fix that, you can set the system property java.rmi.server.hostname to the correct IP address at the server JVM, before exporting any RMI objects (including Registries). That tells RMI to embed that address in the stub.