Generating a random hex string (of length 50) in Java ME/J2ME - java-me

My app needs to generate a hex string to use as a session ID. Java's SecureRandom doesn't seem to be working ("java/lang/NoClassDefFoundError: java/security/SecureRandom: Cannot create class in system package")
I thought of doing something like this:
byte[] resBuf = new byte[50];
new Random().nextBytes(resBuf);
String resStr = new String(Hex.encode(resBuf));
But the method nextBytes(byte[] bytes) isn't available for some strange reason.
Does anyone have a means of generating a random hex number in Java ME/J2ME?
Many thanks.
Edit: The above generator seems to work when using Bouncy Castle lcrypto-j2me-145 (but not lcrypto-j2me-147).

JavaME is a subset of JavaSE, so many classes and methods in the desktop version are not available.
Looks like you are trying to get a random string of a given length. You can do something like this:
private String getRandomHexString(int numchars){
Random r = new Random();
StringBuffer sb = new StringBuffer();
while(sb.length() < numchars){
sb.append(Integer.toHexString(r.nextInt()));
}
return sb.toString().substring(0, numchars);
}

Related

NodaTime UnparsableValueException due to usage of "Z" in pattern

I am exchanging JSON messages between Java and C# (and vice-versa).
In Java I use a java.time.Instant (JSR-310) to represent a point in time on the global timeline. In order to create a human readable date/time string in JSON, I convert my Instant as follows:
private static final DateTimeFormatter FORMATTER = ofPattern("yyyy-MM-dd'T'HH:mm:ssZ").withZone(ZoneId.systemDefault());
which generates the following output:
2017-04-28T19:54:44-0500
Now, on the message consumer side of things (C#) I wrote a custom Newtonsoft.Json.JsonConverter, which extends the abstract JsonCreationConvert class that contains the following overridden ReadJson() method:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.StartArray)
{
return JToken.Load(reader).ToObject<string[]>();
}
reader.DateParseHandling = DateParseHandling.None; // read NodaTime string Instant as is
serializer.Converters.Add(NodaConverters.InstantConverter);
// Load JObject from stream
var jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
var writer = new StringWriter();
serializer.Serialize(writer, jObject);
using (var newReader = new JsonTextReader(new StringReader(writer.ToString())))
{
newReader.Culture = reader.Culture;
newReader.DateParseHandling = reader.DateParseHandling;
newReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
newReader.FloatParseHandling = reader.FloatParseHandling;
serializer.Populate(newReader, target);
}
return target;
}
Create() is an abstract method.
When I now convert this JSON string into a NodaTime.Instant (v2.0.0) by calling:
InstantPattern.General.Parse(creationTime).Value;
I get this exception:
NodaTime.Text.UnparsableValueException: The value string does not match a quoted string in the pattern. Value being parsed: '2017-04-28T19:54:44^-0500'. (^ indicates error position.)
If I pass a text literal "Z" (so no outputted offset "-0500" and Z is interpreted as 0 offset) the NodaTime.Serialization.JsonNet.NodaConverters.InstantConverter correctly reads without throwing an exception.
Looking into the GeneralPatternImpl I see:
internal static readonly InstantPattern GeneralPatternImpl = InstantPattern.CreateWithInvariantCulture("uuuu-MM-ddTHH:mm:ss'Z'");
Why does an InstantConverter require the offset to be a text literal? Is this happening because an Instant is agnostic to an offset? If this is the case, then why doesn't the InstantConverter just ignore the offset instead of throwing an exception? Do I need to write a custom converter to get around this problem?
That's like asking for 2017-04-28T19:54:44 to be parsed as a LocalDate - there's extra information that we'd silently be dropping. Fundamentally, your conversion from Instant to String in Java is "adding" information which isn't really present in the original instant. What you're ending up with is really an OffsetDateTime, not an Instant - it has more information than an Instant does.
You should decide what information you really care about. If you only care about the instant in time, then change your Java serialization to use UTC, and it should end up with Z in the serialized form, and all will be well. This is what I suggest you do - propagating irrelevant information is misleading, IMO.
If you actually care about the offset in the system default time zone, which your call to .withZone(ZoneId.systemDefault()) implies you do, then you should parse it as an OffsetDateTime on the .NET side of things. You can convert that to an Instant afterwards if you want to (just call ToInstant()).

How to pass string as value in mapper?

I am trying to pass a string as value in the mapper, but getting error that it is not Writable. How to resolve?
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String TempString = value.toString();
String[] SingleRecord = TempString.split("\t");
//using Integer.parseInt to calculate profit
int Amount = Integer.parseInt(SingleRecord[7]);
int Asset = Integer.parseInt(SingleRecord[8]);
int SalesPrice = Integer.parseInt(SingleRecord[9]);
int Profit = Amount*(SalesPrice-Asset);
String ValueProfit = String.valueOf(Profit);
String ValueOne = String.valueOf(one);
custID.set(SingleRecord[2]);
data.set(ValueOne + ValueProfit);
context.write(custID, data);
}
Yahoo's tutorial says :
Objects which can be marshaled to or from files and across the network must obey a particular interface, called Writable, which allows Hadoop to read and write the data in a serialized form for transmission.
From Cloudera site :
The key and value classes must be serializable by the framework and hence must implement the Writable interface. Additionally, the key classes must implement the WritableComparable interface to facilitate sorting.
So you need an implementation of Writable to write it as a value in the context. Hadoop ships with a few stock classes such as IntWritable. The String counterpart you are looking for is the Text class. It can be used as :
context.write(custID, new Text(data));
OR
Text outValue = new Text();
val.set(data);
context.write(custID, outValue)
I case, you need specialized functionality in the value class, you may implement Writable (not a big deal after all). However seems like Text is just enough for you.
you havent set data in map function according to import text in above,and TextWritable is wrong just use Text as well.

Assigning a GUID in C#

I've got a lot of code that is using GUIDs (an architecture handed to me--not my choice).
Mostly, the values come from a database and load into memory from there. However, I'm doing some testing and I'm hard-coding some GUIDs into the code.
I haven't found an easy way to assign GUIDs, so I've ended up using Guid.Parse("...."). Is there an easier way to assign GUIDS in C#?
value = Guid.Parse("11223344-5566-7788-99AA-BBCCDDEEFF00");
It just seems like a lot of overhead to create the string then parse it. I would think there would be an easier way to directly assign it.
If you already have a string representation of the Guid, you can do this:
Guid g = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00");
And if you want a brand new Guid then just do
Guid g = Guid.NewGuid();
In case you use the guid as a constant - you can put the guid in your project settings.
than you can reach you values the following way:
var myGuid = Properties.Settings.Default.MyGuid;
if you go for the constant option you can use this Guid method (one of six available):
private static const Guid PUBLIC_KEY = new Guid((int)0x93EE8E7F, 0x13FA, 0x4C6D,
new byte[] { 0x9D, 0x32, 0xE6, 0xEC, 0xD1, 0x4A, 0x91, 0xA7 });
// {93EE8E7F-13FA-4C6D-9D32-E6ECD14A91A7}

Cassandra convert UUID to string and back

If i use UUID1 for my column names and then retrieve them with php how can i convert that UUID to readable string so i could insert that string to the HTML and then later on use it to select that same column by converting that string back to UUID? Is that even possible?
I could go with UTF8 or something else but i want to avoid collisions and get ordered wide rows, and i really need to store those column names to the HTML, i can't see any other way to do it.
I'm using phpcassa.
You can cast UUID objects to strings to get a nice printable version. That same string can be used with UUID::import() to create an identical UUID object again:
use phpcassa\UUID;
$uuid = UUID::uuid1();
$pretty_uuid = (string)$uuid;
echo("Printable version: " . $pretty_uuid . "\n");
$uuid_copy = UUID::import($pretty_uuid);
assert ($uuid == $uuid_copy);
Assuming you are getting the UUID as byte[], you can use something like this:
public Object convertFromNoSqlImpl(byte[] value) {
byte[] timeArray = new byte[8];
byte[] clockSeqAndNodeArray=new byte[8];
System.arraycopy(value,0,timeArray,0,8);
System.arraycopy(value,8,clockSeqAndNodeArray,0,8);
long time = StandardConverters.convertFromBytes(Long.class, timeArray);
long clockSeqAndNode = StandardConverters.convertFromBytes(Long.class, clockSeqAndNodeArray);
UUID ud = new UUID(time,clockSeqAndNode);
return ud;
}

Calculate Translation Repetitions

I have looked around the web for the standard formula for calculating repetitions in a document to be translated. I have not found it. For those who don't know what repetitions in translation means, this gives a good description of it.
I first tried something like this
using System;
using System.Collection.Generic;
using System.Text.RegularExpressions;
using System.Linq;
<snip>
Dictionary<string, int> _dict = new Dictionary<string, int>();
int CalculateRepetitions(string plainTextDoc) {
foreach (string item in Regex.Split(plainTextDoc, "\\P{L}+"))
if (_dict.ContainsKey(item))
_dict[item]++;
else
_dict.Add(item, 0);
return _dict.Where((key, value) => value > 0).Count();
}
but that was not close to the sample number from Trados for the same document, and was the wrong definition of repetitions anyway. Does anyone have a good example for calculating translation repetitions? I'm not expecting only C# answers, I'm good with java and c++ answers as well.
The GMX/V standard might be your answer and there seems to be a C# implementation.

Resources