code
stringlengths
73
34.1k
label
stringclasses
1 value
public ByteBuffer sliceAsByteBuffer(int index, int length) { if (hasArray()) { return ByteBuffer.wrap((byte[]) base, (int) ((address - ARRAY_BYTE_BASE_OFFSET) + index), length); } else { assert (!isUniversalBuffer); return DirectBufferAccess.newByteBuffer(...
java
public byte[] toByteArray() { byte[] b = new byte[size()]; unsafe.copyMemory(base, address, b, ARRAY_BYTE_BASE_OFFSET, size()); return b; }
java
public void copyTo(int index, MessageBuffer dst, int offset, int length) { unsafe.copyMemory(base, address + index, dst.base, dst.address + offset, length); }
java
@Override public JsonFormat.Value findFormat(Annotated ann) { // If the entity contains JsonFormat annotation, give it higher priority. JsonFormat.Value precedenceFormat = super.findFormat(ann); if (precedenceFormat != null) { return precedenceFormat; } return ARRAY_FORMAT; }
java
@Override public Boolean findIgnoreUnknownProperties(AnnotatedClass ac) { // If the entity contains JsonIgnoreProperties annotation, give it higher priority. final Boolean precedenceIgnoreUnknownProperties = super.findIgnoreUnknownProperties(ac); if (precedenceIgnoreUnknownProperties != null) { re...
java
public OutputStream reset(OutputStream out) throws IOException { OutputStream old = this.out; this.out = out; return old; }
java
public InputStream reset(InputStream in) throws IOException { InputStream old = this.in; this.in = in; return old; }
java
public WritableByteChannel reset(WritableByteChannel channel) throws IOException { WritableByteChannel old = this.channel; this.channel = channel; return old; }
java
public ReadableByteChannel reset(ReadableByteChannel channel) throws IOException { ReadableByteChannel old = this.channel; this.channel = channel; return old; }
java
private MessageBuffer getNextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } assert (buffer != null); totalReadBytes += buffer.size(); return next; }
java
public MessageFormat getNextFormat() throws IOException { // makes sure that buffer has at least 1 byte if (!ensureBuffer()) { throw new MessageInsufficientBufferException(); } byte b = buffer.getByte(position); return MessageFormat.valueOf(b); }
java
private byte readByte() throws IOException { if (buffer.size() > position) { byte b = buffer.getByte(position); position++; return b; } else { nextBuffer(); if (buffer.size() > 0) { byte b = buffer.getByt...
java
public void skipValue(int count) throws IOException { while (count > 0) { byte b = readByte(); MessageFormat f = MessageFormat.valueOf(b); switch (f) { case POSFIXINT: case NEGFIXINT: case BOOLEAN: ...
java
private static MessagePackException unexpected(String expected, byte b) { MessageFormat format = MessageFormat.valueOf(b); if (format == MessageFormat.NEVER_USED) { return new MessageNeverUsedFormatException(String.format("Expected %s, but encountered 0xC1 \"NEVER_USED\" byte", expected)...
java
public boolean tryUnpackNil() throws IOException { // makes sure that buffer has at least 1 byte if (!ensureBuffer()) { throw new MessageInsufficientBufferException(); } byte b = buffer.getByte(position); if (b == Code.NIL) { readByte(); ...
java
public boolean unpackBoolean() throws IOException { byte b = readByte(); if (b == Code.FALSE) { return false; } else if (b == Code.TRUE) { return true; } throw unexpected("boolean", b); }
java
public short unpackShort() throws IOException { byte b = readByte(); if (Code.isFixInt(b)) { return (short) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); return (short) (u8 & 0xff); ...
java
public long unpackLong() throws IOException { byte b = readByte(); if (Code.isFixInt(b)) { return (long) b; } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); return (long) (u8 & 0xff); ...
java
public BigInteger unpackBigInteger() throws IOException { byte b = readByte(); if (Code.isFixInt(b)) { return BigInteger.valueOf((long) b); } switch (b) { case Code.UINT8: // unsigned int 8 byte u8 = readByte(); retu...
java
public float unpackFloat() throws IOException { byte b = readByte(); switch (b) { case Code.FLOAT32: // float float fv = readFloat(); return fv; case Code.FLOAT64: // double double dv = readDouble(); ...
java
public int unpackArrayHeader() throws IOException { byte b = readByte(); if (Code.isFixedArray(b)) { // fixarray return b & 0x0f; } switch (b) { case Code.ARRAY16: { // array 16 int len = readNextLength16(); return l...
java
public int unpackMapHeader() throws IOException { byte b = readByte(); if (Code.isFixedMap(b)) { // fixmap return b & 0x0f; } switch (b) { case Code.MAP16: { // map 16 int len = readNextLength16(); return len; ...
java
public int unpackBinaryHeader() throws IOException { byte b = readByte(); if (Code.isFixedRaw(b)) { // FixRaw return b & 0x1f; } int len = tryReadBinaryHeader(b); if (len >= 0) { return len; } if (allowReadingStringAsBinary...
java
public MessageBuffer readPayloadAsReference(int length) throws IOException { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= length) { MessageBuffer slice = buffer.slice(position, length); position += length; return slice; ...
java
public MessageBuffer reset(MessageBuffer buf) { MessageBuffer old = this.buffer; this.buffer = buf; if (buf == null) { isEmpty = true; } else { isEmpty = false; } return old; }
java
public ModbusRequest buildDiagnostics(DiagnosticsSubFunctionCode subFunctionCode, int serverAddress, int data) throws ModbusNumberException { DiagnosticsRequest request = new DiagnosticsRequest(); request.setServerAddress(serverAddress); request.setSubFunctionCode(subFunctionCode); reque...
java
synchronized public ModbusResponse processRequest(ModbusRequest request) throws ModbusProtocolException, ModbusIOException { try { sendRequest(request); if (request.getServerAddress() != Modbus.BROADCAST_ID) { do { try { ModbusR...
java
public void setResponseTimeout(int timeout) { try { getConnection().setReadTimeout(timeout); } catch (Exception e) { Modbus.log().warning(e.getLocalizedMessage()); } }
java
final public int[] readHoldingRegisters(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadHoldingRegisters(serverAddress, startAddress, quantity); R...
java
final public int[] readInputRegisters(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadInputRegisters(serverAddress, startAddress, quantity); ReadH...
java
final synchronized public boolean[] readCoils(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadCoils(serverAddress, startAddress, quantity); ReadCo...
java
final public boolean[] readDiscreteInputs(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadDiscreteInputs(serverAddress, startAddress, quantity); R...
java
final public void writeSingleRegister(int serverAddress, int startAddress, int register) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleRegister(serverAddress, startAddress, register)); }
java
final public int[] readWriteMultipleRegisters(int serverAddress, int readAddress, int readQuantity, int writeAddress, int[] registers) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadWriteMultipleRegisters...
java
final public ModbusFileRecord[] readFileRecord(int serverAddress, ModbusFileRecord[] records) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadFileRecord(serverAddress, records); ReadFileRecordRespo...
java
final public void writeFileRecord(int serverAddress, ModbusFileRecord record) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { processRequest(ModbusRequestBuilder.getInstance().buildWriteFileRecord(serverAddress, record)); }
java
static public void setLogLevel(LogLevel level) { logLevel = level; log.setLevel(level.value()); for (Handler handler : log.getHandlers()) { handler.setLevel(level.value()); } }
java
static public boolean checkServerAddress(int serverAddress) { /* * hook for server address is equals zero: * some of modbus tcp slaves sets the UnitId value to zero, not ignoring value in this field. */ switch (serverAddress) { case 0x00: //Modbus.log(...
java
public int readShortBE() throws IOException { int h = read(); int l = read(); if (-1 == h || -1 == l) return -1; return DataUtils.toShort(h, l); }
java
public int readShortLE() throws IOException { int l = read(); int h = read(); if (-1 == h || -1 == l) return -1; return DataUtils.toShort(h, l); }
java
public Future<AuthenticationResult> acquireToken(final String resource, final UserAssertion userAssertion, final ClientCredential credential, final AuthenticationCallback callback) { this.validateOnBehalfOfRequestInput(resource, userAssertion, credential, true); final Clien...
java
public Future<AuthenticationResult> acquireToken(final String resource, final UserAssertion userAssertion, final AsymmetricKeyCredential credential, final Aut...
java
public Future<DeviceCode> acquireDeviceCode(final String clientId, final String resource, final AuthenticationCallback<DeviceCode> callback) { validateDeviceCodeRequestInput(clientId, resource); return service.submit( new AcquireDeviceC...
java
public Future<AuthenticationResult> acquireTokenByDeviceCode( final DeviceCode deviceCode, final AuthenticationCallback callback) throws AuthenticationException { final ClientAuthentication clientAuth = new ClientAuthenticationPost( ClientAuthenticationMethod.NONE, ...
java
public Future<AuthenticationResult> acquireTokenByRefreshToken( final String refreshToken, final String clientId, final String resource, final AuthenticationCallback callback) { final ClientAuthentication clientAuth = new ClientAuthenticationPost( ClientAuthenticati...
java
@Override public Map<String, List<String>> toParameters() { final Map<String, List<String>> outParams = new LinkedHashMap<>(); outParams.put("resource", Collections.singletonList(resource)); outParams.put("grant_type", Collections.singletonList(GRANT_TYPE) ); outParams.put("code", Co...
java
public static JSONObject processBadRespStr(int responseCode, String responseMsg) throws JSONException { JSONObject response = new JSONObject(); response.put("responseCode", responseCode); if (responseMsg.equalsIgnoreCase("")) { // good response is empty string response.put("res...
java
static ClientAssertion buildJwt(final AsymmetricKeyCredential credential, final String jwtAudience) throws AuthenticationException { if (credential == null) { throw new IllegalArgumentException("credential is null"); } final long time = System.currentTimeMillis(); ...
java
public static JSONArray fetchDirectoryObjectJSONArray(JSONObject jsonObject) throws Exception { JSONArray jsonArray = new JSONArray(); jsonArray = jsonObject.optJSONObject("responseMsg").optJSONArray("value"); return jsonArray; }
java
public static JSONObject fetchDirectoryObjectJSONObject(JSONObject jsonObject) throws Exception { JSONObject jObj = new JSONObject(); jObj = jsonObject.optJSONObject("responseMsg"); return jObj; }
java
public static String fetchNextSkiptoken(JSONObject jsonObject) throws Exception { String skipToken = ""; // Parse the skip token out of the string. skipToken = jsonObject.optJSONObject("responseMsg").optString("odata.nextLink"); if (!skipToken.equalsIgnoreCase("")) { /...
java
public static String createJSONString(HttpServletRequest request, String controller) throws Exception { JSONObject obj = new JSONObject(); try { Field[] allFields = Class.forName( "com.microsoft.windowsazure.activedirectory.sdk.graph.models." + controller).getDeclared...
java
public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject) throws Exception { // Get the list of all the field names. Field[] fieldList = destObject.getClass().getDeclaredFields(); // For all the declared field. for (int i = 0; i < fieldList.le...
java
public String getPublicCertificateHash() throws CertificateEncodingException, NoSuchAlgorithmException { return Base64.encodeBase64String(AsymmetricKeyCredential .getHash(this.publicCertificate.getEncoded())); }
java
public boolean isDeviceCodeError() { ErrorObject errorObject = getErrorObject(); if (errorObject == null) { return false; } String code = errorObject.getCode(); if (code == null) { return false; } switch (code) { case "authoriza...
java
private StateData validateState(HttpSession session, String state) throws Exception { if (StringUtils.isNotEmpty(state)) { StateData stateDataInSession = removeStateFromSession(session, state); if (stateDataInSession != null) { return stateDataInSession; ...
java
public String getLdapEncoded() { if (components.size() == 0) { throw new IndexOutOfBoundsException("No components in Rdn."); } StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); for (Iterator iter = components.values().iterator(); iter.hasNext();) { LdapRdnComponent component = (LdapRdnCompone...
java
public String encodeUrl() { StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); for (Iterator iter = components.values().iterator(); iter.hasNext();) { LdapRdnComponent component = (LdapRdnComponent) iter.next(); sb.append(component.encodeUrl()); if (iter.hasNext()) { sb.append("+"); } ...
java
public int compareTo(Object obj) { LdapRdn that = (LdapRdn) obj; if(this.components.size() != that.components.size()) { return this.components.size() - that.components.size(); } Set<Map.Entry<String,LdapRdnComponent>> theseEntries = this.components.entrySet(); for...
java
public LdapRdn immutableLdapRdn() { Map<String, LdapRdnComponent> mapWithImmutableRdns = new LinkedHashMap<String, LdapRdnComponent>(components.size()); for (Iterator iterator = components.values().iterator(); iterator.hasNext();) { LdapRdnComponent rdnComponent = (LdapRdnComponent) iterator.next(); ...
java
void doCloseConnection(DirContext context, ContextSource contextSource) throws javax.naming.NamingException { DirContextHolder transactionContextHolder = (DirContextHolder) TransactionSynchronizationManager .getResource(contextSource); if (transactionContextHolder == null ...
java
protected String encodeLdap() { StringBuffer buff = new StringBuffer(key.length() + value.length() * 2); buff.append(key); buff.append('='); buff.append(LdapEncoder.nameEncode(value)); return buff.toString(); }
java
public String encodeUrl() { // Use the URI class to properly URL encode the value. try { URI valueUri = new URI(null, null, value, null); return key + "=" + valueUri.toString(); } catch (URISyntaxException e) { // This should really never happen... return key + "=" + "value"; } }
java
public int compareTo(Object obj) { LdapRdnComponent that = (LdapRdnComponent) obj; // It's safe to compare directly against key and value, // because they are validated not to be null on instance creation. int keyCompare = this.key.toLowerCase().compareTo(that.key.toLowerCase()); if(k...
java
public static void collectAttributeValues(Attributes attributes, String name, Collection<Object> collection) { collectAttributeValues(attributes, name, collection, Object.class); }
java
public static <T> void collectAttributeValues( Attributes attributes, String name, Collection<T> collection, Class<T> clazz) { Assert.notNull(attributes, "Attributes must not be null"); Assert.hasText(name, "Name must not be empty"); Assert.notNull(collection, "Collection must not b...
java
public static void iterateAttributeValues(Attribute attribute, AttributeValueCallbackHandler callbackHandler) { Assert.notNull(attribute, "Attribute must not be null"); Assert.notNull(callbackHandler, "callbackHandler must not be null"); if (attribute instanceof Iterable) { int i = 0; for (Object obj : (It...
java
public static LdapName newLdapName(String distinguishedName) { Assert.notNull(distinguishedName, "distinguishedName must not be null"); try { return new LdapName(distinguishedName); } catch (InvalidNameException e) { throw convertLdapException(e); } }
java
public static Rdn getRdn(Name name, String key) { Assert.notNull(name, "name must not be null"); Assert.hasText(key, "key must not be blank"); LdapName ldapName = returnOrConstructLdapNameFromName(name); List<Rdn> rdns = ldapName.getRdns(); for (Rdn rdn : rdns) { Na...
java
public static Object getValue(Name name, String key) { NamingEnumeration<? extends Attribute> allAttributes = getRdn(name, key).toAttributes().getAll(); while (allAttributes.hasMoreElements()) { Attribute oneAttribute = allAttributes.nextElement(); if(key.equalsIgnoreCase(oneAttr...
java
public static Object getValue(Name name, int index) { Assert.notNull(name, "name must not be null"); LdapName ldapName = returnOrConstructLdapNameFromName(name); Rdn rdn = ldapName.getRdn(index); if(rdn.size() > 1) { LOGGER.warn("Rdn at position " + index + " of dn '" + name...
java
public static String getStringValue(Name name, String key) { return (String) getValue(name, key); }
java
static byte[] numberToBytes(String number, int length, boolean bigEndian) { BigInteger bi = new BigInteger(number); byte[] bytes = bi.toByteArray(); int remaining = length - bytes.length; if (remaining < 0) { bytes = Arrays.copyOfRange(bytes, -remaining, bytes.length); } else { byte[] fill = new byte[re...
java
static String toHexString(final byte b) { String hexString = Integer.toHexString(b & 0xFF); if (hexString.length() % 2 != 0) { // Pad with 0 hexString = "0" + hexString; } return hexString; }
java
static String toHexString(final byte[] b) { StringBuffer sb = new StringBuffer("{"); for (int i = 0; i < b.length; i++) { sb.append(toHexString(b[i])); if (i < b.length - 1) { sb.append(","); } } sb.append("}"); return sb.toString(); }
java
public Context getInnermostDelegateContext() { final Context delegateContext = this.getDelegateContext(); if (delegateContext instanceof DelegatingContext) { return ((DelegatingContext)delegateContext).getInnermostDelegateContext(); } return delegateContext; }
java
public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { if (record != null) { //DN is required. LdapName dn = record.getName(); if (dn != null) { //objectClass definition is required. if (record.get("objectClass") != null) { //Naming attribute is req...
java
public void destroy() { try { ctx.close(); } catch (javax.naming.NamingException e) { LOG.warn("Error when closing", e); } }
java
protected final void parse(String path) { DnParser parser = DefaultDnParserFactory.createDnParser(unmangleCompositeName(path)); DistinguishedName dn; try { dn = parser.dn(); } catch (ParseException e) { throw new BadLdapGrammarException("Failed to parse DN", e); } catch (TokenMgrError e) { throw ...
java
public String toUrl() { StringBuffer buffer = new StringBuffer(DEFAULT_BUFFER_SIZE); for (int i = names.size() - 1; i >= 0; i--) { LdapRdn n = (LdapRdn) names.get(i); buffer.append(n.encodeUrl()); if (i > 0) { buffer.append(","); } } return buffer.toString(); }
java
public int compareTo(Object obj) { DistinguishedName that = (DistinguishedName) obj; ListComparator comparator = new ListComparator(); return comparator.compare(this.names, that.names); }
java
public DistinguishedName immutableDistinguishedName() { List listWithImmutableRdns = new ArrayList(names.size()); for (Iterator iterator = names.iterator(); iterator.hasNext();) { LdapRdn rdn = (LdapRdn) iterator.next(); listWithImmutableRdns.add(rdn.immutableLdapRdn()); } return new DistinguishedName(Co...
java
private boolean processAttributeAnnotation(Field field) { // Default to no syntax specified syntax = ""; // Default to a String based attribute isBinary = false; // Default name of attribute to the name of the field name = new CaseIgnoreString(fi...
java
private static Map<String, String> readSyntaxMap(File syntaxMapFile) throws IOException { Map<String, String> result = new HashMap<String, String>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(syntaxMapFile)); String ...
java
private static ObjectSchema readSchema(String url, String user, String pass, SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses) throws NamingException, ClassNotFoundException { // Set up environment Hashtable<String, String> env = new Ha...
java
private static void createCode(String packageName, String className, ObjectSchema schema, Set<SyntaxToJavaClass.ClassInfo> imports, File outputFile) throws IOException, TemplateException { Configuration freeMarkerConfiguration = new Configuration(); freeMarkerConfiguratio...
java
private static File makeOutputFile(String outputDir, String packageName, String className) throws IOException { // Convert the package name to a path Pattern pattern=Pattern.compile("\\."); Matcher matcher=pattern.matcher(packageName); String sepToUse=File.separator; ...
java
public ObjectSchema getObjectSchema(Set<String> objectClasses) throws NamingException, ClassNotFoundException { ObjectSchema result = new ObjectSchema(); createObjectClass(objectClasses, schemaContext, result); return result; }
java
private void createObjectClass(Set<String> objectClasses, DirContext schemaContext, ObjectSchema schema) throws NamingException, ClassNotFoundException { // Super classes Set<String> supList = new HashSet<String>(); // For each of the given object classes for (String...
java
private void closeContext(DirContext ctx) { if (ctx != null) { try { ctx.close(); } catch (Exception e) { LOG.debug("Exception closing context", e); } } }
java
protected DirContext createContext(Hashtable<String, Object> environment) { DirContext ctx = null; try { ctx = getDirContextInstance(environment); if (LOG.isInfoEnabled()) { Hashtable<?, ?> ctxEnv = ctx.getEnvironment(); String ldapUrl = (String) ctxEnv.get(Context.PROVIDER_URL); LOG.debug("Got ...
java
public void afterPropertiesSet() { if (ObjectUtils.isEmpty(urls)) { throw new IllegalArgumentException("At least one server url must be set"); } if (authenticationSource == null) { LOG.debug("AuthenticationSource not set - " + "using default implementation"); if (!StringUtils.hasText(userDn)) { LOG....
java
public void setBaseEnvironmentProperties(Map<String, Object> baseEnvironmentProperties) { this.baseEnv = new Hashtable<String, Object>(baseEnvironmentProperties); }
java
public LdapNameBuilder add(Name name) { Assert.notNull(name, "name must not be null"); try { ldapName.addAll(ldapName.size(), name); return this; } catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } }
java
public LdapNameBuilder add(String name) { Assert.notNull(name, "name must not be null"); return add(LdapUtils.newLdapName(name)); }
java
protected void deleteRecursively(DirContext ctx, Name name) { NamingEnumeration enumeration = null; try { enumeration = ctx.listBindings(name); while (enumeration.hasMore()) { Binding binding = (Binding) enumeration.next(); LdapName childName = LdapUtils.newLdapName(binding.getName()); childName....
java
private void assureReturnObjFlagSet(SearchControls controls) { Assert.notNull(controls, "controls must not be null"); if (!controls.getReturningObjFlag()) { LOG.debug("The returnObjFlag of supplied SearchControls is not set" + " but a ContextMapper is used - setting flag to true"); control...
java
public DirContext getInnermostDelegateDirContext() { final DirContext delegateDirContext = this.getDelegateDirContext(); if (delegateDirContext instanceof DelegatingDirContext) { return ((DelegatingDirContext)delegateDirContext).getInnermostDelegateDirContext(); } return de...
java
public static Name getFirstArgumentAsName(Object[] args) { Assert.notEmpty(args); Object firstArg = args[0]; return getArgumentAsName(firstArg); }
java
public static Name getArgumentAsName(Object arg) { if (arg instanceof String) { return LdapUtils.newLdapName((String) arg); } else if (arg instanceof Name) { return (Name) arg; } else { throw new IllegalArgumentException( "First argu...
java